// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! One WebSocket to a Sendspin server, plaintext or over TLS, and nothing //! about the protocol spoken on it: one this player opened, with `open`, or //! one the server opened to it and something else accepted, with //! `accepted`. //! //! One task reads; any task may write, and the connection holds a write lock //! around every frame, since the reader writes too -- it answers Pings. const Session = @This(); const std = @import("std"); const Io = std.Io; const tls = @import("tls"); const websocket = @import("websocket"); const log = std.log.scoped(.sendspin); /// Where the server is. pub const Address = struct { hostname: []const u8, /// Null for the default: 8095 in plaintext, which is where Music /// Assistant serves its proxy, and 443 over TLS. port: ?u16 = null, secure: bool = false, /// `/sendspin` is Music Assistant's proxy, and a Sendspin server's own /// path as well. resource: []const u8 = "/sendspin", /// The certificates to trust with `secure`. `Client` fills in the /// system's own when this is left null; `open` itself needs it. root_ca: ?tls.config.cert.Bundle = null, pub fn effectivePort(self: Address) u16 { return self.port orelse if (self.secure) 443 else 8095; } /// The `Host` header: the port only when it is not the scheme's own. pub fn authority(self: Address, buf: []u8) ![]const u8 { const port = self.effectivePort(); if (port == @as(u16, if (self.secure) 443 else 80)) return std.fmt.bufPrint(buf, "{s}", .{self.hostname}); return std.fmt.bufPrint(buf, "{s}:{d}", .{ self.hostname, port }); } }; pub const Error = error{ /// `Address.secure` was set but no root certificates were given. NoRootCertificates, }; const tls_input_buffer = tls.input_buffer_len; const tls_output_buffer = tls.output_buffer_len; stream: Io.net.Stream, tcp_reader: Io.net.Stream.Reader, tcp_writer: Io.net.Stream.Writer, tcp_read_buf: [tls_input_buffer]u8, tcp_write_buf: [tls_output_buffer]u8, secure: bool, conn: tls.Connection, tls_reader: tls.Connection.Reader, tls_writer: tls.Connection.Writer, tls_read_buf: [64 << 10]u8, tls_write_buf: [64 << 10]u8, write_mutex: Io.Mutex, random: std.Random.IoSource, ws: websocket.Connection, message_buf: []u8, gpa: std.mem.Allocator, /// Whether the server opened this, and whoever accepted it owns the socket /// and the message buffer; then only the WebSocket is this session's. is_accepted: bool = false, /// Open the connection. `session` must already be where it will stay: the /// readers and writers inside point at its own fields. On success the caller /// must `close` it. pub fn open(io: Io, gpa: std.mem.Allocator, session: *Session, address: Address, max_message: usize) !void { session.gpa = gpa; // Set here, as every field is: `session` is fresh memory, and a flag // left to it says whatever the memory did. session.is_accepted = false; session.secure = address.secure; session.random = .{ .io = io }; const host = try Io.net.HostName.init(address.hostname); session.stream = try host.connect(io, address.effectivePort(), .{ .mode = .stream }); errdefer session.stream.close(io); session.tcp_reader = session.stream.reader(io, &session.tcp_read_buf); session.tcp_writer = session.stream.writer(io, &session.tcp_write_buf); var reader: *Io.Reader = &session.tcp_reader.interface; var writer: *Io.Writer = &session.tcp_writer.interface; if (address.secure) { const root_ca = address.root_ca orelse return error.NoRootCertificates; session.conn = try tls.client(reader, writer, .{ .host = address.hostname, .root_ca = root_ca, .rng = session.random.interface(), .now = .now(io, .real), }); session.tls_reader = session.conn.reader(&session.tls_read_buf); session.tls_writer = session.conn.writer(&session.tls_write_buf); reader = &session.tls_reader.interface; writer = &session.tls_writer.interface; } errdefer if (address.secure) session.conn.close() catch {}; session.write_mutex = .init; session.message_buf = try gpa.alloc(u8, max_message); errdefer gpa.free(session.message_buf); var authority_buf: [300]u8 = undefined; var status: u16 = 0; const result = websocket.connect(reader, writer, .{ .resource = address.resource, .host = try address.authority(&authority_buf), .buffer = session.message_buf, .random = session.random.interface(), .status = &status, .config = .{ .write_lock = .{ .io = io, .mutex = &session.write_mutex } }, }) catch |err| { if (status != 0) log.err("the server answered the WebSocket handshake with HTTP {d}", .{status}); return err; }; session.ws = result.connection; } /// A WebSocket a server opened to this player, already through its opening /// handshake: what `Listener` hands `Client.serve`. Reading and writing go /// through whatever accepted it, which keeps the socket; `close` closes the /// WebSocket, and the socket is the acceptor's to close after. /// /// `session.write_mutex` is left as it is: it should already be initialized /// and be the lock `ws` writes under, as `open` arranges for its own. pub fn accepted(session: *Session, gpa: std.mem.Allocator, ws: websocket.Connection) void { session.secure = false; session.ws = ws; session.message_buf = &.{}; session.gpa = gpa; session.is_accepted = true; } pub fn close(self: *Session, io: Io) void { self.ws.close(.normal, "") catch {}; if (self.is_accepted) return; if (self.secure) self.conn.close() catch {}; self.stream.close(io); self.gpa.free(self.message_buf); } /// Wake a reader blocked in another task by shutting the socket under it. pub fn shutdown(self: *Session, io: Io) void { // An accepted session's socket is its acceptor's, and closing the // WebSocket is as near as this can come: the peer answers the Close, // and the reader sees the connection end. if (self.is_accepted) { self.ws.close(.going_away, "") catch {}; return; } self.stream.shutdown(io, .both) catch {}; } /// The next message, borrowed until the next `receive`; null once the /// connection has closed. pub fn receive(self: *Session) !?websocket.Connection.Message { return self.ws.receive() catch |err| return self.underlying(err); } pub fn sendText(self: *Session, text: []const u8) !void { self.ws.sendText(text) catch |err| return self.underlying(err); } pub fn sendBinary(self: *Session, bytes: []const u8) !void { self.ws.sendBinary(bytes) catch |err| return self.underlying(err); } /// The error a failed read or write really was: a canceled one comes back /// as `ReadFailed` or `WriteFailed` with the cancelation kept in the stream, /// and passed on as that it would look like a dropped connection -- and a /// caller that lets a failed send go would swallow the cancelation with it. fn underlying(self: *Session, err: anyerror) anyerror { if (self.is_accepted) return err; const cause = switch (err) { error.ReadFailed => self.tcp_reader.err, error.WriteFailed => self.tcp_writer.err, else => null, }; return if (cause != null and cause.? == error.Canceled) error.Canceled else err; }