use std::collections::HashSet;
use std::process::Command;
use std::sync::LazyLock;
use regex::Regex;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PortHit {
pub port: u16,
pub url: Option<String>,
pub process: Option<String>,
}
impl PortHit {
fn bare(port: u16) -> Self {
Self {
port,
url: None,
process: None,
}
}
}
static URL_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"(?i)\bhttps?://(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])(?::(\d{1,5}))?(?:/[^\s'\x22)\]]*)?")
.expect("port URL regex")
});
static BARE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?i)\b(?:listening|serving|started|running|bound)\b[^\n]{0,40}?(?:\bport\b\s*:?\s*|:\s*)(\d{2,5})\b",
)
.expect("bare port regex")
});
fn is_clock_time(text: &str, start: usize, digits: &str) -> bool {
if digits.len() != 2 {
return false;
}
let before = text[..start].trim_end();
let Some(head) = before.strip_suffix(':') else {
return false;
};
let hour: String = head
.chars()
.rev()
.take_while(|c| c.is_ascii_digit())
.collect();
if hour.is_empty() || hour.len() > 2 {
return false;
}
!head[..head.len() - hour.len()]
.ends_with(|c: char| c == '.' || c == '-' || c == '_' || c.is_ascii_alphanumeric())
}
static CLICK_URL_RE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r#"(?i)\bhttps?://[^\s'"<>()\[\]]+"#).expect("click url regex"));
pub fn url_at(text: &str, col: usize) -> Option<String> {
for m in CLICK_URL_RE.find_iter(text) {
let start = text[..m.start()].chars().count();
let end = start + m.as_str().chars().count();
if col >= start && col < end {
let url = m.as_str().trim_end_matches(['.', ',', ';', ':', '!', '?']);
return Some(url.to_string());
}
}
None
}
pub fn loopback_url_port(url: &str) -> Option<u16> {
let cap = URL_RE.captures(url)?;
if cap.get(0)?.start() != 0 {
return None;
}
cap.get(1).and_then(|m| parse_port(m.as_str())).or(Some(
if url.to_ascii_lowercase().starts_with("https") {
443
} else {
80
},
))
}
fn parse_port(s: &str) -> Option<u16> {
s.parse::<u32>()
.ok()
.filter(|p| *p >= 1 && *p <= 65535)
.map(|p| p as u16)
}
pub struct PortSniffer {
carry: String,
}
const CARRY_BYTES: usize = 256;
impl PortSniffer {
pub fn new() -> Self {
Self {
carry: String::new(),
}
}
pub fn sniff(&mut self, chunk: &[u8], tx: &std::sync::mpsc::Sender<PortHit>) {
let carry_len = self.carry.len();
let text = format!("{}{}", self.carry, String::from_utf8_lossy(chunk));
for (end, hit) in scan_with_pos(&text) {
if end > carry_len {
let _ = tx.send(hit);
}
}
let mut keep_from = text.len().saturating_sub(CARRY_BYTES);
while keep_from < text.len() && !text.is_char_boundary(keep_from) {
keep_from += 1;
}
self.carry = text[keep_from..].to_string();
}
}
impl Default for PortSniffer {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
fn scan(text: &str) -> Vec<PortHit> {
scan_with_pos(text).into_iter().map(|(_, h)| h).collect()
}
fn scan_with_pos(text: &str) -> Vec<(usize, PortHit)> {
let mut out: Vec<(usize, PortHit)> = Vec::new();
for cap in URL_RE.captures_iter(text) {
let m = cap.get(0).expect("group 0 always present");
let whole = m.as_str().to_string();
let port = cap.get(1).and_then(|g| parse_port(g.as_str())).unwrap_or(
if whole.to_ascii_lowercase().starts_with("https") {
443
} else {
80
},
);
out.push((
m.end(),
PortHit {
port,
url: Some(whole),
process: None,
},
));
}
for cap in BARE_RE.captures_iter(text) {
if let Some(g) = cap.get(1)
&& !is_clock_time(text, g.start(), g.as_str())
&& let Some(port) = parse_port(g.as_str())
&& !out.iter().any(|(_, h)| h.port == port)
{
out.push((g.end(), PortHit::bare(port)));
}
}
out
}
fn descendant_pids(root: i32) -> HashSet<i32> {
let mut subtree: HashSet<i32> = HashSet::new();
subtree.insert(root);
let Ok(out) = Command::new("ps").args(["-axo", "pid=,ppid="]).output() else {
return subtree;
};
let text = String::from_utf8_lossy(&out.stdout);
let pairs: Vec<(i32, i32)> = text
.lines()
.filter_map(|l| {
let mut it = l.split_whitespace();
let pid = it.next()?.parse().ok()?;
let ppid = it.next()?.parse().ok()?;
Some((pid, ppid))
})
.collect();
loop {
let before = subtree.len();
for (pid, ppid) in &pairs {
if subtree.contains(ppid) {
subtree.insert(*pid);
}
}
if subtree.len() == before {
break;
}
}
subtree
}
pub fn poll_listeners(shell_pid: i32) -> Vec<PortHit> {
let pids = descendant_pids(shell_pid);
if let Some(hits) = poll_via_lsof(&pids) {
return hits;
}
poll_via_ss(&pids).unwrap_or_default()
}
pub fn poll_all_listening() -> Option<HashSet<u16>> {
let out = Command::new("lsof")
.args(["-nP", "-iTCP", "-sTCP:LISTEN"])
.output()
.ok();
if let Some(out) = out
&& (out.status.success() || !out.stdout.is_empty())
{
return Some(
parse_lsof(&String::from_utf8_lossy(&out.stdout))
.into_iter()
.map(|h| h.port)
.collect(),
);
}
let out = Command::new("ss").args(["-tlnH"]).output().ok()?;
if !out.status.success() {
return None;
}
Some(
String::from_utf8_lossy(&out.stdout)
.lines()
.filter_map(|l| l.split_whitespace().nth(3).and_then(loopback_port))
.collect(),
)
}
fn poll_via_lsof(pids: &HashSet<i32>) -> Option<Vec<PortHit>> {
if pids.is_empty() {
return Some(Vec::new());
}
let pid_arg = pids
.iter()
.map(|p| p.to_string())
.collect::<Vec<_>>()
.join(",");
let out = Command::new("lsof")
.args(["-nP", "-iTCP", "-sTCP:LISTEN", "-a", "-p", &pid_arg])
.output()
.ok()?;
if !out.status.success() && out.stdout.is_empty() {
return None;
}
Some(parse_lsof(&String::from_utf8_lossy(&out.stdout)))
}
fn parse_lsof(text: &str) -> Vec<PortHit> {
let mut out: Vec<PortHit> = Vec::new();
for line in text.lines().skip(1) {
let fields: Vec<&str> = line.split_whitespace().collect();
let Some(cmd) = fields.first() else { continue };
if let Some(port) = fields.iter().find_map(|f| loopback_port(f))
&& !out.iter().any(|h| h.port == port)
{
out.push(PortHit {
port,
url: None,
process: Some((*cmd).to_string()),
});
}
}
out
}
fn poll_via_ss(pids: &HashSet<i32>) -> Option<Vec<PortHit>> {
let out = Command::new("ss").args(["-tlnpH"]).output().ok()?;
if !out.status.success() {
return None;
}
Some(parse_ss(&String::from_utf8_lossy(&out.stdout), pids))
}
fn parse_ss(text: &str, pids: &HashSet<i32>) -> Vec<PortHit> {
let mut out: Vec<PortHit> = Vec::new();
for line in text.lines() {
let fields: Vec<&str> = line.split_whitespace().collect();
let Some(local) = fields.get(3) else { continue };
let Some(port) = loopback_port(local) else {
continue;
};
let proc = fields
.last()
.and_then(|f| ss_pid(f).map(|pid| (pid, ss_proc_name(f))));
match proc {
Some((pid, name))
if (pids.is_empty() || pids.contains(&pid))
&& !out.iter().any(|h| h.port == port) =>
{
out.push(PortHit {
port,
url: None,
process: name,
});
}
_ => {}
}
}
out
}
fn ss_pid(field: &str) -> Option<i32> {
let start = field.find("pid=")? + 4;
let rest = &field[start..];
let end = rest
.find(|c: char| !c.is_ascii_digit())
.unwrap_or(rest.len());
rest[..end].parse().ok()
}
fn ss_proc_name(field: &str) -> Option<String> {
let start = field.find("((\"")? + 3;
let rest = &field[start..];
let end = rest.find('"')?;
Some(rest[..end].to_string())
}
fn loopback_port(addr: &str) -> Option<u16> {
let (host, port) = addr.rsplit_once(':')?;
let host = host.trim_matches(|c| c == '[' || c == ']');
let loopback = matches!(
host,
"" | "*" | "0.0.0.0" | "127.0.0.1" | "::" | "::1" | "localhost"
);
if !loopback {
return None;
}
parse_port(port)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scans_a_vite_banner_url_with_port_and_path() {
let hits = scan(" VITE v5.2 ready -> Local: http://localhost:3000/app");
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].port, 3000);
assert_eq!(hits[0].url.as_deref(), Some("http://localhost:3000/app"));
}
#[test]
fn scans_a_bare_listening_line() {
let hits = scan("INFO server listening on port 8080");
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].port, 8080);
assert!(hits[0].url.is_none());
}
#[test]
fn the_reconciliation_snapshot_covers_listeners_outside_any_subtree() {
let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind a loopback port");
let port = listener.local_addr().unwrap().port();
let Some(all) = poll_all_listening() else {
return;
};
assert!(
all.contains(&port),
"port {port} is listening but missing from the snapshot"
);
}
#[test]
fn a_plain_count_after_an_announce_verb_is_not_a_port() {
for line in [
"running 289 tests",
"Started 15 workers",
"started 42 jobs, running 1200 checks",
] {
assert!(scan(line).is_empty(), "{line:?} must not report a port");
}
}
#[test]
fn a_clock_time_after_an_announce_verb_is_not_a_port() {
for line in [
"Started backup at 03:15",
"server started, running since 10:22",
"running 289 tests across 12:30 minutes",
] {
assert!(scan(line).is_empty(), "{line:?} must not report a port");
}
}
#[test]
fn announce_lines_with_a_port_or_a_colon_still_match() {
for (line, port) in [
("Listening on port 8080", 8080u16),
("Example app listening on port: 3000", 3000),
("Server listening on port : 8080", 8080),
("serving at :4000", 4000),
("bound to 0.0.0.0:9229", 9229),
("bound to 0.0.0.0:80", 80),
("listening on 127.0.0.1:80", 80),
("bound to api1:80", 80),
("listening on web-1:80", 80),
] {
let hits = scan(line);
assert_eq!(hits.len(), 1, "{line:?}");
assert_eq!(hits[0].port, port, "{line:?}");
}
}
#[test]
fn url_wins_over_bare_for_the_same_port() {
let hits = scan("listening on http://127.0.0.1:5000 — now serving 5000");
assert_eq!(hits.iter().filter(|h| h.port == 5000).count(), 1);
assert!(hits.iter().any(|h| h.port == 5000 && h.url.is_some()));
}
#[test]
fn ignores_public_hosts() {
assert!(scan("see https://example.com:8443/docs").is_empty());
}
#[test]
fn https_url_without_explicit_port_defaults_to_443() {
let hits = scan("ready at https://localhost/");
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].port, 443);
}
#[test]
fn sniffer_does_not_double_emit_a_banner_via_the_carry() {
let (tx, rx) = std::sync::mpsc::channel();
let mut s = PortSniffer::new();
s.sniff(b"up at http://localhost:3000/\n", &tx);
s.sniff(b"$ \n", &tx);
let got: Vec<_> = rx.try_iter().collect();
assert_eq!(got.len(), 1, "carried banner is not re-emitted: {got:?}");
assert_eq!(got[0].port, 3000);
}
#[test]
fn sniffer_re_emits_a_port_after_the_server_stops_and_restarts() {
let (tx, rx) = std::sync::mpsc::channel();
let mut s = PortSniffer::new();
s.sniff(b"Serving on http://localhost:8000/\n", &tx);
s.sniff(b"^C\nKeyboard interrupt received, exiting.\n", &tx);
s.sniff(b"Serving on http://localhost:8000/\n", &tx);
let got: Vec<_> = rx.try_iter().collect();
assert_eq!(got.len(), 2, "restart re-emits the port: {got:?}");
assert!(got.iter().all(|h| h.port == 8000));
}
#[test]
fn sniffer_catches_a_port_split_across_chunks() {
let (tx, rx) = std::sync::mpsc::channel();
let mut s = PortSniffer::new();
s.sniff(b"Local: http://localho", &tx);
s.sniff(b"st:4173/ ready", &tx);
let got: Vec<_> = rx.try_iter().collect();
assert_eq!(got.len(), 1);
assert_eq!(got[0].port, 4173);
}
#[test]
fn parses_lsof_loopback_listeners_only() {
let sample = "COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME\n\
node 123 me 21u IPv4 0xabc 0t0 TCP 127.0.0.1:3000 (LISTEN)\n\
ssh 99 me 5u IPv4 0xdef 0t0 TCP 10.0.0.2:22 (LISTEN)\n";
let hits = parse_lsof(sample);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].port, 3000);
assert_eq!(hits[0].process.as_deref(), Some("node"));
}
#[test]
fn parses_ss_rows_scoped_to_pids() {
let sample = "LISTEN 0 511 127.0.0.1:5432 0.0.0.0:* users:((\"postgres\",pid=4242,fd=7))\n\
LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:((\"sshd\",pid=1,fd=3))\n";
let mut pids = HashSet::new();
pids.insert(4242);
let hits = parse_ss(sample, &pids);
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].port, 5432);
assert_eq!(hits[0].process.as_deref(), Some("postgres"));
}
#[test]
fn url_at_finds_the_link_under_the_cursor() {
let line = " visit http://localhost:3000/app for the UI";
assert_eq!(
url_at(line, 20).as_deref(),
Some("http://localhost:3000/app")
);
assert!(url_at(line, 2).is_none());
}
#[test]
fn url_at_trims_trailing_punctuation() {
let line = "see https://example.com/docs.";
assert_eq!(
url_at(line, 10).as_deref(),
Some("https://example.com/docs")
);
}
#[test]
fn loopback_url_port_classifies_dev_servers() {
assert_eq!(loopback_url_port("http://localhost:3000/app"), Some(3000));
assert_eq!(loopback_url_port("https://127.0.0.1/"), Some(443));
assert_eq!(loopback_url_port("http://localhost/"), Some(80));
assert!(loopback_url_port("https://example.com:8443/").is_none());
}
#[test]
fn loopback_port_rejects_public_bind() {
assert_eq!(loopback_port("127.0.0.1:3000"), Some(3000));
assert_eq!(loopback_port("*:8080"), Some(8080));
assert_eq!(loopback_port("[::1]:9000"), Some(9000));
assert_eq!(loopback_port("192.168.1.5:3000"), None);
}
}