callback_server/server.rs
1//! HTTP server for receiving UPnP event notifications.
2
3use axum::body::Bytes;
4use axum::extract::{DefaultBodyLimit, FromRequest, Request, State};
5use axum::http::{header, HeaderMap, StatusCode};
6use axum::response::{IntoResponse, Response};
7use axum::Router;
8use if_addrs::IfAddr;
9use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
10use std::sync::Arc;
11use tokio::sync::mpsc;
12use tracing::{debug, error, info, trace, warn};
13
14use super::router::{EventRouter, NotificationPayload};
15
16/// The only HTTP method this server serves.
17///
18/// UPnP's NOTIFY is not a standard HTTP verb, so it is not in `http::Method`'s set
19/// of constants and axum's `MethodFilter` cannot express it. Comparing
20/// `Method::as_str()` against this constant is the whole gate: no `Method` value is
21/// constructed per request, which is what the old
22/// `Method::from_bytes(b"NOTIFY").unwrap()` did on every single call.
23const NOTIFY_METHOD: &str = "NOTIFY";
24
25/// Maximum accepted size of a UPnP NOTIFY body, in bytes (64 KiB).
26///
27/// The endpoint is unauthenticated by design (UPnP eventing has no auth), so any
28/// host on the LAN can POST to it. Without a limit the whole body is buffered and
29/// then a second full copy is made when it is decoded to a `String` — two
30/// concurrent 1 GB posts would be ~4 GB resident.
31///
32/// Sizing: real Sonos propertysets are ~1-5 KB. The largest realistic case is a
33/// `ZoneGroupTopology` event, whose double-escaped `ZoneGroupState` payload runs
34/// a few hundred bytes per player; at the 32-player household maximum that is
35/// roughly 20-30 KB. 64 KiB leaves ~2x headroom over that worst case and ~10x
36/// over typical events, while capping the cost of a hostile request at 128 KiB
37/// (bytes + string copy) instead of unbounded.
38///
39/// Enforced in two independent places, deliberately. [`declared_content_length`]
40/// refuses on the declared size before a single body byte is read, which is also
41/// what turns a body with no declared size into 411 Length Required rather than a
42/// read of unknown length (chunked bodies; Sonos never sends them).
43/// [`DefaultBodyLimit`] then caps the bytes actually read, so the ceiling holds even
44/// if that header check is later changed or bypassed.
45const MAX_NOTIFY_BODY_BYTES: usize = 64 * 1024;
46
47/// How many bytes of event XML to include in trace-level logs.
48const TRACE_PREVIEW_BYTES: usize = 200;
49
50/// Truncate `s` to at most `max` bytes, snapping back to a UTF-8 char boundary.
51///
52/// Slicing a `&str` at a byte index that falls inside a multi-byte codepoint
53/// panics. Event XML routinely carries non-ASCII track metadata, so a naive
54/// `&s[..max]` in the trace-logging path is a reachable panic.
55fn preview(s: &str, max: usize) -> &str {
56 if s.len() <= max {
57 return s;
58 }
59 let mut end = max;
60 while end > 0 && !s.is_char_boundary(end) {
61 end -= 1;
62 }
63 &s[..end]
64}
65
66/// An IPv4 interface as (address, netmask).
67///
68/// A pair rather than `if_addrs::Interface` so the selection logic below is a pure
69/// function over synthetic data and can be tested without real NICs.
70type Interface = (Ipv4Addr, Ipv4Addr);
71
72/// Enumerate IPv4 interface addresses that could plausibly reach a speaker.
73///
74/// Loopback is excluded because a speaker cannot reach it, link-local
75/// (169.254.0.0/16) because it indicates a failed DHCP lease, and unspecified
76/// because it is not an address.
77///
78/// This mirrors `usable_interfaces()` / `is_usable_ipv4()` in
79/// `sonos-discovery/src/ssdp.rs`. The ~15 lines are duplicated deliberately:
80/// `callback-server` sits *below* `sonos-discovery` in the dependency graph, so
81/// importing the helper from there would invert the layering for the sake of a
82/// filter predicate.
83fn usable_interfaces() -> Vec<Interface> {
84 let addrs = match if_addrs::get_if_addrs() {
85 Ok(addrs) => addrs,
86 Err(e) => {
87 // Surfaces to callers as "no local IP"; this keeps the cause.
88 debug!(error = %e, "failed to enumerate network interfaces");
89 return Vec::new();
90 }
91 };
92
93 let mut interfaces: Vec<Interface> = addrs
94 .into_iter()
95 .filter_map(|iface| match iface.addr {
96 IfAddr::V4(v4) if is_usable_ipv4(&v4.ip) => Some((v4.ip, v4.netmask)),
97 _ => None,
98 })
99 .collect();
100
101 interfaces.sort();
102 interfaces.dedup();
103 interfaces
104}
105
106/// Whether an IPv4 address belongs to an interface that could reach a speaker.
107fn is_usable_ipv4(addr: &Ipv4Addr) -> bool {
108 !addr.is_loopback() && !addr.is_link_local() && !addr.is_unspecified()
109}
110
111/// Prefix length of a netmask, used only to rank specificity.
112fn prefix_len(netmask: Ipv4Addr) -> u32 {
113 u32::from_be_bytes(netmask.octets()).count_ones()
114}
115
116/// Whether `target` falls inside the subnet described by `(addr, netmask)`.
117///
118/// The interface's *actual* netmask is used. Assuming /24 would be wrong on this
119/// project's own test network, which is a single /22 (`192.168.4.0/22`): a speaker
120/// at `192.168.5.19` is directly reachable from an interface at `192.168.4.32`,
121/// but a /24 comparison would call it off-net.
122fn contains(addr: Ipv4Addr, netmask: Ipv4Addr, target: Ipv4Addr) -> bool {
123 let mask = u32::from_be_bytes(netmask.octets());
124 (u32::from_be_bytes(addr.octets()) & mask) == (u32::from_be_bytes(target.octets()) & mask)
125}
126
127/// Pick the local address a speaker at `target` would see us on.
128///
129/// Selects the interface whose subnet actually contains `target`, most specific
130/// prefix first. Returns `None` when no interface is on the target's subnet, which
131/// is the honest answer: we have no address that speaker can reach directly.
132///
133/// A pure function over `(addr, netmask)` pairs so the /22 and VPN cases are
134/// provable offline.
135fn select_interface(interfaces: &[Interface], target: Ipv4Addr) -> Option<Ipv4Addr> {
136 interfaces
137 .iter()
138 .filter(|(addr, netmask)| contains(*addr, *netmask, target))
139 .max_by_key(|(_, netmask)| prefix_len(*netmask))
140 .map(|(addr, _)| *addr)
141}
142
143/// Pick a local address when no target speaker is known yet.
144///
145/// The callback server is constructed before any speaker is registered, so there
146/// is no target to match against; this is the target-less fallback that
147/// [`CallbackServer::base_url`] is built from.
148///
149/// Preference order — RFC 1918 private, then anything else, then CGNAT
150/// (100.64.0.0/10) last. CGNAT is deprioritised because that is where VPN tunnel
151/// interfaces (e.g. Tailscale) live, and a tunnel address is exactly what the old
152/// route-to-8.8.8.8 probe used to return: a plausible-looking address that no
153/// speaker on the LAN can reach. Ties break on address value so the choice is
154/// deterministic across runs.
155fn preferred_local_ip(interfaces: &[Interface]) -> Option<Ipv4Addr> {
156 interfaces
157 .iter()
158 .min_by_key(|(addr, _)| {
159 let class = if is_cgnat(addr) {
160 2
161 } else if addr.is_private() {
162 0
163 } else {
164 1
165 };
166 (class, u32::from_be_bytes(addr.octets()))
167 })
168 .map(|(addr, _)| *addr)
169}
170
171/// Whether an address is in the carrier-grade NAT range (100.64.0.0/10).
172fn is_cgnat(addr: &Ipv4Addr) -> bool {
173 let [a, b, ..] = addr.octets();
174 a == 100 && (64..128).contains(&b)
175}
176
177/// HTTP callback server for receiving UPnP event notifications.
178///
179/// The `CallbackServer` binds to a local port and provides an HTTP endpoint
180/// for receiving UPnP NOTIFY requests. It validates UPnP headers and routes
181/// events through an `EventRouter` to a channel.
182///
183/// # Example
184///
185/// ```no_run
186/// use tokio::sync::mpsc;
187/// use callback_server::{CallbackServer, NotificationPayload};
188///
189/// #[tokio::main]
190/// async fn main() {
191/// let (tx, mut rx) = mpsc::unbounded_channel::<NotificationPayload>();
192///
193/// let server = CallbackServer::new((3400, 3500), tx)
194/// .await
195/// .expect("Failed to create callback server");
196///
197/// println!("Server listening at: {}", server.base_url());
198///
199/// // Process notifications
200/// while let Some(notification) = rx.recv().await {
201/// println!("Received event for subscription: {}", notification.subscription_id);
202/// }
203/// }
204/// ```
205pub struct CallbackServer {
206 /// The port the server is bound to
207 port: u16,
208 /// The base URL for callback registration
209 base_url: String,
210 /// Event router for handling incoming events
211 event_router: Arc<EventRouter>,
212 /// Shutdown signal sender
213 shutdown_tx: Option<mpsc::Sender<()>>,
214 /// Server task handle
215 server_handle: Option<tokio::task::JoinHandle<()>>,
216}
217
218impl CallbackServer {
219 /// Create and start a new unified callback server.
220 ///
221 /// This method creates a single HTTP server that efficiently handles all UPnP
222 /// event notifications from multiple speakers and services. The server:
223 /// - Finds an available port in the specified range
224 /// - Detects the local IP address for callback URLs
225 /// - Starts an HTTP server to receive all UPnP NOTIFY requests
226 /// - Routes events through a unified event router to registered handlers
227 ///
228 /// # Unified Event Stream Processing
229 ///
230 /// The callback server is designed to support the unified event stream processor
231 /// pattern where a single HTTP endpoint receives events from multiple UPnP
232 /// services and speakers, then routes them to appropriate handlers based on
233 /// subscription IDs.
234 ///
235 /// # Arguments
236 ///
237 /// * `port_range` - Range of ports to try binding to (start, end)
238 /// * `event_sender` - Channel for sending notification payloads to the unified processor
239 ///
240 /// # Returns
241 ///
242 /// Returns the callback server instance or an error if no port could be bound
243 /// or the local IP address could not be detected.
244 ///
245 /// # Example
246 ///
247 /// ```no_run
248 /// # use tokio::sync::mpsc;
249 /// # use callback_server::{CallbackServer, NotificationPayload};
250 /// # #[tokio::main]
251 /// # async fn main() {
252 /// let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
253 /// let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
254 /// println!("Unified callback server listening at: {}", server.base_url());
255 /// # }
256 /// ```
257 pub async fn new(
258 port_range: (u16, u16),
259 event_sender: mpsc::UnboundedSender<NotificationPayload>,
260 ) -> Result<Self, String> {
261 // Find an available port in the range
262 let port = Self::find_available_port(port_range.0, port_range.1).ok_or_else(|| {
263 format!(
264 "No available port found in range {}-{}",
265 port_range.0, port_range.1
266 )
267 })?;
268
269 // Detect the local IP address speakers should call back to.
270 let local_ip = Self::detect_local_ip()
271 .ok_or_else(|| "Failed to detect local IP address".to_string())?;
272
273 let base_url = format!("http://{local_ip}:{port}");
274
275 // Create event router
276 let event_router = Arc::new(EventRouter::new(event_sender));
277
278 // Create shutdown channel
279 let (shutdown_tx, shutdown_rx) = mpsc::channel::<()>(1);
280
281 // Create ready signal channel
282 let (ready_tx, mut ready_rx) = mpsc::channel::<()>(1);
283
284 // Start the HTTP server
285 let server_handle = Self::start_server(port, event_router.clone(), shutdown_rx, ready_tx);
286
287 // Wait for server to be ready
288 ready_rx
289 .recv()
290 .await
291 .ok_or_else(|| "Server failed to start".to_string())?;
292
293 Ok(Self {
294 port,
295 base_url,
296 event_router,
297 shutdown_tx: Some(shutdown_tx),
298 server_handle: Some(server_handle),
299 })
300 }
301
302 /// Get the unified callback URL for subscription registration.
303 ///
304 /// This URL should be used when subscribing to UPnP events from any speaker
305 /// or service. The unified callback server will route all incoming events
306 /// based on their subscription IDs to the appropriate handlers.
307 ///
308 /// The format is `http://<local_ip>:<port>` and this same URL is used for
309 /// all subscriptions, enabling the unified event stream processing pattern.
310 ///
311 /// # Example
312 ///
313 /// ```no_run
314 /// # use tokio::sync::mpsc;
315 /// # use callback_server::{CallbackServer, NotificationPayload};
316 /// # #[tokio::main]
317 /// # async fn main() {
318 /// # let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
319 /// # let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
320 /// let callback_url = server.base_url();
321 /// println!("Use this URL for all subscriptions: {}", callback_url);
322 /// # }
323 /// ```
324 pub fn base_url(&self) -> &str {
325 &self.base_url
326 }
327
328 /// Get the port the server is bound to.
329 pub fn port(&self) -> u16 {
330 self.port
331 }
332
333 /// Get a reference to the event router.
334 ///
335 /// The router can be used to register and unregister subscription IDs
336 /// for event routing.
337 ///
338 /// # Example
339 ///
340 /// ```no_run
341 /// # use tokio::sync::mpsc;
342 /// # use callback_server::{CallbackServer, NotificationPayload};
343 /// # #[tokio::main]
344 /// # async fn main() {
345 /// # let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
346 /// # let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
347 /// server.router().register("uuid:subscription-123".to_string()).await;
348 /// # }
349 /// ```
350 pub fn router(&self) -> &Arc<EventRouter> {
351 &self.event_router
352 }
353
354 /// Shutdown the callback server gracefully.
355 ///
356 /// Sends a shutdown signal to the HTTP server and waits for it to complete
357 /// any in-flight requests.
358 ///
359 /// # Example
360 ///
361 /// ```no_run
362 /// # use tokio::sync::mpsc;
363 /// # use callback_server::{CallbackServer, NotificationPayload};
364 /// # #[tokio::main]
365 /// # async fn main() {
366 /// # let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
367 /// # let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
368 /// server.shutdown().await.unwrap();
369 /// # }
370 /// ```
371 pub async fn shutdown(mut self) -> Result<(), String> {
372 // Send shutdown signal to HTTP server
373 if let Some(tx) = self.shutdown_tx.take() {
374 let _ = tx.send(()).await;
375 }
376
377 // Wait for server task to complete
378 if let Some(handle) = self.server_handle.take() {
379 let _ = handle.await;
380 }
381
382 Ok(())
383 }
384
385 /// Find an available port in the given range.
386 fn find_available_port(start: u16, end: u16) -> Option<u16> {
387 (start..=end).find(|&port| Self::is_port_available(port))
388 }
389
390 /// Check if a port is available for binding.
391 fn is_port_available(port: u16) -> bool {
392 TcpListener::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port)).is_ok()
393 }
394
395 /// Detect the local IP address to advertise in callback URLs.
396 ///
397 /// Enumerates usable IPv4 interfaces and picks one via [`preferred_local_ip`].
398 ///
399 /// This replaces a "connect a UDP socket to 8.8.8.8 and read back the local
400 /// address" probe, which reported whichever interface won the *default route*.
401 /// With a VPN up that is the tunnel, so the callback URL advertised a tunnel
402 /// address no speaker could reach — every event was then silently lost and
403 /// misreported as a firewall block.
404 fn detect_local_ip() -> Option<Ipv4Addr> {
405 preferred_local_ip(&usable_interfaces())
406 }
407
408 /// The local address a speaker at `speaker_ip` would see us on, if any.
409 ///
410 /// Selects the interface whose subnet actually contains `speaker_ip`, using
411 /// that interface's real netmask. Exposed so callers can tell whether
412 /// [`Self::base_url`] is genuinely reachable from a given speaker; see the
413 /// single-`base_url` limitation in `docs/specs/callback-server.md` §14.1.
414 pub fn local_ip_for_speaker(speaker_ip: Ipv4Addr) -> Option<Ipv4Addr> {
415 select_interface(&usable_interfaces(), speaker_ip)
416 }
417
418 /// Start the HTTP server on the given port.
419 fn start_server(
420 port: u16,
421 event_router: Arc<EventRouter>,
422 mut shutdown_rx: mpsc::Receiver<()>,
423 ready_tx: mpsc::Sender<()>,
424 ) -> tokio::task::JoinHandle<()> {
425 tokio::spawn(async move {
426 // One catch-all endpoint: any path, method gated to NOTIFY inside the
427 // `NotifyRequest` extractor. `fallback` is what makes the path
428 // arbitrary — the SID header, not the URL, is the routing key.
429 let app = Router::new()
430 .fallback(handle_notify)
431 // Caps the bytes actually read, independently of the declared
432 // Content-Length check. See MAX_NOTIFY_BODY_BYTES.
433 .layer(DefaultBodyLimit::max(MAX_NOTIFY_BODY_BYTES))
434 .with_state(event_router);
435
436 let listener = match tokio::net::TcpListener::bind(SocketAddr::new(
437 IpAddr::V4(Ipv4Addr::UNSPECIFIED),
438 port,
439 ))
440 .await
441 {
442 Ok(listener) => listener,
443 Err(e) => {
444 // `ready_tx` drops here, so `new()` reports "Server failed to
445 // start" rather than handing back a server nothing can reach.
446 error!(port, error = %e, "callback server failed to bind");
447 return;
448 }
449 };
450
451 info!(
452 address = ?listener.local_addr(),
453 "callback server listening for UPnP events"
454 );
455 // The socket is accepting as soon as `bind` returns, so signalling here
456 // means callers can subscribe knowing events have somewhere to land.
457 let _ = ready_tx.send(()).await;
458
459 if let Err(e) = axum::serve(listener, app)
460 .with_graceful_shutdown(async move {
461 shutdown_rx.recv().await;
462 })
463 .await
464 {
465 error!(error = %e, "callback server stopped with an error");
466 }
467 })
468 }
469
470 /// Validate UPnP event notification headers.
471 ///
472 /// SID is required — without it an event cannot be routed. NT and NTS are
473 /// optional (some devices omit them) but each is checked **independently** when
474 /// present: the previous `if let (Some(nt), Some(nts))` form meant a request
475 /// carrying only one of the two skipped validation entirely.
476 fn validate_upnp_headers(sid: Option<&str>, nt: Option<&str>, nts: Option<&str>) -> bool {
477 // SID header is required for event notifications
478 if sid.is_none() {
479 return false;
480 }
481
482 if nt.is_some_and(|nt| nt != "upnp:event") {
483 return false;
484 }
485
486 if nts.is_some_and(|nts| nts != "upnp:propchange") {
487 return false;
488 }
489
490 true
491 }
492}
493
494/// A NOTIFY request that has passed every gate: NOTIFY-only method, declared and
495/// actual body size within [`MAX_NOTIFY_BODY_BYTES`], and valid SID/NT/NTS.
496///
497/// Expressed as an extractor so the checks run before the handler body, and so each
498/// failure carries its own status via [`IntoResponse`] rather than needing a
499/// separate error-to-status mapping table.
500struct NotifyRequest {
501 /// Value of the SID header; the routing key.
502 subscription_id: String,
503 /// Raw request body, at most [`MAX_NOTIFY_BODY_BYTES`].
504 body: Bytes,
505}
506
507/// Why a request was not a servable NOTIFY. Each variant carries the status a
508/// malformed request has always received (404/411/413/400).
509enum NotifyRejection {
510 /// Not a NOTIFY request at all.
511 NotNotify,
512 /// No usable `Content-Length`, so the body cannot be bounded before reading it.
513 LengthRequired,
514 /// `Content-Length` declares more than [`MAX_NOTIFY_BODY_BYTES`]; carries the
515 /// declared length.
516 BodyTooLarge(u64),
517 /// The body could not be buffered — over the limit while reading, or the
518 /// connection failed part-way through.
519 UnreadableBody(axum::extract::rejection::BytesRejection),
520 /// Missing SID, or an NT/NTS that is present with the wrong value.
521 InvalidUpnpHeaders,
522}
523
524impl IntoResponse for NotifyRejection {
525 fn into_response(self) -> Response {
526 match self {
527 // 404, as before: the speaker asked for something this server does not
528 // serve. Deliberately not 405, which would advertise the NOTIFY verb.
529 Self::NotNotify => (StatusCode::NOT_FOUND, "Subscription not found").into_response(),
530 // Sonos always sends Content-Length; a missing one means we cannot
531 // bound the body before reading it, so refuse.
532 Self::LengthRequired => (
533 StatusCode::LENGTH_REQUIRED,
534 "Content-Length header is required",
535 )
536 .into_response(),
537 // Warn, not debug: if a speaker sent this, a real event was lost.
538 Self::BodyTooLarge(declared_bytes) => {
539 warn!(
540 declared_bytes,
541 limit_bytes = MAX_NOTIFY_BODY_BYTES,
542 "rejected NOTIFY body exceeding size limit"
543 );
544 (StatusCode::PAYLOAD_TOO_LARGE, "NOTIFY body too large").into_response()
545 }
546 // 413 when the read hit the limit, 400 otherwise — axum's own mapping.
547 Self::UnreadableBody(rejection) => {
548 debug!(
549 limit_bytes = MAX_NOTIFY_BODY_BYTES,
550 status = %rejection.status(),
551 error = %rejection,
552 "could not buffer NOTIFY body"
553 );
554 rejection.into_response()
555 }
556 Self::InvalidUpnpHeaders => {
557 (StatusCode::BAD_REQUEST, "Invalid UPnP headers").into_response()
558 }
559 }
560 }
561}
562
563impl<S> FromRequest<S> for NotifyRequest
564where
565 S: Send + Sync,
566{
567 type Rejection = NotifyRejection;
568
569 async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> {
570 // Only NOTIFY is served. This gate runs *before* anything looks at the
571 // body so that ordinary bodiless requests (e.g. a browser GET) still get
572 // 404 rather than 411 Length Required.
573 if req.method().as_str() != NOTIFY_METHOD {
574 return Err(NotifyRejection::NotNotify);
575 }
576
577 // Reject on the declared length before reading a single byte.
578 let content_length = declared_content_length(req.headers())?;
579
580 // Owned copies because reading the body below consumes the request. Three
581 // short strings, and only for requests that already passed the method gate.
582 let path = req.uri().path().to_owned();
583 let sid = upnp_header(req.headers(), "sid")?;
584 let nt = upnp_header(req.headers(), "nt")?;
585 let nts = upnp_header(req.headers(), "nts")?;
586
587 let body = Bytes::from_request(req, state)
588 .await
589 .map_err(NotifyRejection::UnreadableBody)?;
590
591 trace!(
592 method = NOTIFY_METHOD,
593 path = %path,
594 content_length,
595 body_size = body.len(),
596 sid = ?sid,
597 nt = ?nt,
598 nts = ?nts,
599 "received UPnP NOTIFY"
600 );
601
602 // Validate UPnP headers *before* decoding the body to a `String`, so junk
603 // requests never pay for that second full allocation.
604 if !CallbackServer::validate_upnp_headers(sid.as_deref(), nt.as_deref(), nts.as_deref()) {
605 // Remote input the server answers with 400; not a local failure.
606 debug!(
607 sid = ?sid,
608 nt = ?nt,
609 nts = ?nts,
610 "rejected NOTIFY with invalid UPnP headers"
611 );
612 return Err(NotifyRejection::InvalidUpnpHeaders);
613 }
614
615 // Guaranteed present by the validation above.
616 let subscription_id = sid.ok_or_else(|| {
617 debug!("rejected NOTIFY without a SID header");
618 NotifyRejection::InvalidUpnpHeaders
619 })?;
620
621 Ok(Self {
622 subscription_id,
623 body,
624 })
625 }
626}
627
628/// The declared body size, refusing requests we cannot bound up front.
629///
630/// A missing or unparseable `Content-Length` yields 411 rather than being treated
631/// as zero: a chunked body declares no size at all, and real Sonos devices always
632/// send the header (see `docs/specs/callback-server.md` §14.1).
633fn declared_content_length(headers: &HeaderMap) -> Result<u64, NotifyRejection> {
634 let length = headers
635 .get(header::CONTENT_LENGTH)
636 .and_then(|value| value.to_str().ok())
637 .and_then(|value| value.parse::<u64>().ok())
638 .ok_or(NotifyRejection::LengthRequired)?;
639
640 if length > MAX_NOTIFY_BODY_BYTES as u64 {
641 return Err(NotifyRejection::BodyTooLarge(length));
642 }
643
644 Ok(length)
645}
646
647/// Read a UPnP header as text. Absent is `None`; present-but-not-UTF-8 is invalid.
648///
649/// A non-UTF-8 value previously fell through to an unhandled rejection and became a
650/// 500. None of these three headers can be valid without being text, so 400 is the
651/// honest answer.
652fn upnp_header(headers: &HeaderMap, name: &str) -> Result<Option<String>, NotifyRejection> {
653 match headers.get(name) {
654 None => Ok(None),
655 Some(value) => match value.to_str() {
656 Ok(value) => Ok(Some(value.to_owned())),
657 Err(_) => Err(NotifyRejection::InvalidUpnpHeaders),
658 },
659 }
660}
661
662/// Handle a validated UPnP NOTIFY: decode, log, route.
663///
664/// Always answers 200 OK. The event is either delivered immediately (registered
665/// SID) or buffered for replay; returning 404 could cause the speaker to cancel the
666/// subscription.
667async fn handle_notify(
668 State(router): State<Arc<EventRouter>>,
669 notify: NotifyRequest,
670) -> StatusCode {
671 let NotifyRequest {
672 subscription_id,
673 body,
674 } = notify;
675
676 // Second full copy of the body; bounded by MAX_NOTIFY_BODY_BYTES.
677 let event_xml = String::from_utf8_lossy(&body).to_string();
678 if event_xml.len() > TRACE_PREVIEW_BYTES {
679 trace!(
680 event_xml_preview = %preview(&event_xml, TRACE_PREVIEW_BYTES),
681 total_length = event_xml.len(),
682 "UPnP event XML content (truncated)"
683 );
684 } else {
685 trace!(event_xml = %event_xml, "UPnP event XML content (full)");
686 }
687
688 router.route_event(subscription_id.clone(), event_xml).await;
689
690 debug!(subscription_id = %subscription_id, "UPnP event accepted");
691 StatusCode::OK
692}
693
694#[cfg(test)]
695mod tests {
696 use super::*;
697
698 #[test]
699 fn test_is_port_available() {
700 // Port 0 should always be available (OS assigns a free port)
701 assert!(CallbackServer::is_port_available(0));
702
703 // Bind to a port and verify it's no longer available
704 let _listener = TcpListener::bind("0.0.0.0:0").unwrap();
705 let port = _listener.local_addr().unwrap().port();
706 // While the listener is held, the port should not be available
707 assert!(!CallbackServer::is_port_available(port));
708 // Keep listener alive for the assertion
709 drop(_listener);
710 }
711
712 /// A port range the OS just told us is free.
713 ///
714 /// Tests used to hardcode 50000-50100. Two concurrent `cargo test --workspace`
715 /// runs then raced for the same ports and one failed with "Address already in
716 /// use" — separate `CARGO_TARGET_DIR`s do not help, because the contended
717 /// resource is the host's port space. Asking the OS for an ephemeral port and
718 /// releasing it narrows the race to the microseconds between drop and rebind.
719 fn free_port_range() -> (u16, u16) {
720 let listener = TcpListener::bind("0.0.0.0:0").unwrap();
721 let port = listener.local_addr().unwrap().port();
722 drop(listener);
723 (port, port)
724 }
725
726 #[test]
727 fn test_find_available_port() {
728 // A range whose only port is held is exhausted; the same range is usable
729 // once the holder releases it.
730 let listener = TcpListener::bind("0.0.0.0:0").unwrap();
731 let port = listener.local_addr().unwrap().port();
732 assert_eq!(CallbackServer::find_available_port(port, port), None);
733 drop(listener);
734 assert_eq!(CallbackServer::find_available_port(port, port), Some(port));
735 }
736
737 #[test]
738 fn test_detect_local_ip() {
739 let ip = CallbackServer::detect_local_ip();
740 assert!(ip.is_some());
741
742 // Should not be localhost
743 if let Some(addr) = ip {
744 assert_ne!(addr, Ipv4Addr::new(127, 0, 0, 1));
745 }
746 }
747
748 /// The real network this SDK is developed against is a single **/22**
749 /// (`192.168.4.0/22`, netmask `255.255.252.0`), not two /24s: speakers sit on
750 /// both `192.168.4.x` and `192.168.5.x` and are all directly reachable from
751 /// the one interface at `192.168.4.32`.
752 ///
753 /// An implementation that assumed /24 would decide `192.168.5.19` is off-net
754 /// and either refuse to subscribe or advertise a wrong callback address. This
755 /// test fails under such an implementation, which is the point of it.
756 #[test]
757 fn test_selects_interface_across_22_subnet() {
758 let lan = (
759 Ipv4Addr::new(192, 168, 4, 32),
760 Ipv4Addr::new(255, 255, 252, 0),
761 );
762
763 // A speaker in the *upper* half of the /22, outside a naive /24 read.
764 assert_eq!(
765 select_interface(&[lan], Ipv4Addr::new(192, 168, 5, 19)),
766 Some(Ipv4Addr::new(192, 168, 4, 32))
767 );
768 // And one in the same /24, which both readings get right.
769 assert_eq!(
770 select_interface(&[lan], Ipv4Addr::new(192, 168, 4, 20)),
771 Some(Ipv4Addr::new(192, 168, 4, 32))
772 );
773 // Just past the /22 boundary is genuinely off-net.
774 assert_eq!(
775 select_interface(&[lan], Ipv4Addr::new(192, 168, 8, 1)),
776 None
777 );
778 }
779
780 #[test]
781 fn test_selects_interface_on_target_subnet() {
782 let interfaces = [
783 (Ipv4Addr::new(10, 0, 0, 5), Ipv4Addr::new(255, 255, 255, 0)),
784 (
785 Ipv4Addr::new(192, 168, 4, 32),
786 Ipv4Addr::new(255, 255, 252, 0),
787 ),
788 (
789 Ipv4Addr::new(172, 16, 3, 9),
790 Ipv4Addr::new(255, 255, 255, 0),
791 ),
792 ];
793
794 // Each target picks the interface sharing its subnet, not merely the first.
795 assert_eq!(
796 select_interface(&interfaces, Ipv4Addr::new(192, 168, 5, 19)),
797 Some(Ipv4Addr::new(192, 168, 4, 32))
798 );
799 assert_eq!(
800 select_interface(&interfaces, Ipv4Addr::new(10, 0, 0, 200)),
801 Some(Ipv4Addr::new(10, 0, 0, 5))
802 );
803 // Overlapping subnets resolve to the more specific prefix.
804 let overlapping = [
805 (
806 Ipv4Addr::new(192, 168, 4, 32),
807 Ipv4Addr::new(255, 255, 0, 0),
808 ),
809 (
810 Ipv4Addr::new(192, 168, 5, 7),
811 Ipv4Addr::new(255, 255, 255, 0),
812 ),
813 ];
814 assert_eq!(
815 select_interface(&overlapping, Ipv4Addr::new(192, 168, 5, 19)),
816 Some(Ipv4Addr::new(192, 168, 5, 7))
817 );
818 }
819
820 /// A live Tailscale/VPN tunnel is what made the old route-to-8.8.8.8 probe
821 /// dangerous: the tunnel wins the default route, so the callback URL advertised
822 /// a CGNAT address unreachable from the LAN and every event vanished.
823 #[test]
824 fn test_tunnel_interface_not_chosen_for_lan_target() {
825 let interfaces = [
826 // Tailscale CGNAT /32 — sorts first numerically, so ordering alone
827 // would pick it.
828 (
829 Ipv4Addr::new(100, 78, 222, 31),
830 Ipv4Addr::new(255, 255, 255, 255),
831 ),
832 (
833 Ipv4Addr::new(192, 168, 4, 32),
834 Ipv4Addr::new(255, 255, 252, 0),
835 ),
836 ];
837
838 // Subnet containment rules the tunnel out for a LAN speaker.
839 assert_eq!(
840 select_interface(&interfaces, Ipv4Addr::new(192, 168, 5, 19)),
841 Some(Ipv4Addr::new(192, 168, 4, 32))
842 );
843 // And the target-less fallback deprioritises CGNAT too, since base_url is
844 // built before any speaker is known.
845 assert_eq!(
846 preferred_local_ip(&interfaces),
847 Some(Ipv4Addr::new(192, 168, 4, 32))
848 );
849 }
850
851 #[test]
852 fn test_unusable_addresses_are_filtered() {
853 assert!(is_usable_ipv4(&Ipv4Addr::new(192, 168, 4, 32)));
854 assert!(!is_usable_ipv4(&Ipv4Addr::LOCALHOST));
855 assert!(!is_usable_ipv4(&Ipv4Addr::UNSPECIFIED));
856 // Link-local means DHCP failed; it cannot reach a speaker.
857 assert!(!is_usable_ipv4(&Ipv4Addr::new(169, 254, 1, 1)));
858 }
859
860 #[test]
861 fn test_validate_upnp_headers() {
862 // Valid headers with NT and NTS
863 assert!(CallbackServer::validate_upnp_headers(
864 Some("uuid:123"),
865 Some("upnp:event"),
866 Some("upnp:propchange"),
867 ));
868
869 // Valid headers without NT and NTS (event notification)
870 assert!(CallbackServer::validate_upnp_headers(
871 Some("uuid:123"),
872 None,
873 None
874 ));
875
876 // Invalid: missing SID
877 assert!(!CallbackServer::validate_upnp_headers(
878 None,
879 Some("upnp:event"),
880 Some("upnp:propchange"),
881 ));
882
883 // Invalid: wrong NT value
884 assert!(!CallbackServer::validate_upnp_headers(
885 Some("uuid:123"),
886 Some("wrong"),
887 Some("upnp:propchange"),
888 ));
889
890 // Invalid: wrong NTS value
891 assert!(!CallbackServer::validate_upnp_headers(
892 Some("uuid:123"),
893 Some("upnp:event"),
894 Some("wrong"),
895 ));
896 }
897
898 /// NT and NTS used to be checked inside `if let (Some(nt), Some(nts))`, so a
899 /// request carrying only one of the two bypassed validation entirely: a bogus
900 /// `NT` with no `NTS` was accepted. Each header is now checked independently.
901 #[test]
902 fn test_validate_upnp_headers_checks_nt_and_nts_independently() {
903 // A single valid header on its own is still fine.
904 assert!(CallbackServer::validate_upnp_headers(
905 Some("uuid:123"),
906 Some("upnp:event"),
907 None
908 ));
909 assert!(CallbackServer::validate_upnp_headers(
910 Some("uuid:123"),
911 None,
912 Some("upnp:propchange"),
913 ));
914
915 // A single *invalid* header on its own is now rejected; both of these
916 // returned true before the fix.
917 assert!(!CallbackServer::validate_upnp_headers(
918 Some("uuid:123"),
919 Some("upnp:not-an-event"),
920 None,
921 ));
922 assert!(!CallbackServer::validate_upnp_headers(
923 Some("uuid:123"),
924 None,
925 Some("upnp:not-a-propchange"),
926 ));
927 }
928
929 /// Slicing event XML at a fixed byte offset panics when that offset lands
930 /// inside a multi-byte codepoint — very reachable for non-Latin track titles.
931 #[test]
932 fn test_event_xml_preview_handles_multibyte_boundary() {
933 // 198 ASCII bytes + a 3-byte codepoint occupying bytes 198..201, so byte
934 // index 200 is *not* a char boundary.
935 let xml = format!("{}日本語", "a".repeat(198));
936 assert!(!xml.is_char_boundary(TRACE_PREVIEW_BYTES));
937
938 let out = preview(&xml, TRACE_PREVIEW_BYTES);
939
940 // Snapped back to the boundary at 198, still valid UTF-8, still a prefix.
941 assert_eq!(out.len(), 198);
942 assert!(xml.starts_with(out));
943 assert!(std::str::from_utf8(out.as_bytes()).is_ok());
944 }
945
946 #[test]
947 fn test_event_xml_preview_short_and_exact_inputs() {
948 // Shorter than the limit is returned whole.
949 assert_eq!(preview("<event/>", TRACE_PREVIEW_BYTES), "<event/>");
950 // Exactly at the limit is returned whole.
951 let exact = "a".repeat(TRACE_PREVIEW_BYTES);
952 assert_eq!(
953 preview(&exact, TRACE_PREVIEW_BYTES).len(),
954 TRACE_PREVIEW_BYTES
955 );
956 // A single wide codepoint over the limit truncates to empty, not a panic.
957 assert_eq!(preview("日", 1), "");
958 }
959
960 #[tokio::test]
961 async fn test_callback_server_creation() {
962 let (tx, _rx) = mpsc::unbounded_channel();
963
964 let range = free_port_range();
965 let server = CallbackServer::new(range, tx).await;
966 assert!(server.is_ok());
967
968 let server = server.unwrap();
969 assert_eq!(server.port(), range.0);
970 assert!(server.base_url().contains(&server.port().to_string()));
971 // The advertised host is a real interface address, not a route probe result.
972 assert!(server.base_url().starts_with("http://"));
973
974 // Cleanup
975 server.shutdown().await.unwrap();
976 }
977
978 #[tokio::test]
979 async fn test_callback_server_register_unregister() {
980 let (tx, _rx) = mpsc::unbounded_channel();
981 let server = CallbackServer::new(free_port_range(), tx).await.unwrap();
982
983 let sub_id = "test-sub-123".to_string();
984
985 // Register subscription via router
986 server.router().register(sub_id.clone()).await;
987
988 // Unregister subscription via router
989 server.router().unregister(&sub_id).await;
990
991 // Plugin system has been removed
992
993 // Cleanup
994 server.shutdown().await.unwrap();
995 }
996}