use std::borrow::Cow;
use std::ops::Range;
use crate::field::{Scan, field};
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::path::key_part;
use crate::strmatch::{Signature, Specificity};
use crate::tier::MatcherTier;
#[derive(Debug, Clone)]
pub struct Syslog {
signature: Signature,
no_pri: NoPri,
levels: Levels,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Levels {
#[default]
Numbers,
Names,
}
pub const FACILITIES: [&str; 24] = [
"kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp", "cron", "authpriv",
"ftp", "ntp", "audit", "alert", "clockd", "local0", "local1", "local2", "local3", "local4",
"local5", "local6", "local7",
];
pub const SEVERITIES: [&str; 8] = [
"emerg", "alert", "crit", "err", "warning", "notice", "info", "debug",
];
pub const SEVERITY_WORDS: [&str; 8] = [
"emergency",
"alert",
"critical",
"error",
"warning",
"notice",
"informational",
"debug",
];
#[must_use]
pub fn severity_word(code: u8) -> Option<&'static str> {
SEVERITY_WORDS.get(usize::from(code)).copied()
}
#[must_use]
pub fn facility_name(code: u8) -> Option<&'static str> {
FACILITIES.get(usize::from(code)).copied()
}
#[must_use]
pub fn severity_name(code: u8) -> Option<&'static str> {
SEVERITIES.get(usize::from(code)).copied()
}
#[must_use]
pub fn facility_code(name: &str) -> Option<u8> {
FACILITIES
.iter()
.position(|f| *f == name)
.and_then(|i| u8::try_from(i).ok())
}
#[must_use]
pub fn severity_code(name: &str) -> Option<u8> {
SEVERITIES
.iter()
.position(|s| *s == name)
.and_then(|i| u8::try_from(i).ok())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NoPri {
FileHeader,
AnyStamp,
}
impl Default for Syslog {
fn default() -> Self {
Self::new()
}
}
impl Syslog {
#[must_use]
pub fn new() -> Self {
let signature = Signature::builder()
.anchored(std::iter::once("<").chain(MONTHS))
.verify(|span, _| pri(span).is_some() || file_header(span).is_some())
.specificity(Specificity::Generic)
.build()
.unwrap_or_else(|_| unreachable!("invariant: the literals are non-empty"));
Self {
signature,
no_pri: NoPri::FileHeader,
levels: Levels::Numbers,
}
}
#[must_use]
pub fn pri_optional() -> Self {
let signature = Signature::builder()
.build()
.unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
Self {
signature,
no_pri: NoPri::AnyStamp,
levels: Levels::Numbers,
}
}
#[must_use]
pub const fn levels(mut self, levels: Levels) -> Self {
self.levels = levels;
self
}
}
const MONTHS: [&str; 12] = [
"Jan ", "Feb ", "Mar ", "Apr ", "May ", "Jun ", "Jul ", "Aug ", "Sep ", "Oct ", "Nov ", "Dec ",
];
fn digits(h: &[u8], i: usize, min: usize, max: usize) -> Option<(u16, usize)> {
let run = h.get(i..)?;
let n = run
.iter()
.take(max)
.take_while(|b| b.is_ascii_digit())
.count();
let value = run[..n]
.iter()
.fold(0_u16, |v, &d| v * 10 + u16::from(d - b'0'));
(n >= min).then_some((value, i + n))
}
fn file_stamp(h: &[u8]) -> Option<usize> {
let month = h.get(..4)?;
if !MONTHS.iter().any(|m| m.as_bytes() == month) {
return None;
}
let padded = usize::from(h.get(4) == Some(&b' '));
let (day, mut at) = digits(h, 4 + padded, 1, 2 - padded)?;
if let Some((_, year)) = digits(h, at + 1, 4, 4).filter(|_| h.get(at) == Some(&b' ')) {
at = year;
}
let (hour, colon) = digits(h, at + 1, 2, 2).filter(|_| h.get(at) == Some(&b' '))?;
let (minute, at) = digits(h, colon + 1, 2, 2).filter(|_| h.get(colon) == Some(&b':'))?;
let (second, end) = digits(h, at + 1, 2, 2).filter(|_| h.get(at) == Some(&b':'))?;
((1..=31).contains(&day) && hour < 24 && minute < 60 && second < 61).then_some(end)
}
fn file_header(h: &[u8]) -> Option<(usize, usize)> {
let stamp = file_stamp(h)?;
let name = h
.get(stamp + 1..)?
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'-' | b'_'))
.count();
let host = stamp + 1 + name;
if h[stamp] != b' ' || name == 0 || h.get(host) != Some(&b' ') {
return None;
}
(hint(&h[host + 1..]).is_some() || file_tag(&h[host + 1..])).then_some((stamp, host))
}
fn file_tag(rest: &[u8]) -> bool {
let name = rest
.iter()
.take_while(|b| {
b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'/' | b'-' | b'(' | b')' | b'@')
})
.count();
let mut end = name;
if rest.get(end) == Some(&b'[') {
let pid = rest[end + 1..]
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
.count();
if pid == 0 || rest.get(end + 1 + pid) != Some(&b']') {
return false;
}
end += pid + 2;
}
(1..=48).contains(&name)
&& rest.get(end) == Some(&b':')
&& rest.get(end + 1).is_none_or(|&b| b == b' ')
}
fn pri(span: &[u8]) -> Option<(u16, usize)> {
if span.first() != Some(&b'<') {
return None;
}
let n = span[1..]
.iter()
.take(4)
.take_while(|b| b.is_ascii_digit())
.count();
if !(1..=3).contains(&n) || span.get(1 + n) != Some(&b'>') {
return None;
}
let value = span[1..=n]
.iter()
.fold(0_u16, |v, &d| v * 10 + u16::from(d - b'0'));
(value <= 191).then_some((value, n + 2))
}
const fn text(bytes: &[u8]) -> FieldValue<'_> {
FieldValue::borrowed(bytes, Hint::Text)
}
fn number(n: u16) -> FieldValue<'static> {
FieldValue::owned(n.to_string().into_bytes(), Hint::Int)
}
fn token(h: &[u8], i: usize) -> Option<(&[u8], usize)> {
let rest = h.get(i..)?;
let n = rest.iter().position(|&b| b == b' ').unwrap_or(rest.len());
(n > 0).then(|| (&rest[..n], (i + n + 1).min(h.len())))
}
fn hint(message: &[u8]) -> Option<&'static str> {
if message.starts_with(b"CEF:") {
Some("cef")
} else if message.starts_with(b"LEEF:") {
Some("leef")
} else if message.first() == Some(&b'{') {
Some("ndjson")
} else {
None
}
}
fn sd_value(raw: &[u8]) -> FieldValue<'_> {
if !raw.contains(&b'\\') {
return text(raw);
}
let mut out = Vec::with_capacity(raw.len());
let mut i = 0;
while i < raw.len() {
if raw[i] == b'\\' && matches!(raw.get(i + 1), Some(b'"' | b'\\' | b']')) {
out.push(raw[i + 1]);
i += 2;
} else {
out.push(raw[i]);
i += 1;
}
}
FieldValue {
bytes: Cow::Owned(out),
hint: Hint::Text,
}
}
fn sd_params<'a>(h: &'a [u8], mut j: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
while h.get(j) == Some(&b' ') {
let eq = j + 1 + h[j + 1..].iter().position(|&b| b == b'=')?;
let name = std::str::from_utf8(&h[j + 1..eq]).ok()?;
if h.get(eq + 1) != Some(&b'"') {
return None;
}
let mut k = eq + 2;
while *h.get(k)? != b'"' {
k += if h[k] == b'\\' { 2 } else { 1 };
}
out.field(&key_part(Cow::Borrowed(name)), sd_value(&h[eq + 2..k]));
j = k + 1;
}
Some(j)
}
fn structured_data<'a>(h: &'a [u8], mut i: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
if h.get(i) == Some(&b'-') {
return Some(i + 1);
}
let mut seen = false;
while h.get(i) == Some(&b'[') {
seen = true;
let id_end = i + 1 + h[i + 1..].iter().position(|&b| b == b' ' || b == b']')?;
let id = std::str::from_utf8(&h[i + 1..id_end]).ok()?;
out.push_prefix("structured_data.");
out.push_prefix(&key_part(Cow::Borrowed(id)));
out.push_prefix(".");
let params = sd_params(h, id_end, out);
out.pop_prefix();
out.pop_prefix();
out.pop_prefix();
let j = params?;
if h.get(j) != Some(&b']') {
return None;
}
i = j + 1;
}
seen.then_some(i)
}
fn short_header<'a>(h: &'a [u8], start: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
let (stamp, at) = token(h, start)?;
let dated = stamp.first().is_some_and(u8::is_ascii_digit)
&& stamp
.iter()
.all(|b| b.is_ascii_digit() || matches!(b, b'T' | b'Z' | b':' | b'.' | b'+' | b'-'));
if !dated && stamp != b"-" {
return None;
}
let (host, mut at) = token(h, at)?;
if dated {
out.field("timestamp", text(stamp));
}
if host != b"-" {
out.field("hostname", text(host));
}
let named = |b: &u8| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.' | b'/');
if let Some((app, next)) = token(h, at)
&& next < h.len()
&& app.len() <= 48
&& app.iter().all(named)
{
out.field("appname", text(app));
at = next;
if let Some((pid, after_pid)) = token(h, at)
&& (pid == b"-" || pid.iter().all(u8::is_ascii_digit))
&& let Some(([b'-'], after_msgid)) = token(h, after_pid)
&& after_msgid < h.len()
{
if pid != b"-" {
out.field("procid", text(pid));
}
at = after_msgid;
}
}
Some(at)
}
fn rfc5424<'a>(h: &'a [u8], start: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
let version = text(&h[start - 2..start - 1]);
let mark = out.mark();
out.field("version", version.clone());
if let Some(end) = full_header(h, start, out) {
return Some(end);
}
out.rollback(mark);
out.field("version", version);
let end = short_header(h, start, out);
if end.is_none() {
out.rollback(mark);
}
end
}
fn full_header<'a>(h: &'a [u8], start: usize, out: &mut dyn FieldSink<'a>) -> Option<usize> {
let mut i = start;
for name in ["timestamp", "hostname", "appname", "procid", "msgid"] {
let (tok, next) = token(h, i)?;
if tok != b"-" {
out.field(name, text(tok));
}
i = next;
}
let end = structured_data(h, i, out)?;
Some(if h.get(end) == Some(&b' ') {
end + 1
} else {
end
})
}
fn scan(name: &str, h: &[u8], at: usize) -> Option<usize> {
match field(name).map(|f| (f.scan)(h, at)) {
Some(Scan::Match(end)) => Some(end),
_ => None,
}
}
fn with_year(h: &[u8], i: usize) -> Option<usize> {
let month = scan("MONTH", h, i)?;
let day = Some(skip_spaces(h, month))
.filter(|&at| at > month)
.and_then(|at| scan("MONTHDAY", h, at))?;
let year = scan("YEAR", h, day + 1).filter(|_| h.get(day) == Some(&b' '))?;
scan("TIME", h, year + 1).filter(|_| h.get(year) == Some(&b' '))
}
fn stamp_end(h: &[u8], i: usize) -> Option<usize> {
let end = scan("SYSLOGTIMESTAMP", h, i)
.or_else(|| scan("TIMESTAMP_ISO8601", h, i))
.or_else(|| with_year(h, i))?;
match h.get(end) {
Some(b' ') => Some(end),
Some(b':') if h.get(end + 1).is_none_or(|&b| b == b' ') => Some(end),
_ => None,
}
}
fn timestamp_end(h: &[u8], i: usize) -> Option<usize> {
stamp_end(h, i).or_else(|| {
let rest = h.get(i..)?;
let letters = rest.iter().take_while(|b| b.is_ascii_alphabetic()).count();
if letters < 3 {
return None;
}
let mut buf = [0_u8; 40];
let len = rest.len().min(buf.len());
buf[..len].copy_from_slice(&rest[..len]);
buf[0].make_ascii_uppercase();
buf[1..letters.min(len)].make_ascii_lowercase();
(buf[..len] != rest[..len])
.then(|| stamp_end(&buf[..len], 0))
.flatten()
.map(|end| i + end)
})
}
fn skip_spaces(h: &[u8], i: usize) -> usize {
i + h[i..].iter().take_while(|&&b| b == b' ').count()
}
fn stamp_could_start(rest: &[u8]) -> bool {
rest.first().is_some_and(u8::is_ascii_digit)
|| rest.get(..3).is_some_and(|start| {
MONTHS
.iter()
.any(|month| month.as_bytes()[..3].eq_ignore_ascii_case(start))
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Stamp {
IfThere,
Needed,
}
fn tag(h: &[u8], i: usize) -> Option<(&[u8], Option<&[u8]>, usize)> {
let len = h
.get(i..)?
.iter()
.take_while(|&&b| b.is_ascii_graphic() && !matches!(b, b'[' | b':' | b'{' | b'"'))
.count();
if len == 0 {
return None;
}
let mut j = i + len;
let mut procid = None;
if h.get(j) == Some(&b'[')
&& let Some(close) = h[j..].iter().position(|&b| b == b']')
{
procid = Some(&h[j + 1..j + close]);
j += close + 1;
}
(h.get(j) == Some(&b':') && h.get(j + 1).is_none_or(|&b| b == b' '))
.then(|| (&h[i..i + len], procid, (j + 2).min(h.len())))
}
fn after_host<'a>(h: &'a [u8], i: usize, out: &mut dyn FieldSink<'a>) -> usize {
if h.get(i) == Some(&b':') && h.get(i + 1).is_none_or(|&b| b == b' ') {
return (i + 2).min(h.len());
}
let Some((name, procid, message)) = tag(h, i) else {
return i;
};
out.field("appname", text(name));
if let Some(p) = procid {
out.field("procid", text(p));
}
message
}
fn rfc3164<'a>(
h: &'a [u8],
start: usize,
stamp: Stamp,
out: &mut dyn FieldSink<'a>,
) -> Option<usize> {
let start = skip_spaces(h, start);
let seq = h[start..].iter().take_while(|b| b.is_ascii_digit()).count();
let numbered = seq > 0 && h.get(start + seq..start + seq + 2) == Some(b": ");
let mut i = if numbered {
skip_spaces(h, start + seq + 2)
} else {
start
};
if matches!(h.get(i), Some(b'*' | b'.')) && h.get(i + 1).is_some_and(u8::is_ascii_alphabetic) {
i += 1;
}
if stamp == Stamp::Needed && !stamp_could_start(&h[i.min(h.len())..]) {
return None;
}
let end = timestamp_end(h, i);
if stamp == Stamp::Needed && end.is_none() {
return None;
}
if numbered {
out.field("sequence", text(&h[start..start + seq]));
}
if let Some(end) = end {
out.field("timestamp", text(&h[i..end]));
i = skip_spaces(h, end + usize::from(h.get(end) == Some(&b':')));
}
if let Some((tok, next)) = token(h, i)
&& !tok.ends_with(b":")
&& !tok.starts_with(b"<")
&& !tok.iter().any(|b| matches!(b, b'[' | b'|' | b','))
&& h.get(next..).is_some_and(|rest| !rest.is_empty())
{
out.field("hostname", text(tok));
i = skip_spaces(h, next);
}
Some(after_host(h, i, out))
}
impl Parser for Syslog {
fn name(&self) -> &'static str {
match self.no_pri {
NoPri::FileHeader => "syslog",
NoPri::AnyStamp => "syslog_nopri",
}
}
fn tier(&self) -> MatcherTier {
MatcherTier::Field
}
fn signature(&self) -> &Signature {
&self.signature
}
fn escape_value(
&self,
input: &[u8],
_field: usize,
at: Range<usize>,
value: &[u8],
out: &mut Vec<u8>,
) -> Option<Range<usize>> {
let param = input.is_empty()
|| (at
.start
.checked_sub(2)
.and_then(|open| input.get(open..at.start))
== Some(b"=\"")
&& input.get(at.end) == Some(&b'"'));
for &b in value {
if param && matches!(b, b'"' | b'\\' | b']') {
out.push(b'\\');
}
out.push(b);
}
Some(at)
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let body = if let Some((value, at)) = pri(input) {
out.field("pri", number(value));
match self.levels {
Levels::Numbers => {
out.field("facility", number(value / 8));
out.field("severity", number(value % 8));
}
Levels::Names => {
let facility = u8::try_from(value / 8).ok().and_then(facility_name);
let severity = u8::try_from(value % 8).ok().and_then(severity_name);
if let Some(name) = facility {
out.field(
"facility",
FieldValue::borrowed(name.as_bytes(), Hint::Text),
);
}
if let Some(name) = severity {
out.field(
"severity",
FieldValue::borrowed(name.as_bytes(), Hint::Text),
);
}
}
}
let versioned = (input.get(at..at + 2) == Some(b"1 "))
.then(|| rfc5424(input, at + 2, out))
.flatten();
versioned
.or_else(|| rfc3164(input, at, Stamp::IfThere, out))
.unwrap_or(at)
} else if self.no_pri == NoPri::AnyStamp {
let Some(body) = rfc3164(input, 0, Stamp::Needed, out) else {
return Ok(Parsed::NoMatch);
};
body
} else if let Some((stamp, host)) = file_header(input) {
out.field("timestamp", text(&input[..stamp]));
out.field("hostname", text(&input[stamp + 1..host]));
after_host(input, host + 1, out)
} else {
return Ok(Parsed::NoMatch);
};
let mut body = skip_spaces(input, body.min(input.len()));
if input[body..].starts_with(b"\xEF\xBB\xBF") {
body += 3;
}
let trail = input[body..]
.iter()
.rev()
.take_while(|&&b| matches!(b, b'\n' | b'\r' | b'\0'))
.count();
let end = input.len() - trail;
let message = &input[body.min(end)..end];
out.body_field("message", text(message));
Ok(Parsed::Body {
span: body.min(end)..end,
hint: hint(message),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse::Fields;
fn parse(line: &str) -> (Result<Parsed, ParseError>, Vec<(String, String)>) {
let mut out = Fields::new();
let p = Syslog::new().parse(line.as_bytes(), &mut out);
let fields = out
.as_slice()
.iter()
.map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
.collect();
(p, fields)
}
fn get<'f>(fields: &'f [(String, String)], name: &str) -> Option<&'f str> {
fields
.iter()
.find(|(n, _)| n == name)
.map(|(_, v)| v.as_str())
}
#[test]
fn a_dotted_sd_id_and_param_are_written_quoted_and_read_back_whole() {
let line =
r#"<165>1 2026-11-26T11:22:33.003Z host app - ID47 [ex.id@1 k.v="x" plain="y"] msg"#;
for (name, value) in [
(r#"structured_data["ex.id@1"]["k.v"]"#, "x"),
(r#"structured_data["ex.id@1"].plain"#, "y"),
] {
let mut out = Fields::new();
Syslog::new().parse(line.as_bytes(), &mut out).unwrap();
let got = out
.get(name)
.map(|v| String::from_utf8_lossy(&v.bytes).into_owned());
assert_eq!(got.as_deref(), Some(value), "{name}");
#[cfg(feature = "record")]
{
use crate::record::Record;
let keys: Vec<_> = crate::path::keys(name).collect();
let at = (&out).find(&keys[..]).unwrap();
assert_eq!((&out).text(at).unwrap(), value, "{name}");
}
}
}
#[test]
fn levels_as_names_write_the_names_receivers_write() {
let cases = [
(
"<165>1 2026-11-30T10:00:00Z h a - - - m",
"local4",
"notice",
),
("<0>Nov 30 10:00:00 h a: m", "kern", "emerg"),
("<13>Nov 30 10:00:00 h a: m", "user", "notice"),
("<191>Nov 30 10:00:00 h a: m", "local7", "debug"),
("<36>m", "auth", "warning"),
];
for (line, facility, severity) in cases {
let mut out = Fields::new();
let p = Syslog::new()
.levels(Levels::Names)
.parse(line.as_bytes(), &mut out);
assert!(p.is_ok(), "{line}: {p:?}");
let fields: Vec<(String, String)> = out
.as_slice()
.iter()
.map(|(n, v)| (n.clone(), String::from_utf8_lossy(&v.bytes).into_owned()))
.collect();
assert_eq!(get(&fields, "facility"), Some(facility), "{line}");
assert_eq!(get(&fields, "severity"), Some(severity), "{line}");
assert_eq!(
get(&fields, "pri"),
Some(line[1..].split('>').next().unwrap_or("")),
"{line}"
);
}
for code in 0..=u8::MAX {
match facility_name(code) {
Some(name) => assert_eq!(facility_code(name), Some(code)),
None => assert!(code > 23),
}
match severity_name(code) {
Some(name) => assert_eq!(severity_code(name), Some(code)),
None => assert!(code > 7),
}
}
assert_eq!(severity_word(6), Some("informational"));
assert_eq!(severity_word(8), None);
for bad in ["", "LOCAL4", "local8", "warn", "Notice"] {
assert_eq!(facility_code(bad), None, "{bad}");
assert_eq!(severity_code(bad), None, "{bad}");
}
}
#[test]
fn rfc5424_with_structured_data() {
let line = r#"<165>1 2026-11-26T11:22:33.003Z mymachine.example.com evntslog - ID47 [exampleSDID@32473 iut="3" eventSource="App\"lication"][x@1 a="b"] An application event"#;
let (p, f) = parse(line);
let Ok(Parsed::Body { span, hint }) = p else {
panic!("{p:?}")
};
assert_eq!(&line[span], "An application event");
assert_eq!(hint, None);
assert_eq!(get(&f, "facility"), Some("20"));
assert_eq!(get(&f, "severity"), Some("5"));
assert_eq!(get(&f, "hostname"), Some("mymachine.example.com"));
assert_eq!(get(&f, "procid"), None, "a nil field writes nothing");
assert_eq!(get(&f, "msgid"), Some("ID47"));
assert_eq!(
get(&f, "structured_data.exampleSDID@32473.eventSource"),
Some("App\"lication")
);
assert_eq!(get(&f, "structured_data.x@1.a"), Some("b"));
}
fn written(record: &str, at: Range<usize>, value: &str) -> String {
let mut text = Vec::new();
let span = Syslog::new()
.escape_value(record.as_bytes(), 0, at, value.as_bytes(), &mut text)
.unwrap();
let text = String::from_utf8(text).unwrap();
[&record[..span.start], &text, &record[span.end..]].concat()
}
#[test]
fn an_sd_param_value_escapes_and_a_header_field_does_not() {
let line = r#"<165>1 - host app - - [x@1 a="b" c="d"] msg"#;
let sd = line.find("\"b\"").unwrap() + 1;
let host = line.find("host").unwrap();
let cases: &[(Range<usize>, &str, &str)] = &[
(sd..sd + 1, r#"q"b\s]"#, r#"[x@1 a="q\"b\\s\]" c="d"]"#),
(sd..sd + 1, "", r#"[x@1 a="" c="d"]"#),
(host..host + 4, r#"h"\]"#, r#"<165>1 - h"\] app"#),
];
for (at, value, want) in cases {
let after = written(line, at.clone(), value);
assert!(after.contains(want), "{after}");
}
let mut out = Vec::new();
Syslog::new().escape_value(b"", 0, 0..0, br#"a"b"#, &mut out);
assert_eq!(out, br#"a\"b"#);
}
proptest::proptest! {
#[test]
fn an_escaped_sd_param_reads_back(value in r#"[a-z "\\\]=\[]{0,10}"#) {
let line = r#"<165>1 - host app - - [x@1 a="1" b="v" c="2"] msg"#;
let sd = line.find("\"v\"").unwrap() + 1;
let after = written(line, sd..sd + 1, &value);
let (p, f) = parse(&after);
proptest::prop_assert!(p.is_ok());
proptest::prop_assert_eq!(get(&f, "structured_data.x@1.a"), Some("1"));
proptest::prop_assert_eq!(get(&f, "structured_data.x@1.b"), Some(value.as_str()));
proptest::prop_assert_eq!(get(&f, "structured_data.x@1.c"), Some("2"));
}
}
#[test]
fn bsd_syslog_with_tag_and_pid() {
let line = "<34>Oct 11 22:14:15 mymachine su[123]: 'su root' failed\n";
let (p, f) = parse(line);
let Ok(Parsed::Body { span, .. }) = p else {
panic!("{p:?}")
};
assert_eq!(&line[span], "'su root' failed");
assert_eq!(get(&f, "timestamp"), Some("Oct 11 22:14:15"));
assert_eq!(get(&f, "hostname"), Some("mymachine"));
assert_eq!(get(&f, "appname"), Some("su"));
assert_eq!(get(&f, "procid"), Some("123"));
}
#[test]
fn bsd_syslog_without_a_hostname_carries_a_cef_body() {
let line = "<13>Nov 6 08:01:02 CEF:0|v|p|1|id|n|5|src=1.2.3.4";
let (p, f) = parse(line);
let Ok(Parsed::Body { span, hint }) = p else {
panic!("{p:?}")
};
assert_eq!(&line[span], "CEF:0|v|p|1|id|n|5|src=1.2.3.4");
assert_eq!(hint, Some("cef"));
assert_eq!(get(&f, "hostname"), None);
assert_eq!(get(&f, "appname"), None);
}
#[test]
fn bsd_header_variants() {
type Row = (
&'static str,
Option<&'static str>,
Option<&'static str>,
Option<&'static str>,
Option<&'static str>,
&'static str,
);
let rows: [Row; 9] = [
(
"<34>Oct 11 22:14:15 : a message",
Some("Oct 11 22:14:15"),
None,
None,
None,
"a message",
),
(
"<34>OCT 11 22:14:15 : a message",
Some("OCT 11 22:14:15"),
None,
None,
None,
"a message",
),
(
"<34>october 11 22:14:15 host app: m",
Some("october 11 22:14:15"),
Some("host"),
Some("app"),
None,
"m",
),
(
"<54> 1970-01-01T00:01:31+00:00 host :",
Some("1970-01-01T00:01:31+00:00"),
Some("host"),
None,
None,
"",
),
(
"<34>2020-10-11T22:14:15.00Z mymachine app[323]: a message",
Some("2020-10-11T22:14:15.00Z"),
Some("mymachine"),
Some("app"),
Some("323"),
"a message",
),
(
r#"<134>Oct 30 16:05:54 opsaudit {"username": "admin"}"#,
Some("Oct 30 16:05:54"),
Some("opsaudit"),
None,
None,
r#"{"username": "admin"}"#,
),
(
"<131>Jun 8 11:54:08 master apache_error [Tue Jun 08 2021] [php7:emerg] rest",
Some("Jun 8 11:54:08"),
Some("master"),
None,
None,
"apache_error [Tue Jun 08 2021] [php7:emerg] rest",
),
(
"<34>Oct 11 22:14:15 mymachine: a message",
Some("Oct 11 22:14:15"),
None,
Some("mymachine"),
None,
"a message",
),
(
"<34>Oxt 11 22:14:15 host app: m",
None,
Some("Oxt"),
None,
None,
"11 22:14:15 host app: m",
),
];
for (line, timestamp, hostname, appname, procid, message) in rows {
let (p, f) = parse(line);
let Ok(Parsed::Body { span, .. }) = p else {
panic!("{line}: {p:?}")
};
assert_eq!(&line[span], message, "{line}");
assert_eq!(get(&f, "timestamp"), timestamp, "{line}");
assert_eq!(get(&f, "hostname"), hostname, "{line}");
assert_eq!(get(&f, "appname"), appname, "{line}");
assert_eq!(get(&f, "procid"), procid, "{line}");
}
}
#[test]
fn cisco_headers() {
let rows = [
(
"<189>81: *Mar 1 00:04:11.123: %SYS-5-CONFIG_I: Configured from console",
Some("81"),
"Mar 1 00:04:11.123",
None,
"%SYS-5-CONFIG_I",
"Configured from console",
),
(
"<187>Dec 28 2008 16:49:07 router1 %LINK-3-UPDOWN: Interface down",
None,
"Dec 28 2008 16:49:07",
Some("router1"),
"%LINK-3-UPDOWN",
"Interface down",
),
(
"<34>.Dec 28 16:49:07: host app: m",
None,
"Dec 28 16:49:07",
Some("host"),
"app",
"m",
),
];
for (line, sequence, timestamp, hostname, appname, message) in rows {
let (p, f) = parse(line);
let Ok(Parsed::Body { span, .. }) = p else {
panic!("{line}: {p:?}")
};
assert_eq!(&line[span], message, "{line}");
assert_eq!(get(&f, "sequence"), sequence, "{line}");
assert_eq!(get(&f, "timestamp"), Some(timestamp), "{line}");
assert_eq!(get(&f, "hostname"), hostname, "{line}");
assert_eq!(get(&f, "appname"), Some(appname), "{line}");
}
}
type NoPriRow = (
&'static str,
&'static str,
Option<&'static str>,
Option<&'static str>,
Option<&'static str>,
&'static str,
Option<&'static str>,
);
fn reads(parser: &Syslog, rows: &[NoPriRow]) {
for &(line, timestamp, hostname, appname, procid, message, hinted) in rows {
let mut out = Fields::new();
let p = parser.parse(line.as_bytes(), &mut out);
let Ok(Parsed::Body { span, hint }) = p else {
panic!("{line}: {p:?}")
};
let field = |name: &str| out.get(name).map(|v| &*v.bytes);
assert_eq!(&line[span], message, "{line}");
assert_eq!(hint, hinted, "{line}");
assert_eq!(field("timestamp"), Some(timestamp.as_bytes()), "{line}");
assert_eq!(field("hostname"), hostname.map(str::as_bytes), "{line}");
assert_eq!(field("appname"), appname.map(str::as_bytes), "{line}");
assert_eq!(field("procid"), procid.map(str::as_bytes), "{line}");
for absent in ["pri", "facility", "severity"] {
assert_eq!(field(absent), None, "{line}");
}
}
}
const FILE_LINES: &[NoPriRow] = &[
(
"Mar 15 08:00:01 web-01 sshd[1234]: Accepted publickey for deploy from 10.10.1.5",
"Mar 15 08:00:01",
Some("web-01"),
Some("sshd"),
Some("1234"),
"Accepted publickey for deploy from 10.10.1.5",
None,
),
(
"Nov 6 08:01:02 gw01 kernel: [BLOCK] IN=eth0 OUT= SRC=198.51.100.26",
"Nov 6 08:01:02",
Some("gw01"),
Some("kernel"),
None,
"[BLOCK] IN=eth0 OUT= SRC=198.51.100.26",
None,
),
(
"Jan 5 23:59:60 10.0.0.7 postfix/smtpd[77]: connect from mail.example.com",
"Jan 5 23:59:60",
Some("10.0.0.7"),
Some("postfix/smtpd"),
Some("77"),
"connect from mail.example.com",
None,
),
(
"Jan 15 2024 09:00:01 fw-01 sshd[1]: a year after the day",
"Jan 15 2024 09:00:01",
Some("fw-01"),
Some("sshd"),
Some("1"),
"a year after the day",
None,
),
(
"Jan 15 09:00:01 relay01 LEEF:1.0|Acme|Gate|7.3|Allow|src=203.0.113.10\tdst=10.0.0.50",
"Jan 15 09:00:01",
Some("relay01"),
None,
None,
"LEEF:1.0|Acme|Gate|7.3|Allow|src=203.0.113.10\tdst=10.0.0.50",
Some("leef"),
),
(
"Oct 11 22:14:15 app01 {\"a\":1}",
"Oct 11 22:14:15",
Some("app01"),
None,
None,
"{\"a\":1}",
Some("ndjson"),
),
(
"Oct 11 22:14:15 app01 cron: ",
"Oct 11 22:14:15",
Some("app01"),
Some("cron"),
None,
"",
None,
),
];
#[test]
fn a_file_header_with_no_pri_is_read() {
reads(&Syslog::new(), FILE_LINES);
for row in FILE_LINES {
let fires = Syslog::new().signature().may_match(row.0.as_bytes());
assert!(fires, "{}", row.0);
}
}
#[test]
fn syslog_takes_no_other_line_that_lacks_a_pri() {
for line in [
"2026-11-28T09:30:00+11:00 web-01 sshd[1234]: Accepted publickey",
"2026-11-28T09:30:00Z ERROR main: connection lost",
"2026-11-26T00:22:33.123456789Z stdout F a container line",
"Jan",
"Jan 15",
"Jan 15 09:00:01",
"Jan 15 09:00:01 ",
"Jan 15 09:00:01 \r\n",
"Jan 15 09:00:01 web-01",
"Jan 15 09:00:01 web-01 ",
"Jan 15 09:00:01: no host",
"Jan 15 09:00:01 INFO Starting service",
"Jan 15 09:00:01 GET /health HTTP/1.1",
"Jan 15 09:00:01 Disk full on /var",
"Jan 15 09:00:01 devname=\"HQ-01\" action=deny",
"Jan 15 09:00:01 {\"x\":1, \"y\":2}",
"Jan 15 09:00:01 [initandlisten] waiting for connections",
"Jan 15 09:00:01 sshd[1234]: no hostname",
"Jan 15 09:00:01 Disk error[read failed]: retrying",
"Jan 15 09:00:01 backup status=failed: retrying",
"Jan 15 09:00:01 fw-01 %GATE-6-302013: Built inbound TCP connection",
"Jan 15 09:00:01 web-01 sshd[]: an empty pid",
"Jan 15 09:00:01 web-01 sshd[12: an open bracket",
"Jan 15 2024 09:00:01 fw-01 devname=\"HQ-01\" type=\"traffic\"",
"Jan 15 2024 09:00:01 fw-02 : %GATE-6-302013: Built inbound TCP connection",
"Jan 15 09:00:01 1,2024/01/15 09:00:01,0072,TRAFFIC",
"January 15 09:00:01 web-01 sshd[1]: x",
"JAN 15 09:00:01 web-01 sshd[1]: x",
"jan 15 09:00:01 web-01 sshd[1]: x",
"Janet 15 09:00:01 web-01 sshd[1]: x",
"Jan 15 9:00 web-01 sshd[1]: x",
"Jan 15 9:00:01 web-01 sshd[1]: x",
"Jan 15 09:00 web-01 sshd[1]: x",
"Jan 15 09:00:01.123 web-01 sshd[1]: x",
"Jan 99 09:00:01 web-01 sshd[1]: x",
"Jan 0 09:00:01 web-01 sshd[1]: x",
"Jan 15 24:00:01 web-01 sshd[1]: x",
"Jan 15 09:60:01 web-01 sshd[1]: x",
"Jan 15 24 09:00:01 web-01 sshd[1]: x",
"Jan 5 09:00:01 web-01 sshd[1]: x",
" Jan 15 09:00:01 web-01 sshd[1]: x",
"Mon Jan 15 09:00:01 2024 web-01 x",
"May 4 10:30 meeting notes",
"March 15 notes",
] {
assert!(matches!(parse(line).0, Ok(Parsed::NoMatch)), "{line}");
let fires = Syslog::new().signature().may_match(line.as_bytes());
assert!(!fires, "{line}");
}
}
#[test]
fn a_level_where_the_hostname_goes_is_read_as_one() {
let (p, f) = parse("Jan 15 09:00:01 ERROR main: lost connection");
assert!(matches!(p, Ok(Parsed::Body { .. })));
assert_eq!(get(&f, "hostname"), Some("ERROR"));
assert_eq!(get(&f, "appname"), Some("main"));
}
#[test]
fn the_pri_optional_parser_reads_any_line_with_a_timestamp() {
let parser = Syslog::pri_optional();
assert_eq!(parser.name(), "syslog_nopri");
reads(&parser, FILE_LINES);
reads(
&parser,
&[
(
"2026-11-28T09:30:00.123456+11:00 web-01 sshd[1234]: Accepted publickey",
"2026-11-28T09:30:00.123456+11:00",
Some("web-01"),
Some("sshd"),
Some("1234"),
"Accepted publickey",
None,
),
(
"Jan 15 2024 09:00:01 fw-01 devname=\"HQ-01\" type=\"traffic\"",
"Jan 15 2024 09:00:01",
Some("fw-01"),
None,
None,
"devname=\"HQ-01\" type=\"traffic\"",
None,
),
(
"Jan 15 2024 09:00:01 fw-02 : %GATE-6-302013: Built inbound TCP connection",
"Jan 15 2024 09:00:01",
Some("fw-02"),
None,
None,
"%GATE-6-302013: Built inbound TCP connection",
None,
),
(
"Jan 15 2024 09:00:01: %GATE-6-302013: Built inbound TCP connection",
"Jan 15 2024 09:00:01",
None,
Some("%GATE-6-302013"),
None,
"Built inbound TCP connection",
None,
),
(
"*Mar 1 00:04:11.123: %SYS-5-CONFIG_I: Configured from console",
"Mar 1 00:04:11.123",
None,
Some("%SYS-5-CONFIG_I"),
None,
"Configured from console",
None,
),
(
"Jan 15 09:00:01 1,2024/01/15 09:00:01,0072,TRAFFIC,end",
"Jan 15 09:00:01",
None,
None,
None,
"1,2024/01/15 09:00:01,0072,TRAFFIC,end",
None,
),
(
"Jan 15 09:00:01 fw-03 1,2024/01/15 09:00:01,0072,TRAFFIC,end",
"Jan 15 09:00:01",
Some("fw-03"),
None,
None,
"1,2024/01/15 09:00:01,0072,TRAFFIC,end",
None,
),
(
"Jan 15 09:00:01 <local0.info> 10.1.2.3 CEF:0|Acme|Gate|1|100|n|5|src=10.0.0.1",
"Jan 15 09:00:01",
None,
None,
None,
"<local0.info> 10.1.2.3 CEF:0|Acme|Gate|1|100|n|5|src=10.0.0.1",
None,
),
],
);
reads(
&parser,
&[(
"OCT 11 22:14:15 gw01 su[123]: a month in capitals",
"OCT 11 22:14:15",
Some("gw01"),
Some("su"),
Some("123"),
"a month in capitals",
None,
)],
);
for line in [
"",
"no stamp here",
"ERROR main: lost",
"{\"a\":1}",
"<999>x",
"Ja",
"Janitor started the sweep",
"9 lives",
] {
let got = parser.parse(line.as_bytes(), &mut Fields::new());
assert!(matches!(got, Ok(Parsed::NoMatch)), "{line}");
}
}
#[test]
fn both_parsers_read_a_line_with_a_pri_alike() {
for line in [
"<34>Oct 11 22:14:15 mymachine su[123]: 'su root' failed",
"<165>1 2026-11-26T11:22:33.003Z host.example.com evntslog - ID47 - An event",
"<13>Nov 6 08:01:02 CEF:0|v|p|1|id|n|5|src=1.2.3.4",
"<189>81: *Mar 1 00:04:11.123: %SYS-5-CONFIG_I: Configured from console",
] {
let (mut plain, mut optional) = (Fields::new(), Fields::new());
let a = Syslog::new().parse(line.as_bytes(), &mut plain);
let b = Syslog::pri_optional().parse(line.as_bytes(), &mut optional);
assert_eq!(format!("{a:?}"), format!("{b:?}"), "{line}");
assert_eq!(plain.as_slice(), optional.as_slice(), "{line}");
}
}
#[test]
fn a_token_no_hostname_could_be_starts_the_message() {
let line = "<14>Jan 15 09:00:01 1,2024/01/15 09:00:01,0072,TRAFFIC,end";
let (p, f) = parse(line);
let Ok(Parsed::Body { span, .. }) = p else {
panic!("{p:?}")
};
assert_eq!(&line[span], "1,2024/01/15 09:00:01,0072,TRAFFIC,end");
assert_eq!(get(&f, "hostname"), None);
let line = "<14>Jan 15 09:00:01 <local0.info> 10.1.2.3 text";
let (_, f) = parse(line);
assert_eq!(get(&f, "hostname"), None);
}
#[test]
fn a_bad_pri_is_no_match() {
assert!(matches!(parse("<999>x").0, Ok(Parsed::NoMatch)));
assert!(matches!(parse("no pri").0, Ok(Parsed::NoMatch)));
assert!(!Syslog::new().signature().may_match(b"<x>"));
}
#[test]
fn a_short_versioned_header_still_parses() {
let cases = [
(
"<134>1 1647479503.348215340 edge01 flows src=10.0.2.170 dst=10.0.0.34 protocol=udp",
Some("1647479503.348215340"),
Some("edge01"),
Some("flows"),
"src=10.0.2.170 dst=10.0.0.34 protocol=udp",
),
(
r#"<5>1 2021-03-08T18:07:51Z vault01 {"format":"x","n":1}"#,
Some("2021-03-08T18:07:51Z"),
Some("vault01"),
None,
r#"{"format":"x","n":1}"#,
),
(
r#"<13>1 2026-11-28T01:02:03Z host app 1 id [x@1 a="unterminated"#,
Some("2026-11-28T01:02:03Z"),
Some("host"),
Some("app"),
r#"1 id [x@1 a="unterminated"#,
),
("<13>1 - host01 lone", None, Some("host01"), None, "lone"),
];
for (line, timestamp, hostname, appname, message) in cases {
let (p, f) = parse(line);
let Ok(Parsed::Body { span, .. }) = p else {
panic!("{line}: {p:?}")
};
assert_eq!(&line[span], message, "{line}");
assert_eq!(get(&f, "version"), Some("1"), "{line}");
assert!(get(&f, "pri").is_some(), "{line}");
assert_eq!(get(&f, "timestamp"), timestamp, "{line}");
assert_eq!(get(&f, "hostname"), hostname, "{line}");
assert_eq!(get(&f, "appname"), appname, "{line}");
assert_eq!(get(&f, "procid"), None, "{line}");
}
}
#[test]
fn five_header_fields_and_no_structured_data() {
let line = "<30>1 2026-11-28T08:00:01.000Z web01 sshd 1234 - accepted key for deploy";
let (p, f) = parse(line);
let Ok(Parsed::Body { span, .. }) = p else {
panic!("{p:?}")
};
assert_eq!(&line[span], "accepted key for deploy");
assert_eq!(get(&f, "appname"), Some("sshd"));
assert_eq!(get(&f, "procid"), Some("1234"));
let line = "<30>1 2026-11-28T08:00:01.000Z web01 cron - - job done";
let (p, f) = parse(line);
let Ok(Parsed::Body { span, .. }) = p else {
panic!("{p:?}")
};
assert_eq!(&line[span], "job done");
assert_eq!(get(&f, "appname"), Some("cron"));
assert_eq!(get(&f, "procid"), None);
}
#[test]
fn a_one_that_starts_no_header_is_read_as_bsd() {
let line = "<13>1 apples and pears";
let (p, f) = parse(line);
assert!(matches!(p, Ok(Parsed::Body { .. })), "{p:?}");
assert_eq!(get(&f, "version"), None);
assert_eq!(get(&f, "pri"), Some("13"));
}
#[test]
fn the_message_starts_at_its_first_byte_and_ends_before_framing() {
let cases = [
(
"<174>May 24 13:09:53 gw01 uvm[0]: {\"login\":\"admin\"}",
"{\"login\":\"admin\"}",
Some("ndjson"),
),
(
"<165>1 2026-11-30T10:00:00Z h a - - - \u{FEFF}CEF:0|v|p|1|1|n|5|",
"CEF:0|v|p|1|1|n|5|",
Some("cef"),
),
(
"<165>1 2026-11-30T10:00:00Z h a - - - \u{FEFF}plain",
"plain",
None,
),
("<13>Nov 30 10:00:00 h a: m\0", "m", None),
("<13>Nov 30 10:00:00 h a: m\r\n\0", "m", None),
(
"<13>Nov 30 10:00:00 h a: \u{FEFF}{\"a\":1}\0\n",
"{\"a\":1}",
Some("ndjson"),
),
];
for (line, message, want) in cases {
let (p, f) = parse(line);
let Ok(Parsed::Body { span, hint }) = p else {
panic!("{line:?}: {p:?}")
};
assert_eq!(&line[span], message, "{line:?}");
assert_eq!(hint, want, "{line:?}");
assert_eq!(get(&f, "message"), Some(message), "{line:?}");
}
let (_, f) = parse(r#"<174>May 24 13:09:53 gw01 uvm[0]: {"login":"admin"}"#);
assert_eq!(get(&f, "appname"), Some("uvm"));
}
#[test]
fn broken_structured_data_leaves_no_prefix_on_the_sink() {
let mut out = Fields::new();
let line = br#"<13>1 2026-11-28T01:02:03Z host app 1 id [x@1 a="unterminated"#;
let parsed = Syslog::new().parse(line, &mut out);
assert!(matches!(parsed, Ok(Parsed::Body { .. })));
out.field("after", text(b"1"));
let last = out.as_slice().last().map(|(n, _)| n.as_str());
assert_eq!(last, Some("after"));
assert!(
out.as_slice()
.iter()
.all(|(n, _)| !n.starts_with("structured_data."))
);
}
}