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, info, 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        // Spawn task to handle detection results (logging for now)
113        tokio::spawn(async move {
114            while let Some(result) = detection_complete_rx.recv().await {
115                match result.reason {
116                    DetectionReason::EventReceived => {
117                        info!(
118                            device_ip = %result.device_ip,
119                            reason = ?result.reason,
120                            status = ?result.status,
121                            "Firewall detection: Events accessible from device"
122                        );
123                    }
124                    DetectionReason::Timeout => {
125                        warn!(
126                            device_ip = %result.device_ip,
127                            reason = ?result.reason,
128                            status = ?result.status,
129                            "Firewall detection: No events received within timeout"
130                        );
131                    }
132                }
133            }
134        });
135
136        Self {
137            device_states,
138            config,
139            detection_complete_tx,
140            _timeout_task_handle: timeout_task_handle,
141        }
142    }
143
144    /// Called when the first subscription is created for a device.
145    ///
146    /// Returns the cached status if already known, otherwise starts monitoring
147    /// and returns Unknown status while detection is in progress.
148    pub async fn on_first_subscription(&self, device_ip: IpAddr) -> FirewallStatus {
149        if !self.config.enable_caching {
150            // Caching disabled - always return Unknown and start fresh detection
151            self.start_detection_for_device(device_ip).await;
152            return FirewallStatus::Unknown;
153        }
154
155        let device_states = self.device_states.read().await;
156
157        // Check if we already have cached status
158        if let Some(state_arc) = device_states.get(&device_ip) {
159            let state = state_arc.read().await;
160            if state.detection_completed {
161                debug!(
162                    device_ip = %device_ip,
163                    status = ?state.status,
164                    "Firewall detection: Using cached status for device"
165                );
166                return state.status;
167            }
168        }
169
170        drop(device_states); // Release read lock before starting detection
171
172        // First subscription for this device - start monitoring
173        self.start_detection_for_device(device_ip).await;
174
175        debug!(
176            device_ip = %device_ip,
177            timeout = ?self.config.event_wait_timeout,
178            "Firewall detection: Started monitoring device for events"
179        );
180
181        FirewallStatus::Unknown
182    }
183
184    /// Called when any event is received from a device.
185    ///
186    /// If detection is in progress for this device, marks it as accessible.
187    pub async fn on_event_received(&self, device_ip: IpAddr) {
188        let device_states = self.device_states.read().await;
189
190        if let Some(state_arc) = device_states.get(&device_ip) {
191            let mut state = state_arc.write().await;
192
193            if !state.detection_completed {
194                // First event received - mark as accessible
195                state.first_event_time = Some(SystemTime::now());
196                state.status = FirewallStatus::Accessible;
197                state.detection_completed = true;
198
199                let elapsed = SystemTime::now()
200                    .duration_since(state.first_subscription_time)
201                    .unwrap_or(Duration::ZERO);
202
203                // Notify completion
204                let _ = self.detection_complete_tx.send(DetectionResult {
205                    device_ip,
206                    status: FirewallStatus::Accessible,
207                    reason: DetectionReason::EventReceived,
208                });
209
210                info!(
211                    device_ip = %device_ip,
212                    elapsed = ?elapsed,
213                    status = ?FirewallStatus::Accessible,
214                    "Firewall detection: Event received from device, marking as accessible"
215                );
216            }
217        }
218    }
219
220    /// Get the current cached status for a device.
221    pub async fn get_device_status(&self, device_ip: IpAddr) -> FirewallStatus {
222        let device_states = self.device_states.read().await;
223
224        if let Some(state_arc) = device_states.get(&device_ip) {
225            let state = state_arc.read().await;
226            state.status
227        } else {
228            FirewallStatus::Unknown
229        }
230    }
231
232    /// Start detection monitoring for a specific device.
233    async fn start_detection_for_device(&self, device_ip: IpAddr) {
234        let mut device_states = self.device_states.write().await;
235
236        // Create new detection state
237        let new_state = Arc::new(RwLock::new(DeviceFirewallState {
238            device_ip,
239            status: FirewallStatus::Unknown,
240            first_subscription_time: SystemTime::now(),
241            first_event_time: None,
242            detection_completed: false,
243            timeout_duration: self.config.event_wait_timeout,
244        }));
245
246        // Enforce maximum cache size
247        if device_states.len() >= self.config.max_cached_devices {
248            // Remove oldest entry (this is a simple LRU-like behavior)
249            if let Some(oldest_ip) = device_states.keys().next().copied() {
250                device_states.remove(&oldest_ip);
251                debug!(
252                    oldest_ip = %oldest_ip,
253                    cache_size = self.config.max_cached_devices,
254                    "Firewall detection: Removed oldest cached entry due to cache being full"
255                );
256            }
257        }
258
259        device_states.insert(device_ip, new_state);
260    }
261
262    /// Background task that monitors for timeouts.
263    async fn monitor_timeouts(
264        device_states: Arc<RwLock<HashMap<IpAddr, Arc<RwLock<DeviceFirewallState>>>>>,
265        detection_complete_tx: mpsc::UnboundedSender<DetectionResult>,
266    ) {
267        let mut interval = tokio::time::interval(Duration::from_secs(1));
268
269        loop {
270            interval.tick().await;
271
272            let device_states_read = device_states.read().await;
273
274            for (device_ip, state_arc) in device_states_read.iter() {
275                let mut state = state_arc.write().await;
276
277                if !state.detection_completed {
278                    let elapsed = SystemTime::now()
279                        .duration_since(state.first_subscription_time)
280                        .unwrap_or(Duration::ZERO);
281
282                    if elapsed >= state.timeout_duration {
283                        // Timeout reached - mark as blocked
284                        state.status = FirewallStatus::Blocked;
285                        state.detection_completed = true;
286
287                        // Notify completion
288                        let _ = detection_complete_tx.send(DetectionResult {
289                            device_ip: *device_ip,
290                            status: FirewallStatus::Blocked,
291                            reason: DetectionReason::Timeout,
292                        });
293
294                        warn!(
295                            device_ip = %device_ip,
296                            timeout = ?state.timeout_duration,
297                            status = ?FirewallStatus::Blocked,
298                            "Firewall detection: No events received within timeout, marking as blocked"
299                        );
300                    }
301                }
302            }
303        }
304    }
305}
306
307#[cfg(test)]
308mod tests {
309    use super::*;
310    use std::net::Ipv4Addr;
311
312    #[tokio::test]
313    async fn test_coordinator_creation() {
314        let config = FirewallDetectionConfig::default();
315        let _coordinator = FirewallDetectionCoordinator::new(config);
316        // Just verify it doesn't panic
317    }
318
319    #[tokio::test]
320    async fn test_first_subscription_starts_monitoring() {
321        let config = FirewallDetectionConfig::default();
322        let coordinator = FirewallDetectionCoordinator::new(config);
323
324        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
325        let status = coordinator.on_first_subscription(device_ip).await;
326
327        // Should return Unknown while monitoring
328        assert_eq!(status, FirewallStatus::Unknown);
329
330        // Should have cached status
331        let cached_status = coordinator.get_device_status(device_ip).await;
332        assert_eq!(cached_status, FirewallStatus::Unknown);
333    }
334
335    #[tokio::test]
336    async fn test_event_received_marks_accessible() {
337        let config = FirewallDetectionConfig::default();
338        let coordinator = FirewallDetectionCoordinator::new(config);
339
340        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
341
342        // Start monitoring
343        coordinator.on_first_subscription(device_ip).await;
344
345        // Simulate event received
346        coordinator.on_event_received(device_ip).await;
347
348        // Should now be accessible
349        let status = coordinator.get_device_status(device_ip).await;
350        assert_eq!(status, FirewallStatus::Accessible);
351    }
352
353    #[tokio::test]
354    async fn test_timeout_marks_blocked() {
355        let config = FirewallDetectionConfig {
356            event_wait_timeout: Duration::from_millis(100), // Very short timeout for testing
357            ..Default::default()
358        };
359        let coordinator = FirewallDetectionCoordinator::new(config);
360
361        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
362
363        // Start monitoring
364        coordinator.on_first_subscription(device_ip).await;
365
366        // Wait for timeout + monitoring task to run (monitoring runs every 1 second)
367        tokio::time::sleep(Duration::from_millis(1200)).await;
368
369        // Should now be blocked
370        let status = coordinator.get_device_status(device_ip).await;
371        assert_eq!(status, FirewallStatus::Blocked);
372    }
373
374    #[tokio::test]
375    async fn test_cached_status_reused() {
376        let config = FirewallDetectionConfig::default();
377        let coordinator = FirewallDetectionCoordinator::new(config);
378
379        let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
380
381        // Start monitoring and mark as accessible
382        coordinator.on_first_subscription(device_ip).await;
383        coordinator.on_event_received(device_ip).await;
384
385        // Second subscription should return cached status
386        let status = coordinator.on_first_subscription(device_ip).await;
387        assert_eq!(status, FirewallStatus::Accessible);
388    }
389}