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
#![crate_name = "ssh2_config"]
#![crate_type = "lib"]
#![doc(html_playground_url = "https://play.rust-lang.org")]
use std::{io::BufRead, path::PathBuf, time::Duration};
mod host;
mod params;
mod parser;
pub use host::{Host, HostClause};
pub use params::HostParams;
pub use parser::{SshParserError, SshParserResult};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SshConfig {
hosts: Vec<Host>,
}
impl Default for SshConfig {
fn default() -> Self {
Self {
hosts: vec![Host::new(
vec![HostClause::new(String::from("*"), false)],
HostParams::default(),
)],
}
}
}
impl SshConfig {
pub fn query<S: AsRef<str>>(&self, host: S) -> HostParams {
let mut params = self.default_params();
for cfg_host in self.hosts.iter() {
if cfg_host.intersects(host.as_ref()) {
params.merge(&cfg_host.params);
}
}
params
}
pub fn default_params(&self) -> HostParams {
self.hosts.get(0).map(|x| x.params.clone()).unwrap()
}
pub fn parse(mut self, reader: &mut impl BufRead) -> SshParserResult<Self> {
parser::SshConfigParser::parse(&mut self, reader).map(|_| self)
}
}
#[cfg(test)]
mod test {
use super::*;
use pretty_assertions::assert_eq;
#[test]
fn should_init_ssh_config() {
let config = SshConfig::default();
assert_eq!(config.hosts.len(), 1);
assert_eq!(config.default_params(), HostParams::default());
assert_eq!(config.query("192.168.1.2"), HostParams::default());
}
#[test]
fn should_query_ssh_config() {
let mut config = SshConfig::default();
let mut params1 = HostParams::default();
params1.bind_address = Some(String::from("0.0.0.0"));
config.hosts.push(Host::new(
vec![HostClause::new(String::from("192.168.*.*"), false)],
params1.clone(),
));
let mut params2 = HostParams::default();
params2.bind_interface = Some(String::from("tun0"));
config.hosts.push(Host::new(
vec![HostClause::new(String::from("192.168.10.*"), false)],
params2.clone(),
));
let mut params3 = HostParams::default();
params3.host_name = Some(String::from("172.26.104.4"));
config.hosts.push(Host::new(
vec![
HostClause::new(String::from("172.26.*.*"), false),
HostClause::new(String::from("172.26.104.4"), true),
],
params3.clone(),
));
assert_eq!(config.query("192.168.1.32"), params1);
params1.merge(¶ms2);
assert_eq!(config.query("192.168.10.1"), params1);
assert_eq!(config.query("172.26.254.1"), params3);
assert_eq!(config.query("172.26.104.4"), config.default_params());
}
}