1use std::path::Path;
2use std::process::Command;
3
4use anyhow::{Context, Result};
5use log::{debug, error, info, warn};
6
7pub struct ConnectResult {
9 pub status: std::process::ExitStatus,
10 pub stderr_output: String,
11}
12
13#[cfg(unix)]
15pub fn is_in_tmux() -> bool {
16 std::env::var("TMUX").is_ok()
17}
18
19#[cfg(not(unix))]
21pub fn is_in_tmux() -> bool {
22 false
23}
24
25pub fn connect_tmux_window(alias: &str, config_path: &Path, has_active_tunnel: bool) -> Result<()> {
37 info!("SSH connection via tmux: {alias}");
38
39 let config_str = config_path
40 .to_str()
41 .context("SSH config path is not valid UTF-8")?;
42
43 let mut args = vec!["new-window", "-n", alias, "--", "ssh", "-F", config_str];
44
45 if has_active_tunnel {
46 args.extend(["-o", "ClearAllForwardings=yes"]);
47 }
48
49 args.extend(["--", alias]);
50
51 debug!("tmux args: {:?}", args);
52
53 let status = Command::new("tmux")
54 .args(&args)
55 .status()
56 .with_context(|| format!("Failed to launch tmux new-window for '{alias}'"))?;
57
58 if status.success() {
59 info!("tmux window created: {alias}");
60 Ok(())
61 } else {
62 let code = status.code().unwrap_or(-1);
63 error!("[external] tmux new-window failed for {alias} (exit {code})");
64 anyhow::bail!("tmux new-window exited with code {code}")
65 }
66}
67
68#[cfg(unix)]
71struct SignalMaskGuard {
72 old: libc::sigset_t,
73}
74
75#[cfg(unix)]
76impl SignalMaskGuard {
77 fn block_interactive() -> Self {
79 unsafe {
84 let mut old: libc::sigset_t = std::mem::zeroed();
85 let mut mask: libc::sigset_t = std::mem::zeroed();
86 libc::sigemptyset(&mut mask);
87 libc::sigaddset(&mut mask, libc::SIGINT);
88 libc::sigaddset(&mut mask, libc::SIGTSTP);
89 libc::sigprocmask(libc::SIG_BLOCK, &mask, &mut old);
90 Self { old }
91 }
92 }
93}
94
95#[cfg(unix)]
96impl Drop for SignalMaskGuard {
97 fn drop(&mut self) {
98 unsafe {
104 let mut pending: libc::sigset_t = std::mem::zeroed();
108 libc::sigpending(&mut pending);
109 let has_sigint = libc::sigismember(&pending, libc::SIGINT) == 1;
110 let has_sigtstp = libc::sigismember(&pending, libc::SIGTSTP) == 1;
111 if has_sigint {
113 libc::signal(libc::SIGINT, libc::SIG_IGN);
114 }
115 if has_sigtstp {
116 libc::signal(libc::SIGTSTP, libc::SIG_IGN);
117 }
118 libc::sigprocmask(libc::SIG_SETMASK, &self.old, std::ptr::null_mut());
119 if has_sigint {
121 libc::signal(libc::SIGINT, libc::SIG_DFL);
122 }
123 if has_sigtstp {
124 libc::signal(libc::SIGTSTP, libc::SIG_DFL);
125 }
126 }
127 }
128}
129
130fn spawn_ssh_and_wait(mut cmd: Command, alias: &str, log_label: &str) -> Result<ConnectResult> {
140 cmd.stdin(std::process::Stdio::inherit())
141 .stdout(std::process::Stdio::inherit())
142 .stderr(std::process::Stdio::piped());
143
144 #[cfg(unix)]
148 unsafe {
149 use std::os::unix::process::CommandExt;
150 cmd.pre_exec(|| {
151 let mut mask: libc::sigset_t = std::mem::zeroed();
152 libc::sigemptyset(&mut mask);
153 libc::sigprocmask(libc::SIG_SETMASK, &mask, std::ptr::null_mut());
154 Ok(())
155 });
156 }
157
158 let mut child = cmd
159 .spawn()
160 .with_context(|| format!("Failed to launch ssh {} for '{}'", log_label, alias))?;
161
162 #[cfg(unix)]
166 let _signal_guard = SignalMaskGuard::block_interactive();
167
168 let stderr_pipe = child.stderr.take().expect("stderr was piped");
169 let stderr_thread = std::thread::spawn(move || {
170 use std::io::{Read, Write};
171 let mut captured = Vec::new();
172 let mut buf = [0u8; 4096];
173 let mut reader = stderr_pipe;
174 let mut stderr_out = std::io::stderr();
175 loop {
176 match reader.read(&mut buf) {
177 Ok(0) => break,
178 Ok(n) => {
179 let _ = stderr_out.write_all(&buf[..n]);
180 let _ = stderr_out.flush();
181 captured.extend_from_slice(&buf[..n]);
182 }
183 Err(_) => break,
184 }
185 }
186 String::from_utf8_lossy(&captured).to_string()
187 });
188
189 let status = child
190 .wait()
191 .with_context(|| format!("Failed to wait for ssh {} for '{}'", log_label, alias))?;
192 let stderr_output = stderr_thread.join().unwrap_or_else(|_| {
193 warn!("[purple] Stderr capture thread panicked for {alias}");
194 String::new()
195 });
196
197 let code = status.code().unwrap_or(-1);
198 if code == 0 {
199 info!("SSH {} ended: {alias} (exit 0)", log_label);
200 } else {
201 error!("[external] SSH {} failed: {alias} (exit {code})", log_label);
202 if !stderr_output.is_empty() {
203 let stderr = stderr_output.trim();
204 let lower = stderr.to_lowercase();
205 if lower.contains("are too open") || lower.contains("bad permissions") {
206 warn!("[config] SSH key permission issue: {stderr}");
207 } else {
208 debug!("[external] SSH stderr: {stderr}");
209 }
210 }
211 }
212
213 Ok(ConnectResult {
214 status,
215 stderr_output,
216 })
217}
218
219pub fn connect(
226 alias: &str,
227 config_path: &Path,
228 askpass: Option<&str>,
229 bw_session: Option<&str>,
230 has_active_tunnel: bool,
231) -> Result<ConnectResult> {
232 info!("SSH connection started: {alias}");
233 debug!("SSH command: ssh -F {} -- {alias}", config_path.display());
234
235 let mut cmd = Command::new("ssh");
236 cmd.arg("-F").arg(config_path);
237
238 if has_active_tunnel {
241 cmd.arg("-o").arg("ClearAllForwardings=yes");
242 }
243
244 cmd.arg("--").arg(alias);
245
246 if askpass.is_some() {
247 crate::askpass_env::configure_ssh_command(&mut cmd, alias, config_path);
248 }
249
250 if let Some(token) = bw_session {
251 cmd.env("BW_SESSION", token);
252 }
253
254 spawn_ssh_and_wait(cmd, alias, "connection")
255}
256
257pub fn connect_with_remote_command(
270 alias: &str,
271 config_path: &Path,
272 askpass: Option<&str>,
273 bw_session: Option<&str>,
274 has_active_tunnel: bool,
275 remote_command: &str,
276) -> Result<ConnectResult> {
277 info!("SSH exec started: {alias}");
278 debug!(
279 "SSH command: ssh -F {} -t -- {alias} {}",
280 config_path.display(),
281 remote_command
282 );
283
284 let mut cmd = Command::new("ssh");
285 cmd.arg("-F").arg(config_path).arg("-t");
286
287 if has_active_tunnel {
288 cmd.arg("-o").arg("ClearAllForwardings=yes");
289 }
290
291 cmd.arg("--").arg(alias).arg(remote_command);
292
293 if askpass.is_some() {
294 crate::askpass_env::configure_ssh_command(&mut cmd, alias, config_path);
295 }
296
297 if let Some(token) = bw_session {
298 cmd.env("BW_SESSION", token);
299 }
300
301 spawn_ssh_and_wait(cmd, alias, "exec")
302}
303
304pub fn connect_tmux_window_with_remote_command(
309 alias: &str,
310 config_path: &Path,
311 has_active_tunnel: bool,
312 remote_command: &str,
313 window_label: &str,
314) -> Result<()> {
315 info!("SSH exec via tmux: {alias}");
316
317 let config_str = config_path
318 .to_str()
319 .context("SSH config path is not valid UTF-8")?;
320
321 let mut args = vec![
322 "new-window",
323 "-n",
324 window_label,
325 "--",
326 "ssh",
327 "-F",
328 config_str,
329 "-t",
330 ];
331
332 if has_active_tunnel {
333 args.extend(["-o", "ClearAllForwardings=yes"]);
334 }
335
336 args.extend(["--", alias, remote_command]);
337
338 debug!("tmux exec args: {:?}", args);
339
340 let status = Command::new("tmux")
341 .args(&args)
342 .status()
343 .with_context(|| format!("Failed to launch tmux exec window for '{alias}'"))?;
344
345 if status.success() {
346 info!("tmux exec window created: {alias}");
347 Ok(())
348 } else {
349 let code = status.code().unwrap_or(-1);
350 error!("[external] tmux exec window failed for {alias} (exit {code})");
351 anyhow::bail!("tmux new-window exited with code {code}")
352 }
353}
354
355pub fn stderr_summary(stderr: &str) -> Option<String> {
359 let summary: String = stderr
360 .lines()
361 .map(str::trim)
362 .filter(|l| !l.is_empty() && !l.starts_with('@'))
363 .collect::<Vec<_>>()
364 .join(" | ");
365 if summary.is_empty() {
366 return None;
367 }
368 if summary.len() > 200 {
369 let truncated: String = summary.chars().take(197).collect();
370 Some(format!("{truncated}..."))
371 } else {
372 Some(summary)
373 }
374}
375
376pub fn parse_host_key_error(stderr: &str) -> Option<(String, String)> {
386 let has_english_error = stderr.contains("Host key verification failed.");
388 let has_banner = stderr.contains("@@@@@@@@@@@@@@@");
390
391 if !has_english_error && !has_banner {
392 return None;
393 }
394
395 let hostname = stderr
397 .lines()
398 .find(|l| l.contains("Host key for") && l.contains("has changed"))
399 .and_then(|l| {
400 let start = l.find("Host key for ")? + "Host key for ".len();
401 let rest = &l[start..];
402 let end = rest.find(" has changed")?;
403 Some(rest[..end].to_string())
404 });
405
406 let known_hosts_path = stderr
408 .lines()
409 .find(|l| l.starts_with("Offending") && l.contains(" key in "))
410 .and_then(|l| {
411 let start = l.find(" key in ")? + " key in ".len();
412 let rest = &l[start..];
413 let end = rest.rfind(':')?;
414 Some(rest[..end].to_string())
415 });
416
417 let known_hosts_path = known_hosts_path?;
419
420 let hostname = hostname.unwrap_or_else(|| "the remote host".to_string());
425
426 Some((hostname, known_hosts_path))
427}
428
429#[cfg(test)]
430mod tests {
431 use super::*;
432
433 #[test]
434 fn connect_fails_with_nonexistent_config() {
435 let _guard = crate::vault_ssh::tests::ENV_LOCK
441 .lock()
442 .unwrap_or_else(|p| p.into_inner());
443 let result = connect(
444 "nonexistent-host",
445 Path::new("/tmp/__purple_test_nonexistent_config__"),
446 None,
447 None,
448 false,
449 );
450 assert!(result.is_ok()); let r = result.unwrap();
453 assert!(!r.status.success());
454 }
455
456 #[test]
457 fn connect_with_tunnel_flag_does_not_panic() {
458 let _guard = crate::vault_ssh::tests::ENV_LOCK
461 .lock()
462 .unwrap_or_else(|p| p.into_inner());
463 let result = connect(
464 "nonexistent-host",
465 Path::new("/tmp/__purple_test_nonexistent_config__"),
466 None,
467 None,
468 true,
469 );
470 assert!(result.is_ok());
471 assert!(!result.unwrap().status.success());
472 }
473
474 #[test]
475 fn connect_captures_stderr() {
476 let _guard = crate::vault_ssh::tests::ENV_LOCK
479 .lock()
480 .unwrap_or_else(|p| p.into_inner());
481 let result = connect(
482 "nonexistent-host",
483 Path::new("/tmp/__purple_test_nonexistent_config__"),
484 None,
485 None,
486 false,
487 );
488 assert!(result.is_ok());
489 let r = result.unwrap();
492 assert!(
493 !r.stderr_output.is_empty() || !r.status.success(),
494 "SSH should produce stderr or fail"
495 );
496 }
497
498 #[test]
501 fn parse_host_key_error_detects_changed_key() {
502 let stderr = "\
503@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
504@ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @
505@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
506IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
507Someone could be eavesdropping on you right now (man-in-the-middle attack)!
508It is also possible that a host key has just been changed.
509The fingerprint for the ED25519 key sent by the remote host is
510SHA256:ohwPXZbfBMvYWXnKefVYWVAcQsXKLMqaRKbXxRUVXqc.
511Please contact your system administrator.
512Add correct host key in /Users/user/.ssh/known_hosts to get rid of this message.
513Offending ECDSA key in /Users/user/.ssh/known_hosts:55
514Host key for example.com has changed and you have requested strict checking.
515Host key verification failed.
516";
517 let result = parse_host_key_error(stderr);
518 assert!(result.is_some());
519 let (hostname, path) = result.unwrap();
520 assert_eq!(hostname, "example.com");
521 assert_eq!(path, "/Users/user/.ssh/known_hosts");
522 }
523
524 #[test]
525 fn parse_host_key_error_returns_none_for_other_errors() {
526 let stderr = "ssh: connect to host example.com port 22: Connection refused\n";
527 assert!(parse_host_key_error(stderr).is_none());
528 }
529
530 #[test]
531 fn parse_host_key_error_returns_none_for_empty() {
532 assert!(parse_host_key_error("").is_none());
533 }
534
535 #[test]
536 fn parse_host_key_error_handles_ip_address() {
537 let stderr = "\
538Offending ECDSA key in /home/user/.ssh/known_hosts:12
539Host key for 10.0.0.1 has changed and you have requested strict checking.
540Host key verification failed.
541";
542 let result = parse_host_key_error(stderr);
543 assert!(result.is_some());
544 let (hostname, path) = result.unwrap();
545 assert_eq!(hostname, "10.0.0.1");
546 assert_eq!(path, "/home/user/.ssh/known_hosts");
547 }
548
549 #[test]
550 fn parse_host_key_error_handles_custom_known_hosts_path() {
551 let stderr = "\
552Offending RSA key in /etc/ssh/known_hosts:3
553Host key for server.local has changed and you have requested strict checking.
554Host key verification failed.
555";
556 let result = parse_host_key_error(stderr);
557 assert!(result.is_some());
558 let (hostname, path) = result.unwrap();
559 assert_eq!(hostname, "server.local");
560 assert_eq!(path, "/etc/ssh/known_hosts");
561 }
562
563 #[test]
564 fn parse_host_key_error_handles_ipv6() {
565 let stderr = "\
566Offending ED25519 key in /Users/user/.ssh/known_hosts:7
567Host key for ::1 has changed and you have requested strict checking.
568Host key verification failed.
569";
570 let result = parse_host_key_error(stderr);
571 assert!(result.is_some());
572 let (hostname, _) = result.unwrap();
573 assert_eq!(hostname, "::1");
574 }
575
576 #[test]
577 fn connect_tmux_window_fails_gracefully_outside_tmux_session() {
578 let _guard = TMUX_LOCK.lock().unwrap_or_else(|p| p.into_inner());
583 if std::env::var("TMUX").is_ok() {
584 return;
585 }
586 let result = connect_tmux_window(
587 "test-host",
588 Path::new("/tmp/__purple_test_nonexistent_config__"),
589 false,
590 );
591 assert!(result.is_err());
592 let err = result.unwrap_err().to_string();
593 assert!(
594 err.contains("tmux") || err.contains("No such file"),
595 "unexpected error: {err}"
596 );
597 }
598
599 #[test]
600 fn connect_tmux_window_with_tunnel_does_not_panic() {
601 let _guard = TMUX_LOCK.lock().unwrap_or_else(|p| p.into_inner());
605 if std::env::var("TMUX").is_ok() {
606 return;
607 }
608 let result = connect_tmux_window(
609 "tunnel-host",
610 Path::new("/tmp/__purple_test_nonexistent_config__"),
611 true,
612 );
613 assert!(result.is_err());
614 }
615
616 static TMUX_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
618
619 #[test]
620 fn is_in_tmux_returns_true_when_set() {
621 let _guard = TMUX_LOCK.lock().unwrap_or_else(|p| p.into_inner());
622 let prev = std::env::var("TMUX").ok();
623 unsafe { std::env::set_var("TMUX", "/tmp/tmux-1000/default,12345,0") };
625 let result = is_in_tmux();
626 match prev {
628 Some(v) => unsafe { std::env::set_var("TMUX", v) },
629 None => unsafe { std::env::remove_var("TMUX") },
630 }
631 assert!(result);
632 }
633
634 #[test]
635 fn is_in_tmux_returns_false_when_unset() {
636 let _guard = TMUX_LOCK.lock().unwrap_or_else(|p| p.into_inner());
637 let prev = std::env::var("TMUX").ok();
638 unsafe { std::env::remove_var("TMUX") };
640 let result = is_in_tmux();
641 if let Some(v) = prev {
643 unsafe { std::env::set_var("TMUX", v) };
644 }
645 assert!(!result);
646 }
647
648 #[test]
651 fn stderr_summary_joins_all_lines() {
652 let stderr = "channel 0: open failed: administratively prohibited: open failed\n\
653 stdio forwarding failed\n\
654 Connection closed by UNKNOWN port 65535\n";
655 let result = stderr_summary(stderr);
656 assert_eq!(
657 result.as_deref(),
658 Some(
659 "channel 0: open failed: administratively prohibited: open failed | stdio forwarding failed | Connection closed by UNKNOWN port 65535"
660 )
661 );
662 }
663
664 #[test]
665 fn stderr_summary_skips_banner_lines() {
666 let stderr = "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\
667 @ WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED! @\n\
668 @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n\
669 IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!\n";
670 let result = stderr_summary(stderr);
671 assert_eq!(
672 result.as_deref(),
673 Some("IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!")
674 );
675 }
676
677 #[test]
678 fn stderr_summary_returns_none_for_empty() {
679 assert!(stderr_summary("").is_none());
680 assert!(stderr_summary(" \n \n").is_none());
681 assert!(stderr_summary("@@@@@\n@@@@@\n").is_none());
682 }
683
684 #[test]
685 fn stderr_summary_truncates_long_output() {
686 let long = "x".repeat(250);
687 let result = stderr_summary(&long).unwrap();
688 assert_eq!(result.len(), 200);
689 assert!(result.ends_with("..."));
690 }
691
692 #[test]
693 fn stderr_summary_truncates_multibyte_safely() {
694 let long = "日".repeat(100);
696 let result = stderr_summary(&long).unwrap();
697 assert!(result.ends_with("..."));
698 assert!(result.len() <= 600); }
701
702 #[test]
703 fn stderr_summary_simple_errors() {
704 assert_eq!(
705 stderr_summary("Connection refused\n").as_deref(),
706 Some("Connection refused")
707 );
708 assert_eq!(
709 stderr_summary("Permission denied (publickey).\n").as_deref(),
710 Some("Permission denied (publickey).")
711 );
712 }
713}