1use std::collections::HashMap;
19use std::net::TcpListener;
20use std::process::Command;
21use std::sync::{Mutex, OnceLock};
22use std::time::{Duration, Instant};
23
24use crate::models::{CheckStatus, DiagnosticResult};
25
26pub const DEFAULT_DEV_PORTS: &[u16] = &[3000, 5000, 8000, 8080, 9000];
28
29pub const CRITICAL_PORTS: &[u16] = &[80, 443, 5432, 3306, 27017];
31
32pub const CACHE_TTL: Duration = Duration::from_secs(30);
34
35pub fn status_for_port(port: u16) -> CheckStatus {
42 if CRITICAL_PORTS.contains(&port) || port < 1024 {
43 CheckStatus::Fail
44 } else {
45 CheckStatus::Warn
46 }
47}
48
49pub fn parse_netstat(output: &str) -> Vec<(u16, u32)> {
69 let mut out = Vec::new();
70 for line in output.lines() {
71 let upper = line.to_ascii_uppercase();
72 if !(upper.contains("LISTENING") || upper.contains("LISTEN")) {
73 continue;
74 }
75 let fields: Vec<&str> = line.split_whitespace().collect();
76 let Some(local) = fields.iter().find(|f| f.contains(':')) else {
77 continue;
78 };
79 let Some(port) = local.rsplit(':').next().and_then(|s| s.parse::<u16>().ok()) else {
80 continue;
81 };
82 let Some(pid) = fields.last().and_then(|s| s.parse::<u32>().ok()) else {
83 continue;
84 };
85 out.push((port, pid));
86 }
87 out.sort_unstable();
88 out.dedup();
89 out
90}
91
92fn parse_csv_row(line: &str) -> Vec<String> {
94 let mut fields = Vec::new();
95 let mut current = String::new();
96 let mut in_quotes = false;
97 for ch in line.chars() {
98 match ch {
99 '"' => in_quotes = !in_quotes,
100 ',' if !in_quotes => {
101 fields.push(current.trim().to_string());
102 current.clear();
103 }
104 other => current.push(other),
105 }
106 }
107 fields.push(current.trim().to_string());
108 fields
109}
110
111pub fn parse_tasklist(output: &str) -> HashMap<u32, String> {
124 let mut names = HashMap::new();
125 for line in output.lines() {
126 let fields = parse_csv_row(line);
127 if !line.starts_with('"') || fields.len() < 2 {
128 continue;
129 }
130 let (name, pid) = (
131 fields[0].trim_matches('"').to_string(),
132 fields[1].trim_matches('"'),
133 );
134 if let Ok(pid) = pid.parse::<u32>() {
135 names.insert(pid, name);
136 }
137 }
138 names
139}
140
141pub fn parse_lsof(output: &str) -> Vec<(u16, u32, String)> {
157 let mut out = Vec::new();
158 for line in output.lines() {
159 let fields: Vec<&str> = line.split_whitespace().collect();
160 if fields.len() < 2 {
161 continue;
162 }
163 let Ok(pid) = fields[1].parse::<u32>() else {
164 continue; };
166 let command = fields[0].to_string();
167 let Some(port) = fields.iter().rev().find_map(|field| {
168 field
169 .rsplit(':')
170 .next()
171 .and_then(|s| s.trim_end_matches("(LISTEN)").parse::<u16>().ok())
172 }) else {
173 continue;
174 };
175 out.push((port, pid, command));
176 }
177 out.sort_unstable_by_key(|(port, _, _)| *port);
178 out.dedup();
179 out
180}
181
182pub fn parse_proc_net_tcp(output: &str) -> Vec<u16> {
199 let mut out = Vec::new();
200 for line in output.lines() {
201 let fields: Vec<&str> = line.split_whitespace().collect();
202 if fields.len() < 4 {
203 continue;
204 }
205 if fields[3] != "0A" {
206 continue; }
208 let Some((_, hex_port)) = fields[1].rsplit_once(':') else {
209 continue;
210 };
211 if let Ok(port) = u16::from_str_radix(hex_port, 16) {
212 out.push(port);
213 }
214 }
215 out.sort_unstable();
216 out.dedup();
217 out
218}
219
220#[cfg(target_os = "windows")]
225fn platform_command_scan() -> Vec<(u16, u32, String)> {
226 let output = match Command::new("netstat").arg("-ano").output() {
227 Ok(output) => output,
228 Err(_) => return Vec::new(),
229 };
230 if !output.status.success() {
231 return Vec::new();
232 }
233 let text = String::from_utf8_lossy(&output.stdout);
234 let listening = parse_netstat(&text);
235 if listening.is_empty() {
236 return Vec::new();
237 }
238
239 let names = match Command::new("tasklist")
240 .args(["/FO", "CSV", "/NH"])
241 .output()
242 {
243 Ok(output) => parse_tasklist(&String::from_utf8_lossy(&output.stdout)),
244 Err(_) => HashMap::new(),
245 };
246
247 listening
248 .into_iter()
249 .map(|(port, pid)| {
250 let raw_name = names
251 .get(&pid)
252 .cloned()
253 .unwrap_or_else(|| "unknown".to_string());
254 let name = raw_name
255 .strip_suffix(".exe")
256 .unwrap_or(&raw_name)
257 .to_string();
258 (port, pid, name)
259 })
260 .collect()
261}
262
263#[cfg(any(target_os = "macos", target_os = "freebsd"))]
264fn platform_command_scan() -> Vec<(u16, u32, String)> {
265 let output = match Command::new("lsof")
266 .args(["-iTCP", "-sTCP:LISTEN", "-P", "-n"])
267 .output()
268 {
269 Ok(output) => output,
270 Err(_) => return Vec::new(),
271 };
272 if !output.status.success() {
273 return Vec::new();
274 }
275 parse_lsof(&String::from_utf8_lossy(&output.stdout))
276}
277
278#[cfg(target_os = "linux")]
279fn platform_command_scan() -> Vec<(u16, u32, String)> {
280 use std::fs;
281
282 let lsof = Command::new("lsof")
283 .args(["-iTCP", "-sTCP:LISTEN", "-P", "-n"])
284 .output();
285 if let Ok(output) = lsof {
286 if output.status.success() {
287 let found = parse_lsof(&String::from_utf8_lossy(&output.stdout));
288 if !found.is_empty() {
289 return found;
290 }
291 }
292 }
293
294 let mut ports = Vec::new();
296 for proc in ["/proc/net/tcp", "/proc/net/tcp6"] {
297 if let Ok(text) = fs::read_to_string(proc) {
298 ports.extend(parse_proc_net_tcp(&text));
299 }
300 }
301 ports
302 .into_iter()
303 .map(|port| (port, 0, "unknown".to_string()))
304 .collect()
305}
306
307pub fn is_port_in_use(port: u16) -> bool {
309 TcpListener::bind(("127.0.0.1", port)).is_err()
310}
311
312fn parallel_in_use(ports: &[u16]) -> Vec<u16> {
316 let shared: Mutex<Vec<u16>> = Mutex::new(Vec::new());
317 std::thread::scope(|scope| {
318 for chunk in ports.chunks(4) {
319 let chunk = chunk.to_vec();
320 let shared = &shared;
321 scope.spawn(move || {
322 let found: Vec<u16> = chunk
323 .into_iter()
324 .filter(|port| is_port_in_use(*port))
325 .collect();
326 shared.lock().unwrap().extend(found);
327 });
328 }
329 });
330 shared.into_inner().unwrap()
331}
332
333fn platform_scan() -> Vec<(u16, u32, String)> {
335 let scanned = platform_command_scan();
336 if scanned.is_empty() {
337 parallel_in_use(DEFAULT_DEV_PORTS)
338 .into_iter()
339 .map(|port| (port, 0, "unknown".to_string()))
340 .collect()
341 } else {
342 scanned
343 }
344}
345
346#[derive(Debug, Clone, PartialEq, Eq)]
352pub struct PortStatus {
353 pub port: u16,
354 pub pid: u32,
355 pub process_name: String,
356 pub status: CheckStatus,
357}
358
359struct CachedEntry {
360 pid: u32,
361 process_name: String,
362}
363
364pub struct PortWatcher {
367 cache: Mutex<HashMap<u16, CachedEntry>>,
369 observed: Mutex<HashMap<u16, Instant>>,
372 ttl: Duration,
373 scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync>,
374}
375
376fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
377 mutex
378 .lock()
379 .unwrap_or_else(|poisoned| poisoned.into_inner())
380}
381
382impl PortWatcher {
383 pub fn new() -> Self {
385 Self {
386 cache: Mutex::new(HashMap::new()),
387 observed: Mutex::new(HashMap::new()),
388 ttl: CACHE_TTL,
389 scanner: Box::new(platform_scan),
390 }
391 }
392
393 pub fn with_scanner(
395 ttl: Duration,
396 scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync>,
397 ) -> Self {
398 Self {
399 cache: Mutex::new(HashMap::new()),
400 observed: Mutex::new(HashMap::new()),
401 ttl,
402 scanner,
403 }
404 }
405
406 pub fn clear(&self) {
408 lock(&self.cache).clear();
409 lock(&self.observed).clear();
410 }
411
412 pub fn check(&self, ports_to_check: &[u16]) -> Vec<PortStatus> {
415 let now = Instant::now();
416 let stale = {
417 let observed = lock(&self.observed);
418 ports_to_check.iter().any(|port| {
419 observed
420 .get(port)
421 .is_none_or(|checked_at| now.duration_since(*checked_at) >= self.ttl)
422 })
423 };
424
425 if stale {
426 let scan = (self.scanner)();
427 let mut cache = lock(&self.cache);
428 let mut observed = lock(&self.observed);
429 for port in ports_to_check {
430 cache.remove(port);
431 observed.insert(*port, now);
432 }
433 for (port, pid, process_name) in scan {
434 observed.insert(port, now);
435 cache.insert(port, CachedEntry { pid, process_name });
436 }
437 }
438
439 let cache = lock(&self.cache);
440 ports_to_check
441 .iter()
442 .filter_map(|port| {
443 cache.get(port).map(|entry| PortStatus {
444 port: *port,
445 pid: entry.pid,
446 process_name: entry.process_name.clone(),
447 status: status_for_port(*port),
448 })
449 })
450 .collect()
451 }
452
453 pub fn find_blocked(&self, ports_to_check: &[u16]) -> Vec<(u16, u32, String)> {
455 self.check(ports_to_check)
456 .into_iter()
457 .map(|status| (status.port, status.pid, status.process_name))
458 .collect()
459 }
460}
461
462impl Default for PortWatcher {
463 fn default() -> Self {
464 Self::new()
465 }
466}
467
468fn default_watcher() -> &'static PortWatcher {
469 static WATCHER: OnceLock<PortWatcher> = OnceLock::new();
470 WATCHER.get_or_init(PortWatcher::new)
471}
472
473pub fn check_blocked_ports(ports_to_check: &[u16]) -> Vec<(u16, u32, String)> {
480 default_watcher().find_blocked(ports_to_check)
481}
482
483pub fn find_blocked_ports(ports_to_check: &[u16]) -> Vec<(u16, u32)> {
486 check_blocked_ports(ports_to_check)
487 .into_iter()
488 .map(|(port, pid, _)| (port, pid))
489 .collect()
490}
491
492pub fn port_remediation(port: u16, pid: u32) -> String {
494 let kill = if cfg!(windows) {
495 format!("taskkill /PID {pid} /F")
496 } else {
497 format!("kill {pid}")
498 };
499 format!(
500 "Stop the process (e.g. `{kill}`), or configure your app to use another port (e.g. PORT={port})"
501 )
502}
503
504pub fn diagnostic_for(port: u16, pid: u32, process_name: &str) -> DiagnosticResult {
519 let display = if process_name.trim().is_empty() {
520 "unknown process"
521 } else {
522 process_name
523 };
524 DiagnosticResult::new(
525 format!("Port {port}"),
526 status_for_port(port),
527 format!("Port {port} is occupied by PID {pid} ({display})"),
528 )
529 .with_remediation(port_remediation(port, pid))
530}
531
532pub fn blocked_port_results(ports_to_check: &[u16]) -> Vec<DiagnosticResult> {
534 check_blocked_ports(ports_to_check)
535 .into_iter()
536 .map(|(port, pid, process_name)| diagnostic_for(port, pid, &process_name))
537 .collect()
538}
539
540#[cfg(test)]
541mod tests {
542 use super::*;
543 use std::sync::atomic::{AtomicUsize, Ordering};
544 use std::sync::Arc;
545
546 #[test]
549 fn parse_netstat_extracts_port_and_pid() {
550 let netstat = "\
551 TCP 0.0.0.0:3000 0.0.0.0:0 LISTENING 9921
552 TCP 127.0.0.1:8080 0.0.0.0:0 LISTENING 12345
553 TCP [::]:135 0.0.0.0:0 LISTENING 1234
554 UDP 0.0.0.0:137 *:* 65500
555";
556 let found = parse_netstat(netstat);
557 assert_eq!(found, vec![(135, 1234), (3000, 9921), (8080, 12345)]);
558 }
559
560 #[test]
561 fn parse_netstat_ignores_non_listening() {
562 let netstat = "\
563 TCP 127.0.0.1:50001 0.0.0.0:0 ESTABLISHED 55
564 TCP 127.0.0.1:50002 0.0.0.0:0 TIME_WAIT 0
565";
566 assert!(parse_netstat(netstat).is_empty());
567 }
568
569 #[test]
570 fn parse_tasklist_maps_pids_to_names() {
571 let tasks = "\
572\"node.exe\",\"9921\",\"Console\",\"1\",\"30,292 K\"
573\"python.exe\",\"12345\",\"Console\",\"1\",\"11,240 K\"
574INFO: No tasks are running
575";
576 let names = parse_tasklist(tasks);
577 assert_eq!(names.get(&9921).map(String::as_str), Some("node.exe"));
578 assert_eq!(names.get(&12345).map(String::as_str), Some("python.exe"));
579 assert_eq!(names.len(), 2);
580 }
581
582 #[test]
583 fn parse_lsof_extracts_command_pid_and_port() {
584 let lsof = "\
585COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
586node 9921 aseem 21u IPv4 12345 0t0 TCP *:3000 (LISTEN)
587python 12345 aseem 22u IPv6 67890 0t0 TCP [::]:8080 (LISTEN)
588bash 7777 aseem 4u IPv4 11111 0t0 TCP 127.0.0.1:5432 (LISTEN)
589";
590 let found = parse_lsof(lsof);
591 assert!(found.contains(&(3000, 9921, "node".to_string())));
592 assert!(found.contains(&(8080, 12345, "python".to_string())));
593 assert!(found.contains(&(5432, 7777, "bash".to_string())));
594 assert_eq!(found.len(), 3);
595 }
596
597 #[test]
598 fn parse_proc_net_tcp_keeps_only_listening_hex_ports() {
599 let tcp = "\
600 sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode
601 0: 0100007F:0BB8 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 12345 1 0000000000000000 100 0 0 10 0
602 1: 0100007F:D940 0100007F:0BB8 01 00000000:00000000 00:00000000 00000000 0 0 54321 1 0000000000000000 20 4 30 10 -1
603 2: 0100007F:1388 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 99999 1 0000000000000000 100 0 0 10 0
604";
605 assert_eq!(parse_proc_net_tcp(tcp), vec![3000, 5000]);
606 }
607
608 #[test]
611 fn status_classifies_critical_and_privileged_fail() {
612 assert_eq!(status_for_port(3000), CheckStatus::Warn);
613 assert_eq!(status_for_port(5432), CheckStatus::Fail);
614 assert_eq!(status_for_port(443), CheckStatus::Fail);
615 assert_eq!(status_for_port(80), CheckStatus::Fail);
616 }
617
618 #[test]
621 fn diagnostic_for_builds_message_and_remediation() {
622 let d = diagnostic_for(3000, 9921, "node");
623 assert_eq!(d.check_name, "Port 3000");
624 assert_eq!(d.status, CheckStatus::Warn);
625 assert_eq!(d.message, "Port 3000 is occupied by PID 9921 (node)");
626 let remediation = d.remediation.unwrap();
627 assert!(remediation.contains("9921"));
628 assert!(remediation.contains("3000"));
629 if cfg!(windows) {
630 assert!(remediation.contains("taskkill"));
631 } else {
632 assert!(remediation.contains("kill 9921"));
633 }
634 }
635
636 #[test]
637 fn diagnostic_for_unknown_process_is_readable() {
638 let d = diagnostic_for(8080, 0, "");
639 assert!(d.message.contains("unknown process"));
640 }
641
642 #[test]
643 fn diagnostic_for_critical_port_fails() {
644 let d = diagnostic_for(5432, 6880, "postgres");
645 assert_eq!(d.status, CheckStatus::Fail);
646 }
647
648 #[test]
651 fn watcher_caches_scan_results() {
652 let calls = Arc::new(AtomicUsize::new(0));
653 let calls_for_scan = Arc::clone(&calls);
654 let scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync> = Box::new(move || {
655 calls_for_scan.fetch_add(1, Ordering::SeqCst);
656 vec![(3000, 111, "web-server".to_string())]
657 });
658 let watcher = PortWatcher::with_scanner(Duration::from_secs(60), scanner);
659
660 let first = watcher.find_blocked(&[3000, 8080]);
661 let second = watcher.find_blocked(&[3000, 8080]);
662
663 assert_eq!(first, vec![(3000, 111, "web-server".to_string())]);
664 assert_eq!(second, first);
665 assert_eq!(calls.load(Ordering::SeqCst), 1);
666 }
667
668 #[test]
669 fn watcher_rescans_after_clear() {
670 let calls = Arc::new(AtomicUsize::new(0));
671 let calls_for_scan = Arc::clone(&calls);
672 let scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync> = Box::new(move || {
673 calls_for_scan.fetch_add(1, Ordering::SeqCst);
674 vec![(5000, 222, "api".to_string())]
675 });
676 let watcher = PortWatcher::with_scanner(Duration::from_secs(60), scanner);
677
678 let _ = watcher.find_blocked(&[5000]);
679 watcher.clear();
680 let _ = watcher.find_blocked(&[5000]);
681
682 assert_eq!(calls.load(Ordering::SeqCst), 2);
683 }
684
685 #[test]
686 fn watcher_stale_entry_triggers_rescan() {
687 let calls = Arc::new(AtomicUsize::new(0));
688 let calls_for_scan = Arc::clone(&calls);
689 let scanner: Box<dyn Fn() -> Vec<(u16, u32, String)> + Send + Sync> = Box::new(move || {
690 calls_for_scan.fetch_add(1, Ordering::SeqCst);
691 vec![(9000, 333, "old".to_string())]
692 });
693 let watcher = PortWatcher::with_scanner(Duration::ZERO, scanner);
695
696 let _ = watcher.find_blocked(&[9000]);
697 let _ = watcher.find_blocked(&[9000]);
698
699 assert_eq!(calls.load(Ordering::SeqCst), 2);
700 }
701
702 #[test]
705 fn is_port_in_use_detects_bound_port() {
706 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
707 let port = listener.local_addr().expect("local addr").port();
708 let occupied = is_port_in_use(port);
709 drop(listener);
710 assert!(occupied);
711 }
712
713 #[test]
714 fn is_port_in_use_free_after_drop() {
715 let listener = TcpListener::bind(("127.0.0.1", 0)).expect("bind ephemeral port");
716 let port = listener.local_addr().expect("local addr").port();
717 drop(listener);
718 assert!(!is_port_in_use(port));
719 }
720
721 #[test]
724 fn check_blocked_ports_runs_without_panicking() {
725 let results = check_blocked_ports(DEFAULT_DEV_PORTS);
727 for (port, pid, _) in &results {
728 assert!(DEFAULT_DEV_PORTS.contains(port));
729 assert_ne!(*pid, 0, "port {port} should resolve to a PID");
730 }
731 }
732
733 #[test]
734 fn default_ports_are_well_known_dev_ports() {
735 assert_eq!(DEFAULT_DEV_PORTS, &[3000, 5000, 8000, 8080, 9000]);
736 }
737}