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