Skip to main content

agentmux_srv_core/backend/remote/
address.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Which machine a remote pane is connected to, by name and address, for its
5//! stats badge tooltip (`blockstats.detail`).
6//!
7//! - SSH: `ssh -G` says which host a destination really names (the user's
8//!   ssh config applies: an alias's `HostName`, `Include`, `Match`), and a
9//!   DNS lookup gives its address. Through a `ProxyJump` the address is
10//!   what this computer resolves the name to, which may be none.
11//! - WSL: the distribution's address on the interface its default route
12//!   uses, from `/proc/net/route` and `/proc/net/fib_trie`, which every
13//!   distribution has (BusyBox's `hostname` has no `-I`).
14//!
15//! Answers are kept for [`TTL`], failures too, so a tooltip that asks every
16//! few seconds runs `ssh` or `wsl.exe` at most once in that time.
17
18use std::collections::HashMap;
19use std::net::IpAddr;
20use std::sync::{Arc, Mutex, OnceLock};
21use std::time::{Duration, Instant};
22
23use super::ConnTarget;
24
25/// How long an answer is kept.
26const TTL: Duration = Duration::from_secs(300);
27
28/// How long `ssh -G`, `wsl.exe` or a DNS lookup may take.
29const STEP_TIMEOUT: Duration = Duration::from_secs(3);
30
31/// A remote pane's machine. Either part is `None` when it couldn't be found.
32#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct RemoteAddress {
34    /// SSH: the host name `ssh` connects to. WSL: the distribution.
35    pub host: Option<String>,
36    /// Its IP address.
37    pub address: Option<String>,
38}
39
40/// [`RemoteAddress`] for a remote connection, from the cache when it is
41/// fresh; `None` for a local one.
42pub async fn of(name: &str) -> Option<RemoteAddress> {
43    let target = ConnTarget::parse(name).ok()?;
44    if target == ConnTarget::Local {
45        return None;
46    }
47    // One slot per connection, its lock held across the lookup: a second
48    // tooltip asking for the same connection meanwhile waits for this answer
49    // instead of starting another, and one slow host holds up no other.
50    static SLOTS: OnceLock<Mutex<HashMap<String, Slot>>> = OnceLock::new();
51    let slot = SLOTS.get_or_init(Default::default).lock().unwrap().entry(name.to_string()).or_default().clone();
52    let mut cached = slot.lock().await;
53    if let Some((at, found)) = cached.as_ref() {
54        if at.elapsed() < TTL {
55            return Some(found.clone());
56        }
57    }
58    let found = match &target {
59        ConnTarget::Ssh(dest) => ssh(dest).await,
60        ConnTarget::Wsl(distro) => RemoteAddress {
61            host: Some(distro.clone()),
62            address: wsl_address(distro).await,
63        },
64        ConnTarget::Local => unreachable!(),
65    };
66    *cached = Some((Instant::now(), found.clone()));
67    Some(found)
68}
69
70type Slot = Arc<tokio::sync::Mutex<Option<(Instant, RemoteAddress)>>>;
71
72async fn ssh(dest: &super::conn::SshDest) -> RemoteAddress {
73    let (host, port) = match ssh_g(dest).await {
74        Some(out) => parse_ssh_g(&out),
75        None => (None, None),
76    };
77    let Some(host) = host else {
78        return RemoteAddress::default();
79    };
80    let address = resolve(&host, port.or(dest.port).unwrap_or(22)).await;
81    RemoteAddress { host: Some(host), address }
82}
83
84/// What `ssh -G` prints for `dest`: the options ssh would connect with, the
85/// user's ssh config applied. `None` if it fails or takes too long.
86pub(super) async fn ssh_g(dest: &super::conn::SshDest) -> Option<String> {
87    let binary = super::ssh::binary_for_user()?;
88    let mut cmd = tokio::process::Command::new(binary);
89    // Not ours to configure, and it needs nothing of AgentMux's environment.
90    crate::backend::pane_env::sanitize_external_command(&mut cmd);
91    cmd.arg("-G");
92    if let Some(port) = dest.port {
93        cmd.args(["-p", &port.to_string()]);
94    }
95    // `--` so a destination can never be read as an option.
96    // Killed if it outlives the timeout below, rather than left running.
97    cmd.args(["--", &dest.destination]).stdin(std::process::Stdio::null()).kill_on_drop(true);
98    #[cfg(windows)]
99    {
100        use agentmux_common::win32::NoWindow;
101        cmd.no_window();
102    }
103    match tokio::time::timeout(STEP_TIMEOUT, cmd.output()).await {
104        Ok(Ok(out)) if out.status.success() => Some(String::from_utf8_lossy(&out.stdout).into_owned()),
105        _ => None,
106    }
107}
108
109/// `hostname` and `port` from `ssh -G`'s output.
110fn parse_ssh_g(out: &str) -> (Option<String>, Option<u16>) {
111    let mut host = None;
112    let mut port = None;
113    for line in out.lines() {
114        match line.split_once(' ') {
115            Some(("hostname", v)) if !v.trim().is_empty() => host = Some(v.trim().to_string()),
116            Some(("port", v)) => port = v.trim().parse().ok(),
117            _ => {}
118        }
119    }
120    (host, port)
121}
122
123/// `host`'s address: itself when it is one, else the first a lookup gives,
124/// IPv4 first.
125async fn resolve(host: &str, port: u16) -> Option<String> {
126    if let Ok(ip) = host.trim_matches(['[', ']']).parse::<IpAddr>() {
127        return Some(ip.to_string());
128    }
129    let addrs: Vec<IpAddr> = tokio::time::timeout(STEP_TIMEOUT, tokio::net::lookup_host((host, port)))
130        .await
131        .ok()?
132        .ok()?
133        .map(|a| a.ip())
134        .collect();
135    addrs.iter().find(|ip| ip.is_ipv4()).or(addrs.first()).map(IpAddr::to_string)
136}
137
138async fn wsl_address(distro: &str) -> Option<String> {
139    #[cfg(windows)]
140    {
141        use agentmux_common::win32::NoWindow;
142        let mut cmd = tokio::process::Command::new("wsl.exe");
143        crate::backend::pane_env::sanitize_external_command(&mut cmd);
144        cmd.args(["-d", distro, "--exec", "cat", "/proc/net/route", "/proc/net/fib_trie"])
145            .stdin(std::process::Stdio::null())
146            .kill_on_drop(true)
147            .no_window();
148        match tokio::time::timeout(STEP_TIMEOUT, cmd.output()).await {
149            Ok(Ok(out)) if out.status.success() => linux_address(&String::from_utf8_lossy(&out.stdout)),
150            _ => None,
151        }
152    }
153    #[cfg(not(windows))]
154    {
155        let _ = distro;
156        None
157    }
158}
159
160/// A Linux machine's own IPv4 address, from `/proc/net/route` followed by
161/// `/proc/net/fib_trie`: of its local addresses, the one in a network on the
162/// interface the default route uses, else the first that isn't loopback.
163/// WSL also puts its DNS proxy's address on `lo`, which this skips.
164fn linux_address(out: &str) -> Option<String> {
165    use std::net::Ipv4Addr;
166    // /proc/net/route: tab-separated, addresses in hex, in memory order.
167    let hex = |s: &str| u32::from_str_radix(s, 16).ok().map(|v| Ipv4Addr::from(v.to_le_bytes()));
168    let routes: Vec<(&str, Ipv4Addr, Ipv4Addr)> = out
169        .lines()
170        .filter_map(|l| {
171            let f: Vec<&str> = l.split('\t').map(str::trim).collect();
172            (f.len() >= 8 && f[0] != "Iface").then(|| Some((f[0], hex(f[1])?, hex(f[7])?))).flatten()
173        })
174        .collect();
175    let default_iface = routes.iter().find(|r| r.1.is_unspecified()).map(|r| r.0);
176    let nets: Vec<(u32, u32)> = routes
177        .iter()
178        .filter(|r| Some(r.0) == default_iface && !r.1.is_unspecified())
179        .map(|r| (u32::from(r.1), u32::from(r.2)))
180        .collect();
181    // /proc/net/fib_trie: "|-- <address>" then "/32 host LOCAL" for each of
182    // the machine's own addresses.
183    let lines: Vec<&str> = out.lines().collect();
184    let mut local: Vec<Ipv4Addr> = Vec::new();
185    for w in lines.windows(2) {
186        if let (Some(addr), true) = (w[0].trim().strip_prefix("|-- "), w[1].contains("/32 host LOCAL")) {
187            if let Ok(ip) = addr.trim().parse::<Ipv4Addr>() {
188                if !ip.is_loopback() && !local.contains(&ip) {
189                    local.push(ip);
190                }
191            }
192        }
193    }
194    local
195        .iter()
196        .find(|ip| nets.iter().any(|&(net, mask)| u32::from(**ip) & mask == net))
197        .or(local.first())
198        .map(Ipv4Addr::to_string)
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn ssh_g_gives_the_real_host_and_port() {
207        let out = "user me\nhostname build.example.net\nport 2222\nhostkeyalias none\n";
208        assert_eq!(parse_ssh_g(out), (Some("build.example.net".to_string()), Some(2222)));
209        assert_eq!(parse_ssh_g("user me\n"), (None, None));
210        // Windows' ssh ends lines with CRLF.
211        assert_eq!(parse_ssh_g("hostname box\r\nport 22\r\n"), (Some("box".to_string()), Some(22)));
212    }
213
214    /// What a WSL distribution's `cat /proc/net/route /proc/net/fib_trie`
215    /// prints (docker-desktop's, abridged, with documentation addresses).
216    const WSL_NET: &str = concat!(
217        "Iface\tDestination\tGateway \tFlags\tRefCnt\tUse\tMetric\tMask\t\tMTU\tWindow\tIRTT\n",
218        "eth0\t00000000\t017100CB\t0003\t0\t0\t0\t00000000\t0\t0\t0\n",
219        "eth0\t007100CB\t00000000\t0001\t0\t0\t0\t00FFFFFF\t0\t0\t0\n",
220        "Main:\n",
221        "  +-- 0.0.0.0/0 3 0 5\n",
222        "     |-- 0.0.0.0\n",
223        "        /0 universe UNICAST\n",
224        "     +-- 198.51.100.254/32 host LOCAL\n",
225        "     |-- 198.51.100.254\n",
226        "        /32 host LOCAL\n",
227        "     +-- 127.0.0.0/8 2 0 2\n",
228        "        |-- 127.0.0.1\n",
229        "           /32 host LOCAL\n",
230        "     +-- 203.0.113.0/24 2 0 2\n",
231        "        |-- 203.0.113.121\n",
232        "           /32 host LOCAL\n",
233    );
234
235    #[test]
236    fn a_wsl_distro_is_its_address_on_the_default_route() {
237        assert_eq!(linux_address(WSL_NET), Some("203.0.113.121".to_string()));
238    }
239
240    #[test]
241    fn without_routes_the_first_non_loopback_address() {
242        assert_eq!(linux_address("Main:\n  |-- 127.0.0.1\n     /32 host LOCAL\n  |-- 192.0.2.20\n     /32 host LOCAL\n"), Some("192.0.2.20".to_string()));
243        assert_eq!(linux_address("Main:\n  |-- 127.0.0.1\n     /32 host LOCAL\n"), None);
244        assert_eq!(linux_address(""), None);
245    }
246
247    #[tokio::test]
248    async fn an_address_resolves_to_itself_without_a_lookup() {
249        assert_eq!(resolve("192.0.2.7", 22).await, Some("192.0.2.7".to_string()));
250        assert_eq!(resolve("[2001:db8::1]", 22).await, Some("2001:db8::1".to_string()));
251    }
252
253    #[tokio::test]
254    async fn localhost_resolves() {
255        let ip = resolve("localhost", 22).await.expect("localhost resolves");
256        assert!(ip == "127.0.0.1" || ip == "::1", "{ip}");
257    }
258
259    #[tokio::test]
260    async fn a_local_pane_has_no_remote_address() {
261        assert_eq!(of("").await, None);
262        assert_eq!(of("local").await, None);
263    }
264}