Debian Codegraph @

_transport_rs/src/sftp.rs

raw
1 use pyo3::create_exception;
2 use pyo3::exceptions::{PyException, PyValueError};
3 use pyo3::import_exception;
4 use pyo3::prelude::*;
5 use pyo3::types::{PyBytes, PyType};
6
7 use std::collections::VecDeque;
8 use std::io::{Read, Write};
9 use std::sync::Arc;
10
11 /// Synchronous bidirectional byte stream the SFTP client can run over.
12 /// Either a `std::fs::File` (subprocess vendors hand us an fd) or the
13 /// russh blocking adapter. Boxed so `SFTPClient` has a single concrete
14 /// generic instantiation regardless of backend.
15 pub(crate) trait SshChannel: Read + Write + Send {}
16 impl<T: Read + Write + Send + ?Sized> SshChannel for T {}
17
18 pub(crate) type BoxedChannel = Box<dyn SshChannel>;
19
20 create_exception!(dromedary._transport_rs, SFTPError, PyException);
21 import_exception!(dromedary.errors, NoSuchFile);
22 import_exception!(dromedary.errors, PermissionDenied);
23 import_exception!(dromedary.errors, SocketConnectionError);
24
25 #[pyclass]
26 struct SFTPAttributes(sftp::Attributes);
27
28 #[pymethods]
29 impl SFTPAttributes {
30 #[new]
31 fn new() -> Self {
32 Self(sftp::Attributes::new())
33 }
34
35 #[getter]
36 fn get_st_mode(&self) -> Option<u32> {
37 self.0.permissions
38 }
39
40 #[setter]
41 fn set_st_mode(&mut self, mode: Option<u32>) {
42 self.0.permissions = mode;
43 }
44
45 #[getter]
46 fn get_st_size(&self) -> Option<u64> {
47 self.0.size
48 }
49
50 #[setter]
51 fn set_st_size(&mut self, size: Option<u64>) {
52 self.0.size = size;
53 }
54 }
55
56 #[pyclass]
57 pub(crate) struct SFTPClient {
58 sftp: Arc<sftp::SftpClient<BoxedChannel>>,
59 cwd: Option<String>,
60 }
61
62 impl SFTPClient {
63 /// Construct an SFTP client over an arbitrary sync byte-stream channel.
64 /// Used by library-backed SSH vendors (russh etc.) that produce a stream
65 /// rather than a kernel fd.
66 #[cfg(feature = "russh")]
67 pub(crate) fn from_channel(channel: BoxedChannel) -> std::io::Result<Self> {
68 let session = sftp::SftpClient::new(channel)?;
69 Ok(Self {
70 sftp: Arc::new(session),
71 cwd: None,
72 })
73 }
74 }
75
76 fn sftp_error_to_py_err(e: sftp::Error, path: Option<&str>) -> PyErr {
77 match e {
78 sftp::Error::Io(e) => e.into(),
79 sftp::Error::Eof(_, _) => std::io::Error::from(std::io::ErrorKind::UnexpectedEof).into(),
80 sftp::Error::NoSuchFile(msg, _lang) => {
81 NoSuchFile::new_err((path.map(|p| p.to_string()), msg))
82 }
83 sftp::Error::PermissionDenied(msg, _) => {
84 PermissionDenied::new_err((path.map(|p| p.to_string()), msg))
85 }
86 sftp::Error::Failure(msg, _lang) => SFTPError::new_err(msg),
87 _ => SFTPError::new_err(format!("{:?}", e)),
88 }
89 }
90
91 #[pyclass]
92 struct SFTPFile {
93 sftp: Arc<sftp::SftpClient<BoxedChannel>>,
94 file: sftp::File,
95 offset: u64,
96 }
97
98 impl SFTPClient {
99 fn _adjust_cwd(&self, path: &str) -> String {
100 if self.cwd.is_none() {
101 return path.to_string();
102 }
103
104 if path.starts_with('/') {
105 return path.to_string();
106 }
107
108 if self.cwd == Some("/".to_owned()) {
109 return format!("/{}", path);
110 }
111
112 format!("{}/{}", self.cwd.as_ref().unwrap(), path)
113 }
114 }
115
116 #[pymethods]
117 impl SFTPFile {
118 fn block(&mut self, py: Python, offset: u64, length: u64, lockmask: u32) -> PyResult<()> {
119 py.detach(|| self.sftp.block(&self.file, offset, length, lockmask))
120 .map_err(|e| sftp_error_to_py_err(e, None))
121 }
122
123 fn unblock(&mut self, py: Python, offset: u64, length: u64) -> PyResult<()> {
124 py.detach(|| self.sftp.unblock(&self.file, offset, length))
125 .map_err(|e| sftp_error_to_py_err(e, None))
126 }
127
128 fn setstat(&mut self, py: Python, attr: &SFTPAttributes) -> PyResult<()> {
129 py.detach(|| self.sftp.fsetstat(&self.file, &attr.0))
130 .map_err(|e| sftp_error_to_py_err(e, None))
131 }
132
133 #[pyo3(signature = (flags = None))]
134 fn stat(&mut self, py: Python, flags: Option<u32>) -> PyResult<SFTPAttributes> {
135 py.detach(|| self.sftp.fstat(&self.file, flags).map(SFTPAttributes))
136 .map_err(|e| sftp_error_to_py_err(e, None))
137 }
138
139 fn flush(&mut self, _py: Python) -> PyResult<()> {
140 Ok(())
141 }
142
143 fn pwrite(&mut self, py: Python, offset: u64, data: &[u8]) -> PyResult<()> {
144 py.detach(|| self.sftp.pwrite(&self.file, offset, data))
145 .map_err(|e| sftp_error_to_py_err(e, None))
146 }
147
148 fn pread(&mut self, py: Python, offset: u64, length: u32) -> PyResult<Py<PyAny>> {
149 py.detach(|| self.sftp.pread(&self.file, offset, length))
150 .map_err(|e| sftp_error_to_py_err(e, None))
151 .map(|b| PyBytes::new(py, &b).into())
152 }
153
154 fn close(&mut self, py: Python) -> PyResult<()> {
155 py.detach(|| self.sftp.fclose(&self.file))
156 .map_err(|e| sftp_error_to_py_err(e, None))
157 }
158
159 fn seekable(&self) -> bool {
160 true
161 }
162
163 fn tell(&self) -> u64 {
164 self.offset
165 }
166
167 fn seek(&mut self, py: Python, offset: i64, whence: u32) -> PyResult<u64> {
168 let size = self.stat(py, None)?.0.size.unwrap();
169 let new_offset = match whence {
170 // SEEK_SET
171 0 => offset,
172 // SEEK_CUR
173 1 => self.offset as i64 + offset,
174 // SEEK_END
175 2 => size as i64 - offset,
176 _ => {
177 return Err(PyValueError::new_err(("Invalid whence",)));
178 }
179 };
180
181 if new_offset < 0 {
182 return Err(PyValueError::new_err((format!(
183 "Negative offset: {}",
184 new_offset
185 ),)));
186 }
187
188 self.offset = new_offset as u64;
189 Ok(self.offset)
190 }
191
192 fn readv<'a>(
193 &mut self,
194 py: Python<'a>,
195 offsets: Vec<(u64, u32)>,
196 ) -> PyResult<Bound<'a, PyAny>> {
197 #[pyclass]
198 struct ReadvIter {
199 offsets: VecDeque<(u64, u32)>,
200 sftp: Arc<sftp::SftpClient<BoxedChannel>>,
201 file: sftp::File,
202 }
203
204 #[pymethods]
205 impl ReadvIter {
206 fn __iter__(slf: PyRef<Self>) -> Py<Self> {
207 slf.into()
208 }
209
210 fn __next__(&mut self, py: Python) -> PyResult<Option<Py<PyAny>>> {
211 if let Some((offset, length)) = self.offsets.pop_front() {
212 match py.detach(|| self.sftp.pread(&self.file, offset, length)) {
213 Ok(data) => Ok(Some(PyBytes::new(py, &data).into())),
214 Err(sftp::Error::Eof(_, _)) => Ok(Some(PyBytes::new(py, &[]).into())),
215 Err(e) => Err(sftp_error_to_py_err(e, None)),
216 }
217 } else {
218 Ok(None)
219 }
220 }
221 }
222
223 Ok(Bound::new(
224 py,
225 ReadvIter {
226 offsets: VecDeque::from(offsets),
227 sftp: Arc::clone(&self.sftp),
228 file: self.file.clone(),
229 },
230 )?
231 .into_any())
232 }
233
234 #[pyo3(signature = (length = None))]
235 fn read<'a>(&mut self, py: Python<'a>, length: Option<u32>) -> PyResult<Bound<'a, PyBytes>> {
236 let ret = if let Some(length) = length {
237 py.detach(|| self.sftp.pread(&self.file, self.offset, length))
238 } else {
239 let length = self.stat(py, None)?.0.size.unwrap();
240 if length == 0 {
241 return Ok(PyBytes::new(py, &[]));
242 }
243 py.detach(|| {
244 self.sftp
245 .pread(&self.file, self.offset, (length - self.offset) as u32)
246 })
247 };
248 match ret {
249 Ok(data) => {
250 self.offset += data.len() as u64;
251 Ok(PyBytes::new(py, data.as_slice()))
252 }
253 Err(sftp::Error::Eof(_, _)) => Ok(PyBytes::new(py, &[])),
254 Err(e) => Err(sftp_error_to_py_err(e, None)),
255 }
256 }
257
258 fn write(&mut self, py: Python, data: &[u8]) -> PyResult<()> {
259 py.detach(|| self.sftp.pwrite(&self.file, self.offset, data))
260 .map_err(|e| sftp_error_to_py_err(e, None))?;
261 self.offset += data.len() as u64;
262 Ok(())
263 }
264
265 fn __enter__(slf: PyRef<Self>) -> Py<Self> {
266 slf.into()
267 }
268
269 fn __exit__(
270 &mut self,
271 py: Python,
272 _exc_type: Option<&Bound<PyType>>,
273 _exc_val: Option<&Bound<PyAny>>,
274 _exc_tb: Option<&Bound<PyAny>>,
275 ) -> PyResult<bool> {
276 self.close(py)?;
277 Ok(false)
278 }
279 }
280
281 #[pyclass]
282 struct SFTPDir(Arc<sftp::SftpClient<BoxedChannel>>, sftp::Directory);
283
284 #[pymethods]
285 impl SFTPDir {
286 fn readdir(&mut self, py: Python) -> PyResult<Option<Vec<(String, String, SFTPAttributes)>>> {
287 match py.detach(|| {
288 self.0.readdir(&self.1).map(|e| {
289 e.into_iter()
290 .map(|(k, l, v)| (k, l, SFTPAttributes(v)))
291 .collect::<Vec<_>>()
292 })
293 }) {
294 Ok(v) => Ok(Some(v)),
295 Err(sftp::Error::Eof(_, _)) => Ok(None),
296 Err(e) => Err(sftp_error_to_py_err(e, None)),
297 }
298 }
299
300 fn close(&mut self, py: Python) -> PyResult<()> {
301 py.detach(|| self.0.closedir(&self.1))
302 .map_err(|e| sftp_error_to_py_err(e, None))
303 }
304 }
305
306 #[pymethods]
307 impl SFTPClient {
308 #[new]
309 fn new(py: Python, fd: isize) -> PyResult<Self> {
310 let session = py
311 .detach(|| {
312 #[cfg(unix)]
313 let channel: BoxedChannel = {
314 use std::os::fd::FromRawFd;
315 // SAFETY: `fd` was produced by a vendor that transferred
316 // ownership via `detach_fd`; wrapping it in `File` makes
317 // us the sole owner, closed on `Drop`.
318 Box::new(unsafe { std::fs::File::from_raw_fd(fd as i32) })
319 };
320 #[cfg(windows)]
321 let channel: BoxedChannel = {
322 use std::os::windows::io::{FromRawHandle, RawHandle};
323 // SAFETY: same detach-and-transfer contract as unix above.
324 Box::new(unsafe { std::fs::File::from_raw_handle(fd as RawHandle) })
325 };
326 sftp::SftpClient::new(channel)
327 })
328 .map_err(|e| {
329 // An IO error during the opening SFTP handshake means the
330 // transport (spawned ssh subprocess or plain TCP socket)
331 // died before we could speak SFTP to it. Report it as a
332 // transport-level connection failure rather than letting a
333 // raw BrokenPipeError / EOF surface at the caller.
334 SocketConnectionError::new_err((
335 "".to_string(),
336 "".to_string(),
337 "Failed to open SFTP session",
338 e.to_string(),
339 ))
340 })?;
341 Ok(Self {
342 sftp: Arc::new(session),
343 cwd: None,
344 })
345 }
346
347 #[pyo3(signature = (path, mode = None))]
348 fn mkdir(&mut self, py: Python, path: &str, mode: Option<u32>) -> PyResult<()> {
349 let path = self._adjust_cwd(path);
350 let mut attr = sftp::Attributes::new();
351 attr.permissions = Some(mode.unwrap_or(0o777) | 0o40000);
352 py.detach(|| self.sftp.mkdir(path.as_str(), &attr))
353 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
354 }
355
356 fn extended(&mut self, py: Python, extension: &str, data: &[u8]) -> PyResult<Option<Vec<u8>>> {
357 py.detach(|| self.sftp.extended(extension, data))
358 .map_err(|e| sftp_error_to_py_err(e, None))
359 }
360
361 #[pyo3(signature = (path, flags = None))]
362 fn lstat(&mut self, py: Python, path: &str, flags: Option<u32>) -> PyResult<SFTPAttributes> {
363 let path = self._adjust_cwd(path);
364 py.detach(|| self.sftp.lstat(path.as_str(), flags))
365 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
366 .map(SFTPAttributes)
367 }
368
369 #[pyo3(signature = (path, flags = None))]
370 fn stat(&mut self, py: Python, path: &str, flags: Option<u32>) -> PyResult<SFTPAttributes> {
371 let path = self._adjust_cwd(path);
372 py.detach(|| self.sftp.stat(path.as_str(), flags))
373 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
374 .map(SFTPAttributes)
375 }
376
377 fn chmod(&mut self, py: Python, path: &str, mode: u32) -> PyResult<()> {
378 let path = self._adjust_cwd(path);
379 let attr = sftp::Attributes {
380 permissions: Some(mode),
381 ..Default::default()
382 };
383 py.detach(|| self.sftp.setstat(path.as_str(), &attr))
384 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
385 }
386
387 fn setstat(&mut self, py: Python, path: &str, attr: &SFTPAttributes) -> PyResult<()> {
388 let path = self._adjust_cwd(path);
389 py.detach(|| self.sftp.setstat(path.as_str(), &attr.0))
390 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
391 }
392
393 fn hardlink(&mut self, py: Python, oldpath: &str, newpath: &str) -> PyResult<()> {
394 let newpath = self._adjust_cwd(newpath);
395 py.detach(|| self.sftp.hardlink(oldpath, newpath.as_str()))
396 .map_err(|e| sftp_error_to_py_err(e, Some(newpath.as_str())))
397 }
398
399 #[pyo3(signature = (path, control_byte = None, compose_path = None))]
400 fn realpath(
401 &mut self,
402 py: Python,
403 path: &str,
404 control_byte: Option<u8>,
405 compose_path: Option<&str>,
406 ) -> PyResult<String> {
407 let path = self._adjust_cwd(path);
408 py.detach(|| {
409 self.sftp
410 .realpath(path.as_str(), control_byte, compose_path)
411 })
412 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
413 }
414
415 fn symlink(&mut self, py: Python, oldpath: &str, newpath: &str) -> PyResult<()> {
416 let newpath = self._adjust_cwd(newpath);
417 py.detach(|| self.sftp.symlink(oldpath, newpath.as_str()))
418 .map_err(|e| sftp_error_to_py_err(e, Some(newpath.as_str())))
419 }
420
421 fn readlink(&mut self, py: Python, path: &str) -> PyResult<String> {
422 let path = self._adjust_cwd(path);
423 py.detach(|| self.sftp.readlink(path.as_str()))
424 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
425 }
426
427 #[pyo3(signature = (oldpath, newpath, flags = None))]
428 fn rename(
429 &mut self,
430 py: Python,
431 oldpath: &str,
432 newpath: &str,
433 flags: Option<u32>,
434 ) -> PyResult<()> {
435 let newpath = self._adjust_cwd(newpath);
436 let oldpath = self._adjust_cwd(oldpath);
437 py.detach(|| self.sftp.rename(oldpath.as_str(), newpath.as_str(), flags))
438 .map_err(|e| sftp_error_to_py_err(e, Some(newpath.as_str())))
439 }
440
441 fn remove(&mut self, py: Python, path: &str) -> PyResult<()> {
442 let path = self._adjust_cwd(path);
443 py.detach(|| self.sftp.remove(path.as_str()))
444 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
445 }
446
447 fn rmdir(&mut self, py: Python, path: &str) -> PyResult<()> {
448 let path = self._adjust_cwd(path);
449 py.detach(|| self.sftp.rmdir(path.as_str()))
450 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))
451 }
452
453 fn close(&mut self) -> PyResult<()> {
454 Ok(())
455 }
456
457 #[pyo3(signature = (path, attr, *, read=false, write=false, append=false, create=false, truncate=false, excl=false))]
458 #[allow(clippy::too_many_arguments)]
459 fn open(
460 &mut self,
461 py: Python,
462 path: &str,
463 attr: &SFTPAttributes,
464 read: bool,
465 write: bool,
466 append: bool,
467 create: bool,
468 truncate: bool,
469 excl: bool,
470 ) -> PyResult<SFTPFile> {
471 let path = self._adjust_cwd(path);
472 let options = sftp::OpenOptions::new()
473 .read(read)
474 .write(write)
475 .append(append)
476 .create(create)
477 .truncate(truncate)
478 .excl(excl);
479 let h = py
480 .detach(|| self.sftp.open(path.as_str(), options, &attr.0))
481 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))?;
482 Ok(SFTPFile {
483 sftp: Arc::clone(&self.sftp),
484 file: h,
485 offset: 0,
486 })
487 }
488
489 #[pyo3(signature = (path, mode = None, create_mode = None))]
490 fn file(
491 &mut self,
492 py: Python,
493 path: &str,
494 mode: Option<&str>,
495 create_mode: Option<u32>,
496 ) -> PyResult<SFTPFile> {
497 let path = self._adjust_cwd(path);
498 let offset = 0;
499 let mode = mode.unwrap_or("rt");
500 let options = match mode {
501 "rt" | "rb" => sftp::OpenOptions::new().read(true),
502 "ab" => sftp::OpenOptions::new()
503 .write(true)
504 .create(true)
505 .append(true),
506 "wb" => sftp::OpenOptions::new()
507 .read(true)
508 .write(true)
509 .create(true)
510 .truncate(true),
511 "r+" | "rb+" | "b+" => sftp::OpenOptions::new().read(true).write(true).create(true),
512 "a+" | "ab+" => sftp::OpenOptions::new()
513 .read(true)
514 .write(true)
515 .create(true)
516 .append(true),
517 mode => panic!("Unsupported mode: {}", mode),
518 };
519
520 let attr = sftp::Attributes {
521 permissions: create_mode,
522 ..Default::default()
523 };
524
525 let h = py
526 .detach(|| self.sftp.open(path.as_str(), options, &attr))
527 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))?;
528
529 let mut ret = SFTPFile {
530 sftp: Arc::clone(&self.sftp),
531 file: h,
532 offset,
533 };
534
535 if mode.contains('a') {
536 ret.seek(py, 0, 2)?;
537 }
538
539 Ok(ret)
540 }
541
542 fn opendir(&mut self, py: Python, path: &str) -> PyResult<SFTPDir> {
543 let path = self._adjust_cwd(path);
544 let h = py
545 .detach(|| self.sftp.opendir(path.as_str()))
546 .map_err(|e| sftp_error_to_py_err(e, Some(path.as_str())))?;
547 Ok(SFTPDir(Arc::clone(&self.sftp), h))
548 }
549
550 fn listdir(&mut self, py: Python, path: &str) -> PyResult<Vec<String>> {
551 let path = self._adjust_cwd(path);
552 let mut dir = self.opendir(py, path.as_str())?;
553 let mut entries = Vec::new();
554 while let Some(extra_entries) = dir.readdir(py)? {
555 for (name, _, _) in extra_entries {
556 entries.push(name);
557 }
558 }
559 Ok(entries)
560 }
561 }
562
563 pub fn _sftp_rs(py: Python, m: &Bound<PyModule>) -> PyResult<()> {
564 m.add_class::<SFTPClient>()?;
565 m.add_class::<SFTPAttributes>()?;
566 m.add("SFTPError", py.get_type::<SFTPError>())?;
567 Ok(())
568 }