remotefs-ssh 0.8.3

remotefs SSH client library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
use std::io::{Cursor, Read, Seek, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr as _;
use std::time::UNIX_EPOCH;

use libssh_rs::{AuthMethods, AuthStatus, OpenFlags, SshKey, SshOption};
use remotefs::fs::stream::{ReadAndSeek, WriteAndSeek};
use remotefs::fs::{FileType, Metadata, ReadStream, UnixPex, WriteStream};
use remotefs::{File, RemoteError, RemoteErrorType, RemoteResult};

use super::SshSession;
use crate::SshOpts;
use crate::ssh::backend::Sftp;
use crate::ssh::config::Config;

/// An implementation of [`SshSession`] using libssh as the backend.
///
/// See <https://docs.rs/libssh-rs/0.3.6/libssh_rs/struct.Session.html>
pub struct LibSshSession {
    session: libssh_rs::Session,
}

/// A wrapper around [`libssh_rs::Sftp`] to provide a SFTP client for [`LibSshSession`]
///
/// See <https://docs.rs/libssh-rs/0.3.6/libssh_rs/struct.Sftp.html>
pub struct LibSshSftp {
    inner: libssh_rs::Sftp,
}

/// A wrapper around [`libssh_rs::Channel`] to provide a SCP recv channel for [`LibSshSession`]
struct ScpRecvChannel {
    channel: libssh_rs::Channel,
    /// We must keep track of the total file size
    /// otherwise read will hang
    filesize: usize,
    read: usize,
}

impl Read for ScpRecvChannel {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        if self.read >= self.filesize {
            return Ok(0);
        }

        // read up to
        let max_read = (self.filesize - self.read).min(buf.len());
        let res = self.channel.stdout().read(&mut buf[..max_read])?;

        self.read += res;
        Ok(res)
    }
}

impl Drop for ScpRecvChannel {
    fn drop(&mut self) {
        debug!("Dropping SCP recv channel");
        if let Err(err) = self.channel.send_eof() {
            debug!("Error sending EOF: {err}");
        }
        if let Err(err) = self.channel.close() {
            debug!("Error closing channel: {err}");
        }
    }
}

/// A wrapper around [`libssh_rs::Channel`] to provide a SCP send channel for [`LibSshSession`]
struct ScpSendChannel {
    channel: libssh_rs::Channel,
}

impl Write for ScpSendChannel {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.channel.stdin().write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.channel.stdin().flush()
    }
}

impl Drop for ScpSendChannel {
    fn drop(&mut self) {
        debug!("Dropping SCP send channel");
        if let Err(err) = self.channel.send_eof() {
            debug!("Error sending EOF: {err}");
        }
        if let Err(err) = self.channel.close() {
            debug!("Error closing channel: {err}");
        }
    }
}

impl SshSession for LibSshSession {
    type Sftp = LibSshSftp;

    fn connect(opts: &SshOpts) -> remotefs::RemoteResult<Self> {
        // Resolve host
        debug!("Connecting to '{}'", opts.host);

        // Create session
        let mut session = match libssh_rs::Session::new() {
            Ok(s) => s,
            Err(err) => {
                error!("Could not create session: {err}");
                return Err(RemoteError::new_ex(RemoteErrorType::ConnectionError, err));
            }
        };

        // set hostname
        session
            .set_option(SshOption::Hostname(opts.host.clone()))
            .map_err(|e| RemoteError::new_ex(RemoteErrorType::ConnectionError, e))?;
        if let Some(port) = opts.port {
            debug!("Using port: {port}");
            session
                .set_option(SshOption::Port(port))
                .map_err(|e| RemoteError::new_ex(RemoteErrorType::ConnectionError, e))?;
        }

        let config_file_str = opts.config_file.as_ref().map(|p| p.display().to_string());
        debug!("Using config file: {:?}", config_file_str);
        session
            .options_parse_config(config_file_str.as_deref())
            .map_err(|e| RemoteError::new_ex(RemoteErrorType::ConnectionError, e))?;

        // set methods
        for opt in opts.methods.iter().filter_map(|method| method.ssh_opts()) {
            debug!("Setting SSH option: {opt:?}");
            session
                .set_option(opt)
                .map_err(|e| RemoteError::new_ex(RemoteErrorType::ConnectionError, e))?;
        }

        // Open connection and initialize handshake
        if let Err(err) = session.connect() {
            error!("SSH handshake failed: {err}");
            return Err(RemoteError::new_ex(RemoteErrorType::ProtocolError, err));
        }

        // try to authenticate userauth_none
        authenticate(&mut session, opts)?;

        Ok(Self { session })
    }

