summaryrefslogtreecommitdiffstats
path: root/src/ssh.rs
blob: 29c6de3d3e90533bdc5c59288c3de0a77e53abe7 (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
36
37
38
39
40
41
42
43
44
45
use std::time::{SystemTime, UNIX_EPOCH};

use directories::UserDirs;
use ssh2::KnownHostFileKind;

use crate::{Session, SessionSource, State};

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

    type Iter = Vec<Session>;

    fn sessions(&self) -> Result<Self::Iter, Self::Error> {
        let timestamp = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("Current time is pre-epoch. (Time traveler?)");

        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(Session {
                    state: State::Discovered,
                    timestamp,
                    name: name.to_owned(),
                }),
                None => {
                    tracing::warn!("Invalid host: No plain text host name exists");
                    None
                }
            })
            .collect();

        Ok(sessions)
    }
}