summaryrefslogtreecommitdiffstats
path: root/src/ssh.rs
blob: 4acbe61c5244be19aebbd7521cb9f092fc858e85 (plain)
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
use directories::UserDirs;
use ssh2::KnownHostFileKind;

use crate::{Session, SessionSource};

impl SessionSource for ssh2::Session {
    type Error = ssh2::Error;

    type Iter = Vec<Session>;

    fn sessions(&self) -> Result<Self::Iter, Self::Error> {
        let mut known_hosts = self.known_hosts()?;

        let file = UserDirs::new()
            .ok_or_else(ssh2::Error::unknown)?
            .home_dir()
            .join(".ssh/known_hosts");

        known_hosts.read_file(&file, KnownHostFileKind::OpenSSH)?;

        let sessions = known_hosts
            .hosts()?
            .into_iter()
            .filter_map(|h| match h.name() {
                Some(name) => Some(name.to_owned().into()),
                None => {
                    tracing::warn!("Invalid host: No plain text host name exists");
                    None
                }
            })
            .collect();

        Ok(sessions)
    }
}