    fn authenticated(&self) -> RemoteResult<bool> {
        Ok(self.session.is_connected())
    }

    fn banner(&self) -> RemoteResult<Option<String>> {
        self.session.get_server_banner().map(Some).map_err(|e| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Failed to get banner: {e}"),
            )
        })
    }

    fn disconnect(&self) -> RemoteResult<()> {
        self.session.disconnect();

        Ok(())
    }

    fn cmd<S>(&mut self, cmd: S) -> RemoteResult<(u32, String)>
    where
        S: AsRef<str>,
    {
        let output = perform_shell_cmd(&mut self.session, format!("{}; echo $?", cmd.as_ref()))?;
        if let Some(index) = output.trim().rfind('\n') {
            trace!("Read from stdout: '{output}'");
            let actual_output = (output[0..index + 1]).to_string();
            trace!("Actual output '{actual_output}'");
            trace!("Parsing return code '{}'", output[index..].trim());
            let rc = match u32::from_str(output[index..].trim()).ok() {
                Some(val) => val,
                None => {
                    return Err(RemoteError::new_ex(
                        RemoteErrorType::ProtocolError,
                        "Failed to get command exit code",
                    ));
                }
            };
            debug!(r#"Command output: "{actual_output}"; exit code: {rc}"#);
            Ok((rc, actual_output))
        } else {
            match u32::from_str(output.trim()).ok() {
                Some(val) => Ok((val, String::new())),
                None => Err(RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    "Failed to get command exit code",
                )),
            }
        }
    }

    fn scp_recv(&self, path: &Path) -> RemoteResult<Box<dyn Read + Send>> {
        self.session.set_blocking(true);

        // open channel
        debug!("Opening channel for scp recv");
        let channel = self.session.new_channel().map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not open channel: {err}"),
            )
        })?;
        debug!("Opening channel session");
        channel.open_session().map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not open session: {err}"),
            )
        })?;
        // exec `scp -f %s`
        let cmd = format!("scp -f {}", path.display());
        channel.request_exec(cmd.as_ref()).map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not request command execution: {err}"),
            )
        })?;
        debug!("ACK with 0");
        // write \0
        channel.stdin().write_all(b"\0").map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not write to channel: {err}"),
            )
        })?;

        // read header
        debug!("Reading SCP header");
        let mut header = [0u8; 1024];
        let bytes = channel.stdout().read(&mut header).map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not read from channel: {err}"),
            )
        })?;
        // read filesize from header
        let filesize = parse_scp_header_filesize(&header[..bytes])?;
        debug!("File size: {filesize}");
        // send OK
        debug!("Sending OK");
        channel.stdin().write_all(b"\0").map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not write to channel: {err}"),
            )
        })?;

        debug!("Creating SCP recv channel");
        let reader = ScpRecvChannel {
            channel,
            filesize,
            read: 0,
        };

        Ok(Box::new(reader) as Box<dyn Read + Send>)
    }

    fn scp_send(
        &self,
        remote_path: &Path,
        mode: i32,
        size: u64,
        _times: Option<(u64, u64)>,
    ) -> RemoteResult<Box<dyn Write + Send>> {
        self.session.set_blocking(true);

        // open channel
        debug!("Opening channel for scp send");
        let channel = self.session.new_channel().map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not open channel: {err}"),
            )
        })?;
        debug!("Opening channel session");
        channel.open_session().map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not open session: {err}"),
            )
        })?;
        // exec `scp -t %s`
        let cmd = format!("scp -t {}", remote_path.display());
        channel.request_exec(cmd.as_ref()).map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not request command execution: {err}"),
            )
        })?;

        // wait for ACK
        wait_for_ack(&channel)?;

        let Some(filename) = remote_path.file_name().map(|f| f.to_string_lossy()) else {
            return Err(RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not get file name: {remote_path:?}"),
            ));
        };

        // send file header
        let header = format!("C{mode:04o} {size} {filename}\n", mode = mode & 0o7777,);
        debug!("Sending SCP header: {header}");
        channel
            .stdin()
            .write_all(header.as_bytes())
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    format!("Could not write to channel: {err}"),
                )
            })?;

        // wait for ACK
        wait_for_ack(&channel)?;

        // return channel
        let writer = ScpSendChannel { channel };
        Ok(Box::new(writer) as Box<dyn Write + Send>)
    }

    fn sftp(&self) -> RemoteResult<Self::Sftp> {
        self.session
            .sftp()
            .map(|sftp| LibSshSftp { inner: sftp })
            .map_err(|e| RemoteError::new_ex(RemoteErrorType::ProtocolError, e))
    }
}

