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