Skip to main content

callback_server/
firewall_detection.rs

1//! Firewall detection coordinator for callback server.
2//!
3//! This module implements a per-device firewall detection system that monitors
4//! real UPnP event delivery to determine whether callback servers can receive
5//! external requests from Sonos devices on the local network.
6
7use std::collections::HashMap;
8use std::net::IpAddr;
9use std::sync::Arc;
10use std::time::{Duration, SystemTime};
11use tokio::sync::{mpsc, RwLock};
12use tracing::{debug, warn};
13
14/// Status of firewall detection for a device.
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16pub enum FirewallStatus {
17    /// Detection has not been performed yet
18    #[default]
19    Unknown,
20    /// Server can receive external requests from this device
21    Accessible,
22    /// Server appears to be blocked by firewall for this device
23    Blocked,
24    /// Detection failed due to other errors
25    Error,
26}
27
28/// Configuration for firewall detection behavior.
29#[derive(Debug, Clone)]
30pub struct FirewallDetectionConfig {
31    /// Timeout for waiting for first event from a device
32    pub event_wait_timeout: Duration,
33    /// Enable per-device caching of firewall status
34    pub enable_caching: bool,
35    /// Maximum number of cached device states
36    pub max_cached_devices: usize,
37}
38
39impl Default for FirewallDetectionConfig {
40    fn default() -> Self {
41        Self {
42            event_wait_timeout: Duration::from_secs(15),
43            enable_caching: true,
44            max_cached_devices: 100,
45        }
46    }
47}
48
49/// Per-device firewall detection state.
50#[derive(Debug, Clone)]
51pub struct DeviceFirewallState {
52    pub device_ip: IpAddr,
53    pub status: FirewallStatus,
54    pub first_subscription_time: SystemTime,
55    pub first_event_time: Option<SystemTime>,
56    pub detection_completed: bool,
57    pub timeout_duration: Duration,
58}
59
60/// Result of a firewall detection operation.
61#[derive(Debug, Clone)]
62pub struct DetectionResult {
63    pub device_ip: IpAddr,
64    pub status: FirewallStatus,
65    pub reason: DetectionReason,
66}
67
68/// Reason for detection completion.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum DetectionReason {
71    /// First event arrived within timeout
72    EventReceived,
73    /// No events received within timeout
74    Timeout,
75}
76
77/// Coordinates per-device firewall detection by monitoring real UPnP event delivery.
78///
79/// The coordinator tracks firewall status on a per-device basis, triggering detection
80/// when the first subscription is created for a device and monitoring for event arrivals
81/// to determine connectivity status.
82pub struct FirewallDetectionCoordinator {
83    /// Per-device detection states
84    device_states: Arc<RwLock<HashMap<IpAddr, Arc<RwLock<DeviceFirewallState>>>>>,
85
86    /// Configuration for detection behavior
87    config: FirewallDetectionConfig,
88
89    /// Channel for notifying when detection completes
90    detection_complete_tx: mpsc::UnboundedSender<DetectionResult>,
91
92    /// Handle for the timeout monitoring task
93    _timeout_task_handle: tokio::task::JoinHandle<()>,
94}
95
96impl FirewallDetectionCoordinator {
97    /// Create a new firewall detection coordinator.
98    pub fn new(config: FirewallDetectionConfig) -> Self {
99        let (detection_complete_tx, mut detection_complete_rx) = mpsc::unbounded_channel();
100
101        let device_states = Arc::new(RwLock::new(HashMap::new()));
102
103        // Spawn background task for timeout monitoring
104        let timeout_task_handle = {
105            let device_states = device_states.clone();
106            let detection_complete_tx = detection_complete_tx.clone();
107            tokio::spawn(async move {
108                Self::monitor_timeouts(device_states, detection_complete_tx).await;
109            })
110        };
111
112        // Drain detection results. The user-facing line for each outcome is
113        // logged where the outcome is decided (`on_event_received`,
114        // `monitor_timeouts`), so this only records delivery.
115        tokio::spawn(async move {
116            while let Some(result) = detection_complete_rx.recv().await {
117                debug!(
118                    device_ip = %result.device_ip,
119                    reason = ?result.reason,
120                    status = ?result.status,
121                    "firewall detection result"
122                );
123            }
124        });
125
126        Self {
127            device_states,
128            config,
129            detection_complete_tx,
130            _timeout_task_handle: timeout_task_handle,
131        }
132    }
133
134    /// Called when the first subscription is created for a device.
135    ///
136    /// Returns the cached status if already known, otherwise starts monitoring
137    /// and returns Unknown status while detection is in progress.
138    pub async fn on_first_subscription(&self, device_ip: IpAddr) -> FirewallStatus {
139        if !self.config.enable_caching {
140            // Caching disabled - always return Unknown and start fresh detection
141            self.start_detection_for_device(device_ip).await;
142            return FirewallStatus::Unknown;
143        }
144
145        let device_states = self.device_states.read().await;
146
147        // Check if we already have cached status
148        if let Some(state_arc) = device_states.get(&device_ip) {
149            let state = state_arc.read().await;
150            if state.detection_completed {
151                debug!(
152                    device_ip = %device_ip,
153                    status = ?state.status,
154                    "firewall detection: using cached status for device"
155                );
156                return state.status;
157            }
158        }
159
160        drop(device_states); // Release read lock before starting detection
161
162        // First subscription for this device - start monitoring
163        self.start_detection_for_device(device_ip).await;
164
165        debug!(
166            device_ip = %device_ip,
167            timeout = ?self.config.event_wait_timeout,
168            "firewall detection: waiting for the first event from device"
169        );
170
171        FirewallStatus::Unknown
172    }
173
174    /// Called when any event is received from a device.
175    ///
176    /// If detection is in progress for this device, marks it as accessible.
177    pub async fn on_event_received(&self, device_ip: IpAddr) {
178        let device_states = self.device_states.read().await;
179
180        if let Some(state_arc) = device_states.get(&device_ip) {
181            let mut state = state_arc.write().await;
182
183            if !state.detection_completed {
184                // First event received - mark as accessible
185                state.first_event_time = Some(SystemTime::now());
186                state.status = FirewallStatus::Accessible;
187                state.detection_completed = true;
188
189                let elapsed = SystemTime::now()
190                    .duration_since(state.first_subscription_time)
191                    .unwrap_or(Duration::ZERO);
192
193                // Notify completion
194                let _ = self.detection_complete_tx.send(DetectionResult {
195                    device_ip,
196                    status: FirewallStatus::Accessible,
197                    reason: DetectionReason::EventReceived,
198                });
199
200                debug!(
201                    device_ip = %device_ip,
202                    elapsed = ?elapsed,
203                    status = ?FirewallStatus::Accessible,
204                    "firewall detection: event received from device, marking it accessible"
205                );
206            }
207        }
208    }
209
210    /// Get the current cached status for a device.
211    pub async fn get_device_status(&self, device_ip: IpAddr) -> FirewallStatus {
212        let device_states = self.device_states.read().await;
213
214        if let Some(state_arc) = device_states.get(&device_ip) {
215            let state = state_arc.read().await;
216            state.status
217        } else {
218            FirewallStatus::Unknown
219        }
220    }
221
222    /// Start detection monitoring for a specific device.
223    async fn start_detection_for_device(&self, device_ip: IpAddr) {
224        let mut device_states = self.device_states.write().await;
225
226        // Create new detection state
227        let new_state = Arc::new(RwLock::new(DeviceFirewallState {
228            device_ip,
229            status: FirewallStatus::Unknown,
230            first_subscription_time: SystemTime::now(),
231            first_event_time: None,
232            detection_completed: false,
233            timeout_duration: self.config.event_wait_timeout,
234        }));
235
236        // Enforce maximum cache size
237        if device_states.len() >= self.config.max_cached_devices {
238            // Remove oldest entry (this is a simple LRU-like behavior)
239            if let Some(oldest_ip) = device_states.keys().next().copied() {
240                device_states.remove(&oldest_ip);
241                debug!(
242                    oldest_ip = %oldest_ip,
243                    cache_size = self.config.max_cached_devices,
244                    "firewall detection: cache full, removed oldest entry"
245                );
246            }
247        }
248
249        device_states.insert(device_ip, new_state);
250    }
251
252    /// Background task that monitors for timeouts.
253    async fn monitor_timeouts(
254        device_states: Arc<RwLock<HashMap<IpAddr, Arc<RwLock<DeviceFirewallState>>>>>,
255        detection_complete_tx: mpsc::UnboundedSender<DetectionResult>,
256    ) {
257        let mut interval = tokio::time::interval(Duration::from_secs(1));
258
259        loop {
260            interval.tick().await;
261
262            let device_states_read = device_states.read().await;
263
264            for (device_ip, state_arc) in device_states_read.iter() {
265                let mut state = state_arc.write().await;
266
267                if !state.detection_completed {
268                    let elapsed = SystemTime::now()
269                        .duration_since(state.first_subscription_time)
270                        .unwrap_or(Duration::ZERO);
271
272                    if elapsed >= state.timeout_duration {
273                        // Timeout reached - mark as blocked
274                        state.status = FirewallStatus::Blocked;
275                        state.detection_completed = true;
276
277                        // Notify completion
278                        let _ = detection_complete_tx.send(DetectionResult {
279                            device_ip: *device_ip,
280                            status: FirewallStatus::Blocked,
281                            reason: DetectionReason::Timeout,
282                        });
283
284                        warn!(
285                            device_ip = %device_ip,
286                            timeout = ?state.timeout_duration,
287                            status = ?FirewallStatus::Blocked,
288                            "no UPnP events arrived from speaker within timeout; a firewall may be blocking the callback port"
289                        );
290                    }
291                }
292            }
293        }
294    }
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300    use std::net::Ipv4Addr;
301
302    #[tokio::test]
303    async fn test_coordinator_creation() {
304        let config = FirewallDetectionConfig::default();
305        let _coordinator = FirewallDetectionCoordinator::new(config);
306        // Just verify it doesn't panic
307    }
308
309    #[tokio::test]
310    async fn test_first_subscription_starts_monitoring() {
311        let config = FirewallDetectionConfig::default();
312        let coordinator = FirewallDetectionCoordinator::new(config);
313
314        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
315        let status = coordinator.on_first_subscription(device_ip).await;
316
317        // Should return Unknown while monitoring
318        assert_eq!(status, FirewallStatus::Unknown);
319
320        // Should have cached status
321        let cached_status = coordinator.get_device_status(device_ip).await;
322        assert_eq!(cached_status, FirewallStatus::Unknown);
323    }
324
325    #[tokio::test]
326    async fn test_event_received_marks_accessible() {
327        let config = FirewallDetectionConfig::default();
328        let coordinator = FirewallDetectionCoordinator::new(config);
329
330        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
331
332        // Start monitoring
333        coordinator.on_first_subscription(device_ip).await;
334
335        // Simulate event received
336        coordinator.on_event_received(device_ip).await;
337
338        // Should now be accessible
339        let status = coordinator.get_device_status(device_ip).await;
340        assert_eq!(status, FirewallStatus::Accessible);
341    }
342
343    #[tokio::test]
344    async fn test_timeout_marks_blocked() {
345        let config = FirewallDetectionConfig {
346            event_wait_timeout: Duration::from_millis(100), // Very short timeout for testing
347            ..Default::default()
348        };
349        let coordinator = FirewallDetectionCoordinator::new(config);
350
351        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
352
353        // Start monitoring
354        coordinator.on_first_subscription(device_ip).await;
355
356        // Wait for timeout + monitoring task to run (monitoring runs every 1 second)
357        tokio::time::sleep(Duration::from_millis(1200)).await;
358
359        // Should now be blocked
360        let status = coordinator.get_device_status(device_ip).await;
361        assert_eq!(status, FirewallStatus::Blocked);
362    }
363
364    #[tokio::test]
365    async fn test_cached_status_reused() {
366        let config = FirewallDetectionConfig::default();
367        let coordinator = FirewallDetectionCoordinator::new(config);
368
369        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
370
371        // Start monitoring and mark as accessible
372        coordinator.on_first_subscription(device_ip).await;
373        coordinator.on_event_received(device_ip).await;
374
375        // Second subscription should return cached status
376        let status = coordinator.on_first_subscription(device_ip).await;
377        assert_eq!(status, FirewallStatus::Accessible);
378    }
379}