Skip to main content

asterust_junos/
system.rs

1//! `system { ... }`.
2
3use crate::{
4    active_children, arg_of, args_of, child_block, first_word, has_leaf, list_values, named_children, split_name,
5    top_level, unquote,
6};
7use asterust::config::{Config, ConfigLine};
8
9/// A DNS server from `name-server`.
10#[derive(Clone, Debug, PartialEq, Eq)]
11#[non_exhaustive]
12pub struct NameServer {
13    pub address: String,
14    /// Set when the server is reached through a routing instance such as `mgmt_junos`.
15    pub routing_instance: Option<String>,
16}
17
18/// A `server` or `peer` entry under `ntp`.
19#[derive(Clone, Debug, PartialEq, Eq)]
20#[non_exhaustive]
21pub struct NtpHost {
22    /// Address or hostname.
23    pub address: String,
24    /// Authentication key number.
25    pub key: Option<String>,
26    pub prefer: bool,
27    pub version: Option<String>,
28    pub routing_instance: Option<String>,
29}
30
31/// An `authentication-key`. The key value is not extracted.
32#[derive(Clone, Debug, PartialEq, Eq)]
33#[non_exhaustive]
34pub struct NtpAuthenticationKey {
35    pub number: String,
36    /// `md5`, `sha1` or `sha256`.
37    pub key_type: Option<String>,
38}
39
40/// The `system ntp` configuration.
41#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub struct Ntp {
44    pub boot_server: Option<String>,
45    pub servers: Vec<NtpHost>,
46    pub peers: Vec<NtpHost>,
47    pub source_address: Option<String>,
48    pub trusted_keys: Vec<String>,
49    pub authentication_keys: Vec<NtpAuthenticationKey>,
50    pub broadcast_client: bool,
51}
52
53/// A `<facility> <severity>` line selecting which messages go to a syslog destination.
54#[derive(Clone, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub struct SyslogRule {
57    /// e.g. `"any"`, `"authorization"`, `"interactive-commands"`.
58    pub facility: String,
59    /// e.g. `"info"`, `"notice"`, `"any"`, `"none"`.
60    pub severity: String,
61}
62
63/// A `host <address>` destination.
64#[derive(Clone, Debug, PartialEq, Eq)]
65#[non_exhaustive]
66pub struct SyslogHost {
67    /// Address, hostname, or `other-routing-engine`.
68    pub address: String,
69    pub rules: Vec<SyslogRule>,
70    pub port: Option<String>,
71    pub source_address: Option<String>,
72    pub routing_instance: Option<String>,
73    pub facility_override: Option<String>,
74    pub log_prefix: Option<String>,
75}
76
77/// A `file <name>` or `user <name>` destination.
78#[derive(Clone, Debug, PartialEq, Eq)]
79#[non_exhaustive]
80pub struct SyslogTarget {
81    /// File name, or user name (`*` for all users).
82    pub name: String,
83    pub rules: Vec<SyslogRule>,
84}
85
86/// The `system syslog` configuration. Archive settings are not extracted.
87#[derive(Clone, Debug, PartialEq, Eq)]
88#[non_exhaustive]
89pub struct Syslog {
90    pub hosts: Vec<SyslogHost>,
91    pub files: Vec<SyslogTarget>,
92    pub users: Vec<SyslogTarget>,
93    pub console: Vec<SyslogRule>,
94    pub source_address: Option<String>,
95    /// e.g. `"year millisecond"`.
96    pub time_format: Option<String>,
97}
98
99/// The top-level `system` configuration.
100#[derive(Clone, Debug, PartialEq, Eq)]
101#[non_exhaustive]
102pub struct System {
103    pub host_name: Option<String>,
104    pub name_servers: Vec<NameServer>,
105    pub ntp: Option<Ntp>,
106    pub syslog: Option<Syslog>,
107}
108
109/// The top-level `system` block, or `None` if there is none.
110pub fn system(config: &Config) -> Option<System> {
111    let system = top_level(config, "system")?;
112    Some(System {
113        host_name: arg_of(system, "host-name").map(str::to_string),
114        name_servers: name_servers(system),
115        ntp: child_block(system, "ntp").map(parse_ntp),
116        syslog: child_block(system, "syslog").map(parse_syslog),
117    })
118}
119
120fn parse_syslog(syslog: &ConfigLine) -> Syslog {
121    Syslog {
122        hosts: named_children(syslog, "host")
123            .map(|(address, host)| SyslogHost {
124                address: address.to_string(),
125                rules: syslog_rules(host),
126                port: arg_of(host, "port").map(str::to_string),
127                source_address: arg_of(host, "source-address").map(str::to_string),
128                routing_instance: arg_of(host, "routing-instance").map(str::to_string),
129                facility_override: arg_of(host, "facility-override").map(str::to_string),
130                log_prefix: arg_of(host, "log-prefix").map(str::to_string),
131            })
132            .collect(),
133        files: syslog_targets(syslog, "file"),
134        users: syslog_targets(syslog, "user"),
135        console: child_block(syslog, "console").map(syslog_rules).unwrap_or_default(),
136        source_address: arg_of(syslog, "source-address").map(str::to_string),
137        time_format: arg_of(syslog, "time-format").map(str::to_string),
138    }
139}
140
141fn syslog_targets(syslog: &ConfigLine, keyword: &str) -> Vec<SyslogTarget> {
142    named_children(syslog, keyword)
143        .map(|(name, target)| SyslogTarget {
144            name: name.to_string(),
145            rules: syslog_rules(target),
146        })
147        .collect()
148}
149
150/// Children written `<facility> <severity>`, which tells them apart from options such as `port 514`.
151fn syslog_rules(destination: &ConfigLine) -> Vec<SyslogRule> {
152    const SEVERITIES: [&str; 10] = [
153        "any",
154        "none",
155        "emergency",
156        "alert",
157        "critical",
158        "error",
159        "warning",
160        "notice",
161        "info",
162        "debug",
163    ];
164    active_children(destination)
165        .filter_map(|c| {
166            let (facility, severity) = c.text.split_once(' ')?;
167            SEVERITIES.contains(&severity).then(|| SyslogRule {
168                facility: facility.to_string(),
169                severity: severity.to_string(),
170            })
171        })
172        .collect()
173}
174
175fn parse_ntp(ntp: &ConfigLine) -> Ntp {
176    let hosts = |keyword: &str| -> Vec<NtpHost> {
177        active_children(ntp)
178            .filter_map(|c| Some(ntp_host(c.arg(keyword)?, c)))
179            .collect()
180    };
181    Ntp {
182        boot_server: arg_of(ntp, "boot-server").map(str::to_string),
183        servers: hosts("server"),
184        peers: hosts("peer"),
185        source_address: arg_of(ntp, "source-address").and_then(first_word).map(str::to_string),
186        trusted_keys: args_of(ntp, "trusted-key").into_iter().flat_map(list_values).collect(),
187        authentication_keys: args_of(ntp, "authentication-key")
188            .into_iter()
189            .filter_map(ntp_authentication_key)
190            .collect(),
191        broadcast_client: has_leaf(ntp, "broadcast-client"),
192    }
193}
194
195/// A host written `<address> [key n] [prefer] [version n] [routing-instance x]`, with the options on the line
196/// or in a block.
197fn ntp_host(arg: &str, line: &ConfigLine) -> NtpHost {
198    let (address, options) = split_name(arg);
199    let mut words = options.split_whitespace();
200    let mut host = NtpHost {
201        address: address.to_string(),
202        key: arg_of(line, "key").map(str::to_string),
203        prefer: has_leaf(line, "prefer"),
204        version: arg_of(line, "version").map(str::to_string),
205        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
206    };
207    while let Some(word) = words.next() {
208        match word {
209            "prefer" => host.prefer = true,
210            "key" => host.key = words.next().map(str::to_string),
211            "version" => host.version = words.next().map(str::to_string),
212            "routing-instance" => host.routing_instance = words.next().map(str::to_string),
213            _ => {}
214        }
215    }
216    host
217}
218
219/// `<number> type <type> value <secret>`; the secret is dropped.
220fn ntp_authentication_key(arg: &str) -> Option<NtpAuthenticationKey> {
221    let mut words = arg.split_whitespace();
222    let number = words.next()?.to_string();
223    let key_type = words.skip_while(|w| *w != "type").nth(1).map(str::to_string);
224    Some(NtpAuthenticationKey { number, key_type })
225}
226
227/// Servers written as a `name-server { <address>; ... }` block, or one per `name-server <address>` line.
228fn name_servers(system: &ConfigLine) -> Vec<NameServer> {
229    let mut found = Vec::new();
230    for child in active_children(system) {
231        if child.text == "name-server" {
232            found.extend(active_children(child).map(|server| name_server(&server.text, server)));
233        } else if let Some(address) = child.arg("name-server") {
234            found.push(name_server(address, child));
235        }
236    }
237    found
238}
239
240fn name_server(address: &str, line: &ConfigLine) -> NameServer {
241    NameServer {
242        address: unquote(address).to_string(),
243        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use asterust::config::juniper;
251
252    // Not from documentation: written from the CLI Reference syntax pages. See the README "Sources".
253    #[test]
254    fn extracts_host_name() {
255        let system = system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n")).unwrap();
256        assert_eq!(system.host_name.as_deref(), Some("pe1"));
257    }
258
259    #[test]
260    fn host_name_is_optional() {
261        let system = system(&juniper::parse_braces("system {\n    domain-name example.net;\n}\n")).unwrap();
262        assert_eq!(system.host_name, None);
263    }
264
265    #[test]
266    fn skips_inactive_host_name() {
267        let system = system(&juniper::parse_braces("system {\n    inactive: host-name pe1;\n}\n")).unwrap();
268        assert_eq!(system.host_name, None);
269    }
270
271    #[test]
272    fn extracts_name_server_block() {
273        let system = system(&juniper::parse_braces(
274            "system {\n    name-server {\n        192.0.2.53;\n        2001:db8::53;\n    }\n}\n",
275        ))
276        .unwrap();
277        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
278        assert_eq!(addresses, ["192.0.2.53", "2001:db8::53"]);
279        assert_eq!(system.name_servers[0].routing_instance, None);
280    }
281
282    #[test]
283    fn name_server_in_management_instance() {
284        let system = system(&juniper::parse_braces(
285            "system {\n    name-server {\n        192.0.2.53 {\n            routing-instance mgmt_junos;\n        }\n    }\n}\n",
286        ))
287        .unwrap();
288        assert_eq!(system.name_servers[0].address, "192.0.2.53");
289        assert_eq!(system.name_servers[0].routing_instance.as_deref(), Some("mgmt_junos"));
290    }
291
292    #[test]
293    fn extracts_one_line_name_servers_and_skips_inactive() {
294        let system = system(&juniper::parse_braces(
295            "system {\n    name-server 192.0.2.53;\n    name-server 192.0.2.54;\n    inactive: name-server 192.0.2.55;\n}\n",
296        ))
297        .unwrap();
298        let addresses: Vec<_> = system.name_servers.iter().map(|s| s.address.as_str()).collect();
299        assert_eq!(addresses, ["192.0.2.53", "192.0.2.54"]);
300    }
301
302    const NTP: &str = r#"
303system {
304    ntp {
305        boot-server 192.0.2.10;
306        source-address 192.0.2.1;
307        authentication-key 1 type md5 value "$9$secret";
308        authentication-key 2 type sha256 value "$9$other";
309        trusted-key [ 1 2 ];
310        server 192.0.2.10 key 1 prefer version 4;
311        server 192.0.2.11;
312        server ntp.example.net {
313            key 2;
314            prefer;
315            version 3;
316            routing-instance mgmt_junos;
317        }
318        inactive: server 192.0.2.12;
319        peer 192.0.2.20 key 1;
320        broadcast-client;
321    }
322}
323"#;
324
325    #[test]
326    fn extracts_ntp_servers_in_line_and_block_form() {
327        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
328        let addresses: Vec<_> = ntp.servers.iter().map(|s| s.address.as_str()).collect();
329        assert_eq!(addresses, ["192.0.2.10", "192.0.2.11", "ntp.example.net"]);
330
331        let line = &ntp.servers[0];
332        assert_eq!(line.key.as_deref(), Some("1"));
333        assert!(line.prefer);
334        assert_eq!(line.version.as_deref(), Some("4"));
335
336        assert_eq!(ntp.servers[1].key, None);
337        assert!(!ntp.servers[1].prefer);
338
339        let block = &ntp.servers[2];
340        assert_eq!(block.key.as_deref(), Some("2"));
341        assert!(block.prefer);
342        assert_eq!(block.version.as_deref(), Some("3"));
343        assert_eq!(block.routing_instance.as_deref(), Some("mgmt_junos"));
344    }
345
346    #[test]
347    fn extracts_ntp_peers_keys_and_global_settings() {
348        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
349        assert_eq!(ntp.peers.len(), 1);
350        assert_eq!(ntp.peers[0].address, "192.0.2.20");
351        assert_eq!(ntp.peers[0].key.as_deref(), Some("1"));
352        assert_eq!(ntp.boot_server.as_deref(), Some("192.0.2.10"));
353        assert_eq!(ntp.source_address.as_deref(), Some("192.0.2.1"));
354        assert_eq!(ntp.trusted_keys, ["1", "2"]);
355        assert!(ntp.broadcast_client);
356    }
357
358    #[test]
359    fn ntp_authentication_keys_omit_the_secret() {
360        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
361        assert_eq!(ntp.authentication_keys.len(), 2);
362        assert_eq!(ntp.authentication_keys[0].number, "1");
363        assert_eq!(ntp.authentication_keys[0].key_type.as_deref(), Some("md5"));
364        assert_eq!(ntp.authentication_keys[1].key_type.as_deref(), Some("sha256"));
365    }
366
367    #[test]
368    fn no_ntp_is_none() {
369        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
370            .unwrap()
371            .ntp
372            .is_none());
373    }
374
375    const SYSLOG: &str = r#"
376system {
377    syslog {
378        user * {
379            any emergency;
380        }
381        host 192.0.2.5 {
382            any notice;
383            authorization info;
384            port 514;
385            source-address 192.0.2.1;
386            routing-instance mgmt_junos;
387            facility-override local3;
388            log-prefix pe1;
389        }
390        host other-routing-engine {
391            any critical;
392        }
393        file messages {
394            any notice;
395            authorization info;
396            explicit-priority;
397        }
398        file interactive-commands {
399            interactive-commands any;
400        }
401        inactive: file debug {
402            any debug;
403        }
404        console {
405            any critical;
406        }
407        source-address 192.0.2.1;
408        time-format year millisecond;
409    }
410}
411"#;
412
413    #[test]
414    fn extracts_syslog_hosts() {
415        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
416        let addresses: Vec<_> = syslog.hosts.iter().map(|h| h.address.as_str()).collect();
417        assert_eq!(addresses, ["192.0.2.5", "other-routing-engine"]);
418
419        let host = &syslog.hosts[0];
420        assert_eq!(host.rules.len(), 2);
421        assert_eq!(host.rules[1].facility, "authorization");
422        assert_eq!(host.rules[1].severity, "info");
423        assert_eq!(host.port.as_deref(), Some("514"));
424        assert_eq!(host.source_address.as_deref(), Some("192.0.2.1"));
425        assert_eq!(host.routing_instance.as_deref(), Some("mgmt_junos"));
426        assert_eq!(host.facility_override.as_deref(), Some("local3"));
427        assert_eq!(host.log_prefix.as_deref(), Some("pe1"));
428    }
429
430    #[test]
431    fn extracts_syslog_files_users_and_console() {
432        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
433
434        let files: Vec<_> = syslog.files.iter().map(|f| f.name.as_str()).collect();
435        assert_eq!(files, ["messages", "interactive-commands"]);
436        // `explicit-priority` is an option, not a facility/severity rule.
437        assert_eq!(syslog.files[0].rules.len(), 2);
438        assert_eq!(syslog.files[1].rules[0].facility, "interactive-commands");
439        assert_eq!(syslog.files[1].rules[0].severity, "any");
440
441        assert_eq!(syslog.users[0].name, "*");
442        assert_eq!(syslog.users[0].rules[0].severity, "emergency");
443        assert_eq!(syslog.console[0].facility, "any");
444        assert_eq!(syslog.console[0].severity, "critical");
445    }
446
447    #[test]
448    fn extracts_syslog_global_settings() {
449        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
450        assert_eq!(syslog.source_address.as_deref(), Some("192.0.2.1"));
451        assert_eq!(syslog.time_format.as_deref(), Some("year millisecond"));
452    }
453
454    #[test]
455    fn no_syslog_is_none() {
456        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
457            .unwrap()
458            .syslog
459            .is_none());
460    }
461
462    #[test]
463    fn no_system_is_none() {
464        assert!(system(&juniper::parse_braces("interfaces {\n    lo0;\n}\n")).is_none());
465    }
466}