Debian Codegraph @

_transport_rs/src/ssh/subprocess.rs

raw
1 //! Subprocess-based SSH vendors (OpenSSH, PLink, LSH) plus the loopback
2 //! "vendor" (plain TCP) and the connection wrapper they produce.
3 //!
4 //! These wrap an external `ssh` binary, exposing its stdio as a file
5 //! descriptor that the SFTP client can consume directly. No crypto library
6 //! involved; always compiled.
7 //!
8 //! The Rust surface is deliberately minimal: vendors hand back either an
9 //! fd (SFTP) or an [`SSHSubprocessConnection`] (command exec). Wrapping the
10 //! fd in `_transport_rs.sftp.SFTPClient` happens on the Python side —
11 //! mirrors how `SFTPClient(sock._sock.detach())` is called today and keeps
12 //! the `ssh` and `sftp` Rust submodules decoupled.
13
14 use dromedary::ssh::{build_argv, ArgvError, Flavor};
15 use pyo3::exceptions::PyRuntimeError;
16 use pyo3::import_exception;
17 use pyo3::prelude::*;
18 #[cfg(unix)]
19 use std::os::fd::{IntoRawFd, OwnedFd, RawFd};
20 use std::process::{Child, Command, Stdio};
21 use std::sync::Mutex;
22
23 import_exception!(dromedary.errors, StrangeHostname);
24 import_exception!(dromedary.errors, SocketConnectionError);
25
26 fn argv_err_to_py(err: ArgvError) -> PyErr {
27 match err {
28 ArgvError::StrangeHostname(h) => StrangeHostname::new_err((h,)),
29 ArgvError::InvalidArguments => PyRuntimeError::new_err(err.to_string()),
30 }
31 }
32
33 // ---------------------------------------------------------------------------
34 // Connection wrapper
35 // ---------------------------------------------------------------------------
36
37 struct Inner {
38 child: Option<Child>,
39 #[cfg(unix)]
40 sock_fd: Option<RawFd>,
41 }
42
43 /// Rust port of `dromedary.ssh.SSHSubprocessConnection`.
44 ///
45 /// Does not expose `get_sock_or_pipes()` — that method was paramiko-only and
46 /// goes away with the russh migration. Callers use [`detach_fd`] for the
47 /// SFTP path and [`wait`] / [`close`] for command execution.
48 #[pyclass(
49 module = "dromedary._transport_rs.ssh",
50 name = "SSHSubprocessConnection"
51 )]
52 pub(crate) struct SSHSubprocessConnection {
53 inner: Mutex<Inner>,
54 }
55
56 impl SSHSubprocessConnection {
57 #[cfg(unix)]
58 fn from_parts(child: Child, sock_fd: Option<RawFd>) -> Self {
59 Self {
60 inner: Mutex::new(Inner {
61 child: Some(child),
62 sock_fd,
63 }),
64 }
65 }
66
67 #[cfg(not(unix))]
68 fn from_parts(child: Child) -> Self {
69 Self {
70 inner: Mutex::new(Inner { child: Some(child) }),
71 }
72 }
73 }
74
75 #[pymethods]
76 impl SSHSubprocessConnection {
77 /// Take ownership of the raw fd underlying this connection.
78 ///
79 /// Returns the socketpair fd when one was used, otherwise the child's
80 /// stdout pipe fd. After this call the connection no longer owns the
81 /// fd; `close` / `wait` still manage the child process itself.
82 #[cfg(unix)]
83 fn detach_fd(&self) -> PyResult<RawFd> {
84 let mut inner = self.inner.lock().unwrap();
85 if let Some(fd) = inner.sock_fd.take() {
86 return Ok(fd);
87 }
88 let child = inner
89 .child
90 .as_mut()
91 .ok_or_else(|| PyRuntimeError::new_err("connection already closed"))?;
92 let stdout = child
93 .stdout
94 .take()
95 .ok_or_else(|| PyRuntimeError::new_err("no stdout fd available"))?;
96 Ok(stdout.into_raw_fd())
97 }
98
99 fn wait(&self) -> PyResult<Option<i32>> {
100 let mut inner = self.inner.lock().unwrap();
101 match inner.child.as_mut() {
102 Some(child) => child
103 .wait()
104 .map(|s| s.code())
105 .map_err(|e| PyRuntimeError::new_err(format!("wait failed: {e}"))),
106 None => Ok(None),
107 }
108 }
109
110 fn close(&self) -> PyResult<()> {
111 let mut inner = self.inner.lock().unwrap();
112 #[cfg(unix)]
113 if let Some(fd) = inner.sock_fd.take() {
114 // SAFETY: we owned this fd; `nix::unistd::close` consumes it,
115 // so it's closed exactly once. Errors are ignored to match the
116 // best-effort semantics of Python's `_close_ssh_proc`.
117 let _ = nix::unistd::close(fd);
118 }
119 if let Some(mut child) = inner.child.take() {
120 drop(child.stdin.take());
121 drop(child.stdout.take());
122 let _ = child.wait();
123 }
124 Ok(())
125 }
126 }
127
128 impl Drop for SSHSubprocessConnection {
129 fn drop(&mut self) {
130 let _ = self.close();
131 }
132 }
133
134 // ---------------------------------------------------------------------------
135 // Spawn helper
136 // ---------------------------------------------------------------------------
137
138 /// Spawn the ssh subprocess, preferring a `socketpair` for its stdio (matches
139 /// the Python comment: "we prefer sockets to pipes because they support
140 /// non-blocking short reads").
141 #[cfg(unix)]
142 fn spawn(argv: &[String], host: &str, port: Option<u16>) -> PyResult<SSHSubprocessConnection> {
143 // SOCK_CLOEXEC isn't available as a `SockFlag` on macOS in nix; fall back
144 // to `SockFlag::empty()` and set `FD_CLOEXEC` via fcntl on the parent's
145 // half after creation.
146 #[cfg(any(
147 target_os = "linux",
148 target_os = "android",
149 target_os = "freebsd",
150 target_os = "dragonfly",
151 target_os = "netbsd",
152 target_os = "openbsd",
153 target_os = "illumos",
154 target_os = "solaris",
155 ))]
156 let sock_flags = nix::sys::socket::SockFlag::SOCK_CLOEXEC;
157 #[cfg(not(any(
158 target_os = "linux",
159 target_os = "android",
160 target_os = "freebsd",
161 target_os = "dragonfly",
162 target_os = "netbsd",
163 target_os = "openbsd",
164 target_os = "illumos",
165 target_os = "solaris",
166 )))]
167 let sock_flags = nix::sys::socket::SockFlag::empty();
168
169 let pair = nix::sys::socket::socketpair(
170 nix::sys::socket::AddressFamily::Unix,
171 nix::sys::socket::SockType::Stream,
172 None,
173 sock_flags,
174 )
175 .ok();
176
177 let mut cmd = Command::new(&argv[0]);
178 cmd.args(&argv[1..]);
179
180 let my_sock: Option<OwnedFd> = if let Some((mine, theirs)) = pair {
181 // Dup twice: once for child stdin, once for stdout. The child
182 // inherits them via `Command::stdin` / `stdout`; the parent keeps
183 // its half (`mine`) with CLOEXEC set.
184 let dup_in = nix::unistd::dup(&theirs)
185 .map_err(|e| PyRuntimeError::new_err(format!("dup failed: {e}")))?;
186 let dup_out = nix::unistd::dup(&theirs)
187 .map_err(|e| PyRuntimeError::new_err(format!("dup failed: {e}")))?;
188 cmd.stdin(Stdio::from(dup_in));
189 cmd.stdout(Stdio::from(dup_out));
190 // `theirs` is closed in the parent when this `OwnedFd` drops.
191 drop(theirs);
192 // Ensure CLOEXEC on the parent's retained half on platforms where
193 // `SOCK_CLOEXEC` couldn't be requested at creation time.
194 #[cfg(not(any(
195 target_os = "linux",
196 target_os = "android",
197 target_os = "freebsd",
198 target_os = "dragonfly",
199 target_os = "netbsd",
200 target_os = "openbsd",
201 target_os = "illumos",
202 target_os = "solaris",
203 )))]
204 nix::fcntl::fcntl(
205 &mine,
206 nix::fcntl::FcntlArg::F_SETFD(nix::fcntl::FdFlag::FD_CLOEXEC),
207 )
208 .map_err(|e| PyRuntimeError::new_err(format!("fcntl FD_CLOEXEC failed: {e}")))?;
209 Some(mine)
210 } else {
211 cmd.stdin(Stdio::piped()).stdout(Stdio::piped());
212 None
213 };
214 cmd.stderr(Stdio::inherit());
215
216 let child = cmd.spawn().map_err(|e| {
217 SocketConnectionError::new_err((
218 host.to_string(),
219 port.map(|p| format!(":{p}")).unwrap_or_default(),
220 "Failed to connect to",
221 e.to_string(),
222 ))
223 })?;
224
225 let my_raw: Option<RawFd> = my_sock.map(|fd| fd.into_raw_fd());
226 Ok(SSHSubprocessConnection::from_parts(child, my_raw))
227 }
228
229 #[cfg(not(unix))]
230 fn spawn(argv: &[String], host: &str, port: Option<u16>) -> PyResult<SSHSubprocessConnection> {
231 let mut cmd = Command::new(&argv[0]);
232 cmd.args(&argv[1..])
233 .stdin(Stdio::piped())
234 .stdout(Stdio::piped())
235 .stderr(Stdio::inherit());
236 let child = cmd.spawn().map_err(|e| {
237 SocketConnectionError::new_err((
238 host.to_string(),
239 port.map(|p| format!(":{p}")).unwrap_or_default(),
240 "Failed to connect to",
241 e.to_string(),
242 ))
243 })?;
244 Ok(SSHSubprocessConnection::from_parts(child))
245 }
246
247 // ---------------------------------------------------------------------------
248 // Vendor classes exposed to Python
249 // ---------------------------------------------------------------------------
250
251 macro_rules! subprocess_vendor {
252 ($name:ident, $flavor:expr, $pyname:literal) => {
253 #[pyclass(module = "dromedary._transport_rs.ssh", name = $pyname)]
254 pub(crate) struct $name {
255 executable_path: Mutex<Option<String>>,
256 }
257
258 #[pymethods]
259 impl $name {
260 #[new]
261 fn new() -> Self {
262 Self {
263 executable_path: Mutex::new(None),
264 }
265 }
266
267 /// Override the ssh binary. Matches the Python
268 /// `SSHVendorManager._get_vendor_from_path` flow, where
269 /// `BRZ_SSH=/path/to/ssh` assigns `vendor.executable_path` on
270 /// the detected vendor.
271 #[setter]
272 fn set_executable_path(&self, path: Option<String>) {
273 *self.executable_path.lock().unwrap() = path;
274 }
275
276 #[getter]
277 fn executable_path(&self) -> Option<String> {
278 self.executable_path.lock().unwrap().clone()
279 }
280
281 /// Spawn the ssh binary with the "sftp" subsystem and return
282 /// the raw fd to use with `_transport_rs.sftp.SFTPClient(fd)`.
283 /// The vendor no longer owns the fd after this call.
284 #[cfg(unix)]
285 #[pyo3(signature = (username, host, port=None))]
286 fn spawn_sftp(
287 &self,
288 username: Option<&str>,
289 host: &str,
290 port: Option<u16>,
291 ) -> PyResult<RawFd> {
292 let exe = self.executable_path.lock().unwrap().clone();
293 let argv = build_argv(
294 $flavor,
295 exe.as_deref(),
296 username,
297 host,
298 port,
299 Some("sftp"),
300 None,
301 )
302 .map_err(argv_err_to_py)?;
303 let conn = spawn(&argv, host, port)?;
304 conn.detach_fd()
305 }
306
307 /// Spawn the ssh binary to execute `command` on the remote
308 /// host, returning an [`SSHSubprocessConnection`] for the
309 /// caller to drive.
310 #[pyo3(signature = (username, host, command, port=None))]
311 fn connect_ssh(
312 &self,
313 username: Option<&str>,
314 host: &str,
315 command: Vec<String>,
316 port: Option<u16>,
317 ) -> PyResult<SSHSubprocessConnection> {
318 let exe = self.executable_path.lock().unwrap().clone();
319 let argv = build_argv(
320 $flavor,
321 exe.as_deref(),
322 username,
323 host,
324 port,
325 None,
326 Some(&command),
327 )
328 .map_err(argv_err_to_py)?;
329 spawn(&argv, host, port)
330 }
331 }
332 };
333 }
334
335 subprocess_vendor!(
336 OpenSSHSubprocessVendor,
337 Flavor::OpenSSH,
338 "OpenSSHSubprocessVendor"
339 );
340 subprocess_vendor!(LSHSubprocessVendor, Flavor::Lsh, "LSHSubprocessVendor");
341 subprocess_vendor!(
342 PLinkSubprocessVendor,
343 Flavor::PLink,
344 "PLinkSubprocessVendor"
345 );
346
347 // ---------------------------------------------------------------------------
348 // Loopback "vendor" (plain TCP, no ssh)
349 // ---------------------------------------------------------------------------
350
351 /// Rust port of `dromedary.ssh.LoopbackVendor`. Used by the test suite via
352 /// `stub_sftp.py` to talk to a local SFTP server over a TCP socket with no
353 /// SSH transport in between.
354 #[pyclass(module = "dromedary._transport_rs.ssh", name = "LoopbackVendor")]
355 pub(crate) struct LoopbackVendor;
356
357 #[pymethods]
358 impl LoopbackVendor {
359 #[new]
360 fn new() -> Self {
361 Self
362 }
363
364 /// Open a TCP connection and return the raw fd. Caller wraps it in
365 /// `_transport_rs.sftp.SFTPClient(fd)`.
366 #[cfg(unix)]
367 #[pyo3(signature = (host, port))]
368 fn spawn_sftp(&self, host: &str, port: u16) -> PyResult<RawFd> {
369 let sock = std::net::TcpStream::connect((host, port)).map_err(|e| {
370 SocketConnectionError::new_err((
371 host.to_string(),
372 format!(":{port}"),
373 "Failed to connect to",
374 e.to_string(),
375 ))
376 })?;
377 // Convert to OwnedFd so we can release ownership cleanly.
378 let owned: OwnedFd = sock.into();
379 Ok(owned.into_raw_fd())
380 }
381 }
382
383 // ---------------------------------------------------------------------------
384 // Registration
385 // ---------------------------------------------------------------------------
386
387 pub(crate) fn register(_py: Python, m: &Bound<PyModule>) -> PyResult<()> {
388 m.add_class::<SSHSubprocessConnection>()?;
389 m.add_class::<OpenSSHSubprocessVendor>()?;
390 m.add_class::<LSHSubprocessVendor>()?;
391 m.add_class::<PLinkSubprocessVendor>()?;
392 m.add_class::<LoopbackVendor>()?;
393 Ok(())
394 }
395
396 // Argv construction and tests live in the top-level `dromedary::ssh`
397 // module so they're unit-testable without needing the Python extension
398 // linker symbols (which block `cargo test` on this `cdylib` crate).