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    /// Whether detection has started for a device (in progress or finished).
211    pub async fn is_tracking(&self, device_ip: IpAddr) -> bool {
212        self.device_states.read().await.contains_key(&device_ip)
213    }
214
215    /// Abandon an unfinished detection for a device.
216    ///
217    /// For when the subscription that started it failed: no event can arrive
218    /// without a subscription, so letting the timer run would report a firewall
219    /// that isn't there. A finished detection is kept.
220    pub async fn cancel_detection(&self, device_ip: IpAddr) {
221        let mut device_states = self.device_states.write().await;
222        let unfinished = match device_states.get(&device_ip) {
223            Some(state_arc) => !state_arc.read().await.detection_completed,
224            None => false,
225        };
226        if unfinished {
227            device_states.remove(&device_ip);
228            debug!(
229                device_ip = %device_ip,
230                "firewall detection: subscription failed, abandoning detection"
231            );
232        }
233    }
234
235    /// Get the current cached status for a device.
236    pub async fn get_device_status(&self, device_ip: IpAddr) -> FirewallStatus {
237        let device_states = self.device_states.read().await;
238
239        if let Some(state_arc) = device_states.get(&device_ip) {
240            let state = state_arc.read().await;
241            state.status
242        } else {
243            FirewallStatus::Unknown
244        }
245    }
246
247    /// Start detection monitoring for a specific device.
248    async fn start_detection_for_device(&self, device_ip: IpAddr) {
249        let mut device_states = self.device_states.write().await;
250
251        // Create new detection state
252        let new_state = Arc::new(RwLock::new(DeviceFirewallState {
253            device_ip,
254            status: FirewallStatus::Unknown,
255            first_subscription_time: SystemTime::now(),
256            first_event_time: None,
257            detection_completed: false,
258            timeout_duration: self.config.event_wait_timeout,
259        }));
260
261        // Enforce maximum cache size
262        if device_states.len() >= self.config.max_cached_devices {
263            // Remove oldest entry (this is a simple LRU-like behavior)
264            if let Some(oldest_ip) = device_states.keys().next().copied() {
265                device_states.remove(&oldest_ip);
266                debug!(
267                    oldest_ip = %oldest_ip,
268                    cache_size = self.config.max_cached_devices,
269                    "firewall detection: cache full, removed oldest entry"
270                );
271            }
272        }
273
274        device_states.insert(device_ip, new_state);
275    }
276
277    /// Background task that monitors for timeouts.
278    async fn monitor_timeouts(
279        device_states: Arc<RwLock<HashMap<IpAddr, Arc<RwLock<DeviceFirewallState>>>>>,
280        detection_complete_tx: mpsc::UnboundedSender<DetectionResult>,
281    ) {
282        let mut interval = tokio::time::interval(Duration::from_secs(1));
283
284        loop {
285            interval.tick().await;
286
287            let device_states_read = device_states.read().await;
288
289            for (device_ip, state_arc) in device_states_read.iter() {
290                let mut state = state_arc.write().await;
291
292                if !state.detection_completed {
293                    let elapsed = SystemTime::now()
294                        .duration_since(state.first_subscription_time)
295                        .unwrap_or(Duration::ZERO);
296
297                    if elapsed >= state.timeout_duration {
298                        // Timeout reached - mark as blocked
299                        state.status = FirewallStatus::Blocked;
300                        state.detection_completed = true;
301
302                        // Notify completion
303                        let _ = detection_complete_tx.send(DetectionResult {
304                            device_ip: *device_ip,
305                            status: FirewallStatus::Blocked,
306                            reason: DetectionReason::Timeout,
307                        });
308
309                        warn!(
310                            device_ip = %device_ip,
311                            timeout = ?state.timeout_duration,
312                            status = ?FirewallStatus::Blocked,
313                            "no UPnP events arrived from speaker within timeout; a firewall may be blocking the callback port"
314                        );
315                    }
316                }
317            }
318        }
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use std::net::Ipv4Addr;
326
327    #[tokio::test]
328    async fn test_coordinator_creation() {
329        let config = FirewallDetectionConfig::default();
330        let _coordinator = FirewallDetectionCoordinator::new(config);
331        // Just verify it doesn't panic
332    }
333
334    #[tokio::test]
335    async fn test_first_subscription_starts_monitoring() {
336        let config = FirewallDetectionConfig::default();
337        let coordinator = FirewallDetectionCoordinator::new(config);
338
339        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
340        let status = coordinator.on_first_subscription(device_ip).await;
341
342        // Should return Unknown while monitoring
343        assert_eq!(status, FirewallStatus::Unknown);
344
345        // Should have cached status
346        let cached_status = coordinator.get_device_status(device_ip).await;
347        assert_eq!(cached_status, FirewallStatus::Unknown);
348    }
349
350    #[tokio::test]
351    async fn test_cancel_detection_drops_only_unfinished_detections() {
352        let coordinator = FirewallDetectionCoordinator::new(FirewallDetectionConfig::default());
353        let pending = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
354        let done = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 101));
355
356        coordinator.on_first_subscription(pending).await;
357        coordinator.on_first_subscription(done).await;
358        coordinator.on_event_received(done).await;
359        assert!(coordinator.is_tracking(pending).await);
360
361        coordinator.cancel_detection(pending).await;
362        coordinator.cancel_detection(done).await;
363
364        assert!(!coordinator.is_tracking(pending).await);
365        assert_eq!(
366            coordinator.get_device_status(done).await,
367            FirewallStatus::Accessible
368        );
369    }
370
371    #[tokio::test]
372    async fn test_event_received_marks_accessible() {
373        let config = FirewallDetectionConfig::default();
374        let coordinator = FirewallDetectionCoordinator::new(config);
375
376        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
377
378        // Start monitoring
379        coordinator.on_first_subscription(device_ip).await;
380
381        // Simulate event received
382        coordinator.on_event_received(device_ip).await;
383
384        // Should now be accessible
385        let status = coordinator.get_device_status(device_ip).await;
386        assert_eq!(status, FirewallStatus::Accessible);
387    }
388
389    #[tokio::test]
390    async fn test_timeout_marks_blocked() {
391        let config = FirewallDetectionConfig {
392            event_wait_timeout: Duration::from_millis(100), // Very short timeout for testing
393            ..Default::default()
394        };
395        let coordinator = FirewallDetectionCoordinator::new(config);
396
397        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
398
399        // Start monitoring
400        coordinator.on_first_subscription(device_ip).await;
401
402        // Wait for timeout + monitoring task to run (monitoring runs every 1 second)
403        tokio::time::sleep(Duration::from_millis(1200)).await;
404
405        // Should now be blocked
406        let status = coordinator.get_device_status(device_ip).await;
407        assert_eq!(status, FirewallStatus::Blocked);
408    }
409
410    #[tokio::test]
411    async fn test_cached_status_reused() {
412        let config = FirewallDetectionConfig::default();
413        let coordinator = FirewallDetectionCoordinator::new(config);
414
415        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
416
417        // Start monitoring and mark as accessible
418        coordinator.on_first_subscription(device_ip).await;
419        coordinator.on_event_received(device_ip).await;
420
421        // Second subscription should return cached status
422        let status = coordinator.on_first_subscription(device_ip).await;
423        assert_eq!(status, FirewallStatus::Accessible);
424    }
425}