syncspin_client/discovery.rs
1//! Discovery-facing side of the client: the trait a host implements, and the server-initiated
2//! connection mode.
3//!
4//! `connection.md` lets a client establish connections in exactly one of two ways. In the
5//! client-initiated way it dials the address of a server it found; in the server-initiated way it
6//! advertises `_sendspin._tcp` over mDNS and accepts the server that connects to it. This module
7//! holds the seam for both: the [`Discovery`] trait, the records it carries, and - behind the
8//! `discovery` feature - the inbound listener that serves the WebSocket the advertisement leads to.
9//! Without that feature the module is the trait and the records alone: nothing listens.
10//!
11//! The mDNS backend lives behind the `mdns` feature; without it, [`Discovery`] is the seam and the
12//! host supplies the implementation. The protocol logic here opens no socket of its own: a browse
13//! asks the host's backend, and [`discover_reachable_endpoint`] only probes an address the backend
14//! already reported. The tests drive the advertising with a fake instead of a network. The inbound
15//! listener binds a real address, because it has to: it is the endpoint the advertisement names.
16//!
17//! The inbound connection runs the same session as a dialled one. Only the WebSocket is different:
18//! the server opened it, so the client answers the upgrade instead of sending it, and it rejects
19//! every request that carries an `Origin` header. `connection.md`: a client that advertises
20//! "MUST reject a WebSocket upgrade request to its Sendspin endpoint that carries an `Origin`
21//! header"; a server that dials in knows the address it dialled, and the header is the browser's
22//! cross-origin authorisation, not the protocol's. The Noise handshake is unchanged, because the
23//! server is its initiator in both directions.
24
25use std::net::SocketAddr;
26use std::time::Duration;
27
28use anyhow::{bail, Context, Result};
29use tokio::net::TcpStream;
30
31/// Service type a client publishes when it waits for a server to connect.
32///
33/// `connection.md`, _Server Initiated Connections_: the port, the `path` TXT record and the
34/// optional `name` TXT record travel with it.
35pub const CLIENT_SERVICE_TYPE: &str = "_sendspin._tcp.local.";
36
37/// Service type a server publishes for client-initiated connections.
38pub const SERVER_SERVICE_TYPE: &str = "_sendspin-server._tcp.local.";
39
40/// WebSocket endpoint `connection.md` recommends for both directions.
41pub const DEFAULT_SENDSPIN_PATH: &str = "/sendspin";
42
43/// One service to publish over mDNS.
44///
45/// The record is what a peer needs to reach the endpoint: the service type, the port, and the
46/// `path` TXT record the WebSocket lives on. `name` is the optional friendly-name hint; it is not
47/// an identity and a peer that has the connection takes the name from `client/hello`
48/// (`server/hello` in the other direction) instead.
49#[derive(Debug, Clone, PartialEq, Eq)]
50pub struct ServiceAdvertisement {
51 /// Service type the record is published under, for example [`CLIENT_SERVICE_TYPE`].
52 pub service_type: String,
53 /// Port the endpoint listens on.
54 pub port: u16,
55 /// The `path` TXT record: the WebSocket endpoint, an absolute path such as `/sendspin`.
56 pub path: String,
57 /// The `name` TXT record, when the advertiser sets one.
58 pub name: Option<String>,
59}
60
61impl ServiceAdvertisement {
62 /// Returns the record a client publishes: `_sendspin._tcp`, its port, `path` and `name`.
63 ///
64 /// The name is the player's, which is the value `client/hello` repeats; the spec only asks it to
65 /// match, and calls the `client/hello` value authoritative when the two differ.
66 #[must_use]
67 pub fn client(
68 port: u16,
69 path: impl Into<String>,
70 name: impl Into<String>,
71 ) -> ServiceAdvertisement {
72 ServiceAdvertisement {
73 service_type: CLIENT_SERVICE_TYPE.to_owned(),
74 port,
75 path: path.into(),
76 name: Some(name.into()),
77 }
78 }
79}
80
81/// One server a browser reported.
82#[derive(Debug, Clone, PartialEq, Eq)]
83pub struct DiscoveredServer {
84 /// `host:port` addresses the browser resolved for the service.
85 ///
86 /// [`endpoints`](DiscoveredServer::endpoints) orders them IPv4 first; the vector itself keeps
87 /// whatever order the backend reported.
88 pub addresses: Vec<String>,
89 /// The `path` TXT record the service published.
90 pub path: String,
91 /// The `name` TXT record, when the service published one.
92 pub name: Option<String>,
93}
94
95impl DiscoveredServer {
96 /// Returns the `ws://` endpoint to dial, or `None` when the record cannot name one.
97 ///
98 /// This is the first of [`endpoints`](DiscoveredServer::endpoints), so it is the IPv4 address
99 /// when the record has one.
100 #[must_use]
101 pub fn endpoint(&self) -> Option<String> {
102 self.endpoints().into_iter().next()
103 }
104
105 /// Returns every `ws://` endpoint the record names, IPv4 addresses first.
106 ///
107 /// The scheme is `ws://` even though the path is advertised: `connection.md` requires a
108 /// connection to an advertised address to use plain `ws://`, with confidentiality and integrity
109 /// provided by the Noise layer inside the payloads. An address that carries a scheme already,
110 /// a missing address and a path that is not `path-absolute` (RFC 3986) all yield nothing,
111 /// because dialling them would mean guessing what the advertiser meant.
112 ///
113 /// An mDNS record commonly resolves to several addresses for one service - a dual-stack host
114 /// publishes both. The IPv4 addresses come first so a server that listens on a single IPv4
115 /// wildcard is reached before a client spends a timeout on an IPv6 address nothing accepts; the
116 /// relative order within each family is kept. A record with no valid address yields an empty
117 /// list.
118 #[must_use]
119 pub fn endpoints(&self) -> Vec<String> {
120 self.ordered_addresses()
121 .into_iter()
122 .map(|address| format!("ws://{address}{}", self.path))
123 .collect()
124 }
125
126 /// Returns the usable addresses, IPv4 first.
127 ///
128 /// The path rule is part of the address rule because an endpoint is only dialable when both
129 /// hold; a record with a relative path yields no candidates at all.
130 fn ordered_addresses(&self) -> Vec<&str> {
131 if !self.path.starts_with('/') || self.path.starts_with("//") {
132 return Vec::new();
133 }
134 let mut addresses: Vec<&str> = self
135 .addresses
136 .iter()
137 .map(String::as_str)
138 .filter(|address| !address.contains("://"))
139 .collect();
140 // A stable sort keeps the browser's order inside each family. A host name that is not a
141 // literal socket address sorts with IPv6, after the addresses that are certainly IPv4.
142 addresses.sort_by_key(|address| match address.parse::<SocketAddr>() {
143 Ok(address) if address.is_ipv4() => 0u8,
144 _ => 1u8,
145 });
146 addresses
147 }
148}
149
150/// How long one advertised address gets to accept before the next one is tried.
151///
152/// A refused connection returns at once; the timeout only bounds an address that silently drops
153/// the attempt, such as a stale IPv6 entry on a network without a route to it.
154const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
155
156/// Returns the first endpoint `discovery` reports that accepts a TCP connection.
157///
158/// A browse can report one service with several addresses, and a dual-stack host commonly does.
159/// Trying only the first means an IPv6 address the server does not listen on hides an IPv4 address
160/// it does, and the client retries the same unreachable one forever. This walks the candidates in
161/// the order [`DiscoveredServer::endpoints`] gives - IPv4 first - and stops at the first address
162/// that accepts. A failure moves to the next address immediately instead of waiting for a retry
163/// tick.
164///
165/// The probe is a TCP connection only: it decides reachability, and the session dials the returned
166/// endpoint itself. A host therefore sees one closed probe connection before the real one.
167///
168/// # Errors
169/// Returns the backend's error, an error when nothing advertises a dialable endpoint, and an error
170/// naming every attempt once all addresses refused or timed out. A backend error is not retried
171/// here; the caller decides whether to browse again.
172pub async fn discover_reachable_endpoint(discovery: &dyn Discovery) -> Result<String> {
173 let servers = discover_servers(discovery)?;
174 let candidates: Vec<(String, String)> = servers
175 .iter()
176 .flat_map(|server| {
177 server
178 .ordered_addresses()
179 .into_iter()
180 .map(|address| (address.to_owned(), format!("ws://{address}{}", server.path)))
181 .collect::<Vec<_>>()
182 })
183 .collect();
184 if candidates.is_empty() {
185 bail!(
186 "no server advertised {SERVER_SERVICE_TYPE} with a dialable address; start one with \
187 `server-demo --mdns` or pass --server"
188 );
189 }
190 let mut failures = Vec::new();
191 for (address, endpoint) in candidates {
192 match probe(&address).await {
193 Ok(()) => return Ok(endpoint),
194 Err(error) => failures.push(format!("{address}: {error:#}")),
195 }
196 }
197 bail!(
198 "none of the discovered servers accepted a connection ({})",
199 failures.join("; ")
200 )
201}
202
203/// Opens and immediately drops one TCP connection, to tell a reachable address from a dead one.
204async fn probe(address: &str) -> Result<()> {
205 // Dropping the stream closes the probe; it only decides reachability.
206 tokio::time::timeout(PROBE_TIMEOUT, TcpStream::connect(address))
207 .await
208 .with_context(|| format!("no answer within {} s", PROBE_TIMEOUT.as_secs()))??;
209 Ok(())
210}
211
212/// How a service is published and how remote ones are found.
213///
214/// A host implements this over its mDNS library of choice; the crate decides what the record
215/// contains and what an announcement obliges it to do, so the two stay in one place. The trait never
216/// reports a record it has not published: [`advertise`](Discovery::advertise) returning `Ok` means
217/// a server can find the endpoint, and the whole server-initiated mode rests on that.
218///
219/// A client that advertises must not dial a server itself (`connection.md`, _Server Initiated
220/// Connections_). This crate enforces that: [`connect`](crate::connect) refuses a configuration
221/// that advertises.
222pub trait Discovery: Send + Sync {
223 /// Publishes `service` until its service type is withdrawn.
224 ///
225 /// # Errors
226 /// Returns an error when the record could not be published. The client then refuses to start,
227 /// because accepting connections nobody can find is not the mode it was asked for.
228 fn advertise(&self, service: ServiceAdvertisement) -> Result<()>;
229
230 /// Withdraws the advertisement of `service_type`.
231 ///
232 /// Called when the inbound listener closes: a record that outlives its listener points at a
233 /// closed port. Withdrawing a type that was never advertised is not an error.
234 fn withdraw(&self, service_type: &str) -> Result<()>;
235
236 /// Returns the services currently advertised under `service_type`.
237 fn browse(&self, service_type: &str) -> Result<Vec<DiscoveredServer>>;
238}
239
240/// Returns the servers `discovery` currently reports.
241///
242/// This is the browsing half of the client-initiated mode: the caller picks one
243/// [`DiscoveredServer::endpoint`] and passes it to [`connect`](crate::connect). Browsing is a
244/// client-initiated act, so a host that browses must not advertise at the same time; a
245/// configuration with [`ClientConfig::inbound`](crate::ClientConfig) set cannot dial at all.
246///
247/// # Errors
248/// Returns the backend's error, and nothing when it cannot browse at all; an empty list means no
249/// server is advertising.
250pub fn discover_servers(discovery: &dyn Discovery) -> Result<Vec<DiscoveredServer>> {
251 discovery.browse(SERVER_SERVICE_TYPE)
252}
253
254#[cfg(feature = "discovery")]
255pub use inbound::{advertise, Inbound, DEFAULT_INBOUND_ADDR, DEFAULT_INBOUND_PORT};
256
257#[cfg(feature = "mdns")]
258mod mdns;
259
260#[cfg(feature = "mdns")]
261pub use mdns::MdnsDiscovery;
262
263#[cfg(feature = "discovery")]
264mod inbound {
265 use std::fmt;
266 use std::net::{IpAddr, Ipv4Addr, SocketAddr};
267 use std::sync::atomic::{AtomicBool, AtomicU8};
268 use std::sync::Arc;
269 use std::time::Duration;
270
271 use anyhow::{anyhow, Context, Result};
272 use syncspin_core::pairing::token::encode_v0;
273 use tokio::net::{TcpListener, TcpStream};
274 use tokio::sync::{mpsc, oneshot};
275 use tokio::task::JoinSet;
276 use tokio_tungstenite::accept_hdr_async;
277 use tokio_tungstenite::tungstenite::handshake::server::{ErrorResponse, Request, Response};
278 use tokio_tungstenite::tungstenite::http::header::ORIGIN;
279 use tokio_tungstenite::tungstenite::http::StatusCode;
280 use tokio_tungstenite::tungstenite::Error as WsError;
281
282 use super::{ServiceAdvertisement, DEFAULT_SENDSPIN_PATH};
283 use crate::client::{
284 answer_without_session, ClientHandle, ControlHandle, ControlRequest, Event, EventStream,
285 GoodbyeReason, PairingToken,
286 };
287 use crate::config::ClientConfig;
288 use crate::pairing::{load_or_draw_pairing_psk, PairingPsk};
289 use crate::session::{self, Carried, Transport};
290 use crate::sink::Sink;
291 use crate::Discovery;
292
293 /// Port `connection.md` recommends for a client's Sendspin endpoint.
294 pub const DEFAULT_INBOUND_PORT: u16 = 8928;
295
296 /// Address the inbound listener binds unless the host narrows it.
297 ///
298 /// Encryption is the boundary, not the bind address: a peer that cannot complete the Noise
299 /// handshake is refused whatever interface it reached.
300 pub const DEFAULT_INBOUND_ADDR: SocketAddr =
301 SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), DEFAULT_INBOUND_PORT);
302
303 /// How long the rejection of a second server may take before its socket is dropped.
304 ///
305 /// The provisional connection has to reach its first `server/activate` before admission can be
306 /// applied. A server that never gets there is not worth keeping: the cap already rejected it,
307 /// and the spec's own provisional timeout is 30 seconds.
308 const REJECT_TIMEOUT: Duration = Duration::from_secs(30);
309
310 /// The server-initiated half of the connection mode.
311 ///
312 /// Setting [`ClientConfig::inbound`] puts the client in this mode: [`advertise`] publishes
313 /// [`CLIENT_SERVICE_TYPE`](super::CLIENT_SERVICE_TYPE) with the bound port, the configured path
314 /// and the player name, and then accepts the servers that connect. A manual
315 /// [`connect`](crate::connect) is refused while this is set, because `connection.md` lets a
316 /// client use one of the two methods at a time.
317 #[derive(Clone)]
318 pub struct Inbound {
319 /// Backend that publishes the record and browses for servers.
320 pub discovery: Arc<dyn Discovery>,
321 /// Address the listener binds.
322 pub listen: SocketAddr,
323 /// WebSocket path the listener serves, as the `path` TXT record states it.
324 pub path: String,
325 }
326
327 impl Inbound {
328 /// Returns the server-initiated mode for `discovery`, with the spec's defaults.
329 ///
330 /// The listener binds [`DEFAULT_INBOUND_ADDR`] - every interface on
331 /// [`DEFAULT_INBOUND_PORT`] - and serves `/sendspin`. A host that narrows the address or
332 /// moves the path sets the fields before placing the value in [`ClientConfig::inbound`].
333 #[must_use]
334 pub fn new(discovery: Arc<dyn Discovery>) -> Inbound {
335 Inbound {
336 discovery,
337 listen: DEFAULT_INBOUND_ADDR,
338 path: DEFAULT_SENDSPIN_PATH.to_owned(),
339 }
340 }
341 }
342
343 impl fmt::Debug for Inbound {
344 /// Names the backend without delegating to it: its `Debug` belongs to the host.
345 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
346 formatter
347 .debug_struct("Inbound")
348 .field("discovery", &"<host discovery>")
349 .field("listen", &self.listen)
350 .field("path", &self.path)
351 .finish()
352 }
353 }
354
355 /// Advertises this client and serves the servers that connect to it.
356 ///
357 /// The advertisement is published before this returns, so a caller learns about a backend that
358 /// cannot publish instead of running a listener nobody can find. The port in the record is the
359 /// one that was actually bound, which is how a listen address with port zero becomes reachable.
360 ///
361 /// One server is admitted at a time: while a session is live the loop runs it, and when it ends
362 /// the client reports [`Event::Disconnected`] with a `retry_in` of zero - it schedules nothing,
363 /// because the next connection is the server's decision - and accepts the next one. The
364 /// advertisement is withdrawn when the handle or the event stream is dropped, when
365 /// [`ClientHandle::close`] is called, or when the audio sink fails.
366 ///
367 /// # Errors
368 /// Returns an error for an invalid configuration, for a configuration without
369 /// [`ClientConfig::inbound`], for a [`Storage`](crate::storage::Storage) that cannot hold the
370 /// pairing PSK, for a listen address this build cannot bind, and for a backend that refuses the
371 /// advertisement.
372 ///
373 /// # Panics
374 /// Panics when called outside a Tokio runtime, because the listener is spawned.
375 ///
376 /// Pairing records come from [`ClientConfig::storage`]; this revision has no advertising
377 /// counterpart to [`connect_with_psks`](crate::connect_with_psks).
378 pub async fn advertise(
379 config: ClientConfig,
380 sink: Box<dyn Sink>,
381 ) -> Result<(ClientHandle, EventStream)> {
382 let inbound = config.inbound.clone().ok_or_else(|| {
383 anyhow!(
384 "this configuration has no ClientConfig::inbound, so there is nothing to \
385 advertise and no address to accept a server on"
386 )
387 })?;
388 // An advertising client names no server address, so only the shared fields are checked.
389 config.validate_common()?;
390
391 // The pairing PSK is settled before anything is published, so a store that cannot hold it
392 // is reported here rather than to whichever server happens to connect first.
393 let (pairing, pairing_token) = match config.storage.as_deref() {
394 Some(storage) => {
395 let psk = load_or_draw_pairing_psk(storage)?;
396 let token = PairingToken(encode_v0(&config.identity.public, psk.as_bytes()));
397 (Some(psk), Some(token))
398 }
399 None => (None, None),
400 };
401
402 // The listener comes next: a record that names a port nothing accepts on is a record a
403 // server dials into a closed socket. Nothing after the advertisement can fail, so a client
404 // never stays advertised without a listener behind it.
405 let listener = TcpListener::bind(inbound.listen).await.with_context(|| {
406 format!("failed to bind the inbound listener on {}", inbound.listen)
407 })?;
408 let port = listener
409 .local_addr()
410 .context("failed to read the inbound listener's address")?
411 .port();
412 let record = ServiceAdvertisement::client(port, inbound.path.clone(), &config.player_name);
413 inbound
414 .discovery
415 .advertise(record.clone())
416 .context("the discovery backend refused to advertise this client")?;
417
418 let (events, receiver) = mpsc::unbounded_channel();
419 let (commands, control) = mpsc::unbounded_channel();
420 let (shutdown, shutdown_rx) = oneshot::channel();
421 let reported_volume = Arc::new(AtomicU8::new(config.volume));
422 // The dynamic flow's round counter belongs to the process, not to a connection: it starts
423 // clean here and is carried across every inbound session.
424 #[cfg(feature = "pairing-code")]
425 let failed_rounds = Arc::new(std::sync::atomic::AtomicU32::new(0));
426
427 let carried = Carried {
428 sink,
429 control: Some(control),
430 volume: config.volume,
431 muted: config.muted,
432 active_roles: Vec::new(),
433 unpaired_access: Arc::new(AtomicBool::new(config.unpaired_access)),
434 #[cfg(feature = "pairing-code")]
435 failed_rounds,
436 };
437
438 let task = tokio::spawn(serve(
439 listener,
440 config,
441 inbound,
442 record,
443 pairing,
444 carried,
445 events,
446 Arc::clone(&reported_volume),
447 shutdown_rx,
448 ));
449
450 let handle = ClientHandle {
451 task: Some(task),
452 control: ControlHandle {
453 commands,
454 volume: reported_volume,
455 pairing_token,
456 },
457 shutdown: Some(shutdown),
458 };
459 Ok((handle, EventStream { events: receiver }))
460 }
461
462 /// Runs the listener until the host is done, then withdraws the advertisement.
463 #[allow(clippy::too_many_arguments)]
464 async fn serve(
465 listener: TcpListener,
466 config: ClientConfig,
467 inbound: Inbound,
468 record: ServiceAdvertisement,
469 pairing: Option<PairingPsk>,
470 carried: Carried,
471 events: mpsc::UnboundedSender<Event>,
472 reported_volume: Arc<AtomicU8>,
473 mut shutdown: oneshot::Receiver<GoodbyeReason>,
474 ) -> Result<()> {
475 let outcome = accept_loop(
476 &listener,
477 &config,
478 &inbound.path,
479 pairing,
480 carried,
481 &events,
482 &reported_volume,
483 &mut shutdown,
484 )
485 .await;
486 // An advertisement that outlives the listener points a server at a closed port, so it goes
487 // away whatever ended the loop.
488 let withdrawn = inbound
489 .discovery
490 .withdraw(&record.service_type)
491 .context("the discovery backend refused to withdraw the advertisement");
492 match outcome {
493 Ok(()) => withdrawn,
494 Err(error) => Err(error),
495 }
496 }
497
498 /// Accepts and serves one connection at a time until the host ends the client.
499 #[allow(clippy::too_many_arguments)]
500 async fn accept_loop(
501 listener: &TcpListener,
502 config: &ClientConfig,
503 path: &str,
504 pairing: Option<PairingPsk>,
505 mut carried: Carried,
506 events: &mpsc::UnboundedSender<Event>,
507 reported_volume: &AtomicU8,
508 shutdown: &mut oneshot::Receiver<GoodbyeReason>,
509 ) -> Result<()> {
510 loop {
511 let Some(stream) =
512 wait_for_connection(listener, &mut carried, events, shutdown).await?
513 else {
514 return Ok(());
515 };
516 // The upgrade answers every request it refuses, so neither a wrong path nor a rejected
517 // `Origin` reaches the protocol. A peer that breaks the upgrade itself - a truncated
518 // request, a hello for another protocol - is equally not a connection, and neither
519 // stops the listener for the servers that follow.
520 let transport = match upgrade(stream, path).await {
521 Ok(Some(transport)) => transport,
522 Ok(None) | Err(_) => continue,
523 };
524
525 // The server-initiated mode admits one server at a time. A second one that arrives
526 // while this session runs is not left in the listen backlog: its handshake is completed
527 // in a task of its own and it is rejected with `concurrent_attempt`, as `connection.md`
528 // requires. The task owns no state of the admitted session, so a slow rejection cannot
529 // hold up playback.
530 //
531 // The rejection task runs while the admitted session owns the carried state, so it
532 // gets the shared unpaired-access value as a handle of its own.
533 let unpaired_access = Arc::clone(&carried.unpaired_access);
534 let mut rejections = JoinSet::new();
535 let mut attempt = Box::pin(session::attempt(
536 transport,
537 config,
538 events,
539 &[],
540 pairing,
541 reported_volume,
542 carried,
543 shutdown,
544 ));
545 let attempt = loop {
546 tokio::select! {
547 attempt = &mut attempt => break attempt,
548 // Accepting is cancel-safe: a connection that arrives while another branch is
549 // busy waits in the backlog for the next round.
550 accepted = listener.accept() => {
551 let (stream, _address) =
552 accepted.context("failed to accept an inbound connection")?;
553 rejections.spawn(reject_connection(
554 stream,
555 config.clone(),
556 path.to_owned(),
557 pairing,
558 Arc::clone(&unpaired_access),
559 ));
560 }
561 joined = rejections.join_next(), if !rejections.is_empty() => {
562 // A rejection that failed changed nothing: the admitted session is the one
563 // the host hears about.
564 let _ = joined;
565 }
566 }
567 };
568 // A rejection that has not finished belongs to a client that is already ending; it is
569 // dropped with the set, which closes its socket.
570 drop(rejections);
571 carried = attempt.carried;
572
573 // Nothing buffered for the session that ended may become audible later; the flush runs
574 // before the host hears about the drop. A deliberate close is not a drop.
575 let flush_error = carried.sink.flush().err().map(|error| {
576 error.context("the audio sink rejected a flush after the connection ended")
577 });
578 if matches!(&attempt.ending, session::Ending::Shutdown) {
579 return Ok(());
580 }
581 // No attempt follows: the next connection is the server's decision, not the client's,
582 // so there is no delay to recommend.
583 let _ = events.send(Event::Disconnected {
584 reason: attempt.ending.reason(),
585 retry_in: Duration::ZERO,
586 });
587
588 // A broken output cannot be repaired by another connection, and neither can a flush
589 // that fails after the session; both end the client so the host can repair it.
590 if attempt.sink_failed {
591 return match attempt.ending {
592 session::Ending::Failed(error) => Err(error),
593 session::Ending::Closed
594 | session::Ending::Unpaired
595 | session::Ending::PairingRequired
596 | session::Ending::UnpairedAccessOff
597 | session::Ending::Restart
598 | session::Ending::Unauthorized
599 | session::Ending::Shutdown => Err(anyhow!("the audio sink failed")),
600 };
601 }
602 if let Some(error) = flush_error {
603 return Err(error);
604 }
605 }
606 }
607
608 /// Rejects one connection that arrived while another server is admitted.
609 ///
610 /// The upgrade rules are the same as for the admitted connection - the path must match and an
611 /// `Origin` header is refused - because a rejected server learns nothing a browser could use.
612 async fn reject_connection(
613 stream: TcpStream,
614 config: ClientConfig,
615 path: String,
616 pairing: Option<PairingPsk>,
617 unpaired_access: Arc<AtomicBool>,
618 ) {
619 let Ok(Some(transport)) = upgrade(stream, &path).await else {
620 return;
621 };
622 let _ = tokio::time::timeout(
623 REJECT_TIMEOUT,
624 session::reject_concurrent(transport, &config, pairing, &[], &unpaired_access),
625 )
626 .await;
627 }
628
629 /// Waits for the next inbound connection, answering control requests meanwhile.
630 ///
631 /// Returns `None` when the host ended the client: the handle was closed or the event stream was
632 /// dropped. There is no session to say goodbye on while the listener waits, exactly as in the
633 /// reconnect wait of a dialling client.
634 async fn wait_for_connection(
635 listener: &TcpListener,
636 carried: &mut Carried,
637 events: &mpsc::UnboundedSender<Event>,
638 shutdown: &mut oneshot::Receiver<GoodbyeReason>,
639 ) -> Result<Option<TcpStream>> {
640 loop {
641 if events.is_closed() {
642 return Ok(None);
643 }
644 let control = &mut carried.control;
645 let wakeup = tokio::select! {
646 biased;
647 request = async {
648 match control {
649 Some(receiver) => receiver.recv().await,
650 None => std::future::pending().await,
651 }
652 } => Wakeup::Control(request),
653 // Accepting is cancel-safe: a connection that arrives while this select is busy
654 // waits in the backlog.
655 accepted = listener.accept() => Wakeup::Accepted(accepted),
656 reason = &mut *shutdown => {
657 let _ = reason;
658 return Ok(None);
659 }
660 () = events.closed() => Wakeup::Closed,
661 };
662 match wakeup {
663 Wakeup::Control(Some(request)) => answer_without_session(carried, request),
664 Wakeup::Control(None) => *control = None,
665 Wakeup::Accepted(Ok((stream, _address))) => return Ok(Some(stream)),
666 Wakeup::Accepted(Err(error)) => {
667 return Err(anyhow!(error).context("failed to accept an inbound connection"))
668 }
669 Wakeup::Closed => return Ok(None),
670 }
671 }
672 }
673
674 /// One wake-up while the listener waits for a server.
675 enum Wakeup {
676 /// A control handle sent a request, or every handle was dropped.
677 Control(Option<ControlRequest>),
678 /// The listener accepted a TCP connection.
679 Accepted(std::io::Result<(TcpStream, SocketAddr)>),
680 /// The host dropped the event stream.
681 Closed,
682 }
683
684 /// Serves `stream` if it asks for `path` and carries no `Origin` header.
685 ///
686 /// `Ok(None)` means the request was refused with an HTTP answer and its socket is closed; the
687 /// caller keeps listening.
688 // Error responses are the handshake crate's large `http::Response` type; a rejection happens
689 // once per refused upgrade, so boxing it would buy nothing.
690 #[allow(clippy::result_large_err)]
691 async fn upgrade(stream: TcpStream, path: &str) -> Result<Option<Transport>> {
692 let expected = path.to_owned();
693 let callback = move |request: &Request, response: Response| {
694 // `connection.md`: a client must reject an upgrade that carries an `Origin` header. A
695 // server that dials in knows the address it dialled, so the header can only come from
696 // something acting for a page - which is what the rule exists to refuse.
697 if request.headers().contains_key(ORIGIN) {
698 let mut error = ErrorResponse::new(Some(
699 "a server-initiated Sendspin upgrade must not carry an Origin header"
700 .to_owned(),
701 ));
702 *error.status_mut() = StatusCode::FORBIDDEN;
703 return Err(error);
704 }
705 if request.uri().path() == expected {
706 return Ok(response);
707 }
708 let mut error =
709 ErrorResponse::new(Some("this endpoint is not a Sendspin endpoint".to_owned()));
710 *error.status_mut() = StatusCode::NOT_FOUND;
711 Err(error)
712 };
713 match accept_hdr_async(stream, callback).await {
714 Ok(socket) => Ok(Some(Transport::accept(socket))),
715 // The two answers above: the peer was told why and the socket is closed.
716 Err(WsError::Http(response))
717 if response.status() == StatusCode::FORBIDDEN
718 || response.status() == StatusCode::NOT_FOUND =>
719 {
720 Ok(None)
721 }
722 Err(error) => Err(error).context("the WebSocket upgrade failed"),
723 }
724 }
725}
726
727#[cfg(test)]
728mod tests {
729 use super::*;
730
731 /// A [`Discovery`] that answers from memory, so the record shape is tested without a network.
732 #[derive(Default)]
733 struct MemoryDiscovery {
734 browsed: std::sync::Mutex<Vec<String>>,
735 servers: Vec<DiscoveredServer>,
736 }
737
738 impl Discovery for MemoryDiscovery {
739 fn advertise(&self, _service: ServiceAdvertisement) -> Result<()> {
740 Ok(())
741 }
742
743 fn withdraw(&self, _service_type: &str) -> Result<()> {
744 Ok(())
745 }
746
747 fn browse(&self, service_type: &str) -> Result<Vec<DiscoveredServer>> {
748 self.browsed
749 .lock()
750 .expect("the query list is not poisoned")
751 .push(service_type.to_owned());
752 Ok(self.servers.clone())
753 }
754 }
755
756 /// The record a client publishes carries the three things a server dials with, plus its name.
757 #[test]
758 fn a_client_record_names_the_service_the_port_the_path_and_the_player() {
759 let record = ServiceAdvertisement::client(8928, DEFAULT_SENDSPIN_PATH, "Test player");
760 assert_eq!(record.service_type, CLIENT_SERVICE_TYPE);
761 assert_eq!(record.port, 8928);
762 assert_eq!(record.path, "/sendspin");
763 assert_eq!(record.name.as_deref(), Some("Test player"));
764 assert_ne!(
765 CLIENT_SERVICE_TYPE, SERVER_SERVICE_TYPE,
766 "the two directions use two service types"
767 );
768 }
769
770 /// A discovered record becomes a plain `ws://` endpoint, and nothing else.
771 #[test]
772 fn a_discovered_server_builds_a_plain_ws_endpoint() {
773 let server = DiscoveredServer {
774 addresses: vec!["192.0.2.7:8927".to_owned()],
775 path: "/sendspin".to_owned(),
776 name: Some("A server".to_owned()),
777 };
778 assert_eq!(
779 server.endpoint().as_deref(),
780 Some("ws://192.0.2.7:8927/sendspin"),
781 "connection.md requires plain ws:// to an advertised address"
782 );
783
784 // A record that cannot name an endpoint is refused here rather than guessed at later.
785 for broken in [
786 DiscoveredServer {
787 addresses: Vec::new(),
788 ..server.clone()
789 },
790 DiscoveredServer {
791 path: "sendspin".to_owned(),
792 ..server.clone()
793 },
794 DiscoveredServer {
795 path: "//sendspin".to_owned(),
796 ..server.clone()
797 },
798 DiscoveredServer {
799 addresses: vec!["wss://192.0.2.7:8927".to_owned()],
800 ..server
801 },
802 ] {
803 assert_eq!(
804 broken.endpoint(),
805 None,
806 "a record that does not name a ws:// endpoint is not dialled"
807 );
808 }
809 }
810
811 /// A record with several addresses names the IPv4 ones first, keeping each family's order.
812 #[test]
813 fn a_dual_stack_record_lists_its_ipv4_addresses_first() {
814 let server = DiscoveredServer {
815 addresses: vec![
816 "[fd41::2]:8927".to_owned(),
817 "[fd41::1]:8927".to_owned(),
818 "192.0.2.8:8927".to_owned(),
819 "192.0.2.7:8927".to_owned(),
820 ],
821 path: "/sendspin".to_owned(),
822 name: None,
823 };
824 assert_eq!(
825 server.endpoints(),
826 vec![
827 "ws://192.0.2.8:8927/sendspin".to_owned(),
828 "ws://192.0.2.7:8927/sendspin".to_owned(),
829 "ws://[fd41::2]:8927/sendspin".to_owned(),
830 "ws://[fd41::1]:8927/sendspin".to_owned(),
831 ],
832 "IPv4 comes first and the browser's order within each family is kept"
833 );
834 assert_eq!(
835 server.endpoint().as_deref(),
836 Some("ws://192.0.2.8:8927/sendspin"),
837 "endpoint is the first of the ordered list"
838 );
839 }
840
841 /// An address that refuses does not consume the attempt: the next one is tried at once.
842 #[tokio::test]
843 async fn the_next_address_is_tried_when_the_first_refuses() {
844 // A listener that accepts the probe, so the second address is the one that works.
845 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
846 .await
847 .expect("the loopback listener binds");
848 let accepting = listener
849 .local_addr()
850 .expect("the bound address is readable");
851 let accept = tokio::spawn(async move {
852 let _ = listener.accept().await;
853 });
854
855 // A port nobody listens on: binding it and dropping the listener makes the connect refuse.
856 let closed = tokio::net::TcpListener::bind("127.0.0.1:0")
857 .await
858 .expect("the second loopback listener binds");
859 let refusing = closed.local_addr().expect("the bound address is readable");
860 drop(closed);
861
862 let discovery = MemoryDiscovery {
863 servers: vec![DiscoveredServer {
864 addresses: vec![refusing.to_string(), accepting.to_string()],
865 path: "/sendspin".to_owned(),
866 name: Some("A server".to_owned()),
867 }],
868 ..MemoryDiscovery::default()
869 };
870 let endpoint = discover_reachable_endpoint(&discovery)
871 .await
872 .expect("the second address accepts");
873 assert_eq!(endpoint, format!("ws://{accepting}/sendspin"));
874 accept.await.expect("the accepting task finishes");
875 }
876
877 /// When every address refuses, the error names all of them instead of only the first.
878 #[tokio::test]
879 async fn an_error_names_every_address_that_refused() {
880 let first_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
881 .await
882 .expect("the first loopback listener binds");
883 let second_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
884 .await
885 .expect("the second loopback listener binds");
886 let first = first_listener
887 .local_addr()
888 .expect("the bound address is readable");
889 let second = second_listener
890 .local_addr()
891 .expect("the bound address is readable");
892 assert_ne!(first, second, "two ephemeral listeners get two ports");
893 // Releasing both makes every connect to them refuse.
894 drop(first_listener);
895 drop(second_listener);
896
897 let discovery = MemoryDiscovery {
898 servers: vec![DiscoveredServer {
899 addresses: vec![first.to_string(), second.to_string()],
900 path: "/sendspin".to_owned(),
901 name: None,
902 }],
903 ..MemoryDiscovery::default()
904 };
905 let Err(error) = discover_reachable_endpoint(&discovery).await else {
906 panic!("both addresses refuse");
907 };
908 let text = format!("{error:#}");
909 assert!(text.contains(&first.to_string()), "got: {text}");
910 assert!(text.contains(&second.to_string()), "got: {text}");
911 }
912
913 /// Browsing always asks for the server service type; the client never looks for clients.
914 #[test]
915 fn browsing_asks_the_backend_for_servers() {
916 let discovery = MemoryDiscovery::default();
917 let servers = discover_servers(&discovery).expect("the backend answers");
918 assert!(servers.is_empty());
919 assert_eq!(
920 discovery
921 .browsed
922 .lock()
923 .expect("the query list is not poisoned")
924 .as_slice(),
925 &[SERVER_SERVICE_TYPE.to_owned()]
926 );
927 }
928}