// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Make the seeds the fuzz targets in `tests/fuzz.zig` start from, and //! write them out as a Zig source file. //! //! A seed is only worth having if it gets deep: a session that locks the //! clock, starts a stream and plays it, so that a mutation of it reaches the //! decoders and the scheduler rather than being turned away by the first //! parse. So the sessions here are what a server would send -- clock //! exchanges, a `stream/start`, audio stamped to be heard on time, commands //! -- in each codec, with real FLAC frames and Opus packets encoded here, //! interleaved with the audio device asking for samples. The handshakes are //! a real server's `server/init` and Noise message 1 for the client identity //! the target uses. //! //! The script format is `tests/fuzz.zig`'s; see `session` there. const std = @import("std"); const flac = @import("flac"); const opus = @import("opus"); const noise = @import("noise"); const sendspin = @import("sendspin"); const secure = sendspin.secure; /// The client's static key in the handshake target, and the server's. const client_secret: [32]u8 = @splat(0x42); const server_secret: [32]u8 = @splat(0x24); /// Server time is the client's plus this, in microseconds. const server_offset: i64 = 1_000_000_000; pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa; var args: std.process.Args.Iterator = .init(init.minimal.args); _ = args.skip(); const path = args.next() orelse return error.MissingArgument; var arena_state: std.heap.ArenaAllocator = .init(gpa); defer arena_state.deinit(); const arena = arena_state.allocator(); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); const w = &out.writer; try w.writeAll( \\// Generated by tools/fuzz_corpus.zig; see there. \\ \\ ); try w.print("pub const client_secret = [32]u8{{", .{}); for (client_secret, 0..) |b, i| try w.print("{s}0x{x:0>2}", .{ if (i == 0) "" else ", ", b }); try w.writeAll("};\n\n"); try w.print("pub const server_secret = [32]u8{{", .{}); for (server_secret, 0..) |b, i| try w.print("{s}0x{x:0>2}", .{ if (i == 0) "" else ", ", b }); try w.writeAll("};\n\n"); try writeList(w, "messages", &messages); try writeList(w, "client_messages", &client_messages); var sessions: std.ArrayList([]const u8) = .empty; try sessions.append(arena, try session(arena, .{ .codec = .pcm, .rate = 48000, .channels = 2, .bits = 16 })); try sessions.append(arena, try session(arena, .{ .codec = .pcm, .rate = 44100, .channels = 2, .bits = 24 })); try sessions.append(arena, try session(arena, .{ .codec = .pcm, .rate = 48000, .channels = 1, .bits = 32 })); try sessions.append(arena, try session(arena, .{ .codec = .flac, .rate = 48000, .channels = 2, .bits = 16 })); try sessions.append(arena, try session(arena, .{ .codec = .flac, .rate = 44100, .channels = 2, .bits = 24 })); try sessions.append(arena, try session(arena, .{ .codec = .opus, .rate = 48000, .channels = 2, .bits = 16 })); try sessions.append(arena, try session(arena, .{ .codec = .opus, .rate = 16000, .channels = 1, .bits = 16 })); try writeList(w, "sessions", sessions.items); try writeList(w, "channels", &.{ // Whole messages, sealed by the server's own channel. try messageScript(arena, &.{ "{\"type\":\"server/hello\"}", "\x04abcdefgh" }), try channelScript(arena, &.{ .{ .kind = 0, .len = 40 }, .{ .kind = 4, .len = 200 } }), // A message in fragments: first, middle, last. try channelScript(arena, &.{ .{ .kind = 2, .len = 300 }, .{ .kind = 2, .len = 300 }, .{ .kind = 3, .len = 100 } }), try channelScript(arena, &.{ .{ .kind = 2, .len = 2 }, .{ .kind = 3, .len = 1 }, .{ .kind = 0, .len = 10 } }), }); try writeList(w, "handshakes", &.{try handshake(arena)}); try writeList(w, "server_handshakes", &.{try serverHandshake(arena)}); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = out.written() }); } /// What a server says, one message each. const messages = [_][]const u8{ \\{"type":"auth_ok"} , \\{"type":"server/hello","payload":{"server_id":"s","name":"Music Assistant","version":1,"active_roles":["player@v1"],"connection_reason":"playback"}} , \\{"type":"server/time","payload":{"client_transmitted":100000,"server_received":1000100500,"server_transmitted":1000100510,"client_received":101010}} , \\{"type":"stream/start","payload":{"player":{"codec":"flac","sample_rate":48000,"channels":2,"bit_depth":16}}} , \\{"type":"stream/start","payload":{"player":{"codec":"opus","sample_rate":48000,"channels":2,"bit_depth":16}}} , \\{"type":"stream/clear","payload":{"roles":["player"]}} , \\{"type":"stream/end","payload":{}} , \\{"type":"server/command","payload":{"player":{"command":"volume","volume":42}}} , \\{"type":"server/command","payload":{"player":{"command":"mute","mute":true}}} , \\{"type":"server/activate","payload":{"activities":["playback"],"active_roles":["player@v1"]}} , \\{"type":"group/update","payload":{"playback_state":"playing"}} , \\{"type":"server/state","payload":{"metadata":{"timestamp":1}}} , \\{"type":"server/state","payload":{"metadata":{"timestamp":1000000,"title":"Overture","artist":"Rush","album":"2112","year":1976,"track":1,"progress":{"track_progress":60000,"track_duration":1233000,"playback_speed":1000}},"controller":{"supported_commands":["play","pause","next","previous","volume","mute","seek"],"volume":55,"muted":false,"repeat":"all","shuffle":true,"seek_max_ms":1233000}}} , \\{"type":"server/state","payload":{"metadata":{"timestamp":5000000,"artist":null,"progress":{"track_progress":64000,"track_duration":0,"playback_speed":0}}}} , \\{"type":"server/state","payload":{"metadata":null}} , \\{"type":"stream/start","payload":{"artwork":{"channels":[{"source":"album","format":"jpeg","width":256,"height":256}]}}} , \\{"type":"stream/end","payload":{"roles":["artwork"]}} , }; /// What a client says, one message each: aiosendspin 9.1's, sealed, and /// 4.4's unencrypted hello. const client_messages = [_][]const u8{ \\{"type":"client/hello","payload":{"name":"Kitchen","device_info":{"product_name":"aiosendspin","software_version":"9.1.1"},"supported_roles":["player@v1","metadata@v1","controller@v1","artwork@v1"],"player@v1_support":{"supported_formats":[{"codec":"flac","channels":2,"sample_rate":48000,"bit_depth":24},{"codec":"opus","channels":2,"sample_rate":48000,"bit_depth":16},{"codec":"pcm","channels":2,"sample_rate":44100,"bit_depth":16}],"buffer_capacity":1048576,"supported_commands":["volume","mute"]},"artwork@v1_support":{"channels":[{"source":"album","format":"jpeg","media_width":300,"media_height":300},{"source":"artist","format":"png","media_width":64,"media_height":64}]},"pairing":{"methods":[{"method":"dynamic_pin","min_pin_length":6}],"unpaired_access":true}}} , \\{"type":"client/hello","payload":{"client_id":"legacy","name":"Old","version":1,"supported_roles":["player@v1"],"player_support":{"supported_formats":[{"codec":"pcm","channels":1,"sample_rate":8000,"bit_depth":16}],"buffer_capacity":64000,"supported_commands":[]}}} , \\{"type":"client/time","payload":{"client_transmitted":123456789}} , \\{"type":"client/state","payload":{"available":true,"player":{"volume":80,"muted":false,"static_delay_ms":20,"required_lead_time_ms":500,"min_buffer_ms":250}}} , \\{"type":"client/state","payload":{"state":"synchronized","player":{"volume":100,"muted":true}}} , \\{"type":"client/command","payload":{"controller":{"command":"volume","volume":30}}} , \\{"type":"client/command","payload":{"controller":{"command":"seek","position_ms":60000}}} , \\{"type":"client/command","payload":{"controller":{"command":"switch"}}} , \\{"type":"stream/request-format","payload":{"player":{"codec":"flac","sample_rate":48000,"bit_depth":16}}} , \\{"type":"client/goodbye","payload":{"reason":"shutdown"}} , \\{"type":"client/pair-init","payload":{"pairing_index":1,"commit_B":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}} , \\{"type":"client/pair-auth","payload":{"pake_msg_2":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}} , \\{"type":"client/pair-confirm","payload":{"client_kc":"BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB","nonce_B":"CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC"}} , \\{"type":"client/pair-finalize","payload":{"wrapped_psk":"DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD"}} , \\{"type":"pair/abort","payload":{"reason":"pin_mismatch"}} , }; const Format = struct { codec: sendspin.message.Codec, rate: u32, channels: u8, bits: u8, }; /// A session script: `op`, a little-endian `u16` length, that many bytes. const Script = struct { bytes: std.ArrayList(u8) = .empty, a: std.mem.Allocator, fn op(s: *Script, kind: u8, data: []const u8) !void { try s.bytes.append(s.a, kind); var len: [2]u8 = undefined; std.mem.writeInt(u16, &len, @intCast(data.len), .little); try s.bytes.appendSlice(s.a, &len); try s.bytes.appendSlice(s.a, data); } fn text(s: *Script, comptime fmt: []const u8, args: anytype) !void { try s.op(0, try std.fmt.allocPrint(s.a, fmt, args)); } fn audio(s: *Script, server_us: i64, data: []const u8) !void { const b = try s.a.alloc(u8, 9 + data.len); b[0] = 4; std.mem.writeInt(i64, b[1..9], server_us, .big); @memcpy(b[9..], data); try s.op(1, b); } fn fill(s: *Script, frames: u16, client_us: i64) !void { var b: [10]u8 = undefined; std.mem.writeInt(u16, b[0..2], frames, .little); std.mem.writeInt(i64, b[2..10], client_us, .little); try s.op(2, &b); } fn received(s: *Script, client_us: i64) !void { var b: [8]u8 = undefined; std.mem.writeInt(i64, &b, client_us, .little); try s.op(3, &b); } fn fade(s: *Script, fade_us: u32, hold_us: u32) !void { var b: [8]u8 = undefined; std.mem.writeInt(u32, b[0..4], fade_us, .little); std.mem.writeInt(u32, b[4..8], hold_us, .little); try s.op(4, &b); } /// One clock exchange, taken at `client_us` with a millisecond's round /// trip. fn time(s: *Script, client_us: i64) !void { try s.received(client_us + 1010); try s.text( \\{{"type":"server/time","payload":{{"client_transmitted":{d},"server_received":{d},"server_transmitted":{d}}}}} , .{ client_us, client_us + server_offset + 500, client_us + server_offset + 510 }); } }; /// A session as Music Assistant would run it for `format`: the clock /// locked, the stream started, 100 ms of audio played through, a command, a /// clear, more audio, a fade, and the end. fn session(a: std.mem.Allocator, format: Format) ![]const u8 { var s: Script = .{ .a = a }; try s.time(100_000); try s.time(300_000); const chunk_frames: u32 = format.rate / 50; // 20 ms const chunks = 5; var samples = try a.alloc(f32, chunks * chunk_frames * format.channels); for (0..chunks * chunk_frames) |i| for (0..format.channels) |c| { const t: f32 = @as(f32, @floatFromInt(i)) / @as(f32, @floatFromInt(format.rate)); samples[i * format.channels + c] = 0.5 * @sin(2 * std.math.pi * (440 + 110 * @as(f32, @floatFromInt(c))) * t); }; var encoded: [chunks][]const u8 = undefined; var header: ?[]const u8 = null; switch (format.codec) { .pcm => for (&encoded, 0..) |*e, k| { const width = format.bits / 8; const chunk = samples[k * chunk_frames * format.channels ..][0 .. chunk_frames * format.channels]; const b = try a.alloc(u8, chunk.len * width); for (chunk, 0..) |v, i| { const scaled: i64 = @intFromFloat(v * @as(f32, @floatFromInt(@as(i64, 1) << @intCast(format.bits - 1)))); switch (width) { 2 => std.mem.writeInt(i16, b[i * 2 ..][0..2], @intCast(scaled), .little), 3 => std.mem.writeInt(i24, b[i * 3 ..][0..3], @intCast(scaled), .little), else => std.mem.writeInt(i32, b[i * 4 ..][0..4], @intCast(scaled), .little), } } e.* = b; }, .flac => { const ints = try a.alloc(i32, samples.len); for (ints, samples) |*o, v| o.* = @intFromFloat(v * @as(f32, @floatFromInt(@as(i32, 1) << @intCast(format.bits - 1)))); var out: std.Io.Writer.Allocating = .init(a); var encoder = try flac.Encoder.init(a, &out.writer, .{ .sample_rate = format.rate, .channels = format.channels, .bits_per_sample = format.bits, }, .{ .block_size = chunk_frames }); try encoder.writeInterleaved(ints); try encoder.finish(); encoder.deinit(); const bytes = out.written(); // Where each frame starts, as a decoder finds them. var reader: std.Io.Reader = .fixed(bytes); var decoder = try flac.Decoder.init(a, &reader, .{}); const audio_at: usize = @intCast(decoder.audioOffset()); var starts: std.ArrayList(usize) = .empty; while (try decoder.next()) |frame| try starts.append(a, audio_at + @as(usize, @intCast(frame.offset))); decoder.deinit(); for (&encoded, 0..) |*e, i| { const end = if (i + 1 < starts.items.len) starts.items[i + 1] else bytes.len; e.* = bytes[starts.items[i]..end]; } // The signature and the streaminfo alone, marked as the last // block, as aiosendspin sends it. var head: [4 + 4 + 34]u8 = undefined; @memcpy(head[0..4], "fLaC"); head[4] = 0x80; std.mem.writeInt(u24, head[5..8], 34, .big); @memcpy(head[8..], bytes[8..][0..34]); const b64 = try a.alloc(u8, std.base64.standard.Encoder.calcSize(head.len)); header = std.base64.standard.Encoder.encode(b64, &head); }, .opus => { var e = try opus.Encoder.init(format.rate, format.channels, .audio); try e.setBitrate(.{ .bps = 48000 * @as(i32, format.channels) }); for (&encoded, 0..) |*p, k| { const chunk = samples[k * chunk_frames * format.channels ..][0 .. chunk_frames * format.channels]; var buf: [1500]u8 = undefined; const n = try e.encodeFloat(chunk, chunk_frames, &buf); p.* = try a.dupe(u8, buf[0..n]); } }, } try s.text( \\{{"type":"stream/start","payload":{{"player":{{"codec":"{t}","sample_rate":{d},"channels":{d},"bit_depth":{d}{s}{s}{s}}}}}}} , .{ format.codec, format.rate, format.channels, format.bits, if (header != null) ",\"codec_header\":\"" else "", header orelse "", if (header != null) "\"" else "", }); // The first two chunks, then the device asking for the first 10 ms, // then the rest as it plays. const start_us: i64 = 400_000; for (encoded[0..2], 0..) |e, k| try s.audio(start_us + server_offset + @as(i64, @intCast(k)) * 20_000, e); const period: u16 = @intCast(format.rate / 100); try s.fill(period, start_us); try s.fill(period, start_us + 10_000); try s.text( \\{{"type":"server/command","payload":{{"player":{{"command":"volume","volume":60}}}}}} , .{}); // What the metadata role hears alongside, changing as it plays. try s.text( \\{{"type":"server/state","payload":{{"metadata":{{"timestamp":{d},"title":"Tone","artist":"zig-sendspin","progress":{{"track_progress":0,"track_duration":1000,"playback_speed":1000}}}},"controller":{{"supported_commands":["next","seek"],"volume":60,"muted":false,"repeat":"off","shuffle":false,"seek_max_ms":1000}}}}}} , .{start_us + server_offset}); for (encoded[2..], 2..) |e, k| try s.audio(start_us + server_offset + @as(i64, @intCast(k)) * 20_000, e); for (2..6) |k| try s.fill(period, start_us + @as(i64, @intCast(k)) * 10_000); try s.time(450_000); try s.fade(5_000, 20_000); try s.fill(period, start_us + 60_000); try s.text( \\{{"type":"stream/clear","payload":{{"roles":["player"]}}}} , .{}); try s.audio(start_us + server_offset + 200_000, encoded[0]); try s.fill(period, start_us + 200_000); try s.text( \\{{"type":"server/command","payload":{{"player":{{"command":"mute","mute":true}}}}}} , .{}); try s.fill(period, start_us + 210_000); try s.text( \\{{"type":"stream/end","payload":{{}}}} , .{}); try s.fill(period, start_us + 220_000); return s.bytes.items; } const Sealed = struct { kind: u8, len: u16 }; /// A channel script: a little-endian `u16` length, its top bit set to say /// the bytes are a plaintext to seal as they are, then that many bytes, for /// each frame the server seals. fn channelScript(a: std.mem.Allocator, frames: []const Sealed) ![]const u8 { var out: std.ArrayList(u8) = .empty; for (frames) |f| { var len: [2]u8 = undefined; std.mem.writeInt(u16, &len, f.len | 0x8000, .little); try out.appendSlice(a, &len); for (0..f.len) |i| try out.append(a, if (i == 0) f.kind else if (f.kind == 2 and i == 1) 4 else @truncate(i *% 31)); } return out.items; } /// A channel script of whole messages for the server's channel to seal, /// the second eight times over, so that it needs fragments. fn messageScript(a: std.mem.Allocator, bodies: []const []const u8) ![]const u8 { var out: std.ArrayList(u8) = .empty; for (bodies, 0..) |body, i| { var len: [2]u8 = undefined; std.mem.writeInt(u16, &len, @as(u16, @intCast(body.len)) | @as(u16, if (i == 1) 0x4000 else 0), .little); try out.appendSlice(a, &len); try out.appendSlice(a, body); } return out.items; } /// `server/init` and `noise/handshake`, as a server would send them to the /// client whose key is `client_secret`: a `u16` length and the text, twice. fn handshake(a: std.mem.Allocator) ![]const u8 { const client = noise.KeyPair.fromSecret(client_secret); const server = noise.KeyPair.fromSecret(server_secret); var prng: std.Random.DefaultPrng = .init(1); var ch: secure.ClientHandshake = .init(a, client, prng.random()); const client_init = try ch.begin(); const server_id = secure.peerId(server.public); const server_init = try std.fmt.allocPrint(a, \\{{"type":"server/init","payload":{{"server_id":"{s}","version":1}}}} , .{&server_id}); var s = try noise.HandshakeState.init(.{ .protocol_name = secure.protocol_name, .role = .initiator, .prologue = try std.mem.concat(a, u8, &.{ client_init, server_init }), .s = server, .rs = client.public, .psks = &.{secure.sentinel_psk}, .random = prng.random(), }); var m1_buf: [256]u8 = undefined; const m1 = try s.writeMessage(try std.fmt.allocPrint(a, "{{\"psk_id\":\"{s}\"}}", .{&secure.pskId(secure.sentinel_psk)}), &m1_buf); var data_buf: [512]u8 = undefined; const hs1 = try std.fmt.allocPrint(a, \\{{"type":"noise/handshake","payload":{{"data":"{s}"}}}} , .{std.base64.url_safe_no_pad.Encoder.encode(&data_buf, m1)}); var out: std.ArrayList(u8) = .empty; for ([_][]const u8{ server_init, hs1 }) |t| { var len: [2]u8 = undefined; std.mem.writeInt(u16, &len, @intCast(t.len), .little); try out.appendSlice(a, &len); try out.appendSlice(a, t); } return out.items; } /// A client's `client/init` and its Noise message 2, answering the /// server's message 1 as `tests/fuzz.zig`'s server target makes it: the /// same key, and randomness from the same seed. fn serverHandshake(a: std.mem.Allocator) ![]const u8 { var client_prng: std.Random.DefaultPrng = .init(2); var ch: secure.ClientHandshake = .init(a, noise.KeyPair.fromSecret(client_secret), client_prng.random()); const client_init = try a.dupe(u8, try ch.begin()); var server_prng: std.Random.DefaultPrng = .init(1); var sh: secure.ServerHandshake = .init(a, noise.KeyPair.fromSecret(server_secret), server_prng.random(), null); const reply = try sh.clientInit(client_init); try ch.serverInit(reply.server_init); const message_2 = try ch.message1(reply.message_1); var out: std.ArrayList(u8) = .empty; for ([_][]const u8{ client_init, message_2 }) |t| { var len: [2]u8 = undefined; std.mem.writeInt(u16, &len, @intCast(t.len), .little); try out.appendSlice(a, &len); try out.appendSlice(a, t); } return out.items; } fn writeList(w: *std.Io.Writer, name: []const u8, items: []const []const u8) !void { try w.print("pub const {s} = [_][]const u8{{\n", .{name}); for (items) |item| { try w.writeAll(" \""); for (item) |b| try w.print("\\x{x:0>2}", .{b}); try w.writeAll("\",\n"); } try w.writeAll("};\n\n"); }