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