/// Number of bytes per SFTP read call for buffered reads.
///
/// libssh caps each `sftp_read` at the server's maximum packet payload
/// (typically 64 KiB). Using a larger request size lets the C library
/// issue fewer round-trips when possible, while still working correctly
/// when the server returns less.
const SFTP_READ_BUF_SIZE: usize = 256 * 1024;

struct SftpFileWriter(libssh_rs::SftpFile);

impl Write for SftpFileWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0.write(buf)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.0.flush()
    }
}

impl Seek for SftpFileWriter {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.0.seek(pos)
    }
}

impl WriteAndSeek for SftpFileWriter {}

/// A seekable, in-memory read buffer wrapping file data fetched via SFTP.
struct BufferedSftpReader(Cursor<Vec<u8>>);

impl Read for BufferedSftpReader {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.0.read(buf)
    }
}

impl Seek for BufferedSftpReader {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.0.seek(pos)
    }
}

impl ReadAndSeek for BufferedSftpReader {}

impl Sftp for LibSshSftp {
    fn mkdir(&self, path: &Path, mode: i32) -> RemoteResult<()> {
        self.inner
            .create_dir(conv_path_to_str(path), mode as u32)
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::FileCreateDenied,
                    format!(
                        "Could not create directory '{path}': {err}",
                        path = path.display()
                    ),
                )
            })
    }

    fn open_read(&self, path: &Path) -> RemoteResult<ReadStream> {
        let data = buffered_sftp_read(&self.inner, path)?;
        Ok(ReadStream::from(
            Box::new(BufferedSftpReader(Cursor::new(data))) as Box<dyn ReadAndSeek>,
        ))
    }

    fn open_write(
        &self,
        path: &Path,
        flags: super::WriteMode,
        mode: i32,
    ) -> RemoteResult<WriteStream> {
        let flags = match flags {
            super::WriteMode::Append => {
                OpenFlags::WRITE_ONLY | OpenFlags::APPEND | OpenFlags::CREATE
            }
            super::WriteMode::Truncate => {
                OpenFlags::WRITE_ONLY | OpenFlags::CREATE | OpenFlags::TRUNCATE
            }
        };

        //panic!("Figa");

        self.inner
            .open(conv_path_to_str(path), flags, mode as u32)
            .map(|file| WriteStream::from(Box::new(SftpFileWriter(file)) as Box<dyn WriteAndSeek>))
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    format!(
                        "Could not open file at '{path}': {err}",
                        path = path.display()
                    ),
                )
            })
    }

    fn readdir<T>(&self, dirname: T) -> RemoteResult<Vec<remotefs::File>>
    where
        T: AsRef<Path>,
    {
        self.inner
            .read_dir(conv_path_to_str(dirname.as_ref()))
            .map(|files| {
                files
                    .into_iter()
                    .filter(|metadata| {
                        metadata.name() != Some(".") && metadata.name() != Some("..")
                    })
                    .map(|metadata| {
                        self.make_fsentry(MakePath::Directory(dirname.as_ref()), metadata)
                    })
                    .collect()
            })
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    format!("Could not read directory: {err}",),
                )
            })
    }

    fn realpath(&self, path: &Path) -> RemoteResult<PathBuf> {
        self.inner
            .canonicalize(conv_path_to_str(path))
            .map(PathBuf::from)
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    format!(
                        "Could not resolve real path for '{path}': {err}",
                        path = path.display()
                    ),
                )
            })
    }

    fn rename(&self, src: &Path, dest: &Path) -> RemoteResult<()> {
        self.inner
            .rename(conv_path_to_str(src), conv_path_to_str(dest))
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    format!("Could not rename file '{src}': {err}", src = src.display()),
                )
            })
    }

    fn rmdir(&self, path: &Path) -> RemoteResult<()> {
        self.inner
            .remove_dir(conv_path_to_str(path))
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::CouldNotRemoveFile,
                    format!(
                        "Could not remove directory '{path}': {err}",
                        path = path.display()
                    ),
                )
            })
    }

    fn setstat(&self, path: &Path, metadata: Metadata) -> RemoteResult<()> {
        self.inner
            .set_metadata(conv_path_to_str(path), &Self::set_attributes(metadata))
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    format!(
                        "Could not set file attributes for '{path}': {err}",
                        path = path.display()
                    ),
                )
            })
    }

    fn stat(&self, filename: &Path) -> RemoteResult<File> {
        self.inner
            .metadata(conv_path_to_str(filename))
            .map(|metadata| self.make_fsentry(MakePath::File(filename), metadata))
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::ProtocolError,
                    format!(
                        "Could not get file attributes for '{filename}': {err}",
                        filename = filename.display()
                    ),
                )
            })
    }

    fn symlink(&self, path: &Path, target: &Path) -> RemoteResult<()> {
        self.inner
            .symlink(conv_path_to_str(path), conv_path_to_str(target))
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::FileCreateDenied,
                    format!(
                        "Could not create symlink '{path}': {err}",
                        path = path.display()
                    ),
                )
            })
    }

    fn unlink(&self, path: &Path) -> RemoteResult<()> {
        self.inner
            .remove_file(conv_path_to_str(path))
            .map_err(|err| {
                RemoteError::new_ex(
                    RemoteErrorType::CouldNotRemoveFile,
                    format!(
                        "Could not remove file '{path}': {err}",
                        path = path.display()
                    ),
                )
            })
    }
}

