syslog_loose 0.23.0

A loose parser for syslog messages.
Documentation
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
use nom::{
    IResult, Parser,
    branch::alt,
    bytes::complete::{escaped, tag, take_till1, take_until, take_while1},
    character::complete::{anychar, space0},
    combinator::map,
    error,
    multi::{many1, separated_list0},
    sequence::{delimited, separated_pair, terminated},
};
use std::fmt;

#[derive(Clone, Debug, Eq)]
pub struct StructuredElement<S: AsRef<str> + Ord + Clone> {
    pub id: S,
    pub params: Vec<(S, S)>,
}

pub struct ParamsIter<'a, S: AsRef<str>> {
    pos: usize,
    params: &'a Vec<(S, S)>,
}

impl<S: AsRef<str> + Ord + Clone> StructuredElement<S> {
    /// Since we parse the message without any additional allocations, we can't parse out the
    /// escapes during parsing as that would require allocating an extra string to store the
    /// stripped version.
    /// So params returns an iterator that will allocate and return a string with the escapes
    /// stripped out.
    pub fn params(&self) -> ParamsIter<'_, S> {
        ParamsIter {
            pos: 0,
            params: &self.params,
        }
    }
}

impl<S: AsRef<str> + Ord + Clone> fmt::Display for StructuredElement<S> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "[{}", self.id.as_ref())?;

        for (name, value) in &self.params {
            write!(f, " {}=\"{}\"", name.as_ref(), value.as_ref())?;
        }

        write!(f, "]")
    }
}

impl<S: AsRef<str> + Ord + Clone> PartialEq for StructuredElement<S> {
    fn eq(&self, other: &Self) -> bool {
        if self.id.as_ref() != other.id.as_ref() {
            return false;
        }

        let mut params1 = self.params.clone();
        params1.sort();

        let mut params2 = other.params.clone();
        params2.sort();

        params1
            .iter()
            .zip(params2)
            .all(|((ref name1, ref value1), (ref name2, ref value2))| {
                name1.as_ref() == name2.as_ref() && value1.as_ref() == value2.as_ref()
            })
    }
}

impl From<StructuredElement<&str>> for StructuredElement<String> {
    fn from(element: StructuredElement<&str>) -> Self {
        StructuredElement {
            id: element.id.to_string(),
            params: element
                .params
                .iter()
                .map(|(name, value)| (name.to_string(), value.to_string()))
                .collect(),
        }
    }
}

impl<'a, S: AsRef<str> + Ord + Clone> Iterator for ParamsIter<'a, S> {
    type Item = (&'a S, String);

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.params.len() {
            None
        } else {
            let (key, value) = &self.params[self.pos];
            self.pos += 1;
            let mut trimmed = String::with_capacity(value.as_ref().len());
            let mut escaped = false;
            for c in value.as_ref().chars() {
                if c == '\\' && !escaped {
                    escaped = true;
                } else if c == 'n' && escaped {
                    escaped = false;
                    trimmed.push('\n');
                } else if c != '"' && c != ']' && c != '\\' && escaped {
                    // If the character following the escape isn't a \, " or ] we treat it like an normal unescaped character.
                    escaped = false;
                    trimmed.push('\\');
                    trimmed.push(c);
                } else {
                    escaped = false;
                    trimmed.push(c);
                }
            }
            Some((key, trimmed))
        }
    }
}

