// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! A Sendspin server that pairs: players connect, and one that offers to //! pair by dynamic PIN is asked to, with the PIN it shows typed in on //! standard input, a line each, as an operator would. //! //! ```console //! $ SENDSPIN_IDENTITY_FILE=server.key SENDSPIN_PAIRINGS=pairings sendspin-pair-server [PORT] //! ``` //! //! The server's key is kept in `SENDSPIN_IDENTITY_FILE`, made the first //! time, so that players see the same server each run; the long-term PSKs //! pairing makes are kept in `SENDSPIN_PAIRINGS`, one line per client, and //! a client paired before connects on its PSK. It streams nothing: it says //! who comes and goes, and whether they are paired. //! //! It advertises itself by mDNS as `_sendspin-server._tcp` -- through Avahi //! if Avahi will, or answering mDNS itself -- and with `SENDSPIN_DISCOVER` //! set, to anything, it finds the players advertising `_sendspin._tcp` and //! dials each, as Music Assistant does. const std = @import("std"); const Io = std.Io; const noise = @import("noise"); const sendspin = @import("sendspin"); const server_mod = @import("sendspin_server"); const discovery = @import("sendspin_discovery"); const Server = server_mod.Server; const Connection = server_mod.Connection; const Listener = server_mod.Listener; pub fn main(init: std.process.Init) !void { const io = init.io; const gpa = init.gpa; var args = try init.minimal.args.iterateAllocator(gpa); defer args.deinit(); _ = args.skip(); const port = if (args.next()) |p| try std.fmt.parseInt(u16, p, 10) else 8927; const identity_path = init.environ_map.get("SENDSPIN_IDENTITY_FILE") orelse { std.debug.print("SENDSPIN_IDENTITY_FILE must name a file to keep the server's key in\n", .{}); return error.Usage; }; const identity = try loadIdentity(io, identity_path); var stdin_buf: [256]u8 = undefined; var stdin = Io.File.stdin().reader(io, &stdin_buf); var operator: Operator = .{ .io = io, .gpa = gpa, .path = init.environ_map.get("SENDSPIN_PAIRINGS") orelse "pairings", .stdin = &stdin.interface, }; var server: Server = undefined; try server.init(io, gpa, .{ .name = "sendspin-pair-server", .identity = identity, .psks = .{ .context = &operator, .lookup = Operator.lookup }, .allow_guests = false, .pairing = .{ .context = &operator, .pin = Operator.pin, .save = Operator.save }, }, .{ .context = &operator, .onJoin = Operator.onJoin, .onLeave = Operator.onLeave }); defer server.deinit(); var listener: Listener = undefined; try listener.init(io, gpa, &server, .{ .address = try .parse("0.0.0.0", port) }); defer listener.deinit(); std.debug.print("listening on {d}, as {s}\n", .{ port, &sendspin.secure.peerId(identity.public) }); // Advertising is a courtesy: a server that cannot be found by mDNS can // still be given its URL. const advertiser = discovery.Advertiser.start(io, gpa, init.minimal.environ, .{ .kind = .server, .instance = "sendspin-pair-server", .name = "sendspin-pair-server", .port = port }) catch |err| blk: { std.debug.print("not advertised: {t}\n", .{err}); break :blk null; }; defer if (advertiser) |a| a.stop(); if (advertiser) |a| std.debug.print("advertised through {t}\n", .{a.backend()}); // Players found, dialed: each connection is the server's like any other. var dialer: discovery.Dialer = .init(io, gpa, .{ .context = &server, .connect = connectPlayer }); defer dialer.deinit(); var finder: ?*discovery.Finder = null; defer if (finder) |f| f.stop(); if (init.environ_map.get("SENDSPIN_DISCOVER") != null) { finder = try discovery.Finder.start(io, gpa, init.minimal.environ, dialer.handler(), .auto); std.debug.print("finding players through {t}\n", .{finder.?.backend()}); } try listener.run(); } fn connectPlayer(context: *anyopaque, address: sendspin.Session.Address) anyerror!void { const server: *Server = @ptrCast(@alignCast(context)); return server.connect(address); } /// The person at the server, and the file of the clients paired with it. const Operator = struct { io: Io, gpa: std.mem.Allocator, path: []const u8, stdin: *Io.Reader, /// One pairing reads standard input at a time. lock: Io.Mutex = .init, line: [64]u8 = undefined, const b64 = std.base64.url_safe_no_pad; fn from(context: *anyopaque) *Operator { return @ptrCast(@alignCast(context)); } fn read(self: *Operator, buf: []u8) []const u8 { return Io.Dir.cwd().readFile(self.io, self.path, buf) catch ""; } fn lookup(context: *anyopaque, client_id: []const u8) ?[32]u8 { const self = from(context); var buf: [16384]u8 = undefined; var lines = std.mem.tokenizeScalar(u8, self.read(&buf), '\n'); while (lines.next()) |line| { var fields = std.mem.tokenizeScalar(u8, line, ' '); const client = fields.next() orelse continue; const encoded = fields.next() orelse continue; if (!std.mem.eql(u8, client, client_id)) continue; var psk: [32]u8 = undefined; b64.Decoder.decode(&psk, encoded) catch continue; return psk; } return null; } fn save(context: *anyopaque, client_id: []const u8, psk: [32]u8) anyerror!void { const self = from(context); var buf: [16384]u8 = undefined; var out: Io.Writer.Allocating = .init(self.gpa); defer out.deinit(); var lines = std.mem.tokenizeScalar(u8, self.read(&buf), '\n'); while (lines.next()) |line| { if (std.mem.startsWith(u8, line, client_id) and line.len > client_id.len and line[client_id.len] == ' ') continue; try out.writer.print("{s}\n", .{line}); } var encoded: [43]u8 = undefined; try out.writer.print("{s} {s}\n", .{ client_id, b64.Encoder.encode(&encoded, &psk) }); try Io.Dir.cwd().writeFile(self.io, .{ .sub_path = self.path, .data = out.written(), .flags = .{ .permissions = .fromMode(0o600) } }); std.debug.print("paired {s}\n", .{client_id}); } /// The next line of standard input. It is not printed: a PIN is a /// secret for as long as the pairing it is for. fn pin(context: *anyopaque, client: *Connection, digits: u8) ?[]const u8 { const self = from(context); self.lock.lockUncancelable(self.io); defer self.lock.unlock(self.io); std.debug.print("pin wanted: {d} digits, shown by {s}\n", .{ digits, client.hello.name }); const line = self.stdin.takeDelimiterInclusive('\n') catch return null; const typed = std.mem.trim(u8, line, " \r\n"); if (typed.len > self.line.len) return null; @memcpy(self.line[0..typed.len], typed); return self.line[0..typed.len]; } fn onJoin(_: *anyopaque, c: *Connection) void { std.debug.print("joined {s} ({s}), {s}\n", .{ c.hello.name, c.client_id, if (c.paired) "paired" else "not paired" }); } fn onLeave(_: *anyopaque, c: *Connection) void { std.debug.print("left {s}\n", .{c.hello.name}); } }; /// The key kept at `path`, as base64url of the secret; made and written the /// first time. fn loadIdentity(io: Io, path: []const u8) !noise.KeyPair { const b64 = std.base64.url_safe_no_pad; var buf: [128]u8 = undefined; if (Io.Dir.cwd().readFile(io, path, &buf)) |text| { var secret: [32]u8 = undefined; try b64.Decoder.decode(&secret, std.mem.trim(u8, text, " \n")); return noise.KeyPair.fromSecret(secret); } else |err| if (err != error.FileNotFound) return err; var source: std.Random.IoSource = .{ .io = io }; const pair = noise.KeyPair.generate(source.interface()); var out: [43]u8 = undefined; _ = b64.Encoder.encode(&out, &pair.secret); try Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = &out, .flags = .{ .permissions = .fromMode(0o600) } }); return pair; }