1use std::collections::BTreeMap;
17use std::path::{Path, PathBuf};
18use std::sync::Mutex;
19
20use serde::{Deserialize, Serialize};
21
22const FILE_NAME: &str = "remote-helper-hosts.json";
23
24#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
25struct Hosts {
26 #[serde(default)]
27 hosts: Vec<String>,
28 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
29 info: BTreeMap<String, HostInfo>,
30}
31
32#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
34pub struct HostInfo {
35 #[serde(default, skip_serializing_if = "String::is_empty")]
37 pub uname: String,
38 #[serde(default, skip_serializing_if = "String::is_empty")]
40 pub helper_version: String,
41 #[serde(default)]
43 pub seen_at_ms: u64,
44}
45
46static LOCK: Mutex<()> = Mutex::new(());
48
49fn path_in(config_home: &Path) -> PathBuf {
50 config_home.join(FILE_NAME)
51}
52
53fn read(path: &Path) -> Hosts {
54 std::fs::read_to_string(path)
55 .ok()
56 .and_then(|s| serde_json::from_str(&s).ok())
57 .unwrap_or_default()
58}
59
60fn write(config_home: &Path, hosts: &Hosts) -> std::io::Result<()> {
61 use crate::backend::json_keep::{carry_unknown_keys, read_old, set_aside_if_unreadable};
62 let path = path_in(config_home);
63 std::fs::create_dir_all(config_home)?;
64 set_aside_if_unreadable::<Hosts>(&path);
67 let mut out = serde_json::to_value(hosts).unwrap_or_default();
68 if let Some(old) = read_old(&path) {
69 carry_unknown_keys(&old, &mut out, &["hosts", "info"]);
70 if let (Some(before), Some(now)) = (old.get("info").and_then(|i| i.as_object()), out.get_mut("info").and_then(|i| i.as_object_mut())) {
71 for (host, info) in now.iter_mut() {
72 if let Some(was) = before.get(host) {
73 carry_unknown_keys(was, info, &["uname", "helper_version", "seen_at_ms"]);
74 }
75 }
76 }
77 }
78 let tmp = path.with_extension("json.tmp");
79 std::fs::write(&tmp, serde_json::to_vec_pretty(&out).unwrap_or_default())?;
80 std::fs::rename(&tmp, &path)
81}
82
83fn canonical(connection: &str) -> Option<String> {
84 match super::ConnTarget::parse(connection) {
85 Ok(t @ super::ConnTarget::Ssh(_)) => Some(t.name()),
86 _ => None,
87 }
88}
89
90use agentmux_common::time::now_ms_u64 as now_ms;
91
92fn change_in(
95 config_home: &Path,
96 connection: &str,
97 helper: bool,
98 edit: impl FnOnce(&mut HostInfo),
99) -> std::io::Result<()> {
100 let Some(name) = canonical(connection) else {
101 return Ok(());
102 };
103 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
104 let mut hosts = read(&path_in(config_home));
105 let before = hosts.clone();
106 if helper && !hosts.hosts.contains(&name) {
107 hosts.hosts.push(name.clone());
108 }
109 let info = hosts.info.entry(name).or_default();
110 let mut edited = info.clone();
111 edit(&mut edited);
112 if edited != *info {
113 edited.seen_at_ms = now_ms();
114 *info = edited;
115 }
116 if hosts == before {
117 return Ok(());
118 }
119 write(config_home, &hosts)
120}
121
122pub fn known_in(config_home: &Path, connection: &str) -> bool {
124 let Some(name) = canonical(connection) else {
125 return false;
126 };
127 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
128 read(&path_in(config_home)).hosts.contains(&name)
129}
130
131pub fn remember_in(config_home: &Path, connection: &str, version: &str) -> std::io::Result<()> {
133 change_in(config_home, connection, true, |info| info.helper_version = version.to_string())
134}
135
136pub fn record_uname_in(config_home: &Path, connection: &str, uname: &str) -> std::io::Result<()> {
138 let uname = uname.trim();
139 if uname.is_empty() {
140 return Ok(());
141 }
142 change_in(config_home, connection, false, |info| info.uname = uname.to_string())
143}
144
145pub fn all_in(config_home: &Path) -> (Vec<String>, BTreeMap<String, HostInfo>) {
147 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
148 let hosts = read(&path_in(config_home));
149 (hosts.hosts, hosts.info)
150}
151
152pub fn known(connection: &str) -> bool {
154 known_in(&crate::backend::base::get_mux_config_dir(), connection)
155}
156
157pub fn remember(connection: &str) {
162 let config_home = crate::backend::base::get_mux_config_dir();
163 let version = env!("CARGO_PKG_VERSION");
164 let had = |c: &str| {
165 let (hosts, info) = all_in(&config_home);
166 canonical(c).is_some_and(|n| hosts.contains(&n) && info.get(&n).is_some_and(|i| i.helper_version == version))
167 };
168 let already = had(connection);
169 if let Err(e) = remember_in(&config_home, connection, version) {
170 tracing::warn!(connection = %connection, error = %e, "could not remember a helper host");
171 }
172 if !already {
173 on_machine_later(connection, true);
174 }
175}
176
177fn on_machine_later(connection: &str, installed: bool) {
180 let Ok(rt) = tokio::runtime::Handle::try_current() else {
181 return;
182 };
183 let connection = connection.to_string();
184 rt.spawn(async move {
185 if installed {
186 remember_on_machine(&connection).await;
187 } else if let Err(e) = forget_helper_on_machine(&connection).await {
188 tracing::warn!(connection = %connection, error = %e, "could not forget the helper record");
189 }
190 });
191}
192
193pub fn record_uname(connection: &str, uname: &str) {
195 if let Err(e) = record_uname_in(&crate::backend::base::get_mux_config_dir(), connection, uname) {
196 tracing::warn!(connection = %connection, error = %e, "could not record a host's platform");
197 }
198}
199
200pub fn forget_helper_in(config_home: &Path, connection: &str) -> std::io::Result<()> {
203 let Some(name) = canonical(connection) else {
204 return Ok(());
205 };
206 let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
207 let mut hosts = read(&path_in(config_home));
208 let before = hosts.clone();
209 hosts.hosts.retain(|h| h != &name);
210 if let Some(info) = hosts.info.get_mut(&name) {
211 if !info.helper_version.is_empty() {
212 info.helper_version.clear();
213 info.seen_at_ms = now_ms();
214 }
215 }
216 if hosts == before {
217 return Ok(());
218 }
219 write(config_home, &hosts)
220}
221
222pub fn forget_helper(connection: &str) -> std::io::Result<()> {
225 forget_helper_in(&crate::backend::base::get_mux_config_dir(), connection)?;
226 on_machine_later(connection, false);
227 Ok(())
228}
229
230fn machine_from_ssh_g(out: &str) -> Option<String> {
240 let (mut user, mut host, mut port) = (None, None, None);
241 for line in out.lines() {
242 match line.trim_end().split_once(' ') {
243 Some(("user", v)) if !v.trim().is_empty() => user = Some(v.trim().to_string()),
244 Some(("hostname", v)) if !v.trim().is_empty() => host = Some(v.trim().to_ascii_lowercase()),
245 Some(("port", v)) => port = v.trim().parse::<u16>().ok(),
246 _ => {}
247 }
248 }
249 Some(format!("{}@{}:{}", user?, host?, port?))
250}
251
252const SSH_G_AT_ONCE: usize = 4;
254
255const MACHINE_TTL: std::time::Duration = std::time::Duration::from_secs(300);
258
259async fn machine(connection: &str) -> Option<String> {
262 use std::collections::HashMap;
263 use std::sync::LazyLock;
264 use std::time::Instant;
265 static CACHE: LazyLock<Mutex<HashMap<String, (Instant, Option<String>)>>> = LazyLock::new(Default::default);
266 let name = canonical(connection)?;
267 if let Some((at, found)) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).get(&name) {
268 if at.elapsed() < MACHINE_TTL {
269 return found.clone();
270 }
271 }
272 let found = match super::ConnTarget::parse(&name) {
273 Ok(super::ConnTarget::Ssh(dest)) => super::address::ssh_g(&dest).await.and_then(|out| machine_from_ssh_g(&out)),
274 _ => None,
275 };
276 CACHE.lock().unwrap_or_else(|e| e.into_inner()).insert(name, (Instant::now(), found.clone()));
277 found
278}
279
280async fn same_machine(connection: &str) -> Vec<String> {
283 let Some(name) = canonical(connection) else {
284 return Vec::new();
285 };
286 let Some(target) = machine(&name).await else {
287 return Vec::new();
288 };
289 let mut names = tokio::task::spawn_blocking(super::ssh_config::hosts).await.unwrap_or_default();
290 let (recorded, info) = all_in(&crate::backend::base::get_mux_config_dir());
291 names.extend(recorded);
292 names.extend(info.into_keys());
293 let mut names: Vec<String> = names.iter().filter_map(|n| canonical(n)).filter(|n| *n != name).collect();
294 names.sort();
295 names.dedup();
296 use futures_util::StreamExt;
299 let machines: Vec<Option<String>> = futures_util::stream::iter(names.clone())
300 .map(|n| async move { machine(&n).await })
301 .buffered(SSH_G_AT_ONCE)
302 .collect()
303 .await;
304 names.into_iter().zip(machines).filter(|(_, m)| m.as_deref() == Some(target.as_str())).map(|(n, _)| n).collect()
305}
306
307fn remember_on_machine_in(config_home: &Path, connection: &str, same: &[String], version: &str) -> std::io::Result<()> {
309 remember_in(config_home, connection, version)?;
310 same.iter().try_for_each(|n| remember_in(config_home, n, version))
311}
312
313fn forget_on_machine_in(config_home: &Path, connection: &str, same: &[String]) -> std::io::Result<()> {
315 forget_helper_in(config_home, connection)?;
316 same.iter().try_for_each(|n| forget_helper_in(config_home, n))
317}
318
319pub async fn remember_on_machine(connection: &str) {
321 let same = same_machine(connection).await;
322 if let Err(e) = remember_on_machine_in(
323 &crate::backend::base::get_mux_config_dir(),
324 connection,
325 &same,
326 env!("CARGO_PKG_VERSION"),
327 ) {
328 tracing::warn!(connection = %connection, error = %e, "could not remember a helper host");
329 }
330}
331
332pub async fn forget_helper_on_machine(connection: &str) -> std::io::Result<()> {
334 let same = same_machine(connection).await;
335 forget_on_machine_in(&crate::backend::base::get_mux_config_dir(), connection, &same)
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 #[test]
343 fn a_removed_helper_is_forgotten_but_the_platform_kept() {
344 let dir = tempfile::tempdir().unwrap();
345 record_uname_in(dir.path(), "user@box", "Linux x86_64").unwrap();
346 remember_in(dir.path(), "user@box", "0.59.9").unwrap();
347 remember_in(dir.path(), "other@box", "0.59.9").unwrap();
348 forget_helper_in(dir.path(), " user@box ").unwrap();
349 assert!(!known_in(dir.path(), "user@box"));
350 assert!(known_in(dir.path(), "other@box"), "other hosts untouched");
351 let (_, info) = all_in(dir.path());
352 assert_eq!(info["user@box"].uname, "Linux x86_64");
353 assert_eq!(info["user@box"].helper_version, "");
354 }
355
356 #[test]
357 fn a_host_is_remembered_once_however_it_is_spelled() {
358 let dir = tempfile::tempdir().unwrap();
359 assert!(!known_in(dir.path(), "user@box"));
360 remember_in(dir.path(), "user@box", "0.59.9").unwrap();
361 remember_in(dir.path(), " user@box ", "0.59.9").unwrap();
362 assert!(known_in(dir.path(), "user@box"));
363 assert_eq!(read(&path_in(dir.path())).hosts.len(), 1);
364 assert!(!known_in(dir.path(), "other@box"));
365 remember_in(dir.path(), "wsl://Ubuntu", "0.59.9").unwrap();
367 assert!(!known_in(dir.path(), "wsl://Ubuntu"));
368 assert!(!known_in(dir.path(), "local"));
369 }
370
371 #[test]
372 fn a_hosts_platform_and_helper_version_are_kept_with_it() {
373 let dir = tempfile::tempdir().unwrap();
374 record_uname_in(dir.path(), "user@box", "Linux x86_64\n").unwrap();
375 assert!(!known_in(dir.path(), "user@box"), "a platform alone is not the helper");
376 remember_in(dir.path(), "user@box", "0.59.9").unwrap();
377 let (hosts, info) = all_in(dir.path());
378 assert_eq!(hosts, vec!["user@box".to_string()]);
379 let box_info = &info["user@box"];
380 assert_eq!(box_info.uname, "Linux x86_64");
381 assert_eq!(box_info.helper_version, "0.59.9");
382 assert!(box_info.seen_at_ms > 0);
383
384 remember_in(dir.path(), "user@box", "0.60.0").unwrap();
386 record_uname_in(dir.path(), "user@box", " ").unwrap();
387 let (_, info) = all_in(dir.path());
388 assert_eq!(info["user@box"].helper_version, "0.60.0");
389 assert_eq!(info["user@box"].uname, "Linux x86_64");
390 }
391
392 #[test]
393 fn a_file_from_before_the_records_still_reads() {
394 let dir = tempfile::tempdir().unwrap();
395 std::fs::write(path_in(dir.path()), r#"{ "hosts": ["user@box"] }"#).unwrap();
396 assert!(known_in(dir.path(), "user@box"));
397 let (_, info) = all_in(dir.path());
398 assert!(info.is_empty());
399 }
400
401 #[test]
405 fn a_helper_is_recorded_for_every_name_of_its_machine() {
406 let dir = tempfile::tempdir().unwrap();
407 let same = |n: &str| vec![if n == "box-key" { "box-pw" } else { "box-key" }.to_string()];
408 remember_on_machine_in(dir.path(), "box-key", &same("box-key"), "0.59.24").unwrap();
409 assert!(known_in(dir.path(), "box-key") && known_in(dir.path(), "box-pw"));
410 let (_, info) = all_in(dir.path());
411 assert_eq!(info["box-pw"].helper_version, "0.59.24");
412
413 forget_on_machine_in(dir.path(), "box-pw", &same("box-pw")).unwrap();
414 assert!(!known_in(dir.path(), "box-key") && !known_in(dir.path(), "box-pw"));
415
416 remember_on_machine_in(dir.path(), "other", &[], "0.59.24").unwrap();
418 forget_on_machine_in(dir.path(), "box-key", &same("box-key")).unwrap();
419 assert!(known_in(dir.path(), "other"));
420 }
421
422 #[test]
423 fn a_machine_is_the_account_host_and_port_ssh_connects_to() {
424 let g = "user tester\nhostname 127.0.0.1\nport 2222\npubkeyauthentication no\n";
425 assert_eq!(machine_from_ssh_g(g).as_deref(), Some("tester@127.0.0.1:2222"));
426 assert_eq!(machine_from_ssh_g("user me\nhostname Box.LAN\nport 22\n").as_deref(), Some("me@box.lan:22"));
428 assert_eq!(machine_from_ssh_g("hostname box\nport 22\n"), None);
429 }
430}