fn conv_path_to_str(path: &Path) -> &str {
    path.to_str().unwrap_or_default()
}

/// Reads an entire remote file into memory using a large buffer to minimize
/// SFTP round-trips.
///
/// Each `sftp_read` call in libssh is a synchronous request-response cycle,
/// and file handles from the same session serialize through a mutex, so true
/// pipelining is not possible without the AIO FFI. Reading with a large
/// buffer (256 KiB) reduces the number of round-trips compared to the
/// default 64 KiB reads the caller would otherwise perform.
fn buffered_sftp_read(sftp: &libssh_rs::Sftp, path: &Path) -> RemoteResult<Vec<u8>> {
    let path_str = conv_path_to_str(path);

    let file_size = sftp
        .metadata(path_str)
        .map(|m| m.len().unwrap_or(0) as usize)
        .map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not stat '{path}': {err}", path = path.display()),
            )
        })?;

    if file_size == 0 {
        return Ok(Vec::new());
    }

    let mut file = sftp
        .open(path_str, OpenFlags::READ_ONLY, 0)
        .map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!(
                    "Could not open file at '{path}': {err}",
                    path = path.display()
                ),
            )
        })?;

    let mut data = Vec::with_capacity(file_size);
    let mut buf = [0_u8; SFTP_READ_BUF_SIZE];

    loop {
        let n = file.read(&mut buf).map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::IoError,
                format!("Failed to read file '{path}': {err}", path = path.display()),
            )
        })?;
        if n == 0 {
            break;
        }
        data.extend_from_slice(&buf[..n]);
    }

    Ok(data)
}

