Skip to main content

virtuoso_cli/transport/
ssh.rs

1#![allow(dead_code)]
2
3use crate::error::{Result, VirtuosoError};
4use std::cell::Cell;
5use std::collections::HashMap;
6use std::io::Write;
7use std::process::{Command, Stdio};
8use std::time::Instant;
9
10use crate::models::RemoteTaskResult;
11
12fn shell_quote(s: &str) -> String {
13    shlex::try_quote(s)
14        .unwrap_or(std::borrow::Cow::Borrowed(s))
15        .into_owned()
16}
17
18pub struct SSHRunner {
19    pub host: String,
20    pub user: Option<String>,
21    pub jump_host: Option<String>,
22    pub jump_user: Option<String>,
23    pub ssh_port: Option<u16>,
24    pub ssh_key_path: Option<String>,
25    pub ssh_config_path: Option<String>,
26    pub timeout: u64,
27    pub connect_timeout: u64,
28    pub verbose: bool,
29    /// Dynamically disabled when a ControlMaster failure is detected at runtime.
30    pub use_control_master: Cell<bool>,
31}
32
33impl SSHRunner {
34    pub fn new(host: &str) -> Self {
35        Self {
36            host: host.into(),
37            user: None,
38            jump_host: None,
39            jump_user: None,
40            ssh_port: None,
41            ssh_key_path: None,
42            ssh_config_path: None,
43            timeout: 30,
44            connect_timeout: 10,
45            verbose: false,
46            use_control_master: Cell::new(true),
47        }
48    }
49
50    /// Detect ControlMaster failure patterns in SSH stderr output.
51    /// These typically appear on Windows/WSL2 when the CM socket path contains
52    /// non-ASCII characters or the named pipe cannot be created.
53    pub fn is_cm_failure(stderr: &str) -> bool {
54        stderr.contains("mux_client_request_session")
55            || stderr.contains("could not create named pipe")
56            || stderr.contains("ControlPath")
57            || stderr.contains("Control socket connect")
58            || stderr.contains("multiplexing not supported")
59            || stderr.contains("mux_client_hello_exchange")
60    }
61
62    pub fn with_jump(mut self, jump: &str) -> Self {
63        self.jump_host = Some(jump.into());
64        self
65    }
66
67    pub fn with_user(mut self, user: &str) -> Self {
68        self.user = Some(user.into());
69        self
70    }
71
72    pub fn test_connection(&self, timeout: Option<u64>) -> Result<bool> {
73        let effective_timeout = timeout.unwrap_or(self.connect_timeout);
74        let output = self.run_test_connection(effective_timeout)?;
75
76        if !output.status.success() {
77            let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
78            if Self::is_cm_failure(&stderr) && self.use_control_master.get() {
79                tracing::warn!(
80                    "ControlMaster failure in test_connection, retrying without CM: {}",
81                    stderr.lines().next().unwrap_or("")
82                );
83                self.use_control_master.set(false);
84                let output2 = self.run_test_connection(effective_timeout)?;
85                return Ok(output2.status.success());
86            }
87        }
88        Ok(output.status.success())
89    }
90
91    fn run_test_connection(&self, connect_timeout: u64) -> Result<std::process::Output> {
92        let mut cmd = self.build_ssh_cmd_with_timeout(connect_timeout);
93        cmd.arg("exit").arg("0");
94        cmd.stdin(Stdio::null())
95            .stdout(Stdio::null())
96            .stderr(Stdio::piped())
97            .output()
98            .map_err(|e| VirtuosoError::Ssh(format!("failed to run ssh: {e}")))
99    }
100
101    pub fn run_command(&self, command: &str, timeout: Option<u64>) -> Result<RemoteTaskResult> {
102        let result = self.run_command_inner(command, timeout)?;
103        if !result.success
104            && Self::is_cm_failure(&result.stderr)
105            && self.use_control_master.get()
106        {
107            tracing::warn!(
108                "ControlMaster failure detected, retrying without CM: {}",
109                result.stderr.lines().next().unwrap_or("")
110            );
111            self.use_control_master.set(false);
112            return self.run_command_inner(command, timeout);
113        }
114        Ok(result)
115    }
116
117    fn run_command_inner(&self, command: &str, timeout: Option<u64>) -> Result<RemoteTaskResult> {
118        let _timeout = timeout.unwrap_or(self.timeout);
119        let start = Instant::now();
120
121        let mut cmd = self.build_ssh_cmd();
122        cmd.arg("sh").arg("-s");
123
124        let output = cmd
125            .stdin(Stdio::piped())
126            .stdout(Stdio::piped())
127            .stderr(Stdio::piped())
128            .spawn()
129            .map_err(|e| VirtuosoError::Ssh(format!("failed to spawn ssh: {e}")))?;
130
131        if let Some(mut stdin) = output.stdin.as_ref() {
132            stdin
133                .write_all(command.as_bytes())
134                .map_err(|e| VirtuosoError::Ssh(format!("failed to write command: {e}")))?;
135        }
136
137        let output = output
138            .wait_with_output()
139            .map_err(|e| VirtuosoError::Ssh(format!("ssh failed: {e}")))?;
140
141        let elapsed = start.elapsed().as_secs_f64();
142        let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
143        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
144        let error = if output.status.success() {
145            None
146        } else {
147            Some(self.summarize_error(&stderr))
148        };
149
150        let mut timings = HashMap::new();
151        timings.insert("total".into(), elapsed);
152
153        Ok(RemoteTaskResult {
154            success: output.status.success(),
155            returncode: output.status.code().unwrap_or(-1),
156            stdout,
157            stderr,
158            remote_dir: None,
159            error,
160            timings,
161        })
162    }
163
164    pub fn upload(&self, local: &str, remote: &str) -> Result<()> {
165        let _target = self.remote_target();
166
167        let status = Command::new("tar")
168            .arg("cf")
169            .arg("-")
170            .arg("-C")
171            .arg(
172                std::path::Path::new(local)
173                    .parent()
174                    .unwrap_or_else(|| std::path::Path::new(".")),
175            )
176            .arg(std::path::Path::new(local).file_name().unwrap_or_default())
177            .stdout(Stdio::piped())
178            .spawn()
179            .map_err(|e| VirtuosoError::Ssh(format!("tar failed: {e}")))?;
180
181        let tar_stdout = status.stdout.unwrap();
182
183        let remote_dir = std::path::Path::new(remote)
184            .parent()
185            .unwrap_or_else(|| std::path::Path::new("."))
186            .to_string_lossy();
187
188        let mut ssh = self.build_ssh_cmd();
189        let quoted_dir = shell_quote(&remote_dir);
190        // Must pass "sh -c 'command'" as a single argument to SSH,
191        // otherwise "sh", "-c", "command" are concatenated without quotes,
192        // breaking commands with &&.
193        let inner_cmd = format!("mkdir -p {quoted_dir} && cd {quoted_dir} && tar xf -");
194        ssh.arg(format!("sh -c {}", shell_quote(&inner_cmd)));
195        ssh.stdin(tar_stdout);
196
197        let output = ssh
198            .stdout(Stdio::null())
199            .stderr(Stdio::piped())
200            .output()
201            .map_err(|e| VirtuosoError::Ssh(format!("ssh upload failed: {e}")))?;
202
203        if !output.status.success() {
204            let stderr = String::from_utf8_lossy(&output.stderr);
205            return Err(VirtuosoError::Ssh(format!("upload failed: {stderr}")));
206        }
207
208        Ok(())
209    }
210
211    pub fn upload_text(&self, text: &str, remote: &str) -> Result<()> {
212        let remote_dir = std::path::Path::new(remote)
213            .parent()
214            .unwrap_or_else(|| std::path::Path::new("."))
215            .to_string_lossy();
216
217        let quoted_dir = shell_quote(&remote_dir);
218        let mkdir_cmd = format!("mkdir -p {quoted_dir}");
219        let mkdir = self.run_command(&mkdir_cmd, None)?;
220        if !mkdir.success {
221            return Err(VirtuosoError::Ssh(format!(
222                "failed to create remote dir: {}",
223                mkdir.stderr
224            )));
225        }
226
227        let mut cmd = self.build_ssh_cmd();
228        let quoted_remote = shell_quote(remote);
229        // Must pass "sh -c 'command'" as a single argument to SSH,
230        // otherwise "sh", "-c", "command" are concatenated without quotes,
231        // breaking commands with &&.
232        cmd.arg(format!(
233            "sh -c {}",
234            shell_quote(&format!("cat > {quoted_remote}"))
235        ));
236
237        let output = cmd
238            .stdin(Stdio::piped())
239            .stdout(Stdio::null())
240            .stderr(Stdio::piped())
241            .spawn()
242            .map_err(|e| VirtuosoError::Ssh(format!("ssh failed: {e}")))?;
243
244        if let Some(mut stdin) = output.stdin.as_ref() {
245            stdin
246                .write_all(text.as_bytes())
247                .map_err(|e| VirtuosoError::Ssh(format!("write failed: {e}")))?;
248        }
249
250        let output = output
251            .wait_with_output()
252            .map_err(|e| VirtuosoError::Ssh(format!("upload failed: {e}")))?;
253
254        if !output.status.success() {
255            let stderr = String::from_utf8_lossy(&output.stderr);
256            return Err(VirtuosoError::Ssh(format!("upload failed: {stderr}")));
257        }
258
259        Ok(())
260    }
261
262    pub fn download(&self, remote: &str, local: &str) -> Result<()> {
263        let _target = self.remote_target();
264
265        let local_path = std::path::Path::new(local);
266        if let Some(parent) = local_path.parent() {
267            std::fs::create_dir_all(parent)
268                .map_err(|e| VirtuosoError::Ssh(format!("failed to create local dir: {e}")))?;
269        }
270
271        let mut cmd = self.build_ssh_cmd();
272        cmd.arg("cat").arg(remote);
273
274        let output = cmd
275            .stdout(Stdio::piped())
276            .stderr(Stdio::piped())
277            .output()
278            .map_err(|e| VirtuosoError::Ssh(format!("ssh download failed: {e}")))?;
279
280        if !output.status.success() {
281            let stderr = String::from_utf8_lossy(&output.stderr);
282            return Err(VirtuosoError::Ssh(format!("download failed: {stderr}")));
283        }
284
285        std::fs::write(local, output.stdout)
286            .map_err(|e| VirtuosoError::Ssh(format!("failed to write local file: {e}")))?;
287
288        Ok(())
289    }
290
291    pub fn detect_python(&self) -> Result<Option<String>> {
292        for py in &["python3", "python", "python2.7"] {
293            let result = self.run_command(&format!("which {py} 2>/dev/null"), None)?;
294            if result.success && !result.stdout.trim().is_empty() {
295                return Ok(Some(py.to_string()));
296            }
297        }
298        Ok(None)
299    }
300
301    pub fn detect_arch(&self) -> Result<String> {
302        let result = self.run_command("uname -m", None)?;
303        if result.success {
304            Ok(result.stdout.trim().to_string())
305        } else {
306            Err(VirtuosoError::Ssh(format!(
307                "failed to detect arch: {}",
308                result.stderr
309            )))
310        }
311    }
312
313    pub(crate) fn build_ssh_cmd(&self) -> Command {
314        self.build_ssh_cmd_with_timeout(self.connect_timeout)
315    }
316
317    fn build_ssh_cmd_with_timeout(&self, connect_timeout: u64) -> Command {
318        let mut cmd = Command::new("ssh");
319        cmd.args([
320            "-o",
321            "BatchMode=yes",
322            "-o",
323            "StrictHostKeyChecking=accept-new",
324            "-o",
325            &format!("ConnectTimeout={connect_timeout}"),
326            // EDA lab KDC stalls masquerade as banner-exchange timeouts;
327            // disable both auth methods we never use.
328            "-o",
329            "GSSAPIAuthentication=no",
330            "-o",
331            "HostbasedAuthentication=no",
332        ]);
333
334        if self.use_control_master.get() {
335            // ControlMaster: reuse SSH connections to avoid repeated handshakes.
336            // Disabled at runtime if a CM failure is detected (WSL2/Windows paths
337            // with non-ASCII characters, named pipe creation failures, etc.).
338            let control_dir = dirs::cache_dir()
339                .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
340                .join("virtuoso_bridge")
341                .join("ssh");
342            let _ = std::fs::create_dir_all(&control_dir);
343            let control_path = control_dir.join("%h-%p-%r");
344            cmd.args([
345                "-o",
346                "ControlMaster=auto",
347                "-o",
348                &format!("ControlPath={}", control_path.display()),
349                "-o",
350                "ControlPersist=600",
351            ]);
352        }
353
354        if let Some(port) = self.ssh_port {
355            cmd.arg("-p").arg(port.to_string());
356        }
357        if let Some(ref key) = self.ssh_key_path {
358            cmd.arg("-i").arg(key);
359        }
360        if let Some(ref config) = self.ssh_config_path {
361            cmd.arg("-F").arg(config);
362        }
363        if let Some(ref jump) = self.jump_host {
364            let jump_target = match &self.jump_user {
365                Some(u) => format!("{u}@{jump}"),
366                None => jump.clone(),
367            };
368            cmd.arg("-J").arg(jump_target);
369        }
370
371        cmd.arg(self.remote_target());
372        cmd
373    }
374
375    pub fn remote_target(&self) -> String {
376        match &self.user {
377            Some(u) => format!("{u}@{}", self.host),
378            None => self.host.clone(),
379        }
380    }
381
382    /// Build a minimal SSH command string for manual connectivity verification.
383    /// Useful for error messages when the tunnel cannot be established.
384    pub fn verify_cmd_hint(&self) -> String {
385        let mut parts = vec!["ssh".to_string()];
386        if let Some(ref jump) = self.jump_host {
387            let jump_target = match &self.jump_user {
388                Some(u) => format!("{u}@{jump}"),
389                None => jump.clone(),
390            };
391            parts.push(format!("-J {jump_target}"));
392        }
393        if let Some(port) = self.ssh_port {
394            parts.push(format!("-p {port}"));
395        }
396        if let Some(ref key) = self.ssh_key_path {
397            parts.push(format!("-i {key}"));
398        }
399        parts.push(self.remote_target());
400        parts.join(" ")
401    }
402
403    pub(crate) fn summarize_error(&self, stderr: &str) -> String {
404        let lower = stderr.to_lowercase();
405        if lower.contains("connection refused") {
406            "connection refused - check if SSH is running".into()
407        } else if lower.contains("authentication") || lower.contains("permission denied") {
408            "authentication failed - check SSH keys".into()
409        } else if lower.contains("timeout") || lower.contains("timed out") {
410            "connection timed out - check network".into()
411        } else if lower.contains("could not resolve") {
412            "hostname resolution failed - check DNS".into()
413        } else {
414            stderr.lines().take(3).collect::<Vec<_>>().join("; ")
415        }
416    }
417}