Skip to main content

asterust_junos/system/
syslog.rs

1//! `system { syslog { ... } }`.
2
3use crate::{active_children, arg_of, child_block, named_children, statement_words};
4use asterust::config::ConfigLine;
5
6/// A `<facility> <severity>` line selecting which messages go to a syslog destination.
7#[derive(Clone, Debug, PartialEq, Eq)]
8#[non_exhaustive]
9pub struct SyslogRule {
10    /// e.g. `"any"`, `"authorization"`, `"interactive-commands"`.
11    pub facility: String,
12    /// e.g. `"info"`, `"notice"`, `"any"`, `"none"`.
13    pub severity: String,
14}
15
16/// A `host <address>` destination.
17#[derive(Clone, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub struct SyslogHost {
20    /// Address, hostname, or `other-routing-engine`.
21    pub address: String,
22    pub rules: Vec<SyslogRule>,
23    pub port: Option<String>,
24    pub source_address: Option<String>,
25    pub routing_instance: Option<String>,
26    pub facility_override: Option<String>,
27    pub log_prefix: Option<String>,
28}
29
30/// A syslog `archive` statement. `archive-sites`, `start-time` and `transfer-interval` are not extracted.
31#[derive(Clone, Debug, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub struct SyslogArchive {
34    /// Maximum number of archived files.
35    pub files: Option<String>,
36    /// Maximum file size, e.g. `"1m"`.
37    pub size: Option<String>,
38    /// `Some(true)` for `world-readable`, `Some(false)` for `no-world-readable`.
39    pub world_readable: Option<bool>,
40}
41
42/// A `file <name>` or `user <name>` destination.
43#[derive(Clone, Debug, PartialEq, Eq)]
44#[non_exhaustive]
45pub struct SyslogTarget {
46    /// File name, or user name (`*` for all users).
47    pub name: String,
48    pub rules: Vec<SyslogRule>,
49    /// Only files have an archive.
50    pub archive: Option<SyslogArchive>,
51}
52
53/// The `system syslog` configuration.
54#[derive(Clone, Debug, PartialEq, Eq)]
55#[non_exhaustive]
56pub struct Syslog {
57    pub hosts: Vec<SyslogHost>,
58    pub files: Vec<SyslogTarget>,
59    pub users: Vec<SyslogTarget>,
60    pub console: Vec<SyslogRule>,
61    pub source_address: Option<String>,
62    /// e.g. `"year millisecond"`.
63    pub time_format: Option<String>,
64    /// The default archive settings that files inherit.
65    pub archive: Option<SyslogArchive>,
66}
67
68pub(super) fn parse_syslog(syslog: &ConfigLine) -> Syslog {
69    Syslog {
70        hosts: named_children(syslog, "host")
71            .map(|(address, host)| SyslogHost {
72                address: address.to_string(),
73                rules: syslog_rules(host),
74                port: arg_of(host, "port").map(str::to_string),
75                source_address: arg_of(host, "source-address").map(str::to_string),
76                routing_instance: arg_of(host, "routing-instance").map(str::to_string),
77                facility_override: arg_of(host, "facility-override").map(str::to_string),
78                log_prefix: arg_of(host, "log-prefix").map(str::to_string),
79            })
80            .collect(),
81        files: syslog_targets(syslog, "file"),
82        users: syslog_targets(syslog, "user"),
83        console: child_block(syslog, "console").map(syslog_rules).unwrap_or_default(),
84        source_address: arg_of(syslog, "source-address").map(str::to_string),
85        time_format: arg_of(syslog, "time-format").map(str::to_string),
86        archive: syslog_archive(syslog),
87    }
88}
89
90fn syslog_targets(syslog: &ConfigLine, keyword: &str) -> Vec<SyslogTarget> {
91    named_children(syslog, keyword)
92        .map(|(name, target)| SyslogTarget {
93            name: name.to_string(),
94            rules: syslog_rules(target),
95            archive: syslog_archive(target),
96        })
97        .collect()
98}
99
100/// An `archive` written as a block or on one line (`archive size 1m files 5 world-readable;`).
101fn syslog_archive(parent: &ConfigLine) -> Option<SyslogArchive> {
102    let mut words = statement_words(parent, "archive")?.into_iter();
103    let mut settings = SyslogArchive::default();
104    while let Some(word) = words.next() {
105        match word {
106            "files" => settings.files = words.next().map(str::to_string),
107            "size" => settings.size = words.next().map(str::to_string),
108            "world-readable" => settings.world_readable = Some(true),
109            "no-world-readable" => settings.world_readable = Some(false),
110            _ => {}
111        }
112    }
113    Some(settings)
114}
115
116/// Children written `<facility> <severity>`, which tells them apart from options such as `port 514`.
117fn syslog_rules(destination: &ConfigLine) -> Vec<SyslogRule> {
118    const SEVERITIES: [&str; 10] = [
119        "any",
120        "none",
121        "emergency",
122        "alert",
123        "critical",
124        "error",
125        "warning",
126        "notice",
127        "info",
128        "debug",
129    ];
130    active_children(destination)
131        .filter_map(|c| {
132            let (facility, severity) = c.text.split_once(' ')?;
133            SEVERITIES.contains(&severity).then(|| SyslogRule {
134                facility: facility.to_string(),
135                severity: severity.to_string(),
136            })
137        })
138        .collect()
139}
140
141#[cfg(test)]
142mod tests {
143    use crate::system::system;
144    use asterust::config::juniper;
145
146    const SYSLOG: &str = r#"
147system {
148    syslog {
149        user * {
150            any emergency;
151        }
152        host 192.0.2.5 {
153            any notice;
154            authorization info;
155            port 514;
156            source-address 192.0.2.1;
157            routing-instance mgmt_junos;
158            facility-override local3;
159            log-prefix pe1;
160        }
161        host other-routing-engine {
162            any critical;
163        }
164        file messages {
165            any notice;
166            authorization info;
167            explicit-priority;
168        }
169        file interactive-commands {
170            interactive-commands any;
171        }
172        inactive: file debug {
173            any debug;
174        }
175        console {
176            any critical;
177        }
178        source-address 192.0.2.1;
179        time-format year millisecond;
180    }
181}
182"#;
183
184    #[test]
185    fn extracts_syslog_hosts() {
186        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
187        let addresses: Vec<_> = syslog.hosts.iter().map(|h| h.address.as_str()).collect();
188        assert_eq!(addresses, ["192.0.2.5", "other-routing-engine"]);
189
190        let host = &syslog.hosts[0];
191        assert_eq!(host.rules.len(), 2);
192        assert_eq!(host.rules[1].facility, "authorization");
193        assert_eq!(host.rules[1].severity, "info");
194        assert_eq!(host.port.as_deref(), Some("514"));
195        assert_eq!(host.source_address.as_deref(), Some("192.0.2.1"));
196        assert_eq!(host.routing_instance.as_deref(), Some("mgmt_junos"));
197        assert_eq!(host.facility_override.as_deref(), Some("local3"));
198        assert_eq!(host.log_prefix.as_deref(), Some("pe1"));
199    }
200
201    #[test]
202    fn extracts_syslog_files_users_and_console() {
203        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
204
205        let files: Vec<_> = syslog.files.iter().map(|f| f.name.as_str()).collect();
206        assert_eq!(files, ["messages", "interactive-commands"]);
207        // `explicit-priority` is an option, not a facility/severity rule.
208        assert_eq!(syslog.files[0].rules.len(), 2);
209        assert_eq!(syslog.files[1].rules[0].facility, "interactive-commands");
210        assert_eq!(syslog.files[1].rules[0].severity, "any");
211
212        assert_eq!(syslog.users[0].name, "*");
213        assert_eq!(syslog.users[0].rules[0].severity, "emergency");
214        assert_eq!(syslog.console[0].facility, "any");
215        assert_eq!(syslog.console[0].severity, "critical");
216    }
217
218    #[test]
219    fn extracts_syslog_global_settings() {
220        let syslog = system(&juniper::parse_braces(SYSLOG)).unwrap().syslog.unwrap();
221        assert_eq!(syslog.source_address.as_deref(), Some("192.0.2.1"));
222        assert_eq!(syslog.time_format.as_deref(), Some("year millisecond"));
223    }
224
225    #[test]
226    fn extracts_syslog_archive_in_line_and_block_form() {
227        let syslog = system(&juniper::parse_braces(
228            r#"
229system {
230    syslog {
231        archive {
232            files 20;
233            size 5m;
234            world-readable;
235        }
236        file messages {
237            any notice;
238            archive size 100k files 10 no-world-readable;
239        }
240        file plain {
241            any info;
242        }
243    }
244}
245"#,
246        ))
247        .unwrap()
248        .syslog
249        .unwrap();
250
251        let default = syslog.archive.unwrap();
252        assert_eq!(default.files.as_deref(), Some("20"));
253        assert_eq!(default.size.as_deref(), Some("5m"));
254        assert_eq!(default.world_readable, Some(true));
255
256        let messages = syslog.files[0].archive.as_ref().unwrap();
257        assert_eq!(messages.files.as_deref(), Some("10"));
258        assert_eq!(messages.size.as_deref(), Some("100k"));
259        assert_eq!(messages.world_readable, Some(false));
260
261        assert_eq!(syslog.files[1].archive, None);
262    }
263
264    #[test]
265    fn no_syslog_is_none() {
266        assert!(system(&juniper::parse_braces("system {\n    host-name pe1;\n}\n"))
267            .unwrap()
268            .syslog
269            .is_none());
270    }
271}