Skip to main content

asterust_junos/system/
ntp.rs

1//! `ntp`
2//! `system { ntp { ... } }`.
3//!
4//! # See also
5//!
6//! - [ntp](https://networkingdocs.hpe.com/documentation/us/en/software/junos/cli-reference/topics/ref/statement/ntp-edit-system.html)
7
8use crate::{active_children, arg_of, args_of, first_word, has_leaf, list_values, split_name};
9use asterust::config::ConfigLine;
10
11/// A `server` or `peer` entry under `ntp`.
12#[derive(Clone, Debug, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct NtpHost {
15    /// Address or hostname.
16    pub address: String,
17    /// Authentication key number.
18    pub key: Option<String>,
19    pub prefer: bool,
20    pub version: Option<String>,
21    pub routing_instance: Option<String>,
22}
23
24/// An `authentication-key`. The key value is not extracted.
25#[derive(Clone, Debug, PartialEq, Eq)]
26#[non_exhaustive]
27pub struct NtpAuthenticationKey {
28    pub number: String,
29    /// `md5`, `sha1` or `sha256`.
30    pub key_type: Option<String>,
31}
32
33/// The `system ntp` configuration.
34#[derive(Clone, Debug, PartialEq, Eq)]
35#[non_exhaustive]
36pub struct Ntp {
37    pub boot_server: Option<String>,
38    pub servers: Vec<NtpHost>,
39    pub peers: Vec<NtpHost>,
40    pub source_address: Option<String>,
41    pub trusted_keys: Vec<String>,
42    pub authentication_keys: Vec<NtpAuthenticationKey>,
43    pub broadcast_client: bool,
44}
45
46pub(super) fn parse_ntp(ntp: &ConfigLine) -> Ntp {
47    let hosts = |keyword: &str| -> Vec<NtpHost> {
48        active_children(ntp)
49            .filter_map(|c| Some(ntp_host(c.arg(keyword)?, c)))
50            .collect()
51    };
52    Ntp {
53        boot_server: arg_of(ntp, "boot-server").map(str::to_string),
54        servers: hosts("server"),
55        peers: hosts("peer"),
56        source_address: arg_of(ntp, "source-address").and_then(first_word).map(str::to_string),
57        trusted_keys: args_of(ntp, "trusted-key").into_iter().flat_map(list_values).collect(),
58        authentication_keys: args_of(ntp, "authentication-key")
59            .into_iter()
60            .filter_map(ntp_authentication_key)
61            .collect(),
62        broadcast_client: has_leaf(ntp, "broadcast-client"),
63    }
64}
65
66/// A host written `<address> [key n] [prefer] [version n] [routing-instance x]`, with the options
67/// on the line or in a block.
68fn ntp_host(arg: &str, line: &ConfigLine) -> NtpHost {
69    let (address, options) = split_name(arg);
70    let mut words = options.split_whitespace();
71    let mut host = NtpHost {
72        address: address.to_string(),
73        key: arg_of(line, "key").map(str::to_string),
74        prefer: has_leaf(line, "prefer"),
75        version: arg_of(line, "version").map(str::to_string),
76        routing_instance: arg_of(line, "routing-instance").map(str::to_string),
77    };
78    while let Some(word) = words.next() {
79        match word {
80            "prefer" => host.prefer = true,
81            "key" => host.key = words.next().map(str::to_string),
82            "version" => host.version = words.next().map(str::to_string),
83            "routing-instance" => host.routing_instance = words.next().map(str::to_string),
84            _ => {}
85        }
86    }
87    host
88}
89
90/// `<number> type <type> value <secret>`; the secret is dropped.
91fn ntp_authentication_key(arg: &str) -> Option<NtpAuthenticationKey> {
92    let mut words = arg.split_whitespace();
93    let number = words.next()?.to_string();
94    let key_type = words.skip_while(|w| *w != "type").nth(1).map(str::to_string);
95    Some(NtpAuthenticationKey { number, key_type })
96}
97
98#[cfg(test)]
99mod tests {
100    use crate::system::system;
101    use asterust::config::juniper;
102
103    const NTP: &str = r#"
104system {
105    ntp {
106        boot-server 192.0.2.10;
107        source-address 192.0.2.1;
108        authentication-key 1 type md5 value "$9$secret";
109        authentication-key 2 type sha256 value "$9$other";
110        trusted-key [ 1 2 ];
111        server 192.0.2.10 key 1 prefer version 4;
112        server 192.0.2.11;
113        server ntp.example.net {
114            key 2;
115            prefer;
116            version 3;
117            routing-instance mgmt_junos;
118        }
119        inactive: server 192.0.2.12;
120        peer 192.0.2.20 key 1;
121        broadcast-client;
122    }
123}
124"#;
125
126    #[test]
127    fn extracts_ntp_servers_in_line_and_block_form() {
128        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
129        let addresses: Vec<_> = ntp.servers.iter().map(|s| s.address.as_str()).collect();
130        assert_eq!(addresses, ["192.0.2.10", "192.0.2.11", "ntp.example.net"]);
131
132        let line = &ntp.servers[0];
133        assert_eq!(line.key.as_deref(), Some("1"));
134        assert!(line.prefer);
135        assert_eq!(line.version.as_deref(), Some("4"));
136
137        assert_eq!(ntp.servers[1].key, None);
138        assert!(!ntp.servers[1].prefer);
139
140        let block = &ntp.servers[2];
141        assert_eq!(block.key.as_deref(), Some("2"));
142        assert!(block.prefer);
143        assert_eq!(block.version.as_deref(), Some("3"));
144        assert_eq!(block.routing_instance.as_deref(), Some("mgmt_junos"));
145    }
146
147    #[test]
148    fn extracts_ntp_peers_keys_and_global_settings() {
149        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
150        assert_eq!(ntp.peers.len(), 1);
151        assert_eq!(ntp.peers[0].address, "192.0.2.20");
152        assert_eq!(ntp.peers[0].key.as_deref(), Some("1"));
153        assert_eq!(ntp.boot_server.as_deref(), Some("192.0.2.10"));
154        assert_eq!(ntp.source_address.as_deref(), Some("192.0.2.1"));
155        assert_eq!(ntp.trusted_keys, ["1", "2"]);
156        assert!(ntp.broadcast_client);
157    }
158
159    #[test]
160    fn ntp_authentication_keys_omit_the_secret() {
161        let ntp = system(&juniper::parse_braces(NTP)).unwrap().ntp.unwrap();
162        assert_eq!(ntp.authentication_keys.len(), 2);
163        assert_eq!(ntp.authentication_keys[0].number, "1");
164        assert_eq!(ntp.authentication_keys[0].key_type.as_deref(), Some("md5"));
165        assert_eq!(ntp.authentication_keys[1].key_type.as_deref(), Some("sha256"));
166    }
167
168    #[test]
169    fn no_ntp_is_none() {
170        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
171            .unwrap()
172            .ntp
173            .is_none());
174    }
175}