// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What a player must do with whatever a server sends it, and a server //! with whatever a client sends it. //! //! Everything a Sendspin server says reaches a player unchecked: the JSON of //! each message, the timestamps and data of each audio frame, the Noise //! handshake and every sealed frame after it. Everything a client says //! reaches the server the same way: its hello and the formats in it, the //! handshake, the pairing messages. So each target here is a property of //! one of those paths rather than an example: whatever arrives, the call //! returns, stays inside its buffers, frees what it allocated, and what //! comes out holds together -- the samples handed to the audio device are //! finite, a message sealed on one side opens as the same message on the //! other, no PSK is taken from a client that did not prove the PIN. //! //! Each target is an ordinary test as well as a fuzz target. Without //! `--fuzz` it runs the seeds `tools/fuzz_corpus.zig` makes, so `zig build //! test` checks the same properties on real sessions. `zig build fuzz --fuzz` //! mutates those seeds with Zig's fuzzer, and `zig build fuzz-run` with the //! loop in `tools/fuzz.zig`. const builtin = @import("builtin"); const std = @import("std"); const Allocator = std.mem.Allocator; const testing = std.testing; const Smith = std.testing.Smith; const noise = @import("noise"); const sendspin = @import("sendspin"); const server_mod = @import("sendspin_server"); const corpus = @import("fuzz_corpus"); const message = sendspin.message; const secure = sendspin.secure; const Player = sendspin.Player; const Scheduler = sendspin.Scheduler; const TimeFilter = sendspin.TimeFilter; /// 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; /// The `Io` the server targets run on: `std.testing.io` in a test build, /// and whatever `tools/fuzz.zig` hands it otherwise. pub var io: std.Io = if (builtin.is_test) testing.io else undefined; fn expectFinite(samples: []const f32) !void { for (samples) |s| if (!std.math.isFinite(s)) return error.NotFinite; } /// One record of a script: a byte saying what it is, a little-endian `u16` /// length, and that many bytes, fewer if the input ends first. const Record = struct { op: u8, data: []const u8 }; fn nextRecord(rest: *[]const u8) ?Record { if (rest.len < 3) return null; const op = rest.*[0]; const len = @min(std.mem.readInt(u16, rest.*[1..3], .little), rest.len - 3); const data = rest.*[3..][0..len]; rest.* = rest.*[3 + len ..]; return .{ .op = op, .data = data }; } /// A little-endian integer from the front of `data`, the missing bytes /// zero. fn readPadded(comptime T: type, data: []const u8) T { var b: [@sizeOf(T)]u8 = @splat(0); const n = @min(b.len, data.len); @memcpy(b[0..n], data[0..n]); return std.mem.readInt(T, &b, .little); } // -- messages ------------------------------------------------------------------ /// Any text parses or is refused, and a clock exchange from it leaves the /// clock able to convert. fn messageProperty(input: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); const a = arena.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, a, input, .{}) catch return; // A pairing message parses, or is refused as malformed. _ = sendspin.pairing.parse(a, v) catch {}; const incoming = message.classify(a, v) catch return; switch (incoming) { .time => |t| { var clock: TimeFilter = .init(); clock.exchange(t.client_transmitted, t.server_received, t.server_transmitted, 0); clock.exchange(t.client_transmitted, t.server_received, t.server_transmitted, 1_000_000); _ = clock.serverTime(2_000_000); _ = clock.clientTime(t.server_transmitted); _ = clock.nextIntervalMs(); }, .command => |c| switch (c) { .volume => |vol| try testing.expect(vol <= 100), .mute => {}, }, else => {}, } } test "fuzz the server's messages" { for (corpus.messages) |seed| try messageProperty(seed); try testing.fuzz({}, fuzzMessages, .{}); } fn fuzzMessages(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; try messageProperty(buffer[0..smith.slice(&buffer)]); } // -- sessions ------------------------------------------------------------------ /// Output planes for `fill`, as many as a stream can have channels. var planes_storage: [Scheduler.max_channels][max_fill]f32 = undefined; const max_fill = 2048; /// A whole session, as a player lives it: a script of what the server sends /// and what the audio device asks for, played into a `Player` and its /// `Scheduler`. Whatever the server sends, the device is only ever handed /// finite samples, and nothing is left allocated. Returns how many of the /// samples it was handed were not silence, which says a seed gets as far as /// playing. /// /// The records, by `op` modulo 5: /// /// - 0: a text message, dispatched as `Client` dispatches it; /// - 1: a binary message, an audio frame if its type says so; /// - 2: the device asking for samples: a `u16` frame count, the `i64` /// moment on this machine's clock they will be heard, and a byte for how /// many channels the device has; /// - 3: the moment on this machine's clock the next message arrives, which /// the next `server/time` is measured by; /// - 4: a fade out, as the application asks for one: two `u32`s of /// microseconds, the fade and the hold. fn sessionProperty(input: []const u8) !usize { // A second of room, not the default thirty: the property is the same, // and every `stream/start` allocates it afresh. var scheduler: Scheduler = .init(backing, .{ .capacity_us = std.time.us_per_s }); defer scheduler.deinit(); var player: Player = .init(backing, &scheduler); defer player.deinit(); const sink = player.sink(); var clock: TimeFilter = .init(); var received: i64 = 0; var heard: usize = 0; var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); // The metadata, merged message into message as `Client` merges it, in // two arenas by turns. var metadata: message.Metadata = .{}; var metadata_arenas: [2]std.heap.ArenaAllocator = .{ .init(backing), .init(backing) }; defer for (&metadata_arenas) |*m| m.deinit(); var metadata_arena: u1 = 0; var rest = input; while (nextRecord(&rest)) |r| switch (r.op % 5) { 0 => { _ = arena.reset(.retain_capacity); const a = arena.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, a, r.data, .{}) catch continue; const incoming = message.classify(a, v) catch continue; // As `Client.dispatch` does, less what it sends back. switch (incoming) { .time => |t| { clock.exchange(t.client_transmitted, t.server_received, t.server_transmitted, received); sink.onClock(sink.context, clock); }, .hello => |h| sink.onConnected(sink.context, h), .stream_start => |starts| if (starts.player) |f| sink.onStreamStart(sink.context, f), .stream_clear => |roles| if (roles.player) sink.onStreamClear(sink.context), .stream_end => |roles| if (roles.player) sink.onStreamEnd(sink.context), .command => |c| sink.onCommand(sink.context, c), .group => |g| sink.onPlayback(sink.context, g), .state => |state| { switch (state.metadata) { .absent => {}, .clear => metadata = .{}, .update => |update| { metadata_arena +%= 1; _ = metadata_arenas[metadata_arena].reset(.retain_capacity); metadata = try metadata.merge(metadata_arenas[metadata_arena].allocator(), update); }, } // Wherever the clock is, the position is on the track. if (metadata.position(received)) |at| { try testing.expect(at >= 0); if (metadata.progress.?.track_duration > 0) try testing.expect(at <= metadata.progress.?.track_duration); } }, .auth_ok, .activate, .other => {}, } }, 1 => { const b = message.parseBinary(r.data) catch continue; if (b.type == .audio) sink.onAudio(sink.context, b.timestamp_us, b.data); }, 2 => { const frames: u32 = @min(readPadded(u16, r.data), max_fill); const play_at = readPadded(i64, if (r.data.len > 2) r.data[2..] else &.{}); const channels = 1 + @as(usize, if (r.data.len > 10) r.data[10] else 1) % Scheduler.max_channels; var planes: [Scheduler.max_channels][]f32 = undefined; for (planes[0..channels], 0..) |*p, c| p.* = &planes_storage[c]; _ = scheduler.fill(planes[0..channels], frames, play_at); for (planes[0..channels]) |p| { try expectFinite(p[0..frames]); for (p[0..frames]) |x| heard += @intFromBool(x != 0); } try testing.expect(scheduler.bufferedUs() >= 0); }, 3 => received = readPadded(i64, r.data), 4 => scheduler.fadeOut(readPadded(u32, r.data), readPadded(u32, if (r.data.len > 4) r.data[4..] else &.{})), else => unreachable, }; sink.onDisconnected(sink.context, error.ConnectionClosed); return heard; } test "fuzz whole sessions" { // Every seed plays something, or it is no seed for the decoders. for (corpus.sessions) |seed| try testing.expect(try sessionProperty(seed) > 0); try testing.fuzz({}, fuzzSessions, .{}); } fn fuzzSessions(_: void, smith: *Smith) !void { var buffer: [32768]u8 = undefined; _ = try sessionProperty(buffer[0..smith.slice(&buffer)]); } // -- the sealed channel -------------------------------------------------------- /// A transport pair keyed by hand, as a finished handshake would leave it: /// the server's and the client's. fn transports() [2]noise.Transport { const to_client: noise.CipherState = .{ .cipher = .chachapoly, .k = @splat(1) }; const to_server: noise.CipherState = .{ .cipher = .chachapoly, .k = @splat(2) }; return .{ .{ .send = to_client, .recv = to_server }, .{ .send = to_server, .recv = to_client }, }; } /// Where the server's frames go: straight into the client's channel, which /// keeps what it opens. const Wire = struct { client: *secure.Channel, opened: std.ArrayList(u8) = .empty, kind: ?enum { text, binary } = null, count: usize = 0, pub fn frame(self: *Wire, bytes: []const u8) !void { const got = try self.client.open(bytes) orelse return; self.count += 1; self.opened.clearRetainingCapacity(); switch (got) { .text => |t| { self.kind = .text; try self.opened.appendSlice(backing, t); }, .binary => |b| { self.kind = .binary; try self.opened.appendSlice(backing, b); }, } } }; var sealed_buf: [noise.HandshakeState.max_message_len]u8 = undefined; /// Each record a `u16` length and then its bytes. With the length's top bit /// set, the bytes are a plaintext the server seals as it is -- anything at /// all, fragment or not -- and the client's channel must open it or refuse /// it, and never hand back more than `max_message`. Without it they are a /// message the server's own channel seals, eight times over with the next /// bit set so as to need fragments, which must open as exactly that message /// whenever the client was not left halfway through a fragmented one. fn channelProperty(input: []const u8) !void { const pair = transports(); var server: secure.Channel = try .init(backing, pair[0]); defer server.deinit(); var client: secure.Channel = try .init(backing, pair[1]); defer client.deinit(); var wire: Wire = .{ .client = &client }; defer wire.opened.deinit(backing); var rest = input; while (rest.len >= 2) { const raw_len = std.mem.readInt(u16, rest[0..2], .little); const len = @min(raw_len & 0x3fff, rest.len - 2); const data = rest[2..][0..len]; rest = rest[2 + len ..]; if (raw_len & 0x8000 != 0) { var transport = &server.transport; const frame = try transport.encrypt(data, &sealed_buf); const got = client.open(frame) catch continue; if (got) |g| switch (g) { .text => |t| try testing.expect(t.len < secure.max_message), .binary => |b| try testing.expect(b.len > 0 and b.len <= secure.max_message), }; continue; } if (data.len == 0) continue; const repeat: usize = if (raw_len & 0x4000 != 0) 8 else 1; const body = try backing.alloc(u8, data.len * repeat); defer backing.free(body); for (0..repeat) |i| @memcpy(body[i * data.len ..][0..data.len], data); const clean = !client.reassembling; wire.count = 0; const as_text = body[0] & 1 == 0; // A binary message's first byte is its type, and the ones that // would open as JSON or a fragment are refused. if (!as_text and (body[0] == 0 or body[0] == 2 or body[0] == 3)) { try testing.expectError(error.InvalidMessageType, server.sealBinary(body, &wire)); continue; } if (as_text) { server.sealText(body, &wire) catch |err| { if (clean) return err; continue; }; } else { server.sealBinary(body, &wire) catch |err| { if (clean) return err; continue; }; } if (!clean) continue; try testing.expectEqual(@as(usize, 1), wire.count); if (as_text) { try testing.expect(wire.kind == .text); try testing.expectEqualSlices(u8, body, wire.opened.items); } else { try testing.expect(wire.kind == .binary); try testing.expectEqualSlices(u8, body, wire.opened.items); } } } test "fuzz the sealed channel" { for (corpus.channels) |seed| try channelProperty(seed); try testing.fuzz({}, fuzzChannel, .{}); } fn fuzzChannel(_: void, smith: *Smith) !void { var buffer: [16384]u8 = undefined; try channelProperty(buffer[0..smith.slice(&buffer)]); } // -- the handshake ------------------------------------------------------------- /// `server/init` and `noise/handshake` as a server might send them: each is /// refused, or taken, and a handshake that finishes answers with a message /// 2 that parses and leaves ciphers behind it. fn handshakeProperty(input: []const u8) !void { var rest = input; var texts: [2][]const u8 = .{ &.{}, &.{} }; for (&texts) |*t| { if (rest.len < 2) break; const len = @min(std.mem.readInt(u16, rest[0..2], .little), rest.len - 2); t.* = rest[2..][0..len]; rest = rest[2 + len ..]; } var prng: std.Random.DefaultPrng = .init(1); var ch: secure.ClientHandshake = .init(backing, noise.KeyPair.fromSecret(corpus.client_secret), prng.random()); defer ch.deinit(); _ = try ch.begin(); ch.serverInit(texts[0]) catch return; const reply = ch.message1(texts[1]) catch return; defer backing.free(reply); var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); const Msg = struct { type: []const u8, payload: struct { data: []const u8 } }; const m = try std.json.parseFromSliceLeaky(Msg, arena.allocator(), reply, .{}); try testing.expectEqualStrings("noise/handshake", m.type); _ = try ch.transport(); } test "fuzz the handshake" { for (corpus.handshakes) |seed| try handshakeProperty(seed); try testing.fuzz({}, fuzzHandshake, .{}); } fn fuzzHandshake(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; try handshakeProperty(buffer[0..smith.slice(&buffer)]); } // -- pairing --------------------------------------------------------------------- /// A server forging its side of a dynamic-PIN attempt: a script of what it /// sends, each a byte saying which message and the bytes of it -- a nonce, /// a share, a tag -- in any order. Whatever it sends, the player answers or /// refuses, and never gets as far as handing over a PSK: that takes the /// server's confirmation tag, which only a server that knows the PIN can /// make, and the PIN depends on a nonce of the player's it has only seen a /// commitment to. fn pairingProperty(input: []const u8) !void { var prng: std.Random.DefaultPrng = .init(std.hash.Wyhash.hash(1, input)); const random = prng.random(); const hh: [32]u8 = @splat(0x5a); var out: std.Io.Writer.Allocating = .init(backing); defer out.deinit(); var dp = try sendspin.pairing.DynamicPin.start(random, &hh, 1, 6, &out.writer); var rest = input; while (rest.len > 0) { const op = rest[0] % 4; rest = rest[1..]; const n: usize = switch (op) { 0 => 32, 1 => 32, 2 => 64, else => 0, }; var bytes: [64]u8 = @splat(0); const take = @min(n, rest.len); @memcpy(bytes[0..take], rest[0..take]); rest = rest[take..]; out.clearRetainingCapacity(); switch (op) { 0 => _ = dp.onInit(random, bytes[0..32].*) catch {}, 1 => dp.onAuth(bytes[0..32].*, &out.writer) catch {}, 2 => if (dp.onConfirm(bytes[0..64].*, &out.writer) catch false) { return error.ForgedTagAccepted; }, else => _ = dp.onFinalize() catch {}, } try testing.expect(dp.state != .finalize_sent and dp.state != .done); } } /// `pattern` written `n` times over, as a string literal: what `**` made /// before Zig 0.17 removed it, for patterns longer than the one byte /// `@splat` can repeat. fn times(comptime pattern: []const u8, comptime n: usize) *const [pattern.len * n]u8 { comptime { @setEvalBranchQuota(10 * n); var out: [pattern.len * n]u8 = undefined; for (0..n) |i| @memcpy(out[i * pattern.len ..][0..pattern.len], pattern); const final = out; return &final; } } const pairing_seeds = [_][]const u8{ // Init, auth, confirm, finalize, in order, with plausible bytes. "\x00" ++ times("\x11", 32) ++ "\x01" ++ times("\x09", 32) ++ "\x02" ++ times("\x22", 64) ++ "\x03", // Out of order, and a low-order point for a share. "\x02" ++ times("\x00", 64) ++ "\x01" ++ "\x01" ++ times("\x00", 31) ++ "\x00" ++ times("\x33", 32), }; test "fuzz a forged pairing" { for (pairing_seeds) |seed| try pairingProperty(seed); try testing.fuzz({}, fuzzPairing, .{}); } fn fuzzPairing(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; try pairingProperty(buffer[0..smith.slice(&buffer)]); } // -- PCM ----------------------------------------------------------------------- /// Any bytes decode at any depth there is to as many samples as fit, each /// from -1 up to 1. fn pcmProperty(input: []const u8) !void { if (input.len == 0) return; const depths = [_]u8{ 16, 24, 32 }; const depth = if (input[0] < 0xf0) depths[input[0] % 3] else input[0]; var out: [1024]f32 = undefined; const n = sendspin.pcm.decode(depth, input[1..], &out) catch |err| { try testing.expectEqual(error.UnsupportedBitDepth, err); return; }; try testing.expectEqual(@min((input.len - 1) / (depth / 8), out.len), n); for (out[0..n]) |s| try testing.expect(s >= -1 and s <= 1); } test "fuzz PCM" { for (corpus.sessions) |seed| try pcmProperty(seed); try testing.fuzz({}, fuzzPcm, .{}); } fn fuzzPcm(_: void, smith: *Smith) !void { var buffer: [8192]u8 = undefined; try pcmProperty(buffer[0..smith.slice(&buffer)]); } // -- a client's messages ----------------------------------------------------- /// Any text a client sends parses or is refused, and what the server takes /// from it is within what it can act on: every format in a hello one the /// encoders can make, every pairing message one the verifier can be fed. fn clientMessageProperty(input: []const u8) !void { var arena: std.heap.ArenaAllocator = .init(backing); defer arena.deinit(); const a = arena.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, a, input, .{}) catch return; _ = sendspin.pairing.parseClient(v) catch {}; switch (sendspin.server_message.classifyClient(a, v) catch return) { .hello => |h| { if (h.player) |p| for (p.formats) |f| try testing.expect(sendspin.server_message.servable(f)); if (h.artwork) |channels| try testing.expect(channels.len <= sendspin.message.max_artwork_channels); }, else => {}, } } test "fuzz a client's messages" { for (corpus.client_messages) |seed| try clientMessageProperty(seed); try testing.fuzz({}, fuzzClientMessages, .{}); } fn fuzzClientMessages(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; try clientMessageProperty(buffer[0..smith.slice(&buffer)]); } // -- the server's handshake ------------------------------------------------------ /// `client/init` and Noise message 2 as a client might send them: each is /// refused or taken, and a handshake that finishes leaves ciphers, with the /// client proved to be the key its `client/init` named. fn serverHandshakeProperty(input: []const u8) !void { var rest = input; var texts: [2][]const u8 = .{ &.{}, &.{} }; for (&texts) |*t| { if (rest.len < 2) break; const len = @min(std.mem.readInt(u16, rest[0..2], .little), rest.len - 2); t.* = rest[2..][0..len]; rest = rest[2 + len ..]; } var prng: std.Random.DefaultPrng = .init(1); var sh: secure.ServerHandshake = .init(backing, noise.KeyPair.fromSecret(corpus.server_secret), prng.random(), null); defer sh.deinit(); _ = sh.clientInit(texts[0]) catch return; sh.message2(texts[1]) catch return; _ = try sh.transport(); try testing.expectEqual(secure.Category.sentinel, sh.category); // Only the seed's client can have finished it: message 2 is sealed to // the key `client/init` named, and only its secret makes one. const client = noise.KeyPair.fromSecret(corpus.client_secret); try testing.expectEqualStrings(&secure.peerId(client.public), &sh.client_id); } test "fuzz the server's handshake" { for (corpus.server_handshakes) |seed| try serverHandshakeProperty(seed); try testing.fuzz({}, fuzzServerHandshake, .{}); } fn fuzzServerHandshake(_: void, smith: *Smith) !void { var buffer: [2048]u8 = undefined; try serverHandshakeProperty(buffer[0..smith.slice(&buffer)]); } // -- the verifier ------------------------------------------------------------------ /// A client forging its side of a dynamic-PIN attempt: a commitment, and /// then a script of shares, tags with nonces, and wrapped PSKs, in any /// order. Whatever it sends, the verifier never confirms it, and so never /// unwraps a PSK: that takes a tag made with the PIN the operator typed, /// which a client that does not know it cannot make. fn verifierProperty(input: []const u8) !void { var prng: std.Random.DefaultPrng = .init(std.hash.Wyhash.hash(2, input)); const random = prng.random(); const hh: [32]u8 = @splat(0xa5); var out: std.Io.Writer.Allocating = .init(backing); defer out.deinit(); var commit: [sendspin.pairing.commit_length]u8 = @splat(0); const take = @min(commit.len, input.len); @memcpy(commit[0..take], input[0..take]); var rest = input[take..]; var vf = try sendspin.pairing.Verifier.start(random, &hh, 1, commit, 6, &out.writer); out.clearRetainingCapacity(); try vf.auth(random, "314159", &out.writer); while (rest.len > 0) { const op = rest[0] % 3; rest = rest[1..]; var bytes: [96]u8 = @splat(0); const n: usize = switch (op) { 0 => 32, 1 => 64 + 32, else => sendspin.pairing.wrapped_length, }; const got = @min(n, rest.len); @memcpy(bytes[0..got], rest[0..got]); rest = rest[got..]; out.clearRetainingCapacity(); switch (op) { 0 => vf.onAuth(bytes[0..32].*, &out.writer) catch {}, 1 => if (vf.onConfirm(bytes[0..64].*, bytes[64..96].*)) { return error.ForgedTagAccepted; } else |_| {}, else => if (vf.onFinalize(bytes[0..sendspin.pairing.wrapped_length].*, &out.writer)) |_| { return error.PskTakenUnconfirmed; } else |_| {}, } try testing.expect(vf.state != .confirmed and vf.state != .done); } } const verifier_seeds = [_][]const u8{ // A commitment, then a share, a confirmation and a wrapped PSK. times("\x11", 32) ++ "\x00" ++ times("\x09", 32) ++ "\x01" ++ times("\x22", 96) ++ "\x02" ++ times("\x33", 48), // Out of order, and a low-order point for a share. times("\x00", 32) ++ "\x02" ++ times("\x44", 48) ++ "\x00" ++ "\x01" ++ times("\x00", 31) ++ "\x01" ++ times("\x00", 96), }; test "fuzz a forged pairing, verified" { for (verifier_seeds) |seed| try verifierProperty(seed); try testing.fuzz({}, fuzzVerifier, .{}); } fn fuzzVerifier(_: void, smith: *Smith) !void { var buffer: [1024]u8 = undefined; try verifierProperty(buffer[0..smith.slice(&buffer)]); } // -- the stream ---------------------------------------------------------------------- /// A group's audio, as the program writes it and as the players asked for /// it: whatever the source's format, the formats the players offer, and /// the samples written -- NaN and infinity among them -- the stream sends /// each player chunks it can take, returns, and frees everything. /// /// The input: a byte for the source's rate and one for its channels; a /// byte for how many players, and four for each one's format; then records /// (see `nextRecord`), by `op` modulo 4: /// /// - 0: samples, each a little-endian `i16`, the high bit of `op` making /// every seventh one NaN or infinite; /// - 1: a clear; /// - 2: the end, after which writes are refused -- canceled as soon as it /// starts, so that its flush is fuzzed without waiting out what it sent, /// and the cancelation's path to `stream/end` with it; /// - 3: a player, by the first byte, leaving or joining again. fn streamProperty(input: []const u8) !void { const Stream = server_mod.Stream; const Connection = server_mod.Connection; const rates = [_]u32{ 8000, 16000, 22050, 44100, 48000, 96000 }; if (input.len < 3) return; const source: Stream.Source = .{ .sample_rate = rates[input[0] % rates.len], .channels = input[1] % 8 + 1 }; const players = input[2] % 3 + 1; var rest = input[3..]; var server: server_mod.Server = undefined; try server.init(io, backing, .{ .name = "fuzz" }, .{ .context = undefined }); defer server.deinit(); const stream = try Stream.create(&server, source, std.math.maxInt(i64) / 4); var stream_live = true; defer if (stream_live) stream.destroy(); const codecs = [_]sendspin.message.Codec{ .pcm, .flac, .opus }; const depths = [_]u8{ 16, 24, 32 }; var formats: [3][1]sendspin.message.Format = undefined; var conns: [3]*Connection = undefined; var made: usize = 0; defer for (conns[0..made]) |c| { drain(c) catch {}; c.release(); }; for (0..players) |i| { if (rest.len < 4) break; formats[i][0] = .{ .codec = codecs[rest[0] % 3], .channels = rest[1] % 8 + 1, .sample_rate = rates[rest[2] % rates.len], .bit_depth = depths[rest[3] % 3], }; rest = rest[4..]; const c = try backing.create(Connection); c.* = .{ .server = &server, .session = undefined, .id = i, .channel = null, .hello = .{ .name = "player", .player = .{ .formats = if (sendspin.server_message.servable(formats[i][0])) &formats[i] else &.{}, .buffer_capacity = std.math.maxInt(u32), } }, .client_id = "", .paired = false, .arena = .init(backing), .roles = .{ .player = true }, .queue = undefined, }; c.queue = .init(&c.queue_buf); c.state_seen.store(true, .release); conns[made] = c; made += 1; try stream.addMember(c, null); } var samples: [4096]f32 = undefined; while (nextRecord(&rest)) |r| { switch (r.op % 4) { 0 => { const n = @min(r.data.len / 2 / source.channels * source.channels, samples.len / source.channels * source.channels); for (samples[0..n], 0..) |*d, i| { d.* = @as(f32, @floatFromInt(std.mem.readInt(i16, r.data[i * 2 ..][0..2], .little))) / 32768; if (r.op & 0x80 != 0 and i % 7 == 0) d.* = switch (i % 3) { 0 => std.math.nan(f32), 1 => std.math.inf(f32), else => -std.math.inf(f32), }; } stream.write(samples[0..n], 0) catch |err| if (err != error.Ended) return err; }, 1 => stream.clear(), 2 => { var ending = try io.concurrent(Stream.end, .{stream}); ending.cancel(io) catch |err| if (err != error.Canceled) return err; }, else => if (made > 0) { const c = conns[(if (r.data.len > 0) r.data[0] else 0) % made]; if (r.data.len > 1 and r.data[1] & 1 != 0) stream.removeMember(c) else try stream.addMember(c, null); }, } for (conns[0..made]) |c| try drain(c); } stream.destroy(); stream_live = false; } /// What the stream queued for `c`, taken and checked: text that is JSON, /// and audio that has a header and something after it. fn drain(c: *server_mod.Connection) !void { var one: [1]server_mod.Connection.Out = undefined; while (true) { const n = c.queue.get(io, &one, 0) catch return; if (n == 0) return; switch (one[0]) { .text => |t| { defer backing.free(t); var parsed = try std.json.parseFromSlice(std.json.Value, backing, t, .{}); parsed.deinit(); }, .binary => |b| { defer backing.free(b); try testing.expect(b.len > 9); try testing.expectEqual(@backingInt(sendspin.message.BinaryType.audio), b[0]); }, .time, .close => {}, } } } const stream_seeds = [_][]const u8{ // 48 kHz stereo to a FLAC player, an Opus player at 16 kHz mono, and // one at 24-bit PCM with six channels; audio, a clear, more, the end. "\x04\x01\x02" ++ "\x01\x01\x04\x00" ++ "\x02\x00\x01\x00" ++ "\x00\x05\x03\x01" ++ "\x00\x00\x10" ++ times("\x10\x20", 2048) ++ "\x01\x00\x00" ++ "\x80\x00\x08" ++ times("\x7f\xff", 1024) ++ "\x02\x00\x00", // 44.1 kHz mono, resampled for a 48 kHz PCM player, which leaves and // comes back. "\x03\x00\x00" ++ "\x00\x01\x04\x00" ++ "\x00\x00\x04" ++ times("\x00\x40", 1024) ++ "\x03\x02\x00\x00\x01" ++ "\x00\x00\x04" ++ times("\x00\xc0", 1024) ++ "\x03\x02\x00\x00\x00" ++ "\x00\x00\x04" ++ times("\x00\x40", 1024), }; test "fuzz a stream" { for (stream_seeds) |seed| try streamProperty(seed); try testing.fuzz({}, fuzzStream, .{}); } fn fuzzStream(_: void, smith: *Smith) !void { var buffer: [32768]u8 = undefined; try streamProperty(buffer[0..smith.slice(&buffer)]); } // -- the table ----------------------------------------------------------------- /// A target, as `tools/fuzz.zig` drives it. pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating, which stand 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 that, not a truncated /// one, so a generator that does not know it feeds the target nothing. content_max: usize, }; 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 = "messages", .run = Driven(fuzzMessages).run, .corpus = &corpus.messages, .content_max = 4096 }, .{ .name = "sessions", .run = Driven(fuzzSessions).run, .corpus = &corpus.sessions, .content_max = 32768 }, .{ .name = "channel", .run = Driven(fuzzChannel).run, .corpus = &corpus.channels, .content_max = 16384 }, .{ .name = "handshake", .run = Driven(fuzzHandshake).run, .corpus = &corpus.handshakes, .content_max = 2048 }, .{ .name = "pcm", .run = Driven(fuzzPcm).run, .corpus = &corpus.sessions, .content_max = 8192 }, .{ .name = "pairing", .run = Driven(fuzzPairing).run, .corpus = &pairing_seeds, .content_max = 1024 }, .{ .name = "client-messages", .run = Driven(fuzzClientMessages).run, .corpus = &corpus.client_messages, .content_max = 4096 }, .{ .name = "server-handshake", .run = Driven(fuzzServerHandshake).run, .corpus = &corpus.server_handshakes, .content_max = 2048 }, .{ .name = "verifier", .run = Driven(fuzzVerifier).run, .corpus = &verifier_seeds, .content_max = 1024 }, .{ .name = "stream", .run = Driven(fuzzStream).run, .corpus = &stream_seeds, .content_max = 32768 }, };