/// Parse the param value - a string delimited by '"' - '\' escapes \ and "
fn param_value(input: &str) -> IResult<&str, &str> {
    alt((
        // We need to handle an empty string separately since `escaped`
        // doesn't work unless it has some input.
        map(tag(r#""""#), |_| ""),
        delimited(
            tag("\""),
            escaped(take_while1(|c: char| c != '\\' && c != '"'), '\\', anychar),
            tag("\""),
        ),
    ))
    .parse(input)
}

/// Parse a param name="value"
fn param(input: &str) -> IResult<&str, (&str, &str)> {
    separated_pair(
        take_till1(|c: char| c == ']' || c == '='),
        terminated(tag("="), space0),
        param_value,
    )
    .parse(input)
}

struct StructuredDatumParser {
    allow_failure: bool,
    allow_empty: bool,
}

impl StructuredDatumParser {
    /// Parse a single structured data record.
    /// [exampleSDID@32473 iut="3" eventSource="Application" eventID="1011"]
    fn structured_datum_strict<'a>(
        &self,
        input: &'a str,
    ) -> IResult<&'a str, Option<StructuredElement<&'a str>>> {
        delimited(
            tag("["),
            map(
                (
                    take_till1(|c: char| c.is_whitespace() || c == ']' || c == '='),
                    space0,
                    separated_list0(tag(" "), param),
                ),
                |(id, _, params)| Some(StructuredElement { id, params }),
            ),
            tag("]"),
        )
        .parse(input)
    }

    /// Parse a single structured data record allowing anything between brackets.
    fn structured_datum_permissive<'a>(
        &self,
        input: &'a str,
    ) -> IResult<&'a str, Option<StructuredElement<&'a str>>> {
        alt((
            |input| self.structured_datum_strict(input),
            // If the element fails to parse, just parse it and return None.
            delimited(tag("["), map(take_until("]"), |_| None), tag("]")),
        ))
        .parse(input)
    }

    pub(crate) fn parse<'a>(
        &mut self,
        input: &'a str,
    ) -> IResult<&'a str, Option<StructuredElement<&'a str>>> {
        let (remaining, result) = if self.allow_failure {
            self.structured_datum_permissive(input)
        } else {
            self.structured_datum_strict(input)
        }?;

        // 3164 often has items that look like structured data, but isn't.
        // Generally, stuff between square brackets that doesn't follow a
        // [id key=value] pattern. This would get parsed as an empty StructuredElement
        // with no parameters. In this case, we want to return an error instead
        // so that it is treated as invalid structured data and incorporated into the
        // message.
        // In 5424 structured data without any parameters is perfectly valid, so
        // needs it returned as a success.
        if !self.allow_empty
            && result
                .as_ref()
                .is_some_and(|element| element.params.is_empty())
        {
            Err(nom::Err::Error(error::Error::new(
                input,
                error::ErrorKind::Fail,
            )))
        } else {
            Ok((remaining, result))
        }
    }
}

/// Parse multiple structured data elements.
fn parse_structured_data(
    allow_failure: bool,
    allow_empty: bool,
    input: &str,
) -> IResult<&str, Vec<StructuredElement<&str>>> {
    alt((
        map(tag("-"), |_| vec![]),
        map(
            many1(|input| {
                StructuredDatumParser {
                    allow_failure,
                    allow_empty,
                }
                .parse(input)
            }),
            |items| items.iter().filter_map(|item| item.clone()).collect(),
        ),
    ))
    .parse(input)
}

/// Parse multiple structured data elements.
pub(crate) fn structured_data(input: &str) -> IResult<&str, Vec<StructuredElement<&str>>> {
    parse_structured_data(true, true, input)
}

