Skip to main content

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