Skip to main content

agentmux_srv/server/
peer_process.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which process holds the other end of a loopback connection: the one that connected from `peer` to `server`. It is read
5//! from the operating system's own connection table (Windows: the extended TCP table; Linux: `/proc/net/tcp` and the
6//! descriptors under `/proc`; macOS: `lsof`). `None` when it cannot be said: the lookup is not supported, the table could
7//! not be read, the peer is not an IPv4 loopback address, or no process was found (a proxy or a tunnel holds the connection).
8//!
9//! The tables are read by the pure functions below, so their tests need no connection.
10
11use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
12
13/// The process that connected from `peer` to `server`, if the system says.
14pub(crate) fn owner_of(peer: SocketAddr, server: SocketAddr) -> Option<u32> {
15    let (SocketAddr::V4(peer), SocketAddr::V4(server)) = (peer, server) else { return None };
16    if !peer.ip().is_loopback() || !server.ip().is_loopback() {
17        return None;
18    }
19    os::owner_of(peer, server)
20}
21
22/// Who listens on an address.
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub(crate) enum Listeners {
25    /// The processes that hold the listening socket.
26    Held(Vec<u32>),
27    /// The socket is listening (these inodes) but no process this one can read holds it: a process that hides its descriptors
28    /// from others, as a packaged srv does on Linux. Only Linux says this.
29    #[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))]
30    Hidden(Vec<u64>),
31}
32
33/// Who listens on `addr`, if the system says: the listener that answers a request sent to that address. `None` when it
34/// cannot be said (not supported, the table could not be read, the address is not an IPv4 loopback address, or nothing
35/// listens there).
36pub(crate) fn listeners_at(addr: SocketAddr) -> Option<Listeners> {
37    let SocketAddr::V4(addr) = addr else { return None };
38    if !addr.ip().is_loopback() {
39        return None;
40    }
41    os::listeners_at(addr)
42}
43
44/// Whether this process can read `pid`'s open descriptors. `Hidden` is a process that hides them from others (Linux: a
45/// process that is not dumpable, as a packaged srv is). A system that does not hide them says `Readable`.
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47#[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))]
48pub(crate) enum Descriptors {
49    Readable,
50    Hidden,
51    Gone,
52}
53
54pub(crate) fn descriptors_of(pid: u32) -> Descriptors {
55    os::descriptors_of(pid)
56}
57
58/// The process ids `lsof` named for a listener or a connection on `port`, own process excluded.
59#[cfg(target_os = "macos")]
60fn lsof_pids(port: u16, state: &str) -> Option<Vec<u32>> {
61    let arg = format!("TCP@127.0.0.1:{port}");
62    let mut lsof = std::process::Command::new("lsof");
63    crate::backend::pane_env::sanitize_external_std_command(&mut lsof);
64    let out = lsof.args(["-nP", "-a", "-i", &arg, state, "-Fp"]).output().ok()?;
65    let own = std::process::id();
66    let mut pids: Vec<u32> = Vec::new();
67    for pid in pids_in_lsof(&String::from_utf8_lossy(&out.stdout)) {
68        if pid != own && !pids.contains(&pid) {
69            pids.push(pid);
70        }
71    }
72    Some(pids)
73}
74
75/// One row of the Windows extended TCP table, in the fields the lookup reads.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77#[cfg_attr(not(any(windows, test)), allow(dead_code))]
78pub(crate) struct TcpRow {
79    pub local: SocketAddrV4,
80    pub remote: SocketAddrV4,
81    pub pid: u32,
82}
83
84/// The rows of a `MIB_TCPTABLE_OWNER_PID` buffer (a count, then 24 bytes a row: state, local address, local port, remote
85/// address, remote port, owning process; ports in network order in the low 16 bits).
86#[cfg_attr(not(any(windows, test)), allow(dead_code))]
87pub(crate) fn parse_tcp_table(bytes: &[u8]) -> Vec<TcpRow> {
88    let word = |at: usize| bytes.get(at..at + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
89    let port = |v: u32| u16::from_be((v & 0xffff) as u16);
90    let Some(count) = word(0) else { return Vec::new() };
91    (0..count as usize)
92        .map_while(|i| {
93            let at = 4 + i * 24;
94            Some(TcpRow {
95                local: SocketAddrV4::new(Ipv4Addr::from(word(at + 4)?.to_le_bytes()), port(word(at + 8)?)),
96                remote: SocketAddrV4::new(Ipv4Addr::from(word(at + 12)?.to_le_bytes()), port(word(at + 16)?)),
97                pid: word(at + 20)?,
98            })
99        })
100        .collect()
101}
102
103/// The process of the row that is the client's end: its local end is `peer` and its remote end is `server`.
104#[cfg_attr(not(any(windows, test)), allow(dead_code))]
105pub(crate) fn owner_in_rows(rows: &[TcpRow], peer: SocketAddrV4, server: SocketAddrV4) -> Option<u32> {
106    rows.iter().find(|r| r.local == peer && r.remote == server).map(|r| r.pid)
107}
108
109/// The processes of the rows that listen on `addr`: a local end on that port (on that address or on every address) and no
110/// remote end.
111#[cfg_attr(not(any(windows, test)), allow(dead_code))]
112pub(crate) fn listeners_in_rows(rows: &[TcpRow], addr: SocketAddrV4) -> Vec<u32> {
113    let mut pids: Vec<u32> = rows
114        .iter()
115        .filter(|r| r.local.port() == addr.port() && (r.local.ip() == addr.ip() || r.local.ip().is_unspecified()) && r.remote.port() == 0)
116        .map(|r| r.pid)
117        .collect();
118    pids.sort_unstable();
119    pids.dedup();
120    pids
121}
122
123/// The socket inodes that listen on `addr` in the text of `/proc/net/tcp` (state `0A`, on that address or on every address).
124#[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))]
125pub(crate) fn listening_inodes_in_proc_net_tcp(text: &str, addr: SocketAddrV4) -> Vec<u64> {
126    text.lines()
127        .skip(1)
128        .filter_map(|line| {
129            let f: Vec<&str> = line.split_whitespace().collect();
130            if f.len() <= 9 || f[3] != "0A" {
131                return None;
132            }
133            let (ip, port) = f[1].split_once(':')?;
134            let ip = Ipv4Addr::from(u32::from_str_radix(ip, 16).ok()?.to_ne_bytes());
135            let port = u16::from_str_radix(port, 16).ok()?;
136            ((ip == *addr.ip() || ip.is_unspecified()) && port == addr.port()).then(|| f[9].parse().ok()).flatten()
137        })
138        .collect()
139}
140
141/// The socket inode of the connection from `peer` to `server` in the text of `/proc/net/tcp`.
142#[cfg_attr(not(any(target_os = "linux", test)), allow(dead_code))]
143pub(crate) fn inode_in_proc_net_tcp(text: &str, peer: SocketAddrV4, server: SocketAddrV4) -> Option<u64> {
144    let end = |s: &str| -> Option<SocketAddrV4> {
145        let (ip, port) = s.split_once(':')?;
146        let ip = u32::from_str_radix(ip, 16).ok()?;
147        Some(SocketAddrV4::new(Ipv4Addr::from(ip.to_ne_bytes()), u16::from_str_radix(port, 16).ok()?))
148    };
149    text.lines().skip(1).find_map(|line| {
150        let f: Vec<&str> = line.split_whitespace().collect();
151        (f.len() > 9 && end(f[1])? == peer && end(f[2])? == server).then(|| f[9].parse().ok()).flatten()
152    })
153}
154
155/// The process ids `lsof -Fp` named, one `p<pid>` line each.
156#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))]
157pub(crate) fn pids_in_lsof(out: &str) -> Vec<u32> {
158    out.lines().filter_map(|l| l.strip_prefix('p')?.trim().parse().ok()).collect()
159}
160
161#[cfg(windows)]
162mod os {
163    use super::*;
164    use windows_sys::Win32::NetworkManagement::IpHelper::{GetExtendedTcpTable, TCP_TABLE_OWNER_PID_ALL};
165    use windows_sys::Win32::Networking::WinSock::AF_INET;
166
167    const ERROR_INSUFFICIENT_BUFFER: u32 = 122;
168
169    pub(super) fn owner_of(peer: SocketAddrV4, server: SocketAddrV4) -> Option<u32> {
170        owner_in_rows(&read_rows()?, peer, server)
171    }
172
173    pub(super) fn listeners_at(addr: SocketAddrV4) -> Option<Listeners> {
174        let pids = listeners_in_rows(&read_rows()?, addr);
175        (!pids.is_empty()).then_some(Listeners::Held(pids))
176    }
177
178    pub(super) fn descriptors_of(_pid: u32) -> Descriptors {
179        Descriptors::Readable
180    }
181
182    fn read_rows() -> Option<Vec<TcpRow>> {
183        let mut size: u32 = 0;
184        // SAFETY: a null table with a zero size only asks how large the table is.
185        unsafe { GetExtendedTcpTable(std::ptr::null_mut(), &mut size, 0, u32::from(AF_INET), TCP_TABLE_OWNER_PID_ALL, 0) };
186        for _ in 0..4 {
187            let mut buf = vec![0u8; size as usize + 4096];
188            size = buf.len() as u32;
189            // SAFETY: `buf` is `size` bytes long and lives through the call.
190            let rc = unsafe { GetExtendedTcpTable(buf.as_mut_ptr().cast(), &mut size, 0, u32::from(AF_INET), TCP_TABLE_OWNER_PID_ALL, 0) };
191            match rc {
192                0 => return Some(parse_tcp_table(&buf)),
193                ERROR_INSUFFICIENT_BUFFER => continue,
194                _ => return None,
195            }
196        }
197        None
198    }
199}
200
201#[cfg(target_os = "linux")]
202mod os {
203    use super::*;
204
205    pub(super) fn owner_of(peer: SocketAddrV4, server: SocketAddrV4) -> Option<u32> {
206        let table = std::fs::read_to_string("/proc/net/tcp").ok()?;
207        let inode = inode_in_proc_net_tcp(&table, peer, server)?;
208        let want = format!("socket:[{inode}]");
209        for entry in std::fs::read_dir("/proc").ok()?.flatten() {
210            let Some(pid) = entry.file_name().to_str().and_then(|n| n.parse::<u32>().ok()) else { continue };
211            let Ok(fds) = std::fs::read_dir(entry.path().join("fd")) else { continue };
212            if fds.flatten().any(|fd| std::fs::read_link(fd.path()).is_ok_and(|t| t.to_str() == Some(want.as_str()))) {
213                return Some(pid);
214            }
215        }
216        None
217    }
218
219    pub(super) fn listeners_at(addr: SocketAddrV4) -> Option<Listeners> {
220        let table = std::fs::read_to_string("/proc/net/tcp").ok()?;
221        let mut inodes = listening_inodes_in_proc_net_tcp(&table, addr);
222        if inodes.is_empty() {
223            return None;
224        }
225        inodes.sort_unstable();
226        let wanted: Vec<String> = inodes.iter().map(|i| format!("socket:[{i}]")).collect();
227        let mut pids = Vec::new();
228        for entry in std::fs::read_dir("/proc").ok()?.flatten() {
229            let Some(pid) = entry.file_name().to_str().and_then(|n| n.parse::<u32>().ok()) else { continue };
230            let Ok(fds) = std::fs::read_dir(entry.path().join("fd")) else { continue };
231            if fds.flatten().any(|fd| std::fs::read_link(fd.path()).is_ok_and(|t| t.to_str().is_some_and(|t| wanted.iter().any(|w| w == t)))) {
232                pids.push(pid);
233            }
234        }
235        // A packaged srv hides its descriptors from every other process, so no process may be readable that holds the socket.
236        Some(if pids.is_empty() { Listeners::Hidden(inodes) } else { Listeners::Held(pids) })
237    }
238
239    pub(super) fn descriptors_of(pid: u32) -> Descriptors {
240        match std::fs::read_dir(format!("/proc/{pid}/fd")) {
241            Ok(_) => Descriptors::Readable,
242            Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => Descriptors::Hidden,
243            Err(_) => Descriptors::Gone,
244        }
245    }
246}
247
248#[cfg(target_os = "macos")]
249mod os {
250    use super::*;
251
252    pub(super) fn listeners_at(addr: SocketAddrV4) -> Option<Listeners> {
253        let mut pids = lsof_pids(addr.port(), "-sTCP:LISTEN")?;
254        pids.sort_unstable();
255        (!pids.is_empty()).then_some(Listeners::Held(pids))
256    }
257
258    pub(super) fn owner_of(peer: SocketAddrV4, _server: SocketAddrV4) -> Option<u32> {
259        lsof_pids(peer.port(), "-sTCP:ESTABLISHED")?.into_iter().next()
260    }
261
262    pub(super) fn descriptors_of(_pid: u32) -> Descriptors {
263        Descriptors::Readable
264    }
265}
266
267#[cfg(not(any(windows, target_os = "linux", target_os = "macos")))]
268mod os {
269    use super::*;
270
271    pub(super) fn owner_of(_peer: SocketAddrV4, _server: SocketAddrV4) -> Option<u32> {
272        None
273    }
274
275    pub(super) fn listeners_at(_addr: SocketAddrV4) -> Option<Listeners> {
276        None
277    }
278
279    pub(super) fn descriptors_of(_pid: u32) -> Descriptors {
280        Descriptors::Readable
281    }
282}
283
284#[cfg(test)]
285#[path = "tests/peer_process_tests.rs"]
286mod tests;