/// Parse multiple structured data elements.
pub(crate) fn structured_data_optional(input: &str) -> IResult<&str, Vec<StructuredElement<&str>>> {
    parse_structured_data(false, false, input)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_param_value() {
        assert_eq!(
            param_value("\"Some \\\"lovely\\\" string\"").unwrap(),
            ("", "Some \\\"lovely\\\" string")
        );
    }

    #[test]
    fn parse_empty_param_value() {
        assert_eq!(param_value(r#""""#).unwrap(), ("", ""));
    }

    #[test]
    fn parse_structured_data() {
        assert_eq!(
            StructuredDatumParser {
                allow_empty: false,
                allow_failure: true,
            }
            .parse("[exampleSDID@32473 iut=\"3\" eventSource=\"Application\" eventID=\"1011\"]")
            .unwrap(),
            (
                "",
                Some(StructuredElement {
                    id: "exampleSDID@32473",
                    params: vec![
                        ("iut", "3"),
                        ("eventSource", "Application"),
                        ("eventID", "1011"),
                    ]
                })
            )
        );
    }

    #[test]
    fn parse_structured_data_no_values() {
        assert_eq!(
            StructuredDatumParser {
                allow_failure: false,
                allow_empty: true,
            }
            .parse("[exampleSDID@32473]")
            .unwrap(),
            (
                "",
                Some(StructuredElement {
                    id: "exampleSDID@32473",
                    params: vec![]
                })
            )
        );
    }

    #[test]
    fn parse_structured_data_with_space() {
        assert_eq!(
            StructuredDatumParser {
                allow_empty: false,
                allow_failure: true,
            }
            .parse("[exampleSDID@32473 iut=\"3\" eventSource= \"Application\" eventID=\"1011\"]")
            .unwrap(),
            (
                "",
                Some(StructuredElement {
                    id: "exampleSDID@32473",
                    params: vec![
                        ("iut", "3"),
                        ("eventSource", "Application"),
                        ("eventID", "1011"),
                    ]
                })
            )
        );
    }

    #[test]
    fn parse_invalid_structured_data() {
        assert_eq!(
            StructuredDatumParser {
                allow_empty: true,
                allow_failure: true,
            }
            .parse("[exampleSDID@32473 iut=]"),
            Ok(("", None))
        );
    }

    #[test]
    fn parse_multiple_structured_data() {
        assert_eq!(
            structured_data(
                "[exampleSDID@32473 iut=\"3\" eventSource= \"Application\" eventID=\"1011\"][sproink onk=\"ponk\" zork=\"shnork\"]"
            ) .unwrap(),
            (
                "",
                vec![
                    StructuredElement {
                        id: "exampleSDID@32473",
                        params: vec![
                            ("iut", "3"),
                            ("eventSource", "Application"),
                            ("eventID", "1011"),
                        ]
                    },
                    StructuredElement {
                        id: "sproink",
                        params: vec![
                            ("onk", "ponk"),
                            ("zork", "shnork"),
                        ]
                    }
                ]
            )
        );
    }

    #[test]
    fn parse_structured_data_dont_keep_empty_elements() {
        assert!(structured_data_optional("[abc] message").is_err())
    }

    #[test]
    fn parse_structured_data_ignores_invalid_elements() {
        assert_eq!(
            structured_data("[abc][id aa=]").unwrap(),
            (
                "",
                vec![StructuredElement {
                    id: "abc",
                    params: vec![],
                },]
            )
        )
    }

    #[test]
    fn parse_multiple_structured_data_first_item_id_only() {
        assert_eq!(
            structured_data("[abc][id aa=\"bb\"]").unwrap(),
            (
                "",
                vec![
                    StructuredElement {
                        id: "abc",
                        params: vec![],
                    },
                    StructuredElement {
                        id: "id",
                        params: vec![("aa", "bb")],
                    },
                ]
            )
        )
    }

    #[test]
    fn params_remove_escapes() {
        let data = structured_data(
            r#"[id aa="hullo \"there\"" bb="let's \\\\do this\\\\" cc="hello [bye\]" dd="hello\nbye" ee="not \esc\aped"]"#,
        )
        .unwrap();
        let params = data.1[0].params().collect::<Vec<_>>();

        assert_eq!(
            params,
            vec![
                (&"aa", r#"hullo "there""#.to_string()),
                (&"bb", r#"let's \\do this\\"#.to_string(),),
                (&"cc", r#"hello [bye]"#.to_string(),),
                (
                    &"dd",
                    r#"hello
bye"#
                        .to_string(),
                ),
                (&"ee", r#"not \esc\aped"#.to_string())
            ]
        );
    }

    #[test]
    fn sd_param_escapes() {
        let (_, value) = param_value(r#""Here are some escaped characters -> \"\\\]""#).unwrap();
        assert_eq!(r#"Here are some escaped characters -> \"\\\]"#, value);

        let (_, value) = param_value(r#""These should not be escaped -> \n\m\o""#).unwrap();
        assert_eq!(r#"These should not be escaped -> \n\m\o"#, value);
    }

    #[test]
    fn parse_empty_structured_data() {
        assert_eq!(
            StructuredDatumParser {
                allow_failure: true,
                allow_empty: true,
            }
            .parse("[WAN_LOCAL-default-D]"),
            Ok((
                "",
                Some(StructuredElement {
                    id: "WAN_LOCAL-default-D",
                    params: vec![]
                })
            ))
        );

        assert!(
            StructuredDatumParser {
                allow_failure: true,
                allow_empty: false,
            }
            .parse("[WAN_LOCAL-default-D]")
            .is_err()
        );
    }
}