Skip to main content

virtuoso_cli/transport/
ssh.rs

1#![allow(dead_code)]
2
3use crate::error::{Result, VirtuosoError};
4use std::collections::HashMap;
5use std::io::Write;
6use std::process::{Command, Stdio};
7use std::time::Instant;
8
9use crate::models::RemoteTaskResult;
10
11fn shell_quote(s: &str) -> String {
12    shlex::try_quote(s)
13        .unwrap_or(std::borrow::Cow::Borrowed(s))
14        .into_owned()
15}
16
17pub struct SSHRunner {
18    pub host: String,
19    pub user: Option<String>,
20    pub jump_host: Option<String>,
21    pub jump_user: Option<String>,
22    pub ssh_port: Option<u16>,
23    pub ssh_key_path: Option<String>,
24    pub ssh_config_path: Option<String>,
25    pub timeout: u64,
26    pub connect_timeout: u64,
27    pub verbose: bool,
28}
29
30impl SSHRunner {
31    pub fn new(host: &str) -> Self {
32        Self {
33            host: host.into(),
34            user: None,
35            jump_host: None,
36            jump_user: None,
37            ssh_port: None,
38            ssh_key_path: None,
39            ssh_config_path: None,
40            timeout: 30,
41            connect_timeout: 10,
42            verbose: false,
43        }
44    }
45
46    pub fn with_jump(mut self, jump: &str) -> Self {
47        self.jump_host = Some(jump.into());
48        self
49    }
50
51    pub fn with_user(mut self, user: &str) -> Self {
52        self.user = Some(user.into());
53        self
54    }
55
56    pub fn test_connection(&self, timeout: Option<u64>) -> Result<bool> {
57        let effective_timeout = timeout.unwrap_or(self.connect_timeout);
58        let mut cmd = self.build_ssh_cmd_with_timeout(effective_timeout);
59        cmd.arg("exit").arg("0");
60
61        let output = cmd
62            .stdin(Stdio::null())
63            .stdout(Stdio::null())
64            .stderr(Stdio::null())
65            .output()
66            .map_err(|e| VirtuosoError::Ssh(format!("failed to run ssh: {e}")))?;
67
68        Ok(output.status.success())
69    }
70
71    pub fn run_command(&self, command: &str, timeout: Option<u64>) -> Result<RemoteTaskResult> {
72        let _timeout = timeout.unwrap_or(self.timeout);
73        let start = Instant::now();
74
75        let mut cmd = self.build_ssh_cmd();
76        cmd.arg("sh").arg("-s");
77
78        let output = cmd
79            .stdin(Stdio::piped())
80            .stdout(Stdio::piped())
81            .stderr(Stdio::piped())
82            .spawn()
83            .map_err(|e| VirtuosoError::Ssh(format!("failed to spawn ssh: {e}")))?;
84
85        if let Some(mut stdin) = output.stdin.as_ref() {
86            stdin
87                .write_all(command.as_bytes())
88                .map_err(|e| VirtuosoError::Ssh(format!("failed to write command: {e}")))?;
89        }
90
91        let output = output
92            .wait_with_output()
93            .map_err(|e| VirtuosoError::Ssh(format!("ssh failed: {e}")))?;
94
95        let elapsed = start.elapsed().as_secs_f64();
96        let stdout = String::from_utf8_lossy(&output.stdout).into_owned();
97        let stderr = String::from_utf8_lossy(&output.stderr).into_owned();
98        let error = if output.status.success() {
99            None
100        } else {
101            Some(self.summarize_error(&stderr))
102        };
103
104        let mut timings = HashMap::new();
105        timings.insert("total".into(), elapsed);
106
107        Ok(RemoteTaskResult {
108            success: output.status.success(),
109            returncode: output.status.code().unwrap_or(-1),
110            stdout,
111            stderr,
112            remote_dir: None,
113            error,
114            timings,
115        })
116    }
117
118    pub fn upload(&self, local: &str, remote: &str) -> Result<()> {
119        let _target = self.remote_target();
120
121        let status = Command::new("tar")
122            .arg("cf")
123            .arg("-")
124            .arg("-C")
125            .arg(
126                std::path::Path::new(local)
127                    .parent()
128                    .unwrap_or_else(|| std::path::Path::new(".")),
129            )
130            .arg(std::path::Path::new(local).file_name().unwrap_or_default())
131            .stdout(Stdio::piped())
132            .spawn()
133            .map_err(|e| VirtuosoError::Ssh(format!("tar failed: {e}")))?;
134
135        let tar_stdout = status.stdout.unwrap();
136
137        let remote_dir = std::path::Path::new(remote)
138            .parent()
139            .unwrap_or_else(|| std::path::Path::new("."))
140            .to_string_lossy();
141
142        let mut ssh = self.build_ssh_cmd();
143        let quoted_dir = shell_quote(&remote_dir);
144        ssh.arg("sh").arg("-c").arg(format!(
145            "mkdir -p {quoted_dir} && cd {quoted_dir} && tar xf -"
146        ));
147        ssh.stdin(tar_stdout);
148
149        let output = ssh
150            .stdout(Stdio::null())
151            .stderr(Stdio::piped())
152            .output()
153            .map_err(|e| VirtuosoError::Ssh(format!("ssh upload failed: {e}")))?;
154
155        if !output.status.success() {
156            let stderr = String::from_utf8_lossy(&output.stderr);
157            return Err(VirtuosoError::Ssh(format!("upload failed: {stderr}")));
158        }
159
160        Ok(())
161    }
162
163    pub fn upload_text(&self, text: &str, remote: &str) -> Result<()> {
164        let remote_dir = std::path::Path::new(remote)
165            .parent()
166            .unwrap_or_else(|| std::path::Path::new("."))
167            .to_string_lossy();
168
169        let quoted_dir = shell_quote(&remote_dir);
170        let mkdir = self.run_command(&format!("mkdir -p {quoted_dir}"), None)?;
171        if !mkdir.success {
172            return Err(VirtuosoError::Ssh(format!(
173                "failed to create remote dir: {}",
174                mkdir.stderr
175            )));
176        }
177
178        let mut cmd = self.build_ssh_cmd();
179        let quoted_remote = shell_quote(remote);
180        cmd.arg("sh")
181            .arg("-c")
182            .arg(format!("cat > {quoted_remote}"));
183
184        let output = cmd
185            .stdin(Stdio::piped())
186            .stdout(Stdio::null())
187            .stderr(Stdio::piped())
188            .spawn()
189            .map_err(|e| VirtuosoError::Ssh(format!("ssh failed: {e}")))?;
190
191        if let Some(mut stdin) = output.stdin.as_ref() {
192            stdin
193                .write_all(text.as_bytes())
194                .map_err(|e| VirtuosoError::Ssh(format!("write failed: {e}")))?;
195        }
196
197        let output = output
198            .wait_with_output()
199            .map_err(|e| VirtuosoError::Ssh(format!("upload failed: {e}")))?;
200
201        if !output.status.success() {
202            let stderr = String::from_utf8_lossy(&output.stderr);
203            return Err(VirtuosoError::Ssh(format!("upload failed: {stderr}")));
204        }
205
206        Ok(())
207    }
208
209    pub fn download(&self, remote: &str, local: &str) -> Result<()> {
210        let _target = self.remote_target();
211
212        let local_path = std::path::Path::new(local);
213        if let Some(parent) = local_path.parent() {
214            std::fs::create_dir_all(parent)
215                .map_err(|e| VirtuosoError::Ssh(format!("failed to create local dir: {e}")))?;
216        }
217
218        let mut cmd = self.build_ssh_cmd();
219        cmd.arg("cat").arg(remote);
220
221        let output = cmd
222            .stdout(Stdio::piped())
223            .stderr(Stdio::piped())
224            .output()
225            .map_err(|e| VirtuosoError::Ssh(format!("ssh download failed: {e}")))?;
226
227        if !output.status.success() {
228            let stderr = String::from_utf8_lossy(&output.stderr);
229            return Err(VirtuosoError::Ssh(format!("download failed: {stderr}")));
230        }
231
232        std::fs::write(local, output.stdout)
233            .map_err(|e| VirtuosoError::Ssh(format!("failed to write local file: {e}")))?;
234
235        Ok(())
236    }
237
238    pub fn detect_python(&self) -> Result<Option<String>> {
239        for py in &["python3", "python", "python2.7"] {
240            let result = self.run_command(&format!("which {py} 2>/dev/null"), None)?;
241            if result.success && !result.stdout.trim().is_empty() {
242                return Ok(Some(py.to_string()));
243            }
244        }
245        Ok(None)
246    }
247
248    pub fn detect_arch(&self) -> Result<String> {
249        let result = self.run_command("uname -m", None)?;
250        if result.success {
251            Ok(result.stdout.trim().to_string())
252        } else {
253            Err(VirtuosoError::Ssh(format!(
254                "failed to detect arch: {}",
255                result.stderr
256            )))
257        }
258    }
259
260    pub(crate) fn build_ssh_cmd(&self) -> Command {
261        self.build_ssh_cmd_with_timeout(self.connect_timeout)
262    }
263
264    fn build_ssh_cmd_with_timeout(&self, connect_timeout: u64) -> Command {
265        let mut cmd = Command::new("ssh");
266        cmd.args([
267            "-o",
268            "BatchMode=yes",
269            "-o",
270            "StrictHostKeyChecking=accept-new",
271            "-o",
272            &format!("ConnectTimeout={connect_timeout}"),
273            // EDA lab KDC stalls masquerade as banner-exchange timeouts;
274            // disable both auth methods we never use.
275            "-o",
276            "GSSAPIAuthentication=no",
277            "-o",
278            "HostbasedAuthentication=no",
279        ]);
280
281        // ControlMaster: reuse SSH connections to avoid repeated handshakes
282        let control_dir = dirs::cache_dir()
283            .unwrap_or_else(|| std::path::PathBuf::from("/tmp"))
284            .join("virtuoso_bridge")
285            .join("ssh");
286        let _ = std::fs::create_dir_all(&control_dir);
287        let control_path = control_dir.join("%h-%p-%r");
288        cmd.args([
289            "-o",
290            "ControlMaster=auto",
291            "-o",
292            &format!("ControlPath={}", control_path.display()),
293            "-o",
294            "ControlPersist=600",
295        ]);
296
297        if let Some(port) = self.ssh_port {
298            cmd.arg("-p").arg(port.to_string());
299        }
300        if let Some(ref key) = self.ssh_key_path {
301            cmd.arg("-i").arg(key);
302        }
303        if let Some(ref config) = self.ssh_config_path {
304            cmd.arg("-F").arg(config);
305        }
306        if let Some(ref jump) = self.jump_host {
307            let jump_target = match &self.jump_user {
308                Some(u) => format!("{u}@{jump}"),
309                None => jump.clone(),
310            };
311            cmd.arg("-J").arg(jump_target);
312        }
313
314        cmd.arg(self.remote_target());
315        cmd
316    }
317
318    pub fn remote_target(&self) -> String {
319        match &self.user {
320            Some(u) => format!("{u}@{}", self.host),
321            None => self.host.clone(),
322        }
323    }
324
325    pub(crate) fn summarize_error(&self, stderr: &str) -> String {
326        let lower = stderr.to_lowercase();
327        if lower.contains("connection refused") {
328            "connection refused - check if SSH is running".into()
329        } else if lower.contains("authentication") || lower.contains("permission denied") {
330            "authentication failed - check SSH keys".into()
331        } else if lower.contains("timeout") || lower.contains("timed out") {
332            "connection timed out - check network".into()
333        } else if lower.contains("could not resolve") {
334            "hostname resolution failed - check DNS".into()
335        } else {
336            stderr.lines().take(3).collect::<Vec<_>>().join("; ")
337        }
338    }
339}