syncspin_client/lib.rs
1//! Client side of Sendspin.
2//!
3//! This crate owns the session: it connects to a server, runs the Noise handshake, keeps a clock
4//! estimate and feeds audio to a sink the host provides. It stays device agnostic - the
5//! application that owns the speakers implements [`Sink`] and decides what playout means.
6//!
7//! A connection always ends in Noise: the client refuses a server that does not complete the
8//! handshake and never falls back to cleartext. A successful attempt reports [`Event::Connected`]
9//! and then one event per change; an attempt that ends reports [`Event::Disconnected`] with the
10//! delay before the next one, and the crate reconnects on its own with the same sink and identity.
11//!
12//! [`connect`] validates the configuration and spawns the connection; the first attempt and every
13//! retry run in that task and reach the caller through the [`EventStream`]. Only an invalid
14//! configuration or an address this build cannot use returns an error - an unreachable server is
15//! reported as [`Event::Disconnected`]. The [`ClientHandle`] waits for the connection to end and
16//! hands out a [`ControlHandle`] for transport commands, seek, the volume level and mute state. The
17//! level follows [`ClientConfig::volume_policy`] - see [`clamp_volume_with`], and [`clamp_volume`]
18//! for the default - and the value the server receives is the applied one. [`ClientConfig::volume`]
19//! and [`ClientConfig::muted`] are the level and mute state the first report carries, so a host
20//! passes the values it restored instead of letting the server see a baseline the output is not at.
21//! [`ControlHandle::report_volume`] is the other direction: a level the host reads from its own
22//! output is recorded and sent unchanged, because the policy limits requests rather than the level
23//! the device is at.
24//!
25//! [`ClientConfig::device_info`] describes the device the client runs on and is announced in
26//! `client/hello`; a host without an answer passes `None` and the server sees only the player name.
27//!
28//! Pairing records and the long-lived pairing PSK belong to the host: it implements
29//! [`storage::Storage`] and the client keeps what it restores, so a paired server is recognised
30//! across restarts. The crate does no file I/O of its own; `storage::FileStorage` is an optional
31//! JSON backend behind the `storage-file` feature for a host that wants one.
32//!
33//! With a store the client offers the Pairing PSK method, the one method the protocol makes
34//! mandatory, and runs it when a server admits an attempt: it draws the long-term PSK, sends
35//! `client/pair-init` and `client/pair-finalize`, and writes the record after `server/pair-finalize`.
36//! [`Event::Paired`] reports the record and [`Event::PairingFailed`] an attempt that ended without
37//! one, always with the reason `pair/abort` carries. Without a store it offers no pairing method at
38//! all: a guest connection is unchanged, and a server that picks pairing anyway is answered with
39//! `pair/abort` reason `method_not_supported`. A pairing attempt is bounded by
40//! [`ClientConfig::pairing_timeout`], [`DEFAULT_PAIRING_TIMEOUT`] by default.
41//!
42//! With the `pairing-code` feature and a code in
43//! `ClientConfig::static_pairing_code`, the client also offers the Static Pairing Code method. Every
44//! attempt is gated by an operator gesture: `ControlHandle::open_pairing_window` opens a window on
45//! the live connection, the client answers a pairing activation with `client/pair-pending` while
46//! none is open, and the fifth failed key confirmation closes the window. The round runs CPace over
47//! X25519 with SHA-512 and delivers the new long-term PSK sealed under its output; that layer has
48//! not had an external review.
49//!
50//! With the same feature and at least one entry in each of `ClientConfig::code_formats` and
51//! `ClientConfig::code_out_channels`, the client offers the Dynamic Pairing Code method instead of
52//! relying on a fixed secret. It draws a nonce per attempt, locks it with `commit_B` in
53//! `client/pair-init`, and derives the per-session code once the server's `nonce_A` arrives: six
54//! digits, or a version-1 pairing token for a QR code. `Event::PairingCode` carries the code and
55//! its round; the code stays the same across the rounds of one attempt. A failed key confirmation
56//! asks the server for another round, and the twentieth failed round ends the attempt. After the
57//! limit the client holds dynamic attempts back - answering them with `client/pair-pending` - until
58//! `ControlHandle::release_holdback` is called, the deliberate operator action the spec requires.
59//!
60//! A pairing record can also be dropped from the server's side. `server/unpair` removes it, reports
61//! [`Event::Unpaired`] and closes the connection after `client/goodbye` with reason `unpaired`; a
62//! server that announces a `psk_id` the client does not hold is reported once per connection as
63//! [`Event::PairingRequired`] with reason [`PairingRequiredReason::CredentialMismatch`], so a host
64//! can offer pairing again instead of the lost record going unnoticed. A deliberate close -
65//! [`ClientHandle::close`] or dropping the handle - sends `client/goodbye` with its reason, so the
66//! server can tell a restart from a shutdown and does not treat the close as a dropped link.
67//!
68//! [`ControlHandle::pairing_token`] hands the operator the version-0 `SP:` token while a store is
69//! configured; it is a credential, so a host renders it only when the operator needs it.
70//!
71//! With the `discovery` feature the client can also take the other half of `connection.md`: instead
72//! of dialling a server it advertises `_sendspin._tcp` and accepts the server that connects.
73//! `Inbound` names the host's [`Discovery`] backend, the address to listen on and the path to
74//! serve; `advertise` publishes the record - the bound port and the `path` and `name` TXT
75//! records - and then serves one server at a time through the same session as a dialled connection.
76//! An upgrade that carries an `Origin` header is refused, as the spec requires, and the Noise
77//! handshake is unchanged because the server initiates it in both directions. A client uses one of
78//! the two methods at a time: while `ClientConfig::inbound` is set, [`connect`] refuses to dial.
79//! A second server that arrives while one is admitted is rejected with `client/goodbye` reason
80//! `concurrent_attempt` and closed, which is the spec's admission rule for a client that caps
81//! itself at one connection. The `mdns` feature carries the `mdns-sd` implementation of
82//! [`Discovery`]; without it the trait is the seam, so a host can supply its own backend and a
83//! fake drives the tests.
84//!
85//! A host that renders the stream sees its lifecycle as events: [`Event::StreamStart`] for a new
86//! format, [`Event::StreamEnd`] when the server pauses or removes the player role, and
87//! [`Event::StreamClear`] for a seek, plus [`Event::Track`] for the now-playing metadata with its
88//! position, duration and playback speed. The end and clear events arrive before the client
89//! discards or flushes the buffered audio, so the host can mute, stop or restart its output first.
90//!
91//! The connection keeps running until the audio sink fails, which the host has to repair, or until
92//! the handle or the event stream is dropped.
93
94mod buffer;
95mod client;
96mod config;
97mod discovery;
98mod pairing;
99mod session;
100mod sink;
101
102pub mod storage;
103
104pub use client::{
105 clamp_volume, clamp_volume_with, connect, connect_with_psks, next_backoff, Client,
106 ClientHandle, ControlHandle, Event, EventStream, GoodbyeReason, PairingFailure,
107 PairingRequiredReason, PlaybackState, StreamEndReason, DEFAULT_PAIRING_TIMEOUT,
108 INITIAL_BACKOFF, NORMAL_PLAYBACK_SPEED,
109};
110pub use config::{
111 AudioMode, ClientConfig, DeviceInfo, PskCategory, StoredPsk, VolumePolicy, DEFAULT_MAX_BACKOFF,
112 MAX_PLAYER_NAME_LEN,
113};
114#[cfg(feature = "pairing-code")]
115pub use config::{
116 CodeFormat, CodeOutChannel, DEFAULT_PAIRING_WINDOW, MAX_PAIRING_PENDING_TEXT_LEN,
117 STATIC_PAIRING_CODE_LEN,
118};
119#[cfg(feature = "mdns")]
120pub use discovery::MdnsDiscovery;
121#[cfg(feature = "discovery")]
122pub use discovery::{advertise, Inbound, DEFAULT_INBOUND_ADDR, DEFAULT_INBOUND_PORT};
123pub use discovery::{
124 discover_reachable_endpoint, discover_servers, DiscoveredServer, Discovery,
125 ServiceAdvertisement, CLIENT_SERVICE_TYPE, DEFAULT_SENDSPIN_PATH, SERVER_SERVICE_TYPE,
126};
127pub use sink::{AudioFormat, AudioFrame, Codec, Sink};
128
129// The identity is part of [`ClientConfig`], so a host that builds a configuration needs it. A
130// re-export keeps a consumer from having to depend on the protocol crate directly.
131pub use syncspin_core::noise::Identity;
132
133/// Returns the version of this crate as recorded in its manifest.
134pub fn version() -> &'static str {
135 env!("CARGO_PKG_VERSION")
136}
137
138#[cfg(test)]
139pub(crate) mod test_support {
140 //! Shared test doubles for the unit tests in this crate.
141
142 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
143 use std::sync::{Mutex, MutexGuard};
144 use std::time::Instant;
145
146 use anyhow::{bail, Result};
147
148 use crate::config::StoredPsk;
149 use crate::sink::{AudioFormat, AudioFrame, Sink};
150 use crate::storage::Storage;
151
152 /// A sink that accepts every call and keeps the trait's default output delay and underrun count.
153 pub(crate) struct NullSink;
154
155 impl Sink for NullSink {
156 fn open(&mut self, _format: AudioFormat) -> anyhow::Result<()> {
157 Ok(())
158 }
159
160 fn write(&mut self, _frame: AudioFrame<'_>, _due: Instant) -> anyhow::Result<()> {
161 Ok(())
162 }
163
164 fn flush(&mut self) -> anyhow::Result<()> {
165 Ok(())
166 }
167 }
168
169 #[test]
170 fn the_test_sink_reports_the_trait_defaults() {
171 let mut sink = NullSink;
172 sink.open(AudioFormat {
173 codec: crate::Codec::Pcm,
174 sample_rate: 48_000,
175 channels: 2,
176 bit_depth: 16,
177 codec_header: None,
178 })
179 .expect("the test sink accepts a format");
180 sink.write(AudioFrame::Pcm(&[1, 2]), Instant::now())
181 .expect("the test sink accepts a frame");
182 sink.flush().expect("the test sink flushes");
183 assert_eq!(
184 sink.output_delay(),
185 None,
186 "a sink that does not report a delay adds none"
187 );
188 assert_eq!(
189 sink.underruns(),
190 0,
191 "a sink that does not count underruns reports none"
192 );
193 }
194
195 /// A [`Storage`] that keeps everything in memory, optionally failing its calls.
196 ///
197 /// The crate's own tests need a store that answers instantly and one that fails a read or a
198 /// write, so a single double carries both. It applies no rule of its own: the record ordering,
199 /// the capacity and the live-record pin belong to [`persist_pairing`](crate::storage::persist_pairing).
200 #[derive(Debug, Default)]
201 pub(crate) struct MemoryStore {
202 pairing: Mutex<Option<[u8; 32]>>,
203 records: Mutex<Vec<StoredPsk>>,
204 read_fails: AtomicBool,
205 write_fails: AtomicBool,
206 stored_pairing_psks: AtomicUsize,
207 }
208
209 impl MemoryStore {
210 /// A store that already holds `pairing`.
211 pub(crate) fn holding(pairing: [u8; 32]) -> MemoryStore {
212 MemoryStore {
213 pairing: Mutex::new(Some(pairing)),
214 ..MemoryStore::default()
215 }
216 }
217
218 /// A store whose reads fail.
219 pub(crate) fn failing_reads() -> MemoryStore {
220 MemoryStore {
221 read_fails: AtomicBool::new(true),
222 ..MemoryStore::default()
223 }
224 }
225
226 /// A store whose writes fail.
227 pub(crate) fn failing_writes() -> MemoryStore {
228 MemoryStore {
229 write_fails: AtomicBool::new(true),
230 ..MemoryStore::default()
231 }
232 }
233
234 /// The pairing PSK the store holds.
235 pub(crate) fn pairing_psk_value(&self) -> Option<[u8; 32]> {
236 *self.pairing.lock().expect("the store lock is not poisoned")
237 }
238
239 /// The records the store holds, oldest first.
240 pub(crate) fn records(&self) -> Vec<StoredPsk> {
241 self.records
242 .lock()
243 .expect("the store lock is not poisoned")
244 .clone()
245 }
246
247 /// How often the client handed back a drawn pairing PSK.
248 pub(crate) fn stored_pairing_psks(&self) -> usize {
249 self.stored_pairing_psks.load(Ordering::SeqCst)
250 }
251
252 /// Puts a record into the store without going through the trait.
253 pub(crate) fn preload(&self, record: StoredPsk) {
254 self.records
255 .lock()
256 .expect("the store lock is not poisoned")
257 .push(record);
258 }
259
260 /// The record list, for a caller that has to hold the lock across a change.
261 fn records_lock(&self) -> MutexGuard<'_, Vec<StoredPsk>> {
262 self.records.lock().expect("the store lock is not poisoned")
263 }
264 }
265
266 impl Storage for MemoryStore {
267 fn pairing_psk(&self) -> Result<Option<[u8; 32]>> {
268 if self.read_fails.load(Ordering::SeqCst) {
269 bail!("the test store was told to fail its reads");
270 }
271 Ok(self.pairing_psk_value())
272 }
273
274 fn store_pairing_psk(&self, psk: &[u8; 32]) -> Result<()> {
275 if self.write_fails.load(Ordering::SeqCst) {
276 bail!("the test store was told to fail its writes");
277 }
278 *self.pairing.lock().expect("the store lock is not poisoned") = Some(*psk);
279 self.stored_pairing_psks.fetch_add(1, Ordering::SeqCst);
280 Ok(())
281 }
282
283 fn load_pairings(&self) -> Result<Vec<StoredPsk>> {
284 if self.read_fails.load(Ordering::SeqCst) {
285 bail!("the test store was told to fail its reads");
286 }
287 Ok(self.records())
288 }
289
290 fn store_pairing(&self, record: StoredPsk) -> Result<()> {
291 if self.write_fails.load(Ordering::SeqCst) {
292 bail!("the test store was told to fail its writes");
293 }
294 let mut records = self.records_lock();
295 records.retain(|held| held.server_id != record.server_id);
296 records.push(record);
297 Ok(())
298 }
299
300 fn remove_pairing(&self, server_id: &str) -> Result<()> {
301 if self.write_fails.load(Ordering::SeqCst) {
302 bail!("the test store was told to fail its writes");
303 }
304 self.records_lock()
305 .retain(|record| record.server_id != server_id);
306 Ok(())
307 }
308 }
309
310 #[test]
311 fn the_test_store_implements_the_storage_surface() {
312 let store = MemoryStore::holding([7u8; 32]);
313 assert_eq!(store.pairing_psk().unwrap(), Some([7u8; 32]));
314 assert_eq!(store.pairing_psk_value(), Some([7u8; 32]));
315 store.store_pairing_psk(&[8u8; 32]).unwrap();
316 assert_eq!(store.pairing_psk().unwrap(), Some([8u8; 32]));
317 assert_eq!(store.stored_pairing_psks(), 1);
318
319 let record = StoredPsk {
320 category: crate::PskCategory::LongTerm,
321 psk: [9u8; 32],
322 server_id: "a-server".to_owned(),
323 };
324 store.store_pairing(record.clone()).unwrap();
325 store.preload(StoredPsk {
326 server_id: "an-older-server".to_owned(),
327 ..record.clone()
328 });
329 assert_eq!(store.records().len(), 2, "the older record stays");
330 store.store_pairing(record.clone()).unwrap();
331 assert_eq!(
332 store.records().len(),
333 2,
334 "a record stored again replaces the one it replaces"
335 );
336 assert_eq!(store.load_pairings().unwrap().len(), 2);
337 store.remove_pairing("a-server").unwrap();
338 assert_eq!(store.load_pairings().unwrap().len(), 1);
339
340 let reads = MemoryStore::failing_reads();
341 assert!(reads.pairing_psk().is_err());
342 assert!(reads.load_pairings().is_err());
343 let writes = MemoryStore::failing_writes();
344 assert!(writes.store_pairing_psk(&[0u8; 32]).is_err());
345 assert!(writes.store_pairing(record).is_err());
346 assert!(writes.remove_pairing("a-server").is_err());
347 }
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353
354 #[test]
355 fn version_is_the_workspace_version() {
356 assert_eq!(version(), "0.4.0");
357 }
358}