// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A Sendspin player's connection to its server, kept up. //! //! `run` is the client's whole life: connect, get through the handshake, //! keep the clocks in step and pass on whatever the server says, until the //! connection ends -- then do it again after a pause that doubles each time //! the server is not there, up to half a minute. It runs until its task is //! canceled, or until the server refuses the token, which it returns. //! //! The handshake, through Music Assistant's proxy: //! //! 1. `{"type": "auth", "token", "client_id"}`, answered by `auth_ok` -- or //! by the connection closing, which is how the proxy refuses a token; //! 2. with an identity, the Noise handshake (see `secure`), after which //! everything is sealed; then `server/hello`, answered by `client/hello`, //! and `server/activate`, which once it grants the player role is //! answered by `client/state`. Without one, `client/hello`, answered by //! `server/hello`, and `client/state` at once; //! 3. `client/time`, and again every so often for as long as the connection //! lasts -- every 200 ms until the clocks agree, every three seconds once //! they agree to within a millisecond. //! //! A Sendspin server reached directly, not through the proxy, starts at the //! second step; leave `Options.token` null for one. //! //! With `Options.pairing`, a sealed connection also offers to pair with a //! dynamic PIN (see `pairing`), and when the server asks, the client runs //! the attempt: shows the PIN, runs CPace on it, hands the server a new //! long-term PSK, and runs the handshake again on it. Later connections to //! that server are on the long-term PSK. //! //! Everything the server says arrives through `Sink`, on `run`'s task. //! `Player` is a sink that plays PCM through a `Scheduler`. //! //! A server may instead connect to the player, which is the other way the //! protocol has of starting: `serve` is one such connection's life, over a //! WebSocket something else accepted -- `Listener` does that. The handshake //! is the same either way, the client speaking first; only who opened the //! socket differs. A client either `run`s or `serve`s, one connection at a //! time. const Client = @This(); const std = @import("std"); const Io = std.Io; const tls = @import("tls"); const noise = @import("noise"); const websocket = @import("websocket"); const message = @import("message.zig"); const pairing = @import("pairing.zig"); const Scheduler = @import("Scheduler.zig"); const secure = @import("secure.zig"); const Session = @import("Session.zig"); const TimeFilter = @import("TimeFilter.zig"); const log = std.log.scoped(.sendspin); pub const Address = Session.Address; pub const Options = struct { address: Address, /// A Music Assistant token, for its proxy. Null for a Sendspin server /// reached directly. token: ?[]const u8 = null, hello: message.Hello, /// The largest message accepted. Audio chunks are the large ones, and /// are a few tens of milliseconds each. max_message: usize = 1 << 20, /// This player's identity: with one, the connection is sealed, as /// aiosendspin 9 and Music Assistant 2.10 expect, and the client's id is /// the key's (`hello.client_id` is not used). Without one it is the /// unencrypted protocol of aiosendspin 4, which Music Assistant 2.10 /// still accepts from "legacy" clients. identity: ?noise.KeyPair = null, /// What a sealed connection's state tells the server of this player's /// timing; see `message.PlayerStatus`. static_delay_ms: u32 = 0, required_lead_time_ms: u32 = 250, min_buffer_ms: u32 = 250, /// Pairing with a dynamic PIN, and the long-term PSKs it makes; only on /// a sealed connection. Without it the player offers no pairing and is /// only ever a guest. pairing: ?Pairing = null, /// Told of every message as it goes by, in either direction, for a /// program that must show what was said in what order -- a conformance /// harness, say. Only which message, never what it said. trace: ?Trace = null, }; pub const Direction = enum { inbound, outbound }; /// One message going by: which way, in what kind of WebSocket frame, whether /// sealed, and what it was. The strings are borrowed until the call returns. pub const TraceEvent = struct { direction: Direction, /// The frame it travelled in: text for the handshake and anything /// unsealed, binary for anything sealed. frame: websocket.Kind, sealed: bool, /// A JSON message's `type`; empty for a binary message. type: []const u8, /// A binary message's type, its first byte: 4 for audio. binary_type: ?u8 = null, /// A binary message's timestamp, on the server's clock, when it has /// one. timestamp_us: ?i64 = null, }; pub const Trace = struct { context: *anyopaque, event: *const fn (context: *anyopaque, event: TraceEvent) void, }; /// What pairing needs of the program: somewhere to keep the long-term /// PSKs, and a way to show a PIN. Called on `run`'s task. pub const Pairing = struct { context: *anyopaque, /// The long-term PSK named `psk_id`, if this player has one for the /// server `server_id`; see `secure.PskLookup`. lookup: *const fn (context: *anyopaque, psk_id: []const u8, server_id: []const u8) ?[32]u8, /// Keep `psk` as the long-term PSK for the server `server_id`, in place /// of any before it, for good: the server keeps it too. save: *const fn (context: *anyopaque, server_id: []const u8, psk: [32]u8) anyerror!void, /// Show `pin` to whoever is at the player, until called with null. show_pin: *const fn (context: *anyopaque, pin: ?[]const u8) void, /// The shortest PIN to accept, 4 to 12 digits; a server asking for a /// shorter one is refused. min_pin_length: u8 = pairing.default_min_pin_digits, }; pub const Error = error{ /// The proxy did not accept the token. AuthFailed, /// The server said something the handshake does not allow. UnexpectedMessage, }; /// What the client passes on, on `run`'s task. Whatever is borrowed is only /// good until the callback returns. pub const Sink = struct { context: *anyopaque, onConnected: *const fn (context: *anyopaque, hello: message.ServerHello) void = ignoreConnected, /// Audio is about to arrive in this format. onStreamStart: *const fn (context: *anyopaque, format: message.StreamStart) void, /// One chunk of encoded audio, to be heard at `timestamp_us` on the /// server's clock. onAudio: *const fn (context: *anyopaque, timestamp_us: i64, data: []const u8) void, /// Drop what is buffered: what comes next is from somewhere else. onStreamClear: *const fn (context: *anyopaque) void, /// There is no more. onStreamEnd: *const fn (context: *anyopaque) void, /// The server has changed the player's volume or mute. onCommand: *const fn (context: *anyopaque, command: message.Command) void = ignoreCommand, /// The clock filter has a new estimate. onClock: *const fn (context: *anyopaque, clock: TimeFilter) void, /// The group the player is in is playing, paused or stopped. onPlayback: *const fn (context: *anyopaque, state: ?message.PlaybackState) void = ignorePlayback, /// The server has activated the connection for something: on a sealed /// connection, what it activated. Nothing is asked of the sink. onActivate: *const fn (context: *anyopaque, activate: message.Activate) void = ignoreActivate, /// For the metadata role: what is playing, all of it, with this /// `server/state`'s changes merged in. A `timestamp` in the future is /// a change scheduled for then, which the specification says to hold /// until then; `Metadata.position` reckons where the track has got to. onMetadata: *const fn (context: *anyopaque, metadata: message.Metadata) void = ignoreMetadata, /// For the controller role: how the group now stands. onController: *const fn (context: *anyopaque, state: message.ControllerState) void = ignoreController, /// For the artwork role: the channels as the server will send them. onArtworkStart: *const fn (context: *anyopaque, channels: []const message.ArtworkChannel) void = ignoreArtworkStart, /// For the artwork role: an image for `channel`, to be shown at /// `timestamp_us` on the server's clock; an empty one clears it. onArtwork: *const fn (context: *anyopaque, channel: u2, timestamp_us: i64, image: []const u8) void = ignoreArtwork, /// For the artwork role: the images are over, and what was shown goes. onArtworkEnd: *const fn (context: *anyopaque) void = ignoreArtworkEnd, onDisconnected: *const fn (context: *anyopaque, reason: anyerror) void = ignoreDisconnected, fn ignoreConnected(_: *anyopaque, _: message.ServerHello) void {} fn ignoreCommand(_: *anyopaque, _: message.Command) void {} fn ignorePlayback(_: *anyopaque, _: ?message.PlaybackState) void {} fn ignoreActivate(_: *anyopaque, _: message.Activate) void {} fn ignoreMetadata(_: *anyopaque, _: message.Metadata) void {} fn ignoreController(_: *anyopaque, _: message.ControllerState) void {} fn ignoreArtworkStart(_: *anyopaque, _: []const message.ArtworkChannel) void {} fn ignoreArtwork(_: *anyopaque, _: u2, _: i64, _: []const u8) void {} fn ignoreArtworkEnd(_: *anyopaque) void {} fn ignoreDisconnected(_: *anyopaque, _: anyerror) void {} }; const backoff_min: Io.Duration = .fromSeconds(1); const backoff_max: Io.Duration = .fromSeconds(30); const backoff_reset: Io.Duration = .fromSeconds(60); io: Io, gpa: std.mem.Allocator, options: Options, sink: Sink, /// Held shared while sending and exclusively while the session is taken /// away, so that nothing writes to a session being freed. session_lock: Io.RwLock = .init, session: ?*Session = null, /// What `client/state` says: the volume, 0 to 100, and mute. volume: std.atomic.Value(u8) = .init(100), muted: std.atomic.Value(bool) = .init(false), /// Set when a server refused the sealed handshake -- closed the connection, /// or answered with anything but `server/init`, as an aiosendspin older than /// 9 does -- so that the next attempt, made at once, speaks the unsealed /// protocol. It lasts one attempt: each reconnection tries sealing first /// again, so a server upgraded meanwhile is met the way it now expects. /// Only the task running `run` touches it. unsealed_next: bool = false, /// Whether the connection being opened is one a server dialed, through /// `serve`, rather than one `run` dialed: then there is no proxy, and no /// token to give it. dialed: bool = false, /// The sealed channel, on a connection that has one; set before the session /// is published and taken down after it is withdrawn. channel: ?secure.Channel = null, /// The system's certificates, read the first time a connection needs them /// -- one with `secure` and no `root_ca` of its own -- and kept until `run` /// returns. system_ca: ?tls.config.cert.Bundle = null, /// Held while a message is sealed and sent, so that frames leave in the /// order of their nonces. send_mutex: Io.Mutex = .init, /// Held while `options.hello` is read for a handshake or changed by /// `setFormats`. hello_mutex: Io.Mutex = .init, /// Whether the server has activated the player role, on a sealed /// connection; the full state is sent once it has. player_active: std.atomic.Value(bool) = .init(false), /// Whether the server has activated the connection at all yet. Nothing but /// the handshake and pairing may pass before it does, so the clock waits. activated: std.atomic.Value(bool) = .init(false), /// The sealed connection's handshake hash, its server, and which PSK it is /// on: what pairing binds to and runs the next handshake from. Only `run`'s /// task touches them. handshake_hash: [32]u8 = undefined, server_id: secure.PeerId = undefined, category: secure.Category = .sentinel, /// Pairing attempts on this connection, counted from one. pairing_index: u32 = 0, /// Wrong PINs in a row; see `pairing.pin_escalation_threshold`. Not kept /// across runs of the program. pin_failures: u32 = 0, /// Set while a pairing attempt runs, when nothing else may be sent: the /// server fails an attempt on any message that is not pairing's. pairing_now: std.atomic.Value(bool) = .init(false), /// Whether the connection up now is sealed, which decides what its state /// looks like and when it is sent. Not whether there is an identity: a /// client with one falls back to the unsealed protocol when a server /// refuses sealing, and that connection's state is the unsealed kind, sent /// at once. sealed: std.atomic.Value(bool) = .init(false), /// What is playing, as merged from every `server/state` of this /// connection, and the two arenas it lives in by turns: each merge copies /// it into the other, and the one before goes. Only `run`'s task touches /// them. metadata: message.Metadata = .{}, metadata_arenas: ?*[2]std.heap.ArenaAllocator = null, metadata_arena: u1 = 0, /// Only ever changed on `run`'s task. clock: TimeFilter = .init(), /// How long the time task waits between exchanges, from the clock filter. sync_interval_ms: std.atomic.Value(u32) = .init(200), /// `options` is borrowed and must outlive the client. pub fn init(io: Io, gpa: std.mem.Allocator, options: Options, sink: Sink) Client { return .{ .io = io, .gpa = gpa, .options = options, .sink = sink }; } /// Stay connected until canceled, or until the token is refused. pub fn run(self: *Client) !void { defer if (self.system_ca) |*b| { b.deinit(self.gpa); self.system_ca = null; }; var backoff = backoff_min; while (true) { const started: Io.Clock.Timestamp = .now(self.io, .awake); const err = if (self.runOnce()) |_| error.ConnectionClosed else |e| e; switch (err) { error.Canceled => return error.Canceled, error.AuthFailed, error.NoRootCertificates => { self.sink.onDisconnected(self.sink.context, err); return err; }, // Not a disconnection: the server speaks the older protocol, and // the next attempt, straight away, speaks it too. error.SealingRefused => { log.info("the Sendspin server does not seal connections; speaking the unsealed protocol", .{}); continue; }, else => { log.info("disconnected from the Sendspin server: {t}", .{err}); self.sink.onDisconnected(self.sink.context, err); }, } const lasted = started.durationTo(.now(self.io, .awake)); if (lasted.raw.nanoseconds >= backoff_reset.nanoseconds) backoff = backoff_min; try self.io.sleep(backoff, .awake); backoff = .fromNanoseconds(@min(backoff.nanoseconds * 2, backoff_max.nanoseconds)); } } /// Where to connect, with the system's certificates where TLS is wanted and /// none were given. fn address(self: *Client) !Session.Address { var a = self.options.address; if (!a.secure or a.root_ca != null) return a; if (self.system_ca == null) { self.system_ca = tls.config.cert.fromSystem(self.gpa, self.io) catch |err| { log.err("could not read the system's certificates: {t}", .{err}); return error.NoRootCertificates; }; } a.root_ca = self.system_ca; return a; } fn runOnce(self: *Client) !void { const session = try self.gpa.create(Session); defer self.gpa.destroy(session); try Session.open(self.io, self.gpa, session, try self.address(), self.options.max_message); return self.runSession(session); } /// One connection a server opened to this player, from the handshake to /// its end: sealed with an identity, unsealed without one, and with no /// token, since there is no proxy in the way. `session` is an accepted one /// (see `Session.accepted`), and closed on return. Returns when the /// connection ends, as `error.ConnectionClosed` if it ended cleanly. /// /// Not while `run` is running: a client has one connection at a time. pub fn serve(self: *Client, session: *Session) !void { self.unsealed_next = false; self.dialed = true; defer self.dialed = false; const err = if (self.runSession(session)) |_| error.ConnectionClosed else |e| e; if (err != error.Canceled) self.sink.onDisconnected(self.sink.context, err); return err; } /// Everything about a connection but opening it: the handshake, then the /// clock and the server's messages until it ends. Closes `session`. fn runSession(self: *Client, session: *Session) !void { var arena: std.heap.ArenaAllocator = .init(self.gpa); defer arena.deinit(); var metadata_arenas: [2]std.heap.ArenaAllocator = .{ .init(self.gpa), .init(self.gpa) }; defer for (&metadata_arenas) |*a| a.deinit(); self.metadata = .{}; self.metadata_arenas = &metadata_arenas; defer self.metadata_arenas = null; self.handshake(session, &arena) catch |err| { session.close(self.io); return err; }; self.clock.reset(); self.sync_interval_ms.store(200, .monotonic); self.session_lock.lockUncancelable(self.io); self.session = session; self.sealed.store(self.channel != null, .monotonic); self.session_lock.unlock(self.io); defer { self.session_lock.lockUncancelable(self.io); self.session = null; if (self.channel) |*ch| ch.deinit(); self.channel = null; self.player_active.store(false, .monotonic); self.activated.store(false, .monotonic); self.sealed.store(false, .monotonic); self.session_lock.unlock(self.io); session.close(self.io); } // A sealed connection's state waits for the server to activate the // player role; an unencrypted one's goes now, and as it has no // activation, so may the clock. if (self.channel == null) { self.activated.store(true, .monotonic); try self.sendState(); } var timer = try self.io.concurrent(timeLoop, .{self}); defer timer.cancel(self.io) catch {}; self.readLoop(session, &arena) catch |err| { if (err == error.Canceled) self.goodbye(.shutdown); return err; }; } fn handshake(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator) !void { var buf: Io.Writer.Allocating = .init(self.gpa); defer buf.deinit(); // Sealed if there is an identity, unless the last attempt found the // server does not seal. const unsealed = self.unsealed_next; self.unsealed_next = false; const identity: ?noise.KeyPair = if (unsealed) null else self.options.identity; // The client's id: the key's, on a sealed connection; the hello's on an // unsealed one, as the proxy and the server must agree on it. const id: ?secure.PeerId = if (identity) |i| secure.peerId(i.public) else null; if (if (self.dialed) null else self.options.token) |token| { try message.writeAuth(&buf.writer, token, if (id) |*i| i else self.options.hello.client_id); self.traceText(.outbound, .text, false, buf.written()); try session.sendText(buf.written()); buf.clearRetainingCapacity(); // The proxy refuses a token by closing the connection. const answer = (session.receive() catch return error.AuthFailed) orelse return error.AuthFailed; if (answer.kind != .text) return error.UnexpectedMessage; self.traceText(.inbound, .text, false, answer.data); const v = try std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), answer.data, .{}); if (try message.classify(arena.allocator(), v) != .auth_ok) return error.AuthFailed; } if (identity) |i| return self.sealedHandshake(session, arena, i); { self.hello_mutex.lockUncancelable(self.io); defer self.hello_mutex.unlock(self.io); try message.writeHello(&buf.writer, self.options.hello, .legacy); } self.traceText(.outbound, .text, false, buf.written()); try session.sendText(buf.written()); // The server may say other things before its hello; they are of no use // before it. while (try session.receive()) |m| { self.traceOpened(m.kind, false, switch (m.kind) { .text => .{ .text = m.data }, .binary => .{ .binary = m.data }, }); if (m.kind != .text) continue; _ = arena.reset(.retain_capacity); const v = std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), m.data, .{}) catch continue; switch (try message.classify(arena.allocator(), v)) { .hello => |hello| { log.info("connected to Sendspin server {s}", .{hello.name}); self.sink.onConnected(self.sink.context, hello); return; }, else => {}, } } return error.UnexpectedMessage; } /// The Noise handshake, then the hellos over the sealed channel. fn sealedHandshake(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator, identity: noise.KeyPair) !void { var source: std.Random.IoSource = .{ .io = self.io }; var hs: secure.ClientHandshake = .init(self.gpa, identity, source.interface()); defer hs.deinit(); hs.psks = self.pskLookup(); const init_text = try hs.begin(); self.traceText(.outbound, .text, false, init_text); try session.sendText(init_text); // An older server does not know `client/init`: it closes the connection, // or says something else. Then this is no sealed server, and the next // attempt is made without sealing. const server_init = self.receiveText(session) catch |err| return self.sealingRefused(err); hs.serverInit(server_init) catch |err| return self.sealingRefused(err); const reply = try hs.message1(try self.receiveText(session)); defer self.gpa.free(reply); self.traceText(.outbound, .text, false, reply); try session.sendText(reply); self.channel = try secure.Channel.init(self.gpa, try hs.transport()); errdefer { self.channel.?.deinit(); self.channel = null; } self.handshake_hash = hs.handshakeHash(); self.server_id = hs.server_id; self.category = hs.category; self.pairing_index = 0; try self.exchangeHellos(session, arena); } /// The long-term PSKs, as the handshake looks them up. fn pskLookup(self: *Client) ?secure.PskLookup { const p = self.options.pairing orelse return null; return .{ .context = p.context, .lookup = p.lookup }; } /// `server/hello`, then ours; `server/activate` follows, in the read loop /// or in pairing's. fn exchangeHellos(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator) !void { while (try self.receiveSealed(session)) |opened| { const text = switch (opened) { .text => |t| t, .binary => continue, }; _ = arena.reset(.retain_capacity); const v = std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), text, .{}) catch continue; switch (try message.classify(arena.allocator(), v)) { .hello => |h| { var hello = h; hello.server_id = &self.server_id; hello.paired = self.category == .long_term; log.info("connected to Sendspin server {s}, encrypted{s}", .{ hello.name, if (hello.paired) ", paired" else "" }); self.sink.onConnected(self.sink.context, hello); var buf: Io.Writer.Allocating = .init(self.gpa); defer buf.deinit(); { self.hello_mutex.lockUncancelable(self.io); defer self.hello_mutex.unlock(self.io); try message.writeHello(&buf.writer, self.options.hello, .{ .encrypted = .{ .dynamic_pin = if (self.options.pairing) |p| p.min_pin_length else null, .paired = hello.paired, } }); } try self.sendOn(session, buf.written()); return; }, else => {}, } } return error.UnexpectedMessage; } fn sealingRefused(self: *Client, err: anyerror) error{SealingRefused} { log.debug("no server/init in answer to client/init: {t}", .{err}); self.unsealed_next = true; return error.SealingRefused; } /// The next text frame, before the channel is sealed. fn receiveText(self: *Client, session: *Session) ![]const u8 { const m = (try session.receive()) orelse return error.ConnectionClosed; if (m.kind != .text) return error.UnexpectedMessage; self.traceText(.inbound, .text, false, m.data); return m.data; } /// The next message on the sealed channel, borrowed until the next; null /// once the connection has closed. fn receiveSealed(self: *Client, session: *Session) !?secure.Opened { while (try session.receive()) |m| { if (m.kind != .binary) return error.UnexpectedMessage; if (try self.channel.?.open(m.data)) |opened| { self.traceOpened(.binary, true, opened); return opened; } } return null; } fn readLoop(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator) !void { while (try session.receive()) |m| { // Taken before anything else, since it is one of the four times a // clock exchange is measured by. const received = Scheduler.now(); const opened: secure.Opened = if (self.channel) |*ch| blk: { if (m.kind != .binary) return error.UnexpectedMessage; break :blk (try ch.open(m.data)) orelse continue; } else switch (m.kind) { .binary => .{ .binary = m.data }, .text => .{ .text = m.data }, }; self.traceOpened(m.kind, self.channel != null, opened); switch (opened) { .binary => |data| { const b = message.parseBinary(data) catch continue; if (b.type == .audio) { self.sink.onAudio(self.sink.context, b.timestamp_us, b.data); } else if (b.type.artworkChannel()) |channel| { // A whole image a message, as aiosendspin sends it. self.sink.onArtwork(self.sink.context, channel, b.timestamp_us, b.data); } }, .text => |text| { _ = arena.reset(.retain_capacity); const a = arena.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}) catch |err| { log.warn("could not parse a message: {t}", .{err}); continue; }; const incoming = message.classify(a, v) catch |err| { log.warn("could not understand a message: {t}", .{err}); continue; }; if (incoming == .activate and incoming.activate.pairing != null and self.channel != null) { // Pairing takes the connection over until the server // activates it for something else, which is dispatched // as any activation is. _ = self.onActivated(incoming.activate); const after = try self.pair(session, arena, incoming.activate); try self.dispatch(.{ .activate = after }, received); continue; } try self.dispatch(incoming, received); }, } } } /// Fails only when canceled: a state that could not be sent is not worth /// ending the connection over, but a cancelation is not a failure to send, /// and swallowed it would leave the task reading on as if it never came. fn dispatch(self: *Client, incoming: message.Incoming, received: i64) error{Canceled}!void { const s = self.sink; switch (incoming) { .time => |t| { self.clock.exchange(t.client_transmitted, t.server_received, t.server_transmitted, received); self.sync_interval_ms.store(self.clock.nextIntervalMs(), .monotonic); s.onClock(s.context, self.clock); }, .stream_start => |starts| { if (starts.player) |f| s.onStreamStart(s.context, f); if (starts.artwork) |channels| s.onArtworkStart(s.context, channels); }, .stream_clear => |roles| if (roles.player) s.onStreamClear(s.context), .stream_end => |roles| { if (roles.player) s.onStreamEnd(s.context); if (roles.artwork) s.onArtworkEnd(s.context); }, .state => |state| { switch (state.metadata) { .absent => {}, .clear => { self.metadata = .{}; s.onMetadata(s.context, self.metadata); }, .update => |update| self.mergeMetadata(update), } if (state.controller) |c| s.onController(s.context, c); }, .command => |c| { switch (c) { .volume => |v| self.volume.store(v, .monotonic), .mute => |m| self.muted.store(m, .monotonic), } s.onCommand(s.context, c); // The server wants to hear that it took. try self.sendStateNow(); }, .group => |g| s.onPlayback(s.context, g), .activate => |act| if (!self.options.hello.roles.player) { // Without the player, the state to send is only that the client // is there, once. if (self.onActivatedFirst(act)) try self.sendStateNow(); } else if (self.onActivated(act)) |active| { // Once the player role is granted -- which for a guest is after // the server approves it, a moment after the first activation -- // the server wants the player's full state. const was = self.player_active.swap(active, .monotonic); if (active and !was) { log.info("the server activated the player", .{}); try self.sendStateNow(); } }, .auth_ok, .hello, .other => {}, } } /// Merge a `server/state` metadata object into what is known, and tell the /// sink. fn mergeMetadata(self: *Client, update: std.json.ObjectMap) void { const arenas = self.metadata_arenas orelse return; const next = self.metadata_arena +% 1; _ = arenas[next].reset(.retain_capacity); self.metadata = self.metadata.merge(arenas[next].allocator(), update) catch |err| { log.warn("could not take the server's metadata: {t}", .{err}); return; }; self.metadata_arena = next; self.sink.onMetadata(self.sink.context, self.metadata); } /// Note an activation, tell the sink, and return whether it was the first. fn onActivatedFirst(self: *Client, act: message.Activate) bool { const first = !self.activated.swap(true, .monotonic); self.sink.onActivate(self.sink.context, act); if (first) self.sync_interval_ms.store(200, .monotonic); return first; } /// Note an activation, tell the sink, and return whether it says the /// player is active, if it says. fn onActivated(self: *Client, act: message.Activate) ?bool { const first = !self.activated.swap(true, .monotonic); self.sink.onActivate(self.sink.context, act); // The clock has waited for this; it need not wait out its interval too. if (first) self.sync_interval_ms.store(200, .monotonic); return act.player; } /// Exchange clock readings with the server, as often as the filter wants. fn timeLoop(self: *Client) !void { var buf: [128]u8 = undefined; while (true) { var w: Io.Writer = .fixed(&buf); try message.writeTime(&w, Scheduler.now()); if (!self.pairing_now.load(.monotonic) and self.activated.load(.monotonic)) try self.send(w.buffered()); try self.io.sleep(.fromMilliseconds(self.sync_interval_ms.load(.monotonic)), .awake); } } /// Send a text message, if connected. Safe from any task. pub fn send(self: *Client, text: []const u8) !void { try self.session_lock.lockShared(self.io); defer self.session_lock.unlockShared(self.io); const session = self.session orelse return; try self.sendOn(session, text); } /// Command the group, as a controller: one of the commands the last /// `ControllerState` listed, or the server ignores it. Safe from any task. pub fn command(self: *Client, c: message.ControllerCommand) !void { var buf: [160]u8 = undefined; var w: Io.Writer = .fixed(&buf); try message.writeCommand(&w, c); try self.send(w.buffered()); } /// Ask the server for a different stream format, mid-stream; it answers /// with a new `stream/start`, through the sink. The format must be one the /// hello offered. Safe from any task. pub fn requestFormat(self: *Client, request: message.FormatRequest) !void { var buf: [192]u8 = undefined; var w: Io.Writer = .fixed(&buf); try message.writeRequestFormat(&w, request); try self.send(w.buffered()); } /// Tell the trace, if there is one, of a text message going by. fn traceText(self: *Client, direction: Direction, frame: websocket.Kind, sealed: bool, text: []const u8) void { const t = self.options.trace orelse return; t.event(t.context, .{ .direction = direction, .frame = frame, .sealed = sealed, .type = message.typeOf(text) orelse "", }); } /// Tell the trace of an opened message, sealed or not, arriving. fn traceOpened(self: *Client, frame: websocket.Kind, sealed: bool, opened: secure.Opened) void { const t = self.options.trace orelse return; switch (opened) { .text => |text| self.traceText(.inbound, frame, sealed, text), .binary => |data| t.event(t.context, .{ .direction = .inbound, .frame = frame, .sealed = sealed, .type = "", .binary_type = if (data.len > 0) data[0] else null, .timestamp_us = if (message.parseBinary(data)) |b| b.timestamp_us else |_| null, }), } } /// Send a text message on `session`: sealed, on a sealed connection. fn sendOn(self: *Client, session: *Session, text: []const u8) !void { self.traceText(.outbound, if (self.channel == null) .text else .binary, self.channel != null, text); const ch = &(self.channel orelse return session.sendText(text)); self.send_mutex.lockUncancelable(self.io); defer self.send_mutex.unlock(self.io); const Frames = struct { session: *Session, pub fn frame(sink: @This(), bytes: []const u8) !void { try sink.session.sendBinary(bytes); } }; try ch.sealText(text, Frames{ .session = session }); } /// Offer `formats` instead, and connect again to offer them: for a player /// whose device has changed rate, say. A server only learns what a player /// can play from its hello, and only asks for one of those, so a change is /// a new connection -- the server is told the player is restarting, and the /// client connects again as it would after any disconnection, with the /// sink told of both. `formats` is borrowed, as `options.hello.formats` is. /// Safe from any task. pub fn setFormats(self: *Client, formats: []const message.Format) !void { { try self.hello_mutex.lock(self.io); defer self.hello_mutex.unlock(self.io); self.options.hello.formats = formats; } try self.session_lock.lockShared(self.io); defer self.session_lock.unlockShared(self.io); const session = self.session orelse return; var buf: [96]u8 = undefined; var w: Io.Writer = .fixed(&buf); message.writeGoodbye(&w, .restart) catch {}; self.sendOn(session, w.buffered()) catch {}; session.shutdown(self.io); } /// `sendState` from the read loop: any failure but cancelation is let go. fn sendStateNow(self: *Client) error{Canceled}!void { self.sendState() catch |err| if (err == error.Canceled) return error.Canceled; } /// Change what the server is told of the player's volume and mute, and tell /// it. Safe from any task. pub fn setState(self: *Client, volume: u8, muted: bool) !void { self.volume.store(@min(volume, 100), .monotonic); self.muted.store(muted, .monotonic); try self.sendState(); } fn sendState(self: *Client) !void { // Nothing but pairing's messages while an attempt runs; the full state // goes when the connection is activated again after it. if (self.pairing_now.load(.monotonic)) return; var buf: [256]u8 = undefined; var w: Io.Writer = .fixed(&buf); if (!self.options.hello.roles.player) { // Not before the server has activated the connection, on a sealed // one: before that there is nobody to be available to. if (self.sealed.load(.monotonic) and !self.activated.load(.monotonic)) return; try message.writeAvailable(&w, true); } else if (!self.sealed.load(.monotonic)) { try message.writeState(&w, .synchronized, self.volume.load(.monotonic), self.muted.load(.monotonic)); } else { // Not until the server has activated the player: before that it has // no player to give the state to. if (!self.player_active.load(.monotonic)) return; try message.writeStatus(&w, .{ .volume = self.volume.load(.monotonic), .muted = self.muted.load(.monotonic), .static_delay_ms = self.options.static_delay_ms, .required_lead_time_ms = self.options.required_lead_time_ms, .min_buffer_ms = self.options.min_buffer_ms, }); } try self.send(w.buffered()); } // --- pairing ----------------------------------------------------------------- /// What pairing reads next: a pairing message, or the `server/activate` that /// ends an attempt or pairing altogether. const PairingRead = union(enum) { pairing: pairing.Incoming, activate: message.Activate, }; /// Pair for as long as the server keeps asking, and return the activation /// it ends with. The connection belongs to pairing meanwhile: no clock /// exchanges, no state, and anything the server sends that is neither /// pairing nor an activation is dropped. fn pair(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator, first: message.Activate) !message.Activate { self.pairing_now.store(true, .monotonic); defer self.pairing_now.store(false, .monotonic); var activate = first; while (activate.pairing) |request| { activate = switch (try self.attempt(session, arena, request)) { .left => |a| a, // The server follows an abort, whoever sent it, with the // activation that says whether it will try again. .aborted => try self.awaitActivate(session, arena), .finalized => blk: { try self.rehandshake(session); try self.exchangeHellos(session, arena); break :blk try self.awaitActivate(session, arena); }, }; } return activate; } const Outcome = union(enum) { /// The server has the new PSK, and runs the handshake again on it. finalized, /// The attempt was abandoned, by either side, and the connection stays. aborted, /// The server ended pairing mid-attempt, with this activation. left: message.Activate, }; /// One attempt, as the server asked for it. fn attempt(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator, request: message.Activate.Pairing) !Outcome { self.pairing_index += 1; const index = self.pairing_index; const p = self.options.pairing orelse return self.abort(session, .method_not_supported); if (request.method != .dynamic_pin) return self.abort(session, .method_not_supported); const digits = request.pin_length orelse return self.abort(session, .pin_length_unacceptable); if (digits < p.min_pin_length or digits > pairing.max_pin_digits) return self.abort(session, .pin_length_unacceptable); var out: Io.Writer.Allocating = .init(self.gpa); defer out.deinit(); // Past the escalation threshold, dynamic PIN needs a gesture on the // player to go on. This one has no way to make one, so it says it is // waiting for one, and waits for the server to give up. if (self.pin_failures >= pairing.pin_escalation_threshold) { log.warn("{d} wrong PINs in a row: not pairing again until the program restarts", .{self.pin_failures}); try pairing.writePending(&out.writer, index); try self.sendOn(session, out.written()); while (true) switch (try self.readPairing(session, arena)) { .pairing => |m| if (m == .abort) return self.remoteAbort(m.abort), .activate => |a| return .{ .left = a }, }; } var source: std.Random.IoSource = .{ .io = self.io }; const random = source.interface(); var dp = try pairing.DynamicPin.start(random, &self.handshake_hash, index, @intCast(digits), &out.writer); try self.sendOn(session, out.written()); var shown = false; defer if (shown) p.show_pin(p.context, null); while (true) { const m = switch (try self.readPairing(session, arena)) { .pairing => |m| m, .activate => |a| return .{ .left = a }, }; out.clearRetainingCapacity(); switch (m) { .abort => |reason| return self.remoteAbort(reason), .init => |nonce_a| { const pin = try dp.onInit(random, nonce_a); // The PIN itself is only ever shown, never logged. log.info("pairing: showing the PIN", .{}); p.show_pin(p.context, pin); shown = true; }, .auth => |share| { try dp.onAuth(share, &out.writer); try self.sendOn(session, out.written()); }, .confirm => |tag| { if (!try dp.onConfirm(tag, &out.writer)) { self.pin_failures += 1; log.info("pairing: the server did not have the PIN", .{}); return self.abort(session, .pin_mismatch); } self.pin_failures = 0; try self.sendOn(session, out.written()); out.clearRetainingCapacity(); try dp.finalize(random, &out.writer); try self.sendOn(session, out.written()); }, .finalize => { const psk = try dp.onFinalize(); try p.save(p.context, &self.server_id, psk); log.info("paired with the Sendspin server", .{}); return .finalized; }, } } } /// Abandon the attempt with `reason`, telling the server. fn abort(self: *Client, session: *Session, reason: pairing.AbortReason) !Outcome { log.info("pairing: abandoned, {t}", .{reason}); var buf: [96]u8 = undefined; var w: Io.Writer = .fixed(&buf); try pairing.writeAbort(&w, reason); try self.sendOn(session, w.buffered()); return .aborted; } /// The server abandoned the attempt. After some reasons it closes the /// connection; after the rest another attempt may follow. fn remoteAbort(_: *Client, reason: ?pairing.AbortReason) !Outcome { log.info("pairing: the server abandoned it, {?t}", .{reason}); if (reason) |r| if (r.closes()) return error.PairingAborted; return .aborted; } /// The next pairing message or activation. A pairing message that does not /// parse fails the attempt, and with it the connection, as aiosendspin's /// client does. fn readPairing(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator) !PairingRead { while (try self.receiveSealed(session)) |opened| { const text = switch (opened) { .text => |t| t, .binary => continue, }; _ = arena.reset(.retain_capacity); const a = arena.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, a, text, .{}) catch continue; if (try pairing.parse(a, v)) |m| return .{ .pairing = m }; switch (message.classify(a, v) catch continue) { .activate => |act| return .{ .activate = act }, else => {}, } } return error.ConnectionClosed; } /// The next activation, anything before it dropped. fn awaitActivate(self: *Client, session: *Session, arena: *std.heap.ArenaAllocator) !message.Activate { while (true) switch (try self.readPairing(session, arena)) { .activate => |a| return a, .pairing => {}, }; } /// The handshake again, on the long-term PSK pairing has just made, inside /// the sealed channel: message 1 arrives sealed, and the reply goes out /// sealed under the old keys before the channel turns to the new. fn rehandshake(self: *Client, session: *Session) !void { const identity = self.options.identity orelse return error.UnexpectedMessage; var source: std.Random.IoSource = .{ .io = self.io }; var hs = try secure.ClientHandshake.initRehandshake(self.gpa, identity, source.interface(), self.server_id, &self.handshake_hash, self.pskLookup()); defer hs.deinit(); const text = while (try self.receiveSealed(session)) |opened| switch (opened) { .text => |t| break t, .binary => {}, } else return error.ConnectionClosed; const reply = try hs.message1(text); defer self.gpa.free(reply); self.traceText(.outbound, .binary, true, reply); self.send_mutex.lockUncancelable(self.io); defer self.send_mutex.unlock(self.io); const Frames = struct { session: *Session, pub fn frame(sink: @This(), bytes: []const u8) !void { try sink.session.sendBinary(bytes); } }; try self.channel.?.sealText(reply, Frames{ .session = session }); self.channel.?.transport = try hs.transport(); self.handshake_hash = hs.handshakeHash(); self.category = hs.category; self.pairing_index = 0; } fn goodbye(self: *Client, reason: message.GoodbyeReason) void { var buf: [96]u8 = undefined; var w: Io.Writer = .fixed(&buf); message.writeGoodbye(&w, reason) catch return; const session = self.session orelse return; self.sendOn(session, w.buffered()) catch {}; }