Debian Codegraph @

src/async.rs

raw
1 //! Asynchronous SFTP client over a tokio `AsyncRead + AsyncWrite` channel.
2 //!
3 //! A single background task owns the read half, demultiplexing responses by
4 //! request id, so multiple requests can be in flight concurrently on a single
5 //! connection.
6
7 use crate::protocol::*;
8 use std::collections::HashMap;
9 use std::sync::atomic::{AtomicU32, Ordering};
10 use std::sync::{Arc, Mutex as StdMutex};
11 use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
12 use tokio::sync::{oneshot, Mutex as TokioMutex};
13
14 type Pending = Arc<StdMutex<HashMap<u32, oneshot::Sender<(u8, Vec<u8>)>>>>;
15
16 pub struct AsyncSftpClient<W> {
17 writer: TokioMutex<W>,
18 pending: Pending,
19 last_request_id: AtomicU32,
20 version: u32,
21 extensions: Vec<(String, String)>,
22 reader_task: TokioMutex<Option<tokio::task::JoinHandle<()>>>,
23 }
24
25 impl<W> Drop for AsyncSftpClient<W> {
26 fn drop(&mut self) {
27 if let Ok(mut guard) = self.reader_task.try_lock() {
28 if let Some(handle) = guard.take() {
29 handle.abort();
30 }
31 }
32 }
33 }
34
35 async fn read_packet_async<R: AsyncRead + Unpin>(r: &mut R) -> std::io::Result<(u8, Vec<u8>)> {
36 let mut hdr = [0u8; 4];
37 r.read_exact(&mut hdr).await?;
38 let len = i32::from_be_bytes(hdr) as usize;
39 if len == 0 {
40 return Err(std::io::Error::other("zero-length packet"));
41 }
42 let mut buf = vec![0u8; len];
43 r.read_exact(&mut buf).await?;
44 let kind = buf[0];
45 Ok((kind, buf[1..].to_vec()))
46 }
47
48 async fn write_packet_async<W: AsyncWrite + Unpin>(
49 w: &mut W,
50 kind: u8,
51 body: &[u8],
52 ) -> std::io::Result<()> {
53 let mut hdr = Vec::with_capacity(5);
54 hdr.extend_from_slice(&(body.len() as u32 + 1).to_be_bytes());
55 hdr.push(kind);
56 w.write_all(&hdr).await?;
57 w.write_all(body).await?;
58 w.flush().await?;
59 Ok(())
60 }
61
62 impl<W: AsyncWrite + Unpin + Send + 'static> AsyncSftpClient<W> {
63 /// Construct a new async SFTP client by negotiating the protocol over the
64 /// given split read/write halves. Spawns a background reader task on the
65 /// current tokio runtime.
66 pub async fn new<R>(mut reader: R, mut writer: W) -> std::io::Result<Self>
67 where
68 R: AsyncRead + Unpin + Send + 'static,
69 {
70 write_packet_async(&mut writer, SSH_FXP_INIT, &build_init()).await?;
71 let (kind, body) = read_packet_async(&mut reader).await?;
72 if kind != SSH_FXP_VERSION {
73 return Err(std::io::Error::other(format!(
74 "Unexpected response to init: {}",
75 kind
76 )));
77 }
78 let (version, extensions) = parse_version(&body)?;
79
80 let pending: Pending = Arc::new(StdMutex::new(HashMap::new()));
81 let pending_for_task = pending.clone();
82 let reader_task = tokio::spawn(async move {
83 run_reader(reader, pending_for_task).await;
84 });
85
86 Ok(Self {
87 writer: TokioMutex::new(writer),
88 pending,
89 last_request_id: AtomicU32::new(0),
90 version,
91 extensions,
92 reader_task: TokioMutex::new(Some(reader_task)),
93 })
94 }
95
96 pub fn extensions(&self) -> &[(String, String)] {
97 &self.extensions
98 }
99
100 pub fn version(&self) -> u32 {
101 self.version
102 }
103
104 async fn process(&self, cmd: u8, body: &[u8]) -> std::io::Result<(u8, Vec<u8>)> {
105 let request_id = self.last_request_id.fetch_add(1, Ordering::SeqCst);
106 let body = with_request_id(request_id, body);
107
108 let (tx, rx) = oneshot::channel();
109 self.pending.lock().unwrap().insert(request_id, tx);
110
111 if let Err(e) = {
112 let mut guard = self.writer.lock().await;
113 write_packet_async(&mut *guard, cmd, &body).await
114 } {
115 self.pending.lock().unwrap().remove(&request_id);
116 return Err(e);
117 }
118
119 rx.await
120 .map_err(|_| std::io::Error::other("reader task closed before response arrived"))
121 }
122
123 pub async fn mkdir(&self, path: &str, attr: &Attributes) -> Result<()> {
124 let (cmd, data) = self
125 .process(SSH_FXP_MKDIR, &build_path_and_attrs(path, attr)?)
126 .await?;
127 expect_status(cmd, &data)
128 }
129
130 pub async fn rmdir(&self, path: &str) -> Result<()> {
131 let (cmd, data) = self.process(SSH_FXP_RMDIR, &build_path_only(path)).await?;
132 expect_status(cmd, &data)
133 }
134
135 pub async fn readlink(&self, path: &str) -> Result<String> {
136 let (cmd, data) = self
137 .process(SSH_FXP_READLINK, &build_path_only(path))
138 .await?;
139 let names = expect_name(cmd, &data)?;
140 Ok(names[0].0.clone())
141 }
142
143 pub async fn symlink(&self, path: &str, target: &str) -> Result<()> {
144 let (cmd, data) = self
145 .process(SSH_FXP_SYMLINK, &build_two_paths(path, target))
146 .await?;
147 expect_status(cmd, &data)
148 }
149
150 pub async fn hardlink(&self, path: &str, target: &str) -> Result<()> {
151 self.link(path, target, false).await
152 }
153
154 pub async fn link(&self, path: &str, target: &str, symlink: bool) -> Result<()> {
155 let (cmd, data) = self
156 .process(SSH_FXP_LINK, &build_link(path, target, symlink))
157 .await?;
158 expect_status(cmd, &data)
159 }
160
161 pub async fn open(&self, path: &str, options: OpenOptions, attr: &Attributes) -> Result<File> {
162 let (cmd, data) = self
163 .process(SSH_FXP_OPEN, &build_open(path, options.get(), attr)?)
164 .await?;
165 Ok(File(expect_handle(cmd, &data)?))
166 }
167
168 pub async fn realpath(
169 &self,
170 path: &str,
171 control_byte: Option<u8>,
172 compose_path: Option<&str>,
173 ) -> Result<String> {
174 let (cmd, data) = self
175 .process(
176 SSH_FXP_REALPATH,
177 &build_realpath(path, control_byte, compose_path),
178 )
179 .await?;
180 let names = expect_name(cmd, &data)?;
181 Ok(names[0].0.clone())
182 }
183
184 pub async fn setstat(&self, path: &str, attr: &Attributes) -> Result<()> {
185 let (cmd, data) = self
186 .process(SSH_FXP_SETSTAT, &build_path_and_attrs(path, attr)?)
187 .await?;
188 expect_status(cmd, &data)
189 }
190
191 pub async fn stat(&self, path: &str, flags: Option<u32>) -> Result<Attributes> {
192 let (cmd, data) = self
193 .process(
194 SSH_FXP_STAT,
195 &build_path_and_flags(path, flags.unwrap_or(0)),
196 )
197 .await?;
198 expect_attrs(cmd, &data)
199 }
200
201 pub async fn remove(&self, path: &str) -> Result<()> {
202 let (cmd, data) = self.process(SSH_FXP_REMOVE, &build_path_only(path)).await?;
203 expect_status(cmd, &data)
204 }
205
206 pub async fn rename(&self, oldpath: &str, newpath: &str, flags: Option<u32>) -> Result<()> {
207 let (cmd, data) = self
208 .process(SSH_FXP_RENAME, &build_rename(oldpath, newpath, flags))
209 .await?;
210 expect_status(cmd, &data)
211 }
212
213 pub async fn lstat(&self, path: &str, flags: Option<u32>) -> Result<Attributes> {
214 let (cmd, data) = self
215 .process(
216 SSH_FXP_LSTAT,
217 &build_path_and_flags(path, flags.unwrap_or(0)),
218 )
219 .await?;
220 expect_attrs(cmd, &data)
221 }
222
223 pub async fn opendir(&self, path: &str) -> Result<Directory> {
224 let (cmd, data) = self
225 .process(SSH_FXP_OPENDIR, &build_path_only(path))
226 .await?;
227 Ok(Directory(expect_handle(cmd, &data)?))
228 }
229
230 pub async fn extended(&self, request: &str, data: &[u8]) -> Result<Option<Vec<u8>>> {
231 let (cmd, payload) = self
232 .process(SSH_FXP_EXTENDED, &build_extended(request, data))
233 .await?;
234 expect_extended(cmd, payload)
235 }
236
237 pub async fn block(&self, file: &File, offset: u64, length: u64, lockmask: u32) -> Result<()> {
238 let (cmd, data) = self
239 .process(
240 SSH_FXP_BLOCK,
241 &build_block(&file.0, offset, length, lockmask),
242 )
243 .await?;
244 expect_status(cmd, &data)
245 }
246
247 pub async fn unblock(&self, file: &File, offset: u64, length: u64) -> Result<()> {
248 let (cmd, data) = self
249 .process(SSH_FXP_UNBLOCK, &build_unblock(&file.0, offset, length))
250 .await?;
251 expect_status(cmd, &data)
252 }
253
254 pub async fn fsetstat(&self, file: &File, attr: &Attributes) -> Result<()> {
255 let (cmd, data) = self
256 .process(SSH_FXP_FSETSTAT, &build_handle_and_attrs(&file.0, attr)?)
257 .await?;
258 expect_status(cmd, &data)
259 }
260
261 pub async fn fstat(&self, file: &File, flags: Option<u32>) -> Result<Attributes> {
262 let (cmd, data) = self
263 .process(
264 SSH_FXP_FSTAT,
265 &build_handle_and_flags(&file.0, flags.unwrap_or(0)),
266 )
267 .await?;
268 expect_attrs(cmd, &data)
269 }
270
271 pub async fn pwrite(&self, file: &File, offset: u64, data: &[u8]) -> Result<()> {
272 let (cmd, payload) = self
273 .process(SSH_FXP_WRITE, &build_pwrite(&file.0, offset, data))
274 .await?;
275 expect_status(cmd, &payload)
276 }
277
278 pub async fn pread(&self, file: &File, offset: u64, length: u32) -> Result<Vec<u8>> {
279 let (cmd, data) = self
280 .process(SSH_FXP_READ, &build_pread(&file.0, offset, length))
281 .await?;
282 expect_data(cmd, &data)
283 }
284
285 pub async fn fclose(&self, file: &File) -> Result<()> {
286 let (cmd, data) = self
287 .process(SSH_FXP_CLOSE, &build_handle_only(&file.0))
288 .await?;
289 expect_status(cmd, &data)
290 }
291
292 pub async fn flineseek(&self, file: &File, lineno: u64) -> Result<()> {
293 let mut buf = build_handle_only(&file.0);
294 buf.extend_from_slice(&lineno.to_be_bytes());
295 self.extended("text-seek", buf.as_slice()).await?;
296 Ok(())
297 }
298
299 pub async fn closedir(&self, dir: &Directory) -> Result<()> {
300 let (cmd, data) = self
301 .process(SSH_FXP_CLOSE, &build_handle_only(&dir.0))
302 .await?;
303 expect_status(cmd, &data)
304 }
305
306 pub async fn readdir(&self, dir: &Directory) -> Result<Vec<(String, String, Attributes)>> {
307 let (cmd, data) = self
308 .process(SSH_FXP_READDIR, &build_handle_only(&dir.0))
309 .await?;
310 expect_readdir(cmd, &data)
311 }
312 }
313
314 async fn run_reader<R: AsyncRead + Unpin>(mut reader: R, pending: Pending) {
315 loop {
316 match read_packet_async(&mut reader).await {
317 Ok((cmd, buf)) => {
318 let (req_id, payload) = match split_request_id(&buf) {
319 Ok(v) => (v.0, v.1.to_vec()),
320 Err(_) => continue,
321 };
322 if let Some(tx) = pending.lock().unwrap().remove(&req_id) {
323 let _ = tx.send((cmd, payload));
324 }
325 }
326 Err(_) => {
327 // Connection closed or fatal read error; drop all pending senders so
328 // their awaits return errors.
329 pending.lock().unwrap().clear();
330 return;
331 }
332 }
333 }
334 }
335
336 #[cfg(test)]
337 mod tests {
338 use super::*;
339 use tokio::io::duplex;
340
341 /// Serve INIT/VERSION then respond to every numbered request with an OK status,
342 /// preserving the request id (which lives in the first 4 bytes of the body).
343 async fn run_stub_server(mut srv: tokio::io::DuplexStream) {
344 // INIT: read its packet
345 let (kind, _body) = read_packet_async(&mut srv).await.unwrap();
346 assert_eq!(kind, SSH_FXP_INIT);
347 // VERSION reply: version=3, no extensions
348 let body = 3u32.to_be_bytes().to_vec();
349 write_packet_async(&mut srv, SSH_FXP_VERSION, &body)
350 .await
351 .unwrap();
352
353 // From here on, echo OK status for every request.
354 loop {
355 match read_packet_async(&mut srv).await {
356 Ok((_cmd, body)) => {
357 let req_id = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
358 let mut resp = Vec::new();
359 resp.extend_from_slice(&req_id.to_be_bytes());
360 resp.extend_from_slice(&SSH_FX_OK.to_be_bytes());
361 resp.extend_from_slice(&0u32.to_be_bytes());
362 resp.extend_from_slice(&0u32.to_be_bytes());
363 if write_packet_async(&mut srv, SSH_FXP_STATUS, &resp)
364 .await
365 .is_err()
366 {
367 return;
368 }
369 }
370 Err(_) => return,
371 }
372 }
373 }
374
375 #[tokio::test]
376 async fn handshake_and_concurrent_requests() {
377 let (client_io, server_io) = duplex(64 * 1024);
378 tokio::spawn(run_stub_server(server_io));
379
380 let (cr, cw) = tokio::io::split(client_io);
381 let client = AsyncSftpClient::new(cr, cw).await.unwrap();
382 assert_eq!(client.version(), 3);
383
384 // Three concurrent requests with distinct ids exercise the demux path.
385 let attrs = Attributes::new();
386 let (r1, r2, r3) = tokio::join!(
387 client.mkdir("/a", &attrs),
388 client.mkdir("/b", &attrs),
389 client.rmdir("/c"),
390 );
391 r1.unwrap();
392 r2.unwrap();
393 r3.unwrap();
394 }
395
396 #[tokio::test]
397 async fn request_fails_after_reader_exits() {
398 let (client_io, mut server_io) = duplex(64 * 1024);
399 tokio::spawn(async move {
400 let (kind, _body) = read_packet_async(&mut server_io).await.unwrap();
401 assert_eq!(kind, SSH_FXP_INIT);
402 let body = 3u32.to_be_bytes().to_vec();
403 write_packet_async(&mut server_io, SSH_FXP_VERSION, &body)
404 .await
405 .unwrap();
406 // Drop the server side so the reader task sees EOF.
407 });
408
409 let (cr, cw) = tokio::io::split(client_io);
410 let client = AsyncSftpClient::new(cr, cw).await.unwrap();
411 let attrs = Attributes::new();
412 // The request must not hang after the reader exits.
413 let result = tokio::time::timeout(
414 std::time::Duration::from_secs(2),
415 client.mkdir("/x", &attrs),
416 )
417 .await;
418 assert!(result.is_ok(), "request hung after reader closed");
419 }
420
421 /// Programmable stub: for each received request, the handler returns
422 /// `(response_cmd, response_body_without_request_id)`. The dispatcher re-adds
423 /// the request id at the front.
424 async fn run_router<F>(mut srv: tokio::io::DuplexStream, mut handler: F)
425 where
426 F: FnMut(u8, &[u8]) -> (u8, Vec<u8>) + Send,
427 {
428 let (kind, _body) = read_packet_async(&mut srv).await.unwrap();
429 assert_eq!(kind, SSH_FXP_INIT);
430 write_packet_async(&mut srv, SSH_FXP_VERSION, &3u32.to_be_bytes())
431 .await
432 .unwrap();
433
434 loop {
435 let (cmd, body) = match read_packet_async(&mut srv).await {
436 Ok(p) => p,
437 Err(_) => return,
438 };
439 let (req_id, payload) = split_request_id(&body).unwrap();
440 let (resp_cmd, resp_body) = handler(cmd, payload);
441 let mut wire = req_id.to_be_bytes().to_vec();
442 wire.extend_from_slice(&resp_body);
443 if write_packet_async(&mut srv, resp_cmd, &wire).await.is_err() {
444 return;
445 }
446 }
447 }
448
449 fn ok_status() -> (u8, Vec<u8>) {
450 let mut body = Vec::new();
451 body.extend_from_slice(&SSH_FX_OK.to_be_bytes());
452 body.extend_from_slice(&0u32.to_be_bytes()); // empty error message
453 body.extend_from_slice(&0u32.to_be_bytes()); // empty lang tag
454 (SSH_FXP_STATUS, body)
455 }
456
457 fn err_status(code: u32) -> (u8, Vec<u8>) {
458 let mut body = Vec::new();
459 body.extend_from_slice(&code.to_be_bytes());
460 body.extend_from_slice(&0u32.to_be_bytes());
461 body.extend_from_slice(&0u32.to_be_bytes());
462 (SSH_FXP_STATUS, body)
463 }
464
465 fn handle_body(handle: &[u8]) -> (u8, Vec<u8>) {
466 let mut body = Vec::with_capacity(4 + handle.len());
467 body.extend_from_slice(&(handle.len() as u32).to_be_bytes());
468 body.extend_from_slice(handle);
469 (SSH_FXP_HANDLE, body)
470 }
471
472 fn attrs_body(a: &Attributes) -> (u8, Vec<u8>) {
473 (SSH_FXP_ATTRS, a.serialize().unwrap())
474 }
475
476 fn data_body(payload: &[u8]) -> (u8, Vec<u8>) {
477 let mut body = Vec::with_capacity(4 + payload.len());
478 body.extend_from_slice(&(payload.len() as u32).to_be_bytes());
479 body.extend_from_slice(payload);
480 (SSH_FXP_DATA, body)
481 }
482
483 fn name_body(entries: &[(&str, Attributes)]) -> (u8, Vec<u8>) {
484 let mut body = Vec::new();
485 body.extend_from_slice(&(entries.len() as u32).to_be_bytes());
486 for (name, attrs) in entries {
487 body.extend_from_slice(&(name.len() as u32).to_be_bytes());
488 body.extend_from_slice(name.as_bytes());
489 body.extend_from_slice(&attrs.serialize().unwrap());
490 }
491 (SSH_FXP_NAME, body)
492 }
493
494 fn readdir_body(entries: &[(&str, &str, Attributes)]) -> (u8, Vec<u8>) {
495 let mut body = Vec::new();
496 body.extend_from_slice(&(entries.len() as u32).to_be_bytes());
497 for (name, longname, attrs) in entries {
498 body.extend_from_slice(&(name.len() as u32).to_be_bytes());
499 body.extend_from_slice(name.as_bytes());
500 body.extend_from_slice(&(longname.len() as u32).to_be_bytes());
501 body.extend_from_slice(longname.as_bytes());
502 body.extend_from_slice(&attrs.serialize().unwrap());
503 }
504 (SSH_FXP_NAME, body)
505 }
506
507 /// Spin up a client against a stub server that uses `handler`.
508 async fn with_stub<F>(
509 handler: F,
510 ) -> AsyncSftpClient<tokio::io::WriteHalf<tokio::io::DuplexStream>>
511 where
512 F: FnMut(u8, &[u8]) -> (u8, Vec<u8>) + Send + 'static,
513 {
514 let (client_io, server_io) = duplex(64 * 1024);
515 tokio::spawn(run_router(server_io, handler));
516 let (cr, cw) = tokio::io::split(client_io);
517 AsyncSftpClient::new(cr, cw).await.unwrap()
518 }
519
520 #[tokio::test]
521 async fn async_open_returns_handle() {
522 let client = with_stub(|cmd, _body| {
523 assert_eq!(cmd, SSH_FXP_OPEN);
524 handle_body(b"HANDLE42")
525 })
526 .await;
527 let f = client
528 .open("/x", OpenOptions::new().read(true), &Attributes::new())
529 .await
530 .unwrap();
531 assert_eq!(f.0, b"HANDLE42".to_vec());
532 }
533
534 #[tokio::test]
535 async fn async_open_propagates_no_such_file() {
536 let client = with_stub(|cmd, _| {
537 assert_eq!(cmd, SSH_FXP_OPEN);
538 err_status(SSH_FX_NO_SUCH_FILE)
539 })
540 .await;
541 match client
542 .open(
543 "/missing",
544 OpenOptions::new().read(true),
545 &Attributes::new(),
546 )
547 .await
548 {
549 Err(Error::NoSuchFile(_, _)) => {}
550 other => panic!("expected NoSuchFile, got {:?}", other),
551 }
552 }
553
554 #[tokio::test]
555 async fn async_stat_returns_attributes() {
556 let mut a = Attributes::new();
557 a.size = Some(1234);
558 a.permissions = Some(0o100644);
559 let a_clone = a.clone();
560 let client = with_stub(move |cmd, _| {
561 assert_eq!(cmd, SSH_FXP_STAT);
562 attrs_body(&a_clone)
563 })
564 .await;
565 let got = client.stat("/file", None).await.unwrap();
566 assert_eq!(got, a);
567 }
568
569 #[tokio::test]
570 async fn async_lstat_returns_attributes() {
571 let client = with_stub(|cmd, _| {
572 assert_eq!(cmd, SSH_FXP_LSTAT);
573 attrs_body(&Attributes::new())
574 })
575 .await;
576 client.lstat("/x", None).await.unwrap();
577 }
578
579 #[tokio::test]
580 async fn async_fstat_returns_attributes() {
581 let client = with_stub(|cmd, _| {
582 assert_eq!(cmd, SSH_FXP_FSTAT);
583 attrs_body(&Attributes::new())
584 })
585 .await;
586 client.fstat(&File(b"h".to_vec()), None).await.unwrap();
587 }
588
589 #[tokio::test]
590 async fn async_pread_returns_data() {
591 let client = with_stub(|cmd, _| {
592 assert_eq!(cmd, SSH_FXP_READ);
593 data_body(b"hello")
594 })
595 .await;
596 let data = client.pread(&File(b"h".to_vec()), 0, 5).await.unwrap();
597 assert_eq!(data, b"hello".to_vec());
598 }
599
600 #[tokio::test]
601 async fn async_pread_propagates_eof() {
602 let client = with_stub(|cmd, _| {
603 assert_eq!(cmd, SSH_FXP_READ);
604 err_status(SSH_FX_EOF)
605 })
606 .await;
607 match client.pread(&File(b"h".to_vec()), 0, 5).await {
608 Err(Error::Eof(_, _)) => {}
609 other => panic!("expected Eof, got {:?}", other),
610 }
611 }
612
613 #[tokio::test]
614 async fn async_pwrite_returns_ok() {
615 let client = with_stub(|cmd, _| {
616 assert_eq!(cmd, SSH_FXP_WRITE);
617 ok_status()
618 })
619 .await;
620 client
621 .pwrite(&File(b"h".to_vec()), 0, b"data")
622 .await
623 .unwrap();
624 }
625
626 #[tokio::test]
627 async fn async_opendir_and_readdir() {
628 let client = with_stub(|cmd, _| match cmd {
629 SSH_FXP_OPENDIR => handle_body(b"D"),
630 SSH_FXP_READDIR => readdir_body(&[
631 ("a", "-rw-r--r-- a", Attributes::new()),
632 ("b", "-rw-r--r-- b", Attributes::new()),
633 ]),
634 other => panic!("unexpected cmd {}", other),
635 })
636 .await;
637 let dir = client.opendir("/d").await.unwrap();
638 let entries = client.readdir(&dir).await.unwrap();
639 assert_eq!(entries.len(), 2);
640 assert_eq!(entries[0].0, "a");
641 assert_eq!(entries[1].0, "b");
642 }
643
644 #[tokio::test]
645 async fn async_readdir_eof_surfaces() {
646 let client = with_stub(|cmd, _| match cmd {
647 SSH_FXP_OPENDIR => handle_body(b"D"),
648 SSH_FXP_READDIR => err_status(SSH_FX_EOF),
649 other => panic!("unexpected cmd {}", other),
650 })
651 .await;
652 let dir = client.opendir("/d").await.unwrap();
653 match client.readdir(&dir).await {
654 Err(Error::Eof(_, _)) => {}
655 other => panic!("expected Eof, got {:?}", other),
656 }
657 }
658
659 #[tokio::test]
660 async fn async_realpath_returns_first_name() {
661 let client = with_stub(|cmd, _| {
662 assert_eq!(cmd, SSH_FXP_REALPATH);
663 name_body(&[("/home/alice", Attributes::new())])
664 })
665 .await;
666 assert_eq!(
667 client.realpath(".", None, None).await.unwrap(),
668 "/home/alice"
669 );
670 }
671
672 #[tokio::test]
673 async fn async_readlink_returns_target() {
674 let client = with_stub(|cmd, _| {
675 assert_eq!(cmd, SSH_FXP_READLINK);
676 name_body(&[("/actual", Attributes::new())])
677 })
678 .await;
679 assert_eq!(client.readlink("/lnk").await.unwrap(), "/actual");
680 }
681
682 #[tokio::test]
683 async fn async_status_mutators() {
684 let client = with_stub(|cmd, _| {
685 assert!(matches!(
686 cmd,
687 SSH_FXP_MKDIR
688 | SSH_FXP_RMDIR
689 | SSH_FXP_REMOVE
690 | SSH_FXP_RENAME
691 | SSH_FXP_SYMLINK
692 | SSH_FXP_LINK
693 | SSH_FXP_SETSTAT
694 | SSH_FXP_FSETSTAT
695 | SSH_FXP_CLOSE
696 | SSH_FXP_BLOCK
697 | SSH_FXP_UNBLOCK
698 ));
699 ok_status()
700 })
701 .await;
702
703 let attrs = Attributes::new();
704 let handle = File(b"h".to_vec());
705 let dir = Directory(b"d".to_vec());
706
707 client.mkdir("/a", &attrs).await.unwrap();
708 client.rmdir("/a").await.unwrap();
709 client.remove("/a").await.unwrap();
710 client.rename("/a", "/b", None).await.unwrap();
711 client.symlink("/b", "/a").await.unwrap();
712 client.hardlink("/b", "/a").await.unwrap();
713 client.setstat("/a", &attrs).await.unwrap();
714 client.fsetstat(&handle, &attrs).await.unwrap();
715 client.fclose(&handle).await.unwrap();
716 client.closedir(&dir).await.unwrap();
717 client.block(&handle, 0, 0, 0).await.unwrap();
718 client.unblock(&handle, 0, 0).await.unwrap();
719 }
720
721 #[tokio::test]
722 async fn async_extended_returns_payload_on_reply() {
723 let client = with_stub(|cmd, _| {
724 assert_eq!(cmd, SSH_FXP_EXTENDED);
725 (SSH_FXP_EXTENDED_REPLY, b"payload".to_vec())
726 })
727 .await;
728 let out = client.extended("x", b"").await.unwrap();
729 assert_eq!(out, Some(b"payload".to_vec()));
730 }
731
732 #[tokio::test]
733 async fn async_extended_returns_none_on_ok_status() {
734 let client = with_stub(|cmd, _| {
735 assert_eq!(cmd, SSH_FXP_EXTENDED);
736 ok_status()
737 })
738 .await;
739 assert_eq!(client.extended("x", b"").await.unwrap(), None);
740 }
741 }