agentmux_srv_core/backend/remote/
address.rs1use std::collections::HashMap;
19use std::net::IpAddr;
20use std::sync::{Arc, Mutex, OnceLock};
21use std::time::{Duration, Instant};
22
23use super::ConnTarget;
24
25const TTL: Duration = Duration::from_secs(300);
27
28const STEP_TIMEOUT: Duration = Duration::from_secs(3);
30
31#[derive(Debug, Clone, Default, PartialEq, Eq)]
33pub struct RemoteAddress {
34 pub host: Option<String>,
36 pub address: Option<String>,
38}
39
40pub async fn of(name: &str) -> Option<RemoteAddress> {
43 let target = ConnTarget::parse(name).ok()?;
44 if target == ConnTarget::Local {
45 return None;
46 }
47 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
84pub(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 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 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
109fn 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
123async 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
160fn linux_address(out: &str) -> Option<String> {
165 use std::net::Ipv4Addr;
166 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 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 assert_eq!(parse_ssh_g("hostname box\r\nport 22\r\n"), (Some("box".to_string()), Some(22)));
212 }
213
214 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}