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::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 #[cfg(feature = "pairing-code")]
434 failed_rounds,
435 };
436
437 let task = tokio::spawn(serve(
438 listener,
439 config,
440 inbound,
441 record,
442 pairing,
443 carried,
444 events,
445 Arc::clone(&reported_volume),
446 shutdown_rx,
447 ));
448
449 let handle = ClientHandle {
450 task: Some(task),
451 control: ControlHandle {
452 commands,
453 volume: reported_volume,
454 pairing_token,
455 },
456 shutdown: Some(shutdown),
457 };
458 Ok((handle, EventStream { events: receiver }))
459 }
460
461 /// Runs the listener until the host is done, then withdraws the advertisement.
462 #[allow(clippy::too_many_arguments)]
463 async fn serve(
464 listener: TcpListener,
465 config: ClientConfig,
466 inbound: Inbound,
467 record: ServiceAdvertisement,
468 pairing: Option<PairingPsk>,
469 carried: Carried,
470 events: mpsc::UnboundedSender<Event>,
471 reported_volume: Arc<AtomicU8>,
472 mut shutdown: oneshot::Receiver<GoodbyeReason>,
473 ) -> Result<()> {
474 let outcome = accept_loop(
475 &listener,
476 &config,
477 &inbound.path,
478 pairing,
479 carried,
480 &events,
481 &reported_volume,
482 &mut shutdown,
483 )
484 .await;
485 // An advertisement that outlives the listener points a server at a closed port, so it goes
486 // away whatever ended the loop.
487 let withdrawn = inbound
488 .discovery
489 .withdraw(&record.service_type)
490 .context("the discovery backend refused to withdraw the advertisement");
491 match outcome {
492 Ok(()) => withdrawn,
493 Err(error) => Err(error),
494 }
495 }
496
497 /// Accepts and serves one connection at a time until the host ends the client.
498 #[allow(clippy::too_many_arguments)]
499 async fn accept_loop(
500 listener: &TcpListener,
501 config: &ClientConfig,
502 path: &str,
503 pairing: Option<PairingPsk>,
504 mut carried: Carried,
505 events: &mpsc::UnboundedSender<Event>,
506 reported_volume: &AtomicU8,
507 shutdown: &mut oneshot::Receiver<GoodbyeReason>,
508 ) -> Result<()> {
509 loop {
510 let Some(stream) =
511 wait_for_connection(listener, &mut carried, events, shutdown).await?
512 else {
513 return Ok(());
514 };
515 // The upgrade answers every request it refuses, so neither a wrong path nor a rejected
516 // `Origin` reaches the protocol. A peer that breaks the upgrade itself - a truncated
517 // request, a hello for another protocol - is equally not a connection, and neither
518 // stops the listener for the servers that follow.
519 let transport = match upgrade(stream, path).await {
520 Ok(Some(transport)) => transport,
521 Ok(None) | Err(_) => continue,
522 };
523
524 // The server-initiated mode admits one server at a time. A second one that arrives
525 // while this session runs is not left in the listen backlog: its handshake is completed
526 // in a task of its own and it is rejected with `concurrent_attempt`, as `connection.md`
527 // requires. The task owns no state of the admitted session, so a slow rejection cannot
528 // hold up playback.
529 let mut rejections = JoinSet::new();
530 let mut attempt = Box::pin(session::attempt(
531 transport,
532 config,
533 events,
534 &[],
535 pairing,
536 reported_volume,
537 carried,
538 shutdown,
539 ));
540 let attempt = loop {
541 tokio::select! {
542 attempt = &mut attempt => break attempt,
543 // Accepting is cancel-safe: a connection that arrives while another branch is
544 // busy waits in the backlog for the next round.
545 accepted = listener.accept() => {
546 let (stream, _address) =
547 accepted.context("failed to accept an inbound connection")?;
548 rejections.spawn(reject_connection(
549 stream,
550 config.clone(),
551 path.to_owned(),
552 pairing,
553 ));
554 }
555 joined = rejections.join_next(), if !rejections.is_empty() => {
556 // A rejection that failed changed nothing: the admitted session is the one
557 // the host hears about.
558 let _ = joined;
559 }
560 }
561 };
562 // A rejection that has not finished belongs to a client that is already ending; it is
563 // dropped with the set, which closes its socket.
564 drop(rejections);
565 carried = attempt.carried;
566
567 // Nothing buffered for the session that ended may become audible later; the flush runs
568 // before the host hears about the drop. A deliberate close is not a drop.
569 let flush_error = carried.sink.flush().err().map(|error| {
570 error.context("the audio sink rejected a flush after the connection ended")
571 });
572 if matches!(&attempt.ending, session::Ending::Shutdown) {
573 return Ok(());
574 }
575 // No attempt follows: the next connection is the server's decision, not the client's,
576 // so there is no delay to recommend.
577 let _ = events.send(Event::Disconnected {
578 reason: attempt.ending.reason(),
579 retry_in: Duration::ZERO,
580 });
581
582 // A broken output cannot be repaired by another connection, and neither can a flush
583 // that fails after the session; both end the client so the host can repair it.
584 if attempt.sink_failed {
585 return match attempt.ending {
586 session::Ending::Failed(error) => Err(error),
587 session::Ending::Closed
588 | session::Ending::Unpaired
589 | session::Ending::PairingRequired
590 | session::Ending::Unauthorized
591 | session::Ending::Shutdown => Err(anyhow!("the audio sink failed")),
592 };
593 }
594 if let Some(error) = flush_error {
595 return Err(error);
596 }
597 }
598 }
599
600 /// Rejects one connection that arrived while another server is admitted.
601 ///
602 /// The upgrade rules are the same as for the admitted connection - the path must match and an
603 /// `Origin` header is refused - because a rejected server learns nothing a browser could use.
604 async fn reject_connection(
605 stream: TcpStream,
606 config: ClientConfig,
607 path: String,
608 pairing: Option<PairingPsk>,
609 ) {
610 let Ok(Some(transport)) = upgrade(stream, &path).await else {
611 return;
612 };
613 let _ = tokio::time::timeout(
614 REJECT_TIMEOUT,
615 session::reject_concurrent(transport, &config, pairing, &[]),
616 )
617 .await;
618 }
619
620 /// Waits for the next inbound connection, answering control requests meanwhile.
621 ///
622 /// Returns `None` when the host ended the client: the handle was closed or the event stream was
623 /// dropped. There is no session to say goodbye on while the listener waits, exactly as in the
624 /// reconnect wait of a dialling client.
625 async fn wait_for_connection(
626 listener: &TcpListener,
627 carried: &mut Carried,
628 events: &mpsc::UnboundedSender<Event>,
629 shutdown: &mut oneshot::Receiver<GoodbyeReason>,
630 ) -> Result<Option<TcpStream>> {
631 loop {
632 if events.is_closed() {
633 return Ok(None);
634 }
635 let control = &mut carried.control;
636 let wakeup = tokio::select! {
637 biased;
638 request = async {
639 match control {
640 Some(receiver) => receiver.recv().await,
641 None => std::future::pending().await,
642 }
643 } => Wakeup::Control(request),
644 // Accepting is cancel-safe: a connection that arrives while this select is busy
645 // waits in the backlog.
646 accepted = listener.accept() => Wakeup::Accepted(accepted),
647 reason = &mut *shutdown => {
648 let _ = reason;
649 return Ok(None);
650 }
651 () = events.closed() => Wakeup::Closed,
652 };
653 match wakeup {
654 Wakeup::Control(Some(request)) => answer_without_session(carried, request),
655 Wakeup::Control(None) => *control = None,
656 Wakeup::Accepted(Ok((stream, _address))) => return Ok(Some(stream)),
657 Wakeup::Accepted(Err(error)) => {
658 return Err(anyhow!(error).context("failed to accept an inbound connection"))
659 }
660 Wakeup::Closed => return Ok(None),
661 }
662 }
663 }
664
665 /// One wake-up while the listener waits for a server.
666 enum Wakeup {
667 /// A control handle sent a request, or every handle was dropped.
668 Control(Option<ControlRequest>),
669 /// The listener accepted a TCP connection.
670 Accepted(std::io::Result<(TcpStream, SocketAddr)>),
671 /// The host dropped the event stream.
672 Closed,
673 }
674
675 /// Serves `stream` if it asks for `path` and carries no `Origin` header.
676 ///
677 /// `Ok(None)` means the request was refused with an HTTP answer and its socket is closed; the
678 /// caller keeps listening.
679 // Error responses are the handshake crate's large `http::Response` type; a rejection happens
680 // once per refused upgrade, so boxing it would buy nothing.
681 #[allow(clippy::result_large_err)]
682 async fn upgrade(stream: TcpStream, path: &str) -> Result<Option<Transport>> {
683 let expected = path.to_owned();
684 let callback = move |request: &Request, response: Response| {
685 // `connection.md`: a client must reject an upgrade that carries an `Origin` header. A
686 // server that dials in knows the address it dialled, so the header can only come from
687 // something acting for a page - which is what the rule exists to refuse.
688 if request.headers().contains_key(ORIGIN) {
689 let mut error = ErrorResponse::new(Some(
690 "a server-initiated Sendspin upgrade must not carry an Origin header"
691 .to_owned(),
692 ));
693 *error.status_mut() = StatusCode::FORBIDDEN;
694 return Err(error);
695 }
696 if request.uri().path() == expected {
697 return Ok(response);
698 }
699 let mut error =
700 ErrorResponse::new(Some("this endpoint is not a Sendspin endpoint".to_owned()));
701 *error.status_mut() = StatusCode::NOT_FOUND;
702 Err(error)
703 };
704 match accept_hdr_async(stream, callback).await {
705 Ok(socket) => Ok(Some(Transport::accept(socket))),
706 // The two answers above: the peer was told why and the socket is closed.
707 Err(WsError::Http(response))
708 if response.status() == StatusCode::FORBIDDEN
709 || response.status() == StatusCode::NOT_FOUND =>
710 {
711 Ok(None)
712 }
713 Err(error) => Err(error).context("the WebSocket upgrade failed"),
714 }
715 }
716}
717
718#[cfg(test)]
719mod tests {
720 use super::*;
721
722 /// A [`Discovery`] that answers from memory, so the record shape is tested without a network.
723 #[derive(Default)]
724 struct MemoryDiscovery {
725 browsed: std::sync::Mutex<Vec<String>>,
726 servers: Vec<DiscoveredServer>,
727 }
728
729 impl Discovery for MemoryDiscovery {
730 fn advertise(&self, _service: ServiceAdvertisement) -> Result<()> {
731 Ok(())
732 }
733
734 fn withdraw(&self, _service_type: &str) -> Result<()> {
735 Ok(())
736 }
737
738 fn browse(&self, service_type: &str) -> Result<Vec<DiscoveredServer>> {
739 self.browsed
740 .lock()
741 .expect("the query list is not poisoned")
742 .push(service_type.to_owned());
743 Ok(self.servers.clone())
744 }
745 }
746
747 /// The record a client publishes carries the three things a server dials with, plus its name.
748 #[test]
749 fn a_client_record_names_the_service_the_port_the_path_and_the_player() {
750 let record = ServiceAdvertisement::client(8928, DEFAULT_SENDSPIN_PATH, "Test player");
751 assert_eq!(record.service_type, CLIENT_SERVICE_TYPE);
752 assert_eq!(record.port, 8928);
753 assert_eq!(record.path, "/sendspin");
754 assert_eq!(record.name.as_deref(), Some("Test player"));
755 assert_ne!(
756 CLIENT_SERVICE_TYPE, SERVER_SERVICE_TYPE,
757 "the two directions use two service types"
758 );
759 }
760
761 /// A discovered record becomes a plain `ws://` endpoint, and nothing else.
762 #[test]
763 fn a_discovered_server_builds_a_plain_ws_endpoint() {
764 let server = DiscoveredServer {
765 addresses: vec!["192.0.2.7:8927".to_owned()],
766 path: "/sendspin".to_owned(),
767 name: Some("A server".to_owned()),
768 };
769 assert_eq!(
770 server.endpoint().as_deref(),
771 Some("ws://192.0.2.7:8927/sendspin"),
772 "connection.md requires plain ws:// to an advertised address"
773 );
774
775 // A record that cannot name an endpoint is refused here rather than guessed at later.
776 for broken in [
777 DiscoveredServer {
778 addresses: Vec::new(),
779 ..server.clone()
780 },
781 DiscoveredServer {
782 path: "sendspin".to_owned(),
783 ..server.clone()
784 },
785 DiscoveredServer {
786 path: "//sendspin".to_owned(),
787 ..server.clone()
788 },
789 DiscoveredServer {
790 addresses: vec!["wss://192.0.2.7:8927".to_owned()],
791 ..server
792 },
793 ] {
794 assert_eq!(
795 broken.endpoint(),
796 None,
797 "a record that does not name a ws:// endpoint is not dialled"
798 );
799 }
800 }
801
802 /// A record with several addresses names the IPv4 ones first, keeping each family's order.
803 #[test]
804 fn a_dual_stack_record_lists_its_ipv4_addresses_first() {
805 let server = DiscoveredServer {
806 addresses: vec![
807 "[fd41::2]:8927".to_owned(),
808 "[fd41::1]:8927".to_owned(),
809 "192.0.2.8:8927".to_owned(),
810 "192.0.2.7:8927".to_owned(),
811 ],
812 path: "/sendspin".to_owned(),
813 name: None,
814 };
815 assert_eq!(
816 server.endpoints(),
817 vec![
818 "ws://192.0.2.8:8927/sendspin".to_owned(),
819 "ws://192.0.2.7:8927/sendspin".to_owned(),
820 "ws://[fd41::2]:8927/sendspin".to_owned(),
821 "ws://[fd41::1]:8927/sendspin".to_owned(),
822 ],
823 "IPv4 comes first and the browser's order within each family is kept"
824 );
825 assert_eq!(
826 server.endpoint().as_deref(),
827 Some("ws://192.0.2.8:8927/sendspin"),
828 "endpoint is the first of the ordered list"
829 );
830 }
831
832 /// An address that refuses does not consume the attempt: the next one is tried at once.
833 #[tokio::test]
834 async fn the_next_address_is_tried_when_the_first_refuses() {
835 // A listener that accepts the probe, so the second address is the one that works.
836 let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
837 .await
838 .expect("the loopback listener binds");
839 let accepting = listener
840 .local_addr()
841 .expect("the bound address is readable");
842 let accept = tokio::spawn(async move {
843 let _ = listener.accept().await;
844 });
845
846 // A port nobody listens on: binding it and dropping the listener makes the connect refuse.
847 let closed = tokio::net::TcpListener::bind("127.0.0.1:0")
848 .await
849 .expect("the second loopback listener binds");
850 let refusing = closed.local_addr().expect("the bound address is readable");
851 drop(closed);
852
853 let discovery = MemoryDiscovery {
854 servers: vec![DiscoveredServer {
855 addresses: vec![refusing.to_string(), accepting.to_string()],
856 path: "/sendspin".to_owned(),
857 name: Some("A server".to_owned()),
858 }],
859 ..MemoryDiscovery::default()
860 };
861 let endpoint = discover_reachable_endpoint(&discovery)
862 .await
863 .expect("the second address accepts");
864 assert_eq!(endpoint, format!("ws://{accepting}/sendspin"));
865 accept.await.expect("the accepting task finishes");
866 }
867
868 /// When every address refuses, the error names all of them instead of only the first.
869 #[tokio::test]
870 async fn an_error_names_every_address_that_refused() {
871 let first_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
872 .await
873 .expect("the first loopback listener binds");
874 let second_listener = tokio::net::TcpListener::bind("127.0.0.1:0")
875 .await
876 .expect("the second loopback listener binds");
877 let first = first_listener
878 .local_addr()
879 .expect("the bound address is readable");
880 let second = second_listener
881 .local_addr()
882 .expect("the bound address is readable");
883 assert_ne!(first, second, "two ephemeral listeners get two ports");
884 // Releasing both makes every connect to them refuse.
885 drop(first_listener);
886 drop(second_listener);
887
888 let discovery = MemoryDiscovery {
889 servers: vec![DiscoveredServer {
890 addresses: vec![first.to_string(), second.to_string()],
891 path: "/sendspin".to_owned(),
892 name: None,
893 }],
894 ..MemoryDiscovery::default()
895 };
896 let Err(error) = discover_reachable_endpoint(&discovery).await else {
897 panic!("both addresses refuse");
898 };
899 let text = format!("{error:#}");
900 assert!(text.contains(&first.to_string()), "got: {text}");
901 assert!(text.contains(&second.to_string()), "got: {text}");
902 }
903
904 /// Browsing always asks for the server service type; the client never looks for clients.
905 #[test]
906 fn browsing_asks_the_backend_for_servers() {
907 let discovery = MemoryDiscovery::default();
908 let servers = discover_servers(&discovery).expect("the backend answers");
909 assert!(servers.is_empty());
910 assert_eq!(
911 discovery
912 .browsed
913 .lock()
914 .expect("the query list is not poisoned")
915 .as_slice(),
916 &[SERVER_SERVICE_TYPE.to_owned()]
917 );
918 }
919}