enum MakePath<'a> {
    Directory(&'a Path),
    File(&'a Path),
}

impl LibSshSftp {
    fn set_attributes(metadata: Metadata) -> libssh_rs::SetAttributes {
        let atime = metadata.accessed.unwrap_or(UNIX_EPOCH);
        let mtime = metadata.modified.unwrap_or(UNIX_EPOCH);

        let uid_gid = match (metadata.uid, metadata.gid) {
            (Some(uid), Some(gid)) => Some((uid, gid)),
            _ => None,
        };

        libssh_rs::SetAttributes {
            size: Some(metadata.size),
            uid_gid,
            permissions: metadata.mode.map(|m| m.into()),
            atime_mtime: Some((atime, mtime)),
        }
    }

    fn make_fsentry(&self, path: MakePath<'_>, metadata: libssh_rs::Metadata) -> File {
        let name = match metadata.name() {
            None => "/".to_string(),
            Some(name) => name.to_string(),
        };
        debug!("Found file {name}");

        let path = match path {
            MakePath::Directory(dir) => dir.join(&name),
            MakePath::File(file) => file.to_path_buf(),
        };
        debug!("Computed path for {name}: {path}", path = path.display());

        // parse metadata
        let uid = metadata.uid();
        let gid = metadata.gid();
        let mode = metadata.permissions().map(UnixPex::from);
        let size = metadata.len().unwrap_or(0);
        let accessed = metadata.accessed();
        let modified = metadata.modified();
        let symlink = match metadata.file_type() {
            Some(libssh_rs::FileType::Symlink) => {
                match self.inner.read_link(conv_path_to_str(&path)) {
                    Ok(target) => Some(PathBuf::from(target)),
                    Err(err) => {
                        error!(
                            "Failed to read link of {} (even it's supposed to be a symlink): {err}",
                            path.display(),
                        );
                        None
                    }
                }
            }
            _ => None,
        };
        let file_type = if symlink.is_some() {
            FileType::Symlink
        } else if matches!(metadata.file_type(), Some(libssh_rs::FileType::Directory)) {
            FileType::Directory
        } else {
            FileType::File
        };
        let entry_metadata = Metadata {
            accessed,
            created: None,
            file_type,
            gid,
            mode,
            modified,
            size,
            symlink,
            uid,
        };
        trace!("Metadata for {}: {:?}", path.display(), entry_metadata);
        File {
            path: path.to_path_buf(),
            metadata: entry_metadata,
        }
    }
}

fn authenticate(session: &mut libssh_rs::Session, opts: &SshOpts) -> RemoteResult<()> {
    // parse configuration
    let ssh_config = Config::try_from(opts)?;
    let username = ssh_config.username.clone();

    debug!("Authenticating to {}", opts.host);
    session
        .set_option(SshOption::User(Some(username)))
        .map_err(|e| {
            RemoteError::new_ex(
                RemoteErrorType::AuthenticationFailed,
                format!("Failed to set username: {e}"),
            )
        })?;

    debug!("Trying with userauth_none");
    match session.userauth_none(opts.username.as_deref()) {
        Ok(AuthStatus::Success) => {
            debug!("Authenticated with userauth_none");
            return Ok(());
        }
        Ok(status) => {
            debug!("userauth_none returned status: {status:?}");
        }
        Err(err) => {
            debug!("userauth_none failed: {err}");
        }
    }

    let auth_methods = session
        .userauth_list(opts.username.as_deref())
        .map_err(|e| RemoteError::new_ex(RemoteErrorType::AuthenticationFailed, e))?;
    debug!("Available authentication methods: {auth_methods:?}");

    if auth_methods.contains(AuthMethods::PUBLIC_KEY) {
        debug!("Trying public key authentication");
        // try with known key to config
        match session.userauth_public_key_auto(None, None) {
            Ok(AuthStatus::Success) => {
                debug!("Authenticated with public key");
                return Ok(());
            }
            Ok(status) => {
                debug!("userauth_public_key_auto returned status: {status:?}");
            }
            Err(err) => {
                debug!("userauth_public_key_auto failed: {err}");
            }
        }

        // try with storage
        match key_storage_auth(session, opts, &ssh_config) {
            Ok(()) => {
                debug!("Authenticated with public key from storage");
                return Ok(());
            }
            Err(err) => {
                debug!("Key storage authentication failed: {err}");
            }
        }
    }

    if auth_methods.contains(AuthMethods::PASSWORD) {
        debug!("Trying password authentication");

        // NOTE: you cannot pass password None. It causes SEGFAULT
        match session.userauth_password(None, Some(opts.password.as_deref().unwrap_or_default())) {
            Ok(AuthStatus::Success) => {
                debug!("Authenticated with password");
                return Ok(());
            }
            Ok(status) => {
                debug!("userauth_password returned status: {status:?}");
            }
            Err(err) => {
                debug!("userauth_password failed: {err}");
            }
        }
    }

    Err(RemoteError::new_ex(
        RemoteErrorType::AuthenticationFailed,
        "all authentication methods failed",
    ))
}

fn key_storage_auth(
    session: &mut libssh_rs::Session,
    opts: &SshOpts,
    ssh_config: &Config,
) -> RemoteResult<()> {
    let Some(key_storage) = &opts.key_storage else {
        return Err(RemoteError::new_ex(
            RemoteErrorType::AuthenticationFailed,
            "no key storage available",
        ));
    };

    let Some(priv_key_path) = key_storage
        .resolve(&ssh_config.host, &ssh_config.username)
        .or(key_storage.resolve(
            ssh_config.resolved_host.as_str(),
            ssh_config.username.as_str(),
        ))
    else {
        return Err(RemoteError::new_ex(
            RemoteErrorType::AuthenticationFailed,
            "no key found in storage",
        ));
    };

    let Ok(privkey) =
        SshKey::from_privkey_file(conv_path_to_str(&priv_key_path), opts.password.as_deref())
    else {
        return Err(RemoteError::new_ex(
            RemoteErrorType::AuthenticationFailed,
            format!(
                "could not load private key from file: {}",
                priv_key_path.display()
            ),
        ));
    };

    match session
        .userauth_publickey(opts.username.as_deref(), &privkey)
        .map_err(|e| RemoteError::new_ex(RemoteErrorType::AuthenticationFailed, e))
    {
        Ok(AuthStatus::Success) => Ok(()),
        Ok(status) => Err(RemoteError::new_ex(
            RemoteErrorType::AuthenticationFailed,
            format!("authentication failed: {status:?}"),
        )),
        Err(err) => Err(err),
    }
}

fn perform_shell_cmd<S: AsRef<str>>(
    session: &mut libssh_rs::Session,
    cmd: S,
) -> RemoteResult<String> {
    // Create channel
    trace!("Running command: {}", cmd.as_ref());
    let channel = match session.new_channel() {
        Ok(ch) => ch,
        Err(err) => {
            return Err(RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not open channel: {err}"),
            ));
        }
    };

    debug!("Opening channel session");
    channel.open_session().map_err(|err| {
        RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            format!("Could not open session: {err}"),
        )
    })?;

    // escape single quotes in command
    let cmd = cmd.as_ref().replace('\'', r#"'\''"#); // close, escape, and reopen

    debug!("Requesting command execution: {cmd}",);
    channel
        .request_exec(&format!("sh -c '{cmd}'"))
        .map_err(|err| {
            RemoteError::new_ex(
                RemoteErrorType::ProtocolError,
                format!("Could not execute command \"{cmd}\": {err}"),
            )
        })?;
    // send EOF
    debug!("Sending EOF");
    channel.send_eof().map_err(|err| {
        RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            format!("Could not send EOF: {err}"),
        )
    })?;

    // Read output
    let mut output: String = String::new();
    match channel.stdout().read_to_string(&mut output) {
        Ok(_) => {
            // Wait close
            let res = channel.get_exit_status();
            trace!("Command output (res: {res:?}): {output}");
            Ok(output)
        }
        Err(err) => Err(RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            format!("Could not read output: {err}"),
        )),
    }
}

/// Read filesize from scp header
fn parse_scp_header_filesize(header: &[u8]) -> RemoteResult<usize> {
    // Header format: C<mode> <size> <filename>\n
    let header_str = std::str::from_utf8(header).map_err(|e| {
        RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            format!("Could not parse header: {e}"),
        )
    })?;
    let parts: Vec<&str> = header_str.split_whitespace().collect();
    if parts.len() < 3 {
        return Err(RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            "Invalid SCP header: not enough parts",
        ));
    }
    if !parts[0].starts_with('C') {
        return Err(RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            "Invalid SCP header: missing 'C'",
        ));
    }
    let size = parts[1].parse::<usize>().map_err(|e| {
        RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            format!("Invalid file size: {e}"),
        )
    })?;

    Ok(size)
}

/// Wait for channel ACK
fn wait_for_ack(channel: &libssh_rs::Channel) -> RemoteResult<()> {
    debug!("Waiting for channel acknowledgment");
    // read ACK
    let mut ack = [0u8; 1024];
    let n = channel.stdout().read(&mut ack).map_err(|err| {
        RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            format!("Could not read from channel: {err}"),
        )
    })?;
    if n == 1 && ack[0] != 0 {
        Err(RemoteError::new_ex(
            RemoteErrorType::ProtocolError,
            format!("Unexpected ACK: {ack:?} (read {n} bytes)"),
        ))
    } else {
        Ok(())
    }
}