Skip to main content

callback_server/
server.rs

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