Skip to main content

callback_server/
server.rs

1//! HTTP server for receiving UPnP event notifications.
2
3use std::net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener};
4use std::sync::Arc;
5use tokio::sync::mpsc;
6use tracing::{debug, error, info, trace};
7use warp::Filter;
8
9use super::router::{EventRouter, NotificationPayload};
10
11/// HTTP callback server for receiving UPnP event notifications.
12///
13/// The `CallbackServer` binds to a local port and provides an HTTP endpoint
14/// for receiving UPnP NOTIFY requests. It validates UPnP headers and routes
15/// events through an `EventRouter` to a channel.
16///
17/// # Example
18///
19/// ```no_run
20/// use tokio::sync::mpsc;
21/// use callback_server::{CallbackServer, NotificationPayload};
22///
23/// #[tokio::main]
24/// async fn main() {
25///     let (tx, mut rx) = mpsc::unbounded_channel::<NotificationPayload>();
26///     
27///     let server = CallbackServer::new((3400, 3500), tx)
28///         .await
29///         .expect("Failed to create callback server");
30///     
31///     println!("Server listening at: {}", server.base_url());
32///     
33///     // Process notifications
34///     while let Some(notification) = rx.recv().await {
35///         println!("Received event for subscription: {}", notification.subscription_id);
36///     }
37/// }
38/// ```
39pub struct CallbackServer {
40    /// The port the server is bound to
41    port: u16,
42    /// The base URL for callback registration
43    base_url: String,
44    /// Event router for handling incoming events
45    event_router: Arc<EventRouter>,
46    /// Shutdown signal sender
47    shutdown_tx: Option<mpsc::Sender<()>>,
48    /// Server task handle
49    server_handle: Option<tokio::task::JoinHandle<()>>,
50}
51
52impl CallbackServer {
53    /// Create and start a new unified callback server.
54    ///
55    /// This method creates a single HTTP server that efficiently handles all UPnP
56    /// event notifications from multiple speakers and services. The server:
57    /// - Finds an available port in the specified range
58    /// - Detects the local IP address for callback URLs
59    /// - Starts an HTTP server to receive all UPnP NOTIFY requests
60    /// - Routes events through a unified event router to registered handlers
61    ///
62    /// # Unified Event Stream Processing
63    ///
64    /// The callback server is designed to support the unified event stream processor
65    /// pattern where a single HTTP endpoint receives events from multiple UPnP
66    /// services and speakers, then routes them to appropriate handlers based on
67    /// subscription IDs.
68    ///
69    /// # Arguments
70    ///
71    /// * `port_range` - Range of ports to try binding to (start, end)
72    /// * `event_sender` - Channel for sending notification payloads to the unified processor
73    ///
74    /// # Returns
75    ///
76    /// Returns the callback server instance or an error if no port could be bound
77    /// or the local IP address could not be detected.
78    ///
79    /// # Example
80    ///
81    /// ```no_run
82    /// # use tokio::sync::mpsc;
83    /// # use callback_server::{CallbackServer, NotificationPayload};
84    /// # #[tokio::main]
85    /// # async fn main() {
86    /// let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
87    /// let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
88    /// println!("Unified callback server listening at: {}", server.base_url());
89    /// # }
90    /// ```
91    pub async fn new(
92        port_range: (u16, u16),
93        event_sender: mpsc::UnboundedSender<NotificationPayload>,
94    ) -> Result<Self, String> {
95        // Find an available port in the range
96        let port = Self::find_available_port(port_range.0, port_range.1).ok_or_else(|| {
97            format!(
98                "No available port found in range {}-{}",
99                port_range.0, port_range.1
100            )
101        })?;
102
103        // Detect local IP address
104        let local_ip = Self::detect_local_ip()
105            .ok_or_else(|| "Failed to detect local IP address".to_string())?;
106
107        let base_url = format!("http://{local_ip}:{port}");
108
109        // Create event router
110        let event_router = Arc::new(EventRouter::new(event_sender));
111
112        // Create shutdown channel
113        let (shutdown_tx, shutdown_rx) = mpsc::channel::<()>(1);
114
115        // Create ready signal channel
116        let (ready_tx, mut ready_rx) = mpsc::channel::<()>(1);
117
118        // Start the HTTP server
119        let server_handle = Self::start_server(port, event_router.clone(), shutdown_rx, ready_tx);
120
121        // Wait for server to be ready
122        ready_rx
123            .recv()
124            .await
125            .ok_or_else(|| "Server failed to start".to_string())?;
126
127        Ok(Self {
128            port,
129            base_url,
130            event_router,
131            shutdown_tx: Some(shutdown_tx),
132            server_handle: Some(server_handle),
133        })
134    }
135
136    /// Get the unified callback URL for subscription registration.
137    ///
138    /// This URL should be used when subscribing to UPnP events from any speaker
139    /// or service. The unified callback server will route all incoming events
140    /// based on their subscription IDs to the appropriate handlers.
141    ///
142    /// The format is `http://<local_ip>:<port>` and this same URL is used for
143    /// all subscriptions, enabling the unified event stream processing pattern.
144    ///
145    /// # Example
146    ///
147    /// ```no_run
148    /// # use tokio::sync::mpsc;
149    /// # use callback_server::{CallbackServer, NotificationPayload};
150    /// # #[tokio::main]
151    /// # async fn main() {
152    /// # let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
153    /// # let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
154    /// let callback_url = server.base_url();
155    /// println!("Use this URL for all subscriptions: {}", callback_url);
156    /// # }
157    /// ```
158    pub fn base_url(&self) -> &str {
159        &self.base_url
160    }
161
162    /// Get the port the server is bound to.
163    pub fn port(&self) -> u16 {
164        self.port
165    }
166
167    /// Get a reference to the event router.
168    ///
169    /// The router can be used to register and unregister subscription IDs
170    /// for event routing.
171    ///
172    /// # Example
173    ///
174    /// ```no_run
175    /// # use tokio::sync::mpsc;
176    /// # use callback_server::{CallbackServer, NotificationPayload};
177    /// # #[tokio::main]
178    /// # async fn main() {
179    /// # let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
180    /// # let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
181    /// server.router().register("uuid:subscription-123".to_string()).await;
182    /// # }
183    /// ```
184    pub fn router(&self) -> &Arc<EventRouter> {
185        &self.event_router
186    }
187
188    /// Shutdown the callback server gracefully.
189    ///
190    /// Sends a shutdown signal to the HTTP server and waits for it to complete
191    /// any in-flight requests.
192    ///
193    /// # Example
194    ///
195    /// ```no_run
196    /// # use tokio::sync::mpsc;
197    /// # use callback_server::{CallbackServer, NotificationPayload};
198    /// # #[tokio::main]
199    /// # async fn main() {
200    /// # let (tx, _rx) = mpsc::unbounded_channel::<NotificationPayload>();
201    /// # let server = CallbackServer::new((3400, 3500), tx).await.unwrap();
202    /// server.shutdown().await.unwrap();
203    /// # }
204    /// ```
205    pub async fn shutdown(mut self) -> Result<(), String> {
206        // Send shutdown signal to HTTP server
207        if let Some(tx) = self.shutdown_tx.take() {
208            let _ = tx.send(()).await;
209        }
210
211        // Wait for server task to complete
212        if let Some(handle) = self.server_handle.take() {
213            let _ = handle.await;
214        }
215
216        Ok(())
217    }
218
219    /// Find an available port in the given range.
220    fn find_available_port(start: u16, end: u16) -> Option<u16> {
221        (start..=end).find(|&port| Self::is_port_available(port))
222    }
223
224    /// Check if a port is available for binding.
225    fn is_port_available(port: u16) -> bool {
226        TcpListener::bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port)).is_ok()
227    }
228
229    /// Detect the local IP address for callback URLs.
230    ///
231    /// This uses a UDP socket connection to determine the local IP address
232    /// that would be used for outbound connections. No data is actually sent.
233    fn detect_local_ip() -> Option<IpAddr> {
234        // Try to connect to a public IP to determine our local IP
235        // We don't actually send data, just use the socket to determine routing
236        let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?;
237        socket.connect("8.8.8.8:80").ok()?;
238        let local_addr = socket.local_addr().ok()?;
239        Some(local_addr.ip())
240    }
241
242    /// Start the HTTP server on the given port.
243    fn start_server(
244        port: u16,
245        event_router: Arc<EventRouter>,
246        mut shutdown_rx: mpsc::Receiver<()>,
247        ready_tx: mpsc::Sender<()>,
248    ) -> tokio::task::JoinHandle<()> {
249        tokio::spawn(async move {
250            // Create the NOTIFY endpoint that accepts any path (like the old code)
251            let notify_route = warp::method()
252                .and(warp::path::full())
253                .and(warp::header::optional::<String>("sid"))
254                .and(warp::header::optional::<String>("nt"))
255                .and(warp::header::optional::<String>("nts"))
256                .and(warp::body::bytes())
257                .and_then({
258                    let router = event_router.clone();
259                    move |method: warp::http::Method,
260                          path: warp::path::FullPath,
261                          sid: Option<String>,
262                          nt: Option<String>,
263                          nts: Option<String>,
264                          body: bytes::Bytes| {
265                        let router = router.clone();
266                        async move {
267                            // Only handle NOTIFY method
268                            if method != warp::http::Method::from_bytes(b"NOTIFY").unwrap() {
269                                return Err(warp::reject::not_found());
270                            }
271
272                            // Log incoming request details for unified event stream monitoring
273                            debug!(
274                                method = %method,
275                                path = %path.as_str(),
276                                body_size = body.len(),
277                                sid = ?sid,
278                                nt = ?nt,
279                                nts = ?nts,
280                                "Received UPnP NOTIFY event"
281                            );
282
283                            // Convert body to string and log content at trace level only
284                            let event_xml = String::from_utf8_lossy(&body).to_string();
285                            if event_xml.len() > 200 {
286                                trace!(
287                                    event_xml_preview = %&event_xml[..200],
288                                    total_length = event_xml.len(),
289                                    "UPnP event XML content (truncated)"
290                                );
291                            } else {
292                                trace!(
293                                    event_xml = %event_xml,
294                                    "UPnP event XML content (full)"
295                                );
296                            }
297
298                            // Validate UPnP headers
299                            if !Self::validate_upnp_headers(&sid, &nt, &nts) {
300                                error!(
301                                    sid = ?sid,
302                                    nt = ?nt,
303                                    nts = ?nts,
304                                    "Invalid UPnP headers in NOTIFY request"
305                                );
306                                return Err(warp::reject::custom(InvalidUpnpHeaders));
307                            }
308
309                            // Extract subscription ID from SID header (required for UPnP events)
310                            let sub_id = sid.ok_or_else(|| {
311                                error!("Missing required SID header in UPnP NOTIFY request");
312                                warp::reject::custom(InvalidUpnpHeaders)
313                            })?;
314
315                            // Route the event through the unified event stream.
316                            // Events are either delivered immediately (registered SID)
317                            // or buffered for replay when register() is called.
318                            router.route_event(sub_id.clone(), event_xml).await;
319
320                            debug!(
321                                subscription_id = %sub_id,
322                                "UPnP event accepted"
323                            );
324                            // Always 200 OK — event is either routed or buffered.
325                            // Returning 404 could cause the speaker to cancel the subscription.
326                            Ok::<_, warp::Rejection>(warp::reply::with_status(
327                                "",
328                                warp::http::StatusCode::OK,
329                            ))
330                        }
331                    }
332                });
333
334            // Configure routes with just the NOTIFY endpoint
335            let routes = notify_route.recover(handle_rejection);
336
337            // Create server with graceful shutdown
338            let (addr, server) = warp::serve(routes).bind_with_graceful_shutdown(
339                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), port),
340                async move {
341                    shutdown_rx.recv().await;
342                },
343            );
344
345            info!(
346                address = %addr,
347                "CallbackServer listening - ready to process UPnP events"
348            );
349            // Signal that server is ready
350            let _ = ready_tx.send(()).await;
351            server.await;
352        })
353    }
354
355    /// Validate UPnP event notification headers.
356    ///
357    /// Checks that the required SID header is present and validates optional
358    /// NT and NTS headers if they are provided.
359    fn validate_upnp_headers(
360        sid: &Option<String>,
361        nt: &Option<String>,
362        nts: &Option<String>,
363    ) -> bool {
364        // SID header is required for event notifications
365        if sid.is_none() {
366            return false;
367        }
368
369        // For UPnP events, NT and NTS headers are typically present
370        // If present, validate they have expected values
371        if let (Some(nt_val), Some(nts_val)) = (nt, nts) {
372            if nt_val != "upnp:event" || nts_val != "upnp:propchange" {
373                return false;
374            }
375        }
376
377        true
378    }
379}
380
381/// Custom rejection for invalid UPnP headers.
382#[derive(Debug)]
383struct InvalidUpnpHeaders;
384
385impl warp::reject::Reject for InvalidUpnpHeaders {}
386
387/// Handle rejections and convert them to HTTP responses.
388async fn handle_rejection(
389    err: warp::Rejection,
390) -> Result<impl warp::Reply, std::convert::Infallible> {
391    let code;
392    let message;
393
394    if err.is_not_found() {
395        code = warp::http::StatusCode::NOT_FOUND;
396        message = "Subscription not found";
397    } else if err.find::<InvalidUpnpHeaders>().is_some() {
398        code = warp::http::StatusCode::BAD_REQUEST;
399        message = "Invalid UPnP headers";
400    } else {
401        code = warp::http::StatusCode::INTERNAL_SERVER_ERROR;
402        message = "Internal server error";
403    }
404
405    Ok(warp::reply::with_status(message, code))
406}
407
408#[cfg(test)]
409mod tests {
410    use super::*;
411
412    #[test]
413    fn test_is_port_available() {
414        // Port 0 should always be available (OS assigns a free port)
415        assert!(CallbackServer::is_port_available(0));
416
417        // Bind to a port and verify it's no longer available
418        let _listener = TcpListener::bind("0.0.0.0:0").unwrap();
419        let port = _listener.local_addr().unwrap().port();
420        // While the listener is held, the port should not be available
421        assert!(!CallbackServer::is_port_available(port));
422        // Keep listener alive for the assertion
423        drop(_listener);
424    }
425
426    #[test]
427    fn test_find_available_port() {
428        // Should find a port in a reasonable range
429        let port = CallbackServer::find_available_port(50000, 50100);
430        assert!(port.is_some());
431        assert!(port.unwrap() >= 50000 && port.unwrap() <= 50100);
432    }
433
434    #[test]
435    fn test_detect_local_ip() {
436        let ip = CallbackServer::detect_local_ip();
437        assert!(ip.is_some());
438
439        // Should not be localhost
440        if let Some(IpAddr::V4(addr)) = ip {
441            assert_ne!(addr, Ipv4Addr::new(127, 0, 0, 1));
442        }
443    }
444
445    #[test]
446    fn test_validate_upnp_headers() {
447        // Valid headers with NT and NTS
448        assert!(CallbackServer::validate_upnp_headers(
449            &Some("uuid:123".to_string()),
450            &Some("upnp:event".to_string()),
451            &Some("upnp:propchange".to_string()),
452        ));
453
454        // Valid headers without NT and NTS (event notification)
455        assert!(CallbackServer::validate_upnp_headers(
456            &Some("uuid:123".to_string()),
457            &None,
458            &None,
459        ));
460
461        // Invalid: missing SID
462        assert!(!CallbackServer::validate_upnp_headers(
463            &None,
464            &Some("upnp:event".to_string()),
465            &Some("upnp:propchange".to_string()),
466        ));
467
468        // Invalid: wrong NT value
469        assert!(!CallbackServer::validate_upnp_headers(
470            &Some("uuid:123".to_string()),
471            &Some("wrong".to_string()),
472            &Some("upnp:propchange".to_string()),
473        ));
474
475        // Invalid: wrong NTS value
476        assert!(!CallbackServer::validate_upnp_headers(
477            &Some("uuid:123".to_string()),
478            &Some("upnp:event".to_string()),
479            &Some("wrong".to_string()),
480        ));
481    }
482
483    #[tokio::test]
484    async fn test_callback_server_creation() {
485        let (tx, _rx) = mpsc::unbounded_channel();
486
487        let server = CallbackServer::new((50000, 50100), tx).await;
488        assert!(server.is_ok());
489
490        let server = server.unwrap();
491        assert!(server.port() >= 50000 && server.port() <= 50100);
492        assert!(server.base_url().contains(&server.port().to_string()));
493
494        // Cleanup
495        server.shutdown().await.unwrap();
496    }
497
498    #[tokio::test]
499    async fn test_callback_server_register_unregister() {
500        let (tx, _rx) = mpsc::unbounded_channel();
501        let server = CallbackServer::new((51000, 51100), tx).await.unwrap();
502
503        let sub_id = "test-sub-123".to_string();
504
505        // Register subscription via router
506        server.router().register(sub_id.clone()).await;
507
508        // Unregister subscription via router
509        server.router().unregister(&sub_id).await;
510
511        // Plugin system has been removed
512
513        // Cleanup
514        server.shutdown().await.unwrap();
515    }
516}