use anyhow::Result;
use serde::{Deserialize, Serialize};
use std::path::Path;
use std::sync::{Mutex, OnceLock};
use std::time::{Duration, Instant};
use crate::utils;
const PORT_TIMEOUT: Duration = Duration::from_millis(500);
static SS_OUTPUT_CACHE: OnceLock<Mutex<Option<(Instant, String)>>> = OnceLock::new();
fn ss_output_cache() -> &'static Mutex<Option<(Instant, String)>> {
SS_OUTPUT_CACHE.get_or_init(|| Mutex::new(None))
}
const SS_OUTPUT_TTL: Duration = Duration::from_secs(2);
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PortInfo {
pub ports: Vec<u16>,
}
pub fn detect_ports(path: &Path) -> Result<PortInfo> {
let abs_path = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
if let Ok(ports) = try_ss_with_cwd_check(&abs_path) {
return Ok(PortInfo { ports });
}
if let Ok(ports) = try_lsof_with_dir(&abs_path) {
return Ok(PortInfo { ports });
}
Ok(PortInfo { ports: Vec::new() })
}
fn try_ss_with_cwd_check(project_path: &Path) -> Result<Vec<u16>> {
let output = ss_output_cached()?;
let mut ports = Vec::new();
for line in output.lines() {
if line.starts_with("State") || line.starts_with("Recv-Q") {
continue;
}
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 6 {
continue;
}
let addr = parts[3];
let port_str = addr.rsplit(':').next().unwrap_or("");
let port: u16 = match port_str.parse() {
Ok(p) => p,
Err(_) => continue,
};
let process_info = parts.last().unwrap_or(&"");
let project_holds_socket = extract_pids(process_info)
.iter()
.any(|pid| pid_cwd_matches(*pid, project_path));
if project_holds_socket && !ports.contains(&port) {
ports.push(port);
}
}
ports.sort();
Ok(ports)
}
fn ss_output_cached() -> Result<String> {
{
let cache = ss_output_cache()
.lock()
.map_err(|e| anyhow::anyhow!("ss output cache poisoned: {}", e))?;
if let Some((at, ref out)) = *cache {
if at.elapsed() < SS_OUTPUT_TTL {
return Ok(out.clone());
}
}
}
let fresh = utils::run_with_timeout_stdout("ss", &["-tlnp"], PORT_TIMEOUT)?;
if let Ok(mut cache) = ss_output_cache().lock() {
*cache = Some((Instant::now(), fresh.clone()));
}
Ok(fresh)
}
fn extract_pids(info: &str) -> Vec<u32> {
let mut pids = Vec::new();
let mut rest = info;
while let Some(pid_start) = rest.find("pid=") {
let pid_str = &rest[pid_start + 4..];
let pid_end = pid_str
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(pid_str.len());
if pid_end > 0 {
if let Ok(pid) = pid_str[..pid_end].parse::<u32>() {
if !pids.contains(&pid) {
pids.push(pid);
}
}
}
rest = &pid_str[pid_end..];
}
pids
}
fn pid_cwd_matches(pid: u32, project_path: &Path) -> bool {
let cwd_link = format!("/proc/{}/cwd", pid);
match std::fs::read_link(&cwd_link) {
Ok(cwd) => {
let cwd_abs = cwd.canonicalize().unwrap_or(cwd);
cwd_abs == project_path || cwd_abs.starts_with(project_path)
}
Err(_) => false,
}
}
fn try_lsof_with_dir(project_path: &Path) -> Result<Vec<u16>> {
let path_str = project_path.to_string_lossy().to_string();
let output = utils::run_with_timeout_stdout(
"lsof",
&["-i", "-P", "-n", "-F", "pcftn", "+D", &path_str],
PORT_TIMEOUT,
)?;
let mut ports = Vec::new();
let mut current_pid: Option<u32> = None;
let mut current_conns: Vec<u16> = Vec::new();
for line in output.lines() {
if line.is_empty() {
continue;
}
let field = &line[..1];
let value = &line[1..];
match field {
"p" => {
if let Some(pid) = current_pid {
if pid_cwd_matches(pid, project_path) {
for port in ¤t_conns {
if !ports.contains(port) {
ports.push(*port);
}
}
}
}
current_conns.clear();
current_pid = value.parse().ok();
}
"n" => {
if value.contains("->") {
continue;
}
if let Some(port_str) = value.rsplit(':').next() {
if let Ok(port) = port_str.parse::<u16>() {
if !current_conns.contains(&port) {
current_conns.push(port);
}
}
}
}
_ => {}
}
}
if let Some(pid) = current_pid {
if pid_cwd_matches(pid, project_path) {
for port in ¤t_conns {
if !ports.contains(port) {
ports.push(*port);
}
}
}
}
ports.sort();
Ok(ports)
}