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 playout;
100mod session;
101mod sink;
102
103pub mod storage;
104
105pub use client::{
106 clamp_volume, clamp_volume_with, connect, connect_with_psks, next_backoff, Client,
107 ClientHandle, ControlHandle, Event, EventStream, GoodbyeReason, PairingFailure,
108 PairingRequiredReason, PlaybackState, StreamEndReason, DEFAULT_PAIRING_TIMEOUT,
109 INITIAL_BACKOFF, NORMAL_PLAYBACK_SPEED,
110};
111pub use config::{
112 AudioMode, ClientConfig, DeviceInfo, PskCategory, StoredPsk, VolumePolicy, DEFAULT_MAX_BACKOFF,
113 MAX_PLAYER_NAME_LEN,
114};
115#[cfg(feature = "pairing-code")]
116pub use config::{
117 CodeFormat, CodeOutChannel, DEFAULT_PAIRING_WINDOW, MAX_PAIRING_PENDING_TEXT_LEN,
118 STATIC_PAIRING_CODE_LEN,
119};
120#[cfg(feature = "mdns")]
121pub use discovery::MdnsDiscovery;
122#[cfg(feature = "discovery")]
123pub use discovery::{advertise, Inbound, DEFAULT_INBOUND_ADDR, DEFAULT_INBOUND_PORT};
124pub use discovery::{
125 discover_reachable_endpoint, discover_servers, reachable_endpoint, DiscoveredServer, Discovery,
126 ServiceAdvertisement, CLIENT_SERVICE_TYPE, DEFAULT_SENDSPIN_PATH, SERVER_SERVICE_TYPE,
127};
128pub use sink::{AudioFormat, AudioFrame, Codec, Sink};
129
130// The identity is part of [`ClientConfig`], so a host that builds a configuration needs it. A
131// re-export keeps a consumer from having to depend on the protocol crate directly.
132pub use syncspin_core::noise::Identity;
133
134/// Returns the version of this crate as recorded in its manifest.
135pub fn version() -> &'static str {
136 env!("CARGO_PKG_VERSION")
137}
138
139#[cfg(test)]
140pub(crate) mod test_support {
141 //! Shared test doubles for the unit tests in this crate.
142
143 use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
144 use std::sync::{Mutex, MutexGuard};
145 use std::time::Instant;
146
147 use anyhow::{bail, Result};
148
149 use crate::config::StoredPsk;
150 use crate::sink::{AudioFormat, AudioFrame, Sink};
151 use crate::storage::Storage;
152
153 /// A sink that accepts every call and keeps the trait's default output delay and underrun count.
154 pub(crate) struct NullSink;
155
156 impl Sink for NullSink {
157 fn open(&mut self, _format: AudioFormat) -> anyhow::Result<()> {
158 Ok(())
159 }
160
161 fn write(&mut self, _frame: AudioFrame<'_>, _due: Instant) -> anyhow::Result<()> {
162 Ok(())
163 }
164
165 fn flush(&mut self) -> anyhow::Result<()> {
166 Ok(())
167 }
168 }
169
170 #[test]
171 fn the_test_sink_reports_the_trait_defaults() {
172 let mut sink = NullSink;
173 sink.open(AudioFormat {
174 codec: crate::Codec::Pcm,
175 sample_rate: 48_000,
176 channels: 2,
177 bit_depth: 16,
178 codec_header: None,
179 })
180 .expect("the test sink accepts a format");
181 sink.write(AudioFrame::Pcm(&[1, 2]), Instant::now())
182 .expect("the test sink accepts a frame");
183 sink.flush().expect("the test sink flushes");
184 assert_eq!(
185 sink.output_delay(),
186 None,
187 "a sink that does not report a delay adds none"
188 );
189 assert_eq!(
190 sink.underruns(),
191 0,
192 "a sink that does not count underruns reports none"
193 );
194 }
195
196 /// A [`Storage`] that keeps everything in memory, optionally failing its calls.
197 ///
198 /// The crate's own tests need a store that answers instantly and one that fails a read or a
199 /// write, so a single double carries both. It applies no rule of its own: the record ordering,
200 /// the capacity and the live-record pin belong to [`persist_pairing`](crate::storage::persist_pairing).
201 #[derive(Debug, Default)]
202 pub(crate) struct MemoryStore {
203 pairing: Mutex<Option<[u8; 32]>>,
204 records: Mutex<Vec<StoredPsk>>,
205 read_fails: AtomicBool,
206 write_fails: AtomicBool,
207 stored_pairing_psks: AtomicUsize,
208 }
209
210 impl MemoryStore {
211 /// A store that already holds `pairing`.
212 pub(crate) fn holding(pairing: [u8; 32]) -> MemoryStore {
213 MemoryStore {
214 pairing: Mutex::new(Some(pairing)),
215 ..MemoryStore::default()
216 }
217 }
218
219 /// A store whose reads fail.
220 pub(crate) fn failing_reads() -> MemoryStore {
221 MemoryStore {
222 read_fails: AtomicBool::new(true),
223 ..MemoryStore::default()
224 }
225 }
226
227 /// A store whose writes fail.
228 pub(crate) fn failing_writes() -> MemoryStore {
229 MemoryStore {
230 write_fails: AtomicBool::new(true),
231 ..MemoryStore::default()
232 }
233 }
234
235 /// The pairing PSK the store holds.
236 pub(crate) fn pairing_psk_value(&self) -> Option<[u8; 32]> {
237 *self.pairing.lock().expect("the store lock is not poisoned")
238 }
239
240 /// The records the store holds, oldest first.
241 pub(crate) fn records(&self) -> Vec<StoredPsk> {
242 self.records
243 .lock()
244 .expect("the store lock is not poisoned")
245 .clone()
246 }
247
248 /// How often the client handed back a drawn pairing PSK.
249 pub(crate) fn stored_pairing_psks(&self) -> usize {
250 self.stored_pairing_psks.load(Ordering::SeqCst)
251 }
252
253 /// Puts a record into the store without going through the trait.
254 pub(crate) fn preload(&self, record: StoredPsk) {
255 self.records
256 .lock()
257 .expect("the store lock is not poisoned")
258 .push(record);
259 }
260
261 /// The record list, for a caller that has to hold the lock across a change.
262 fn records_lock(&self) -> MutexGuard<'_, Vec<StoredPsk>> {
263 self.records.lock().expect("the store lock is not poisoned")
264 }
265 }
266
267 impl Storage for MemoryStore {
268 fn pairing_psk(&self) -> Result<Option<[u8; 32]>> {
269 if self.read_fails.load(Ordering::SeqCst) {
270 bail!("the test store was told to fail its reads");
271 }
272 Ok(self.pairing_psk_value())
273 }
274
275 fn store_pairing_psk(&self, psk: &[u8; 32]) -> Result<()> {
276 if self.write_fails.load(Ordering::SeqCst) {
277 bail!("the test store was told to fail its writes");
278 }
279 *self.pairing.lock().expect("the store lock is not poisoned") = Some(*psk);
280 self.stored_pairing_psks.fetch_add(1, Ordering::SeqCst);
281 Ok(())
282 }
283
284 fn load_pairings(&self) -> Result<Vec<StoredPsk>> {
285 if self.read_fails.load(Ordering::SeqCst) {
286 bail!("the test store was told to fail its reads");
287 }
288 Ok(self.records())
289 }
290
291 fn store_pairing(&self, record: StoredPsk) -> Result<()> {
292 if self.write_fails.load(Ordering::SeqCst) {
293 bail!("the test store was told to fail its writes");
294 }
295 let mut records = self.records_lock();
296 records.retain(|held| held.server_id != record.server_id);
297 records.push(record);
298 Ok(())
299 }
300
301 fn remove_pairing(&self, server_id: &str) -> Result<()> {
302 if self.write_fails.load(Ordering::SeqCst) {
303 bail!("the test store was told to fail its writes");
304 }
305 self.records_lock()
306 .retain(|record| record.server_id != server_id);
307 Ok(())
308 }
309 }
310
311 #[test]
312 fn the_test_store_implements_the_storage_surface() {
313 let store = MemoryStore::holding([7u8; 32]);
314 assert_eq!(store.pairing_psk().unwrap(), Some([7u8; 32]));
315 assert_eq!(store.pairing_psk_value(), Some([7u8; 32]));
316 store.store_pairing_psk(&[8u8; 32]).unwrap();
317 assert_eq!(store.pairing_psk().unwrap(), Some([8u8; 32]));
318 assert_eq!(store.stored_pairing_psks(), 1);
319
320 let record = StoredPsk {
321 category: crate::PskCategory::LongTerm,
322 psk: [9u8; 32],
323 server_id: "a-server".to_owned(),
324 };
325 store.store_pairing(record.clone()).unwrap();
326 store.preload(StoredPsk {
327 server_id: "an-older-server".to_owned(),
328 ..record.clone()
329 });
330 assert_eq!(store.records().len(), 2, "the older record stays");
331 store.store_pairing(record.clone()).unwrap();
332 assert_eq!(
333 store.records().len(),
334 2,
335 "a record stored again replaces the one it replaces"
336 );
337 assert_eq!(store.load_pairings().unwrap().len(), 2);
338 store.remove_pairing("a-server").unwrap();
339 assert_eq!(store.load_pairings().unwrap().len(), 1);
340
341 let reads = MemoryStore::failing_reads();
342 assert!(reads.pairing_psk().is_err());
343 assert!(reads.load_pairings().is_err());
344 let writes = MemoryStore::failing_writes();
345 assert!(writes.store_pairing_psk(&[0u8; 32]).is_err());
346 assert!(writes.store_pairing(record).is_err());
347 assert!(writes.remove_pairing("a-server").is_err());
348 }
349}
350
351#[cfg(test)]
352mod tests {
353 use super::*;
354
355 #[test]
356 fn version_is_the_workspace_version() {
357 assert_eq!(version(), "0.5.0");
358 }
359}