1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16pub enum FirewallStatus {
17 #[default]
19 Unknown,
20 Accessible,
22 Blocked,
24 Error,
26}
27
28#[derive(Debug, Clone)]
30pub struct FirewallDetectionConfig {
31 pub event_wait_timeout: Duration,
33 pub enable_caching: bool,
35 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#[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#[derive(Debug, Clone)]
62pub struct DetectionResult {
63 pub device_ip: IpAddr,
64 pub status: FirewallStatus,
65 pub reason: DetectionReason,
66}
67
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum DetectionReason {
71 EventReceived,
73 Timeout,
75}
76
77pub struct FirewallDetectionCoordinator {
83 device_states: Arc<RwLock<HashMap<IpAddr, Arc<RwLock<DeviceFirewallState>>>>>,
85
86 config: FirewallDetectionConfig,
88
89 detection_complete_tx: mpsc::UnboundedSender<DetectionResult>,
91
92 _timeout_task_handle: tokio::task::JoinHandle<()>,
94}
95
96impl FirewallDetectionCoordinator {
97 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 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 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 pub async fn on_first_subscription(&self, device_ip: IpAddr) -> FirewallStatus {
139 if !self.config.enable_caching {
140 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 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); 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 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 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 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 pub async fn is_tracking(&self, device_ip: IpAddr) -> bool {
212 self.device_states.read().await.contains_key(&device_ip)
213 }
214
215 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 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 async fn start_detection_for_device(&self, device_ip: IpAddr) {
249 let mut device_states = self.device_states.write().await;
250
251 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 if device_states.len() >= self.config.max_cached_devices {
263 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 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 state.status = FirewallStatus::Blocked;
300 state.detection_completed = true;
301
302 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 }
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 assert_eq!(status, FirewallStatus::Unknown);
344
345 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 coordinator.on_first_subscription(device_ip).await;
380
381 coordinator.on_event_received(device_ip).await;
383
384 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), ..Default::default()
394 };
395 let coordinator = FirewallDetectionCoordinator::new(config);
396
397 let device_ip = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 100));
398
399 coordinator.on_first_subscription(device_ip).await;
401
402 tokio::time::sleep(Duration::from_millis(1200)).await;
404
405 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 coordinator.on_first_subscription(device_ip).await;
419 coordinator.on_event_received(device_ip).await;
420
421 let status = coordinator.on_first_subscription(device_ip).await;
423 assert_eq!(status, FirewallStatus::Accessible);
424 }
425}