Debian Codegraph @

src/sync.rs

raw
1 //! Synchronous SFTP client over a `Read + Write` channel.
2
3 use crate::protocol::*;
4 use std::io::{Read, Write};
5 #[cfg(unix)]
6 use std::os::unix::io::FromRawFd;
7 #[cfg(windows)]
8 use std::os::windows::io::{FromRawHandle, RawHandle};
9 use std::sync::Mutex;
10
11 pub struct SftpClient<C> {
12 channel: Mutex<C>,
13 last_request_id: std::sync::atomic::AtomicU32,
14 version: u32,
15 extensions: Vec<(String, String)>,
16 }
17
18 impl SftpClient<std::fs::File> {
19 #[cfg(unix)]
20 pub fn from_fd(fd: i32) -> std::io::Result<SftpClient<std::fs::File>> {
21 let file = unsafe { std::fs::File::from_raw_fd(fd) };
22 SftpClient::new(file)
23 }
24
25 #[cfg(windows)]
26 pub fn from_handle(handle: RawHandle) -> std::io::Result<SftpClient<std::fs::File>> {
27 let file = unsafe { std::fs::File::from_raw_handle(handle) };
28 SftpClient::new(file)
29 }
30 }
31
32 impl<C: Read + Write> SftpClient<C> {
33 pub fn new(mut channel: C) -> std::io::Result<Self> {
34 write_raw_packet(&mut channel, SSH_FXP_INIT, &build_init())?;
35 channel.flush()?;
36 let (kind, body) = read_raw_packet(&mut channel)?;
37 if kind != SSH_FXP_VERSION {
38 return Err(std::io::Error::other(format!(
39 "Unexpected response to init: {}",
40 kind
41 )));
42 }
43 let (version, extensions) = parse_version(&body)?;
44 Ok(Self {
45 channel: Mutex::new(channel),
46 version,
47 extensions,
48 last_request_id: std::sync::atomic::AtomicU32::new(0),
49 })
50 }
51
52 pub fn extensions(&self) -> &[(String, String)] {
53 &self.extensions
54 }
55
56 pub fn version(&self) -> u32 {
57 self.version
58 }
59
60 fn process(&self, cmd: u8, body: &[u8]) -> std::io::Result<(u8, Vec<u8>)> {
61 let request_id = self
62 .last_request_id
63 .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
64 let body = with_request_id(request_id, body);
65
66 write_raw_packet(&mut *self.channel.lock().unwrap(), cmd, body.as_slice())?;
67 let (cmd, buf) = read_raw_packet(&mut *self.channel.lock().unwrap())?;
68 let (resp_id, payload) = split_request_id(&buf)?;
69 assert_eq!(resp_id, request_id);
70 Ok((cmd, payload.to_vec()))
71 }
72
73 /// Create a new directory.
74 pub fn mkdir(&self, path: &str, attr: &Attributes) -> Result<()> {
75 let (cmd, data) = self.process(SSH_FXP_MKDIR, &build_path_and_attrs(path, attr)?)?;
76 expect_status(cmd, &data)
77 }
78
79 /// Remove a directory.
80 pub fn rmdir(&self, path: &str) -> Result<()> {
81 let (cmd, data) = self.process(SSH_FXP_RMDIR, &build_path_only(path))?;
82 expect_status(cmd, &data)
83 }
84
85 pub fn readlink(&self, path: &str) -> Result<String> {
86 let (cmd, data) = self.process(SSH_FXP_READLINK, &build_path_only(path))?;
87 let names = expect_name(cmd, &data)?;
88 Ok(names[0].0.clone())
89 }
90
91 pub fn symlink(&self, path: &str, target: &str) -> Result<()> {
92 let (cmd, data) = self.process(SSH_FXP_SYMLINK, &build_two_paths(path, target))?;
93 expect_status(cmd, &data)
94 }
95
96 pub fn hardlink(&self, path: &str, target: &str) -> Result<()> {
97 self.link(path, target, false)
98 }
99
100 pub fn link(&self, path: &str, target: &str, symlink: bool) -> Result<()> {
101 let (cmd, data) = self.process(SSH_FXP_LINK, &build_link(path, target, symlink))?;
102 expect_status(cmd, &data)
103 }
104
105 pub fn open(&self, path: &str, options: OpenOptions, attr: &Attributes) -> Result<File> {
106 let (cmd, data) = self.process(SSH_FXP_OPEN, &build_open(path, options.get(), attr)?)?;
107 Ok(File(expect_handle(cmd, &data)?))
108 }
109
110 pub fn realpath(
111 &self,
112 path: &str,
113 control_byte: Option<u8>,
114 compose_path: Option<&str>,
115 ) -> Result<String> {
116 let (cmd, data) = self.process(
117 SSH_FXP_REALPATH,
118 &build_realpath(path, control_byte, compose_path),
119 )?;
120 let names = expect_name(cmd, &data)?;
121 Ok(names[0].0.clone())
122 }
123
124 pub fn setstat(&self, path: &str, attr: &Attributes) -> Result<()> {
125 let (cmd, data) = self.process(SSH_FXP_SETSTAT, &build_path_and_attrs(path, attr)?)?;
126 expect_status(cmd, &data)
127 }
128
129 pub fn stat(&self, path: &str, flags: Option<u32>) -> Result<Attributes> {
130 let (cmd, data) = self.process(
131 SSH_FXP_STAT,
132 &build_path_and_flags(path, flags.unwrap_or(0)),
133 )?;
134 expect_attrs(cmd, &data)
135 }
136
137 pub fn remove(&self, path: &str) -> Result<()> {
138 let (cmd, data) = self.process(SSH_FXP_REMOVE, &build_path_only(path))?;
139 expect_status(cmd, &data)
140 }
141
142 pub fn rename(&self, oldpath: &str, newpath: &str, flags: Option<u32>) -> Result<()> {
143 let (cmd, data) = self.process(SSH_FXP_RENAME, &build_rename(oldpath, newpath, flags))?;
144 expect_status(cmd, &data)
145 }
146
147 pub fn lstat(&self, path: &str, flags: Option<u32>) -> Result<Attributes> {
148 let (cmd, data) = self.process(
149 SSH_FXP_LSTAT,
150 &build_path_and_flags(path, flags.unwrap_or(0)),
151 )?;
152 expect_attrs(cmd, &data)
153 }
154
155 pub fn opendir(&self, path: &str) -> Result<Directory> {
156 let (cmd, data) = self.process(SSH_FXP_OPENDIR, &build_path_only(path))?;
157 Ok(Directory(expect_handle(cmd, &data)?))
158 }
159
160 pub fn extended(&self, request: &str, data: &[u8]) -> Result<Option<Vec<u8>>> {
161 let (cmd, payload) = self.process(SSH_FXP_EXTENDED, &build_extended(request, data))?;
162 expect_extended(cmd, payload)
163 }
164
165 pub fn block(&self, file: &File, offset: u64, length: u64, lockmask: u32) -> Result<()> {
166 let (cmd, data) = self.process(
167 SSH_FXP_BLOCK,
168 &build_block(&file.0, offset, length, lockmask),
169 )?;
170 expect_status(cmd, &data)
171 }
172
173 pub fn unblock(&self, file: &File, offset: u64, length: u64) -> Result<()> {
174 let (cmd, data) = self.process(SSH_FXP_UNBLOCK, &build_unblock(&file.0, offset, length))?;
175 expect_status(cmd, &data)
176 }
177
178 pub fn fsetstat(&self, file: &File, attr: &Attributes) -> Result<()> {
179 let (cmd, data) =
180 self.process(SSH_FXP_FSETSTAT, &build_handle_and_attrs(&file.0, attr)?)?;
181 expect_status(cmd, &data)
182 }
183
184 pub fn fstat(&self, file: &File, flags: Option<u32>) -> Result<Attributes> {
185 let (cmd, data) = self.process(
186 SSH_FXP_FSTAT,
187 &build_handle_and_flags(&file.0, flags.unwrap_or(0)),
188 )?;
189 expect_attrs(cmd, &data)
190 }
191
192 pub fn pwrite(&self, file: &File, offset: u64, data: &[u8]) -> Result<()> {
193 let (cmd, payload) = self.process(SSH_FXP_WRITE, &build_pwrite(&file.0, offset, data))?;
194 expect_status(cmd, &payload)
195 }
196
197 pub fn pread(&self, file: &File, offset: u64, length: u32) -> Result<Vec<u8>> {
198 let (cmd, data) = self.process(SSH_FXP_READ, &build_pread(&file.0, offset, length))?;
199 expect_data(cmd, &data)
200 }
201
202 pub fn fclose(&self, file: &File) -> Result<()> {
203 let (cmd, data) = self.process(SSH_FXP_CLOSE, &build_handle_only(&file.0))?;
204 expect_status(cmd, &data)
205 }
206
207 pub fn flineseek(&self, file: &File, lineno: u64) -> Result<()> {
208 use byteorder::{BigEndian, WriteBytesExt};
209 let mut buf = build_handle_only(&file.0);
210 buf.write_u64::<BigEndian>(lineno)?;
211 self.extended("text-seek", buf.as_slice())?;
212 Ok(())
213 }
214
215 pub fn closedir(&self, dir: &Directory) -> Result<()> {
216 let (cmd, data) = self.process(SSH_FXP_CLOSE, &build_handle_only(&dir.0))?;
217 expect_status(cmd, &data)
218 }
219
220 pub fn readdir(&self, dir: &Directory) -> Result<Vec<(String, String, Attributes)>> {
221 let (cmd, data) = self.process(SSH_FXP_READDIR, &build_handle_only(&dir.0))?;
222 expect_readdir(cmd, &data)
223 }
224 }
225
226 #[cfg(feature = "ssh2")]
227 impl TryFrom<ssh2::Channel> for SftpClient<ssh2::Channel> {
228 type Error = std::io::Error;
229
230 fn try_from(mut channel: ssh2::Channel) -> std::result::Result<Self, Self::Error> {
231 channel.subsystem("sftp").map_err(std::io::Error::other)?;
232 SftpClient::new(channel)
233 }
234 }
235
236 #[cfg(test)]
237 mod tests {
238 use super::*;
239 use crate::protocol::{
240 read_raw_packet, split_request_id, write_raw_packet, SSH_FXP_ATTRS, SSH_FXP_CLOSE,
241 SSH_FXP_DATA, SSH_FXP_EXTENDED, SSH_FXP_EXTENDED_REPLY, SSH_FXP_FSETSTAT, SSH_FXP_FSTAT,
242 SSH_FXP_HANDLE, SSH_FXP_INIT, SSH_FXP_LSTAT, SSH_FXP_MKDIR, SSH_FXP_NAME, SSH_FXP_OPEN,
243 SSH_FXP_OPENDIR, SSH_FXP_READ, SSH_FXP_READDIR, SSH_FXP_READLINK, SSH_FXP_REALPATH,
244 SSH_FXP_REMOVE, SSH_FXP_RENAME, SSH_FXP_RMDIR, SSH_FXP_SETSTAT, SSH_FXP_STAT,
245 SSH_FXP_STATUS, SSH_FXP_SYMLINK, SSH_FXP_VERSION, SSH_FXP_WRITE, SSH_FX_EOF,
246 SSH_FX_NO_SUCH_FILE, SSH_FX_OK,
247 };
248 use std::net::{TcpListener, TcpStream};
249 use std::thread::JoinHandle;
250
251 /// Start a background thread that acts as a stub SFTP server on a loopback
252 /// socket. Returns a connected client-side TcpStream plus the server's join
253 /// handle. The handler is called with `(cmd, body_without_req_id)` and must
254 /// return `(response_cmd, response_body_without_req_id)`.
255 fn spawn_stub<F>(mut handler: F) -> (TcpStream, JoinHandle<()>)
256 where
257 F: FnMut(u8, &[u8]) -> (u8, Vec<u8>) + Send + 'static,
258 {
259 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
260 let addr = listener.local_addr().unwrap();
261 let server = std::thread::spawn(move || {
262 let (mut srv, _) = listener.accept().unwrap();
263 // INIT → VERSION handshake.
264 let (kind, _) = read_raw_packet(&mut srv).unwrap();
265 assert_eq!(kind, SSH_FXP_INIT);
266 write_raw_packet(&mut srv, SSH_FXP_VERSION, &3u32.to_be_bytes()).unwrap();
267 loop {
268 let (cmd, body) = match read_raw_packet(&mut srv) {
269 Ok(p) => p,
270 Err(_) => return,
271 };
272 let (req_id, payload) = split_request_id(&body).unwrap();
273 let (resp_cmd, resp_body) = handler(cmd, payload);
274 let mut wire = req_id.to_be_bytes().to_vec();
275 wire.extend_from_slice(&resp_body);
276 if write_raw_packet(&mut srv, resp_cmd, &wire).is_err() {
277 return;
278 }
279 }
280 });
281 let client = TcpStream::connect(addr).unwrap();
282 // Disable Nagle so small test packets flush promptly.
283 client.set_nodelay(true).unwrap();
284 (client, server)
285 }
286
287 fn ok_status() -> (u8, Vec<u8>) {
288 let mut body = Vec::new();
289 body.extend_from_slice(&SSH_FX_OK.to_be_bytes());
290 body.extend_from_slice(&0u32.to_be_bytes());
291 body.extend_from_slice(&0u32.to_be_bytes());
292 (SSH_FXP_STATUS, body)
293 }
294
295 fn err_status(code: u32) -> (u8, Vec<u8>) {
296 let mut body = Vec::new();
297 body.extend_from_slice(&code.to_be_bytes());
298 body.extend_from_slice(&0u32.to_be_bytes());
299 body.extend_from_slice(&0u32.to_be_bytes());
300 (SSH_FXP_STATUS, body)
301 }
302
303 fn handle_body(handle: &[u8]) -> (u8, Vec<u8>) {
304 let mut body = Vec::with_capacity(4 + handle.len());
305 body.extend_from_slice(&(handle.len() as u32).to_be_bytes());
306 body.extend_from_slice(handle);
307 (SSH_FXP_HANDLE, body)
308 }
309
310 fn attrs_body(a: &Attributes) -> (u8, Vec<u8>) {
311 (SSH_FXP_ATTRS, a.serialize().unwrap())
312 }
313
314 fn data_body(payload: &[u8]) -> (u8, Vec<u8>) {
315 let mut body = Vec::with_capacity(4 + payload.len());
316 body.extend_from_slice(&(payload.len() as u32).to_be_bytes());
317 body.extend_from_slice(payload);
318 (SSH_FXP_DATA, body)
319 }
320
321 fn name_body(entries: &[(&str, Attributes)]) -> (u8, Vec<u8>) {
322 let mut body = Vec::new();
323 body.extend_from_slice(&(entries.len() as u32).to_be_bytes());
324 for (name, attrs) in entries {
325 body.extend_from_slice(&(name.len() as u32).to_be_bytes());
326 body.extend_from_slice(name.as_bytes());
327 body.extend_from_slice(&attrs.serialize().unwrap());
328 }
329 (SSH_FXP_NAME, body)
330 }
331
332 fn readdir_body(entries: &[(&str, &str, Attributes)]) -> (u8, Vec<u8>) {
333 let mut body = Vec::new();
334 body.extend_from_slice(&(entries.len() as u32).to_be_bytes());
335 for (name, long, attrs) in entries {
336 body.extend_from_slice(&(name.len() as u32).to_be_bytes());
337 body.extend_from_slice(name.as_bytes());
338 body.extend_from_slice(&(long.len() as u32).to_be_bytes());
339 body.extend_from_slice(long.as_bytes());
340 body.extend_from_slice(&attrs.serialize().unwrap());
341 }
342 (SSH_FXP_NAME, body)
343 }
344
345 fn client(client_io: TcpStream) -> SftpClient<TcpStream> {
346 SftpClient::new(client_io).unwrap()
347 }
348
349 #[test]
350 fn sync_handshake_reads_version() {
351 let (io, srv) = spawn_stub(|_, _| ok_status());
352 let c = client(io);
353 assert_eq!(c.version(), 3);
354 drop(c);
355 let _ = srv.join();
356 }
357
358 #[test]
359 fn sync_version_helper() {
360 // A handshake where the server also advertises extensions.
361 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
362 let addr = listener.local_addr().unwrap();
363 let server = std::thread::spawn(move || {
364 let (mut srv, _) = listener.accept().unwrap();
365 let (kind, _) = read_raw_packet(&mut srv).unwrap();
366 assert_eq!(kind, SSH_FXP_INIT);
367 let mut body = 3u32.to_be_bytes().to_vec();
368 for (k, v) in [("ext1", "v1"), ("ext2", "v2")] {
369 body.extend_from_slice(&(k.len() as u32).to_be_bytes());
370 body.extend_from_slice(k.as_bytes());
371 body.extend_from_slice(&(v.len() as u32).to_be_bytes());
372 body.extend_from_slice(v.as_bytes());
373 }
374 write_raw_packet(&mut srv, SSH_FXP_VERSION, &body).unwrap();
375 });
376 let io = TcpStream::connect(addr).unwrap();
377 let c = SftpClient::new(io).unwrap();
378 assert_eq!(c.version(), 3);
379 assert_eq!(c.extensions().len(), 2);
380 assert_eq!(c.extensions()[0], ("ext1".to_string(), "v1".to_string()));
381 server.join().unwrap();
382 }
383
384 #[test]
385 fn sync_init_fails_on_wrong_response() {
386 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
387 let addr = listener.local_addr().unwrap();
388 std::thread::spawn(move || {
389 let (mut srv, _) = listener.accept().unwrap();
390 let _ = read_raw_packet(&mut srv);
391 // Wrong reply kind.
392 let _ = write_raw_packet(&mut srv, SSH_FXP_STATUS, &[]);
393 });
394 let io = TcpStream::connect(addr).unwrap();
395 assert!(SftpClient::new(io).is_err());
396 }
397
398 #[test]
399 fn sync_open_returns_handle() {
400 let (io, srv) = spawn_stub(|cmd, _| {
401 assert_eq!(cmd, SSH_FXP_OPEN);
402 handle_body(b"HSYNC")
403 });
404 let c = client(io);
405 let f = c
406 .open("/x", OpenOptions::new().read(true), &Attributes::new())
407 .unwrap();
408 assert_eq!(f.0, b"HSYNC".to_vec());
409 drop(c);
410 let _ = srv.join();
411 }
412
413 #[test]
414 fn sync_open_propagates_no_such_file() {
415 let (io, srv) = spawn_stub(|cmd, _| {
416 assert_eq!(cmd, SSH_FXP_OPEN);
417 err_status(SSH_FX_NO_SUCH_FILE)
418 });
419 let c = client(io);
420 match c.open("/x", OpenOptions::new().read(true), &Attributes::new()) {
421 Err(Error::NoSuchFile(_, _)) => {}
422 other => panic!("expected NoSuchFile, got {:?}", other),
423 }
424 drop(c);
425 let _ = srv.join();
426 }
427
428 #[test]
429 fn sync_stat_returns_attributes() {
430 let mut a = Attributes::new();
431 a.size = Some(42);
432 let a_clone = a.clone();
433 let (io, srv) = spawn_stub(move |cmd, _| {
434 assert_eq!(cmd, SSH_FXP_STAT);
435 attrs_body(&a_clone)
436 });
437 let c = client(io);
438 assert_eq!(c.stat("/x", None).unwrap(), a);
439 drop(c);
440 let _ = srv.join();
441 }
442
443 #[test]
444 fn sync_lstat_and_fstat() {
445 let (io, srv) = spawn_stub(|cmd, _| match cmd {
446 SSH_FXP_LSTAT | SSH_FXP_FSTAT => attrs_body(&Attributes::new()),
447 other => panic!("unexpected cmd {}", other),
448 });
449 let c = client(io);
450 c.lstat("/x", None).unwrap();
451 c.fstat(&File(b"h".to_vec()), None).unwrap();
452 drop(c);
453 let _ = srv.join();
454 }
455
456 #[test]
457 fn sync_pread_returns_data() {
458 let (io, srv) = spawn_stub(|cmd, _| {
459 assert_eq!(cmd, SSH_FXP_READ);
460 data_body(b"abcd")
461 });
462 let c = client(io);
463 let data = c.pread(&File(b"h".to_vec()), 0, 4).unwrap();
464 assert_eq!(data, b"abcd".to_vec());
465 drop(c);
466 let _ = srv.join();
467 }
468
469 #[test]
470 fn sync_pread_eof_surfaces() {
471 let (io, srv) = spawn_stub(|cmd, _| {
472 assert_eq!(cmd, SSH_FXP_READ);
473 err_status(SSH_FX_EOF)
474 });
475 let c = client(io);
476 match c.pread(&File(b"h".to_vec()), 0, 4) {
477 Err(Error::Eof(_, _)) => {}
478 other => panic!("expected Eof, got {:?}", other),
479 }
480 drop(c);
481 let _ = srv.join();
482 }
483
484 #[test]
485 fn sync_pwrite_ok() {
486 let (io, srv) = spawn_stub(|cmd, _| {
487 assert_eq!(cmd, SSH_FXP_WRITE);
488 ok_status()
489 });
490 let c = client(io);
491 c.pwrite(&File(b"h".to_vec()), 0, b"xyz").unwrap();
492 drop(c);
493 let _ = srv.join();
494 }
495
496 #[test]
497 fn sync_opendir_readdir() {
498 let (io, srv) = spawn_stub(|cmd, _| match cmd {
499 SSH_FXP_OPENDIR => handle_body(b"D"),
500 SSH_FXP_READDIR => readdir_body(&[
501 ("a", "-rw-r--r-- a", Attributes::new()),
502 ("b", "-rw-r--r-- b", Attributes::new()),
503 ]),
504 other => panic!("unexpected cmd {}", other),
505 });
506 let c = client(io);
507 let dir = c.opendir("/d").unwrap();
508 let entries = c.readdir(&dir).unwrap();
509 assert_eq!(entries.len(), 2);
510 assert_eq!(entries[0].0, "a");
511 drop(c);
512 let _ = srv.join();
513 }
514
515 #[test]
516 fn sync_realpath_and_readlink() {
517 let (io, srv) = spawn_stub(|cmd, _| match cmd {
518 SSH_FXP_REALPATH => name_body(&[("/abs", Attributes::new())]),
519 SSH_FXP_READLINK => name_body(&[("/tgt", Attributes::new())]),
520 other => panic!("unexpected cmd {}", other),
521 });
522 let c = client(io);
523 assert_eq!(c.realpath(".", None, None).unwrap(), "/abs");
524 assert_eq!(c.readlink("/l").unwrap(), "/tgt");
525 drop(c);
526 let _ = srv.join();
527 }
528
529 #[test]
530 fn sync_status_mutators() {
531 let (io, srv) = spawn_stub(|cmd, _| match cmd {
532 SSH_FXP_MKDIR | SSH_FXP_RMDIR | SSH_FXP_REMOVE | SSH_FXP_RENAME | SSH_FXP_SYMLINK
533 | SSH_FXP_SETSTAT | SSH_FXP_FSETSTAT | SSH_FXP_CLOSE => ok_status(),
534 other => panic!("unexpected cmd {}", other),
535 });
536 let c = client(io);
537 let attrs = Attributes::new();
538 let h = File(b"h".to_vec());
539 let d = Directory(b"d".to_vec());
540 c.mkdir("/a", &attrs).unwrap();
541 c.rmdir("/a").unwrap();
542 c.remove("/a").unwrap();
543 c.rename("/a", "/b", None).unwrap();
544 c.symlink("/b", "/a").unwrap();
545 c.setstat("/a", &attrs).unwrap();
546 c.fsetstat(&h, &attrs).unwrap();
547 c.fclose(&h).unwrap();
548 c.closedir(&d).unwrap();
549 drop(c);
550 let _ = srv.join();
551 }
552
553 #[test]
554 fn sync_extended_payload_and_none() {
555 // Two consecutive extended calls: first with a reply, second with OK
556 // status to exercise the `None` branch.
557 let mut call = 0;
558 let (io, srv) = spawn_stub(move |cmd, _| {
559 assert_eq!(cmd, SSH_FXP_EXTENDED);
560 call += 1;
561 if call == 1 {
562 (SSH_FXP_EXTENDED_REPLY, b"P".to_vec())
563 } else {
564 ok_status()
565 }
566 });
567 let c = client(io);
568 assert_eq!(c.extended("x", b"").unwrap(), Some(b"P".to_vec()));
569 assert_eq!(c.extended("x", b"").unwrap(), None);
570 drop(c);
571 let _ = srv.join();
572 }
573 }