use std::collections::HashMap;
use thiserror::Error;
use crate::field::FIELDS;
use crate::parse::Hint;
#[cfg(feature = "parse-backtracking")]
mod backtrack;
mod date;
mod ends;
mod parser;
mod plan;
mod scratch;
mod shadow;
pub mod spec;
#[rustfmt::skip]
#[allow(clippy::all, clippy::pedantic, clippy::nursery, reason = "generated by grippo-macros/examples/stock.rs")]
mod stock;
pub use date::date_pattern;
pub use parser::{Grok, GrokBuildError, GrokBuilder};
const PATTERN_FILES: [&str; 23] = [
include_str!("patterns/base"),
include_str!("patterns/aws"),
include_str!("patterns/bacula"),
include_str!("patterns/bind"),
include_str!("patterns/bro"),
include_str!("patterns/exim"),
include_str!("patterns/firewalls"),
include_str!("patterns/haproxy"),
include_str!("patterns/httpd"),
include_str!("patterns/java"),
include_str!("patterns/junos"),
include_str!("patterns/linux-syslog"),
include_str!("patterns/maven"),
include_str!("patterns/mcollective"),
include_str!("patterns/mcollective-patterns"),
include_str!("patterns/mongodb"),
include_str!("patterns/nagios"),
include_str!("patterns/postgresql"),
include_str!("patterns/rails"),
include_str!("patterns/redis"),
include_str!("patterns/ruby"),
include_str!("patterns/squid"),
include_str!("patterns/formats"),
];
const MAX_DEPTH: usize = 64;
#[derive(Debug, Clone)]
pub struct Library {
defs: HashMap<String, String>,
}
impl Default for Library {
fn default() -> Self {
let mut lib = Self::empty();
for file in PATTERN_FILES {
lib.add_file(file);
}
for f in FIELDS {
lib.add(f.name, f.regex);
}
lib
}
}
impl Library {
#[must_use]
pub fn empty() -> Self {
Self {
defs: HashMap::new(),
}
}
pub fn add(&mut self, name: impl Into<String>, definition: impl Into<String>) {
self.defs.insert(name.into(), definition.into());
}
pub fn add_file(&mut self, text: &str) {
for line in text.lines() {
let line = line.trim_start();
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some((name, def)) = line.split_once(char::is_whitespace) {
self.add(name, def.trim_start());
}
}
}
pub fn add_json(&mut self, text: &str) -> Result<(), GrokError> {
let pairs: Vec<(String, String)> =
serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(text)
.map_err(|e| GrokError::Json(e.to_string()))?
.into_iter()
.map(|(name, def)| match def {
serde_json::Value::String(def) => Ok((name, def)),
_ => Err(GrokError::Json(format!("{name:?} is not a string"))),
})
.collect::<Result<_, _>>()?;
for (name, def) in pairs {
self.add(name, def);
}
Ok(())
}
#[must_use]
pub fn get(&self, name: &str) -> Option<&str> {
self.defs.get(name).map(String::as_str)
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.defs.keys().map(String::as_str)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Dialect {
#[default]
Rust,
Oniguruma,
Pcre,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Span {
#[default]
Part,
Whole,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Capture {
pub field: String,
pub hint: Hint,
pub filter: Option<Filter>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Filter {
Lowercase,
Uppercase,
NullIf(String),
}
impl Capture {
#[must_use]
pub fn value<'a>(&self, bytes: &'a [u8]) -> Option<crate::parse::FieldValue<'a>> {
use crate::parse::FieldValue;
Some(match &self.filter {
Some(Filter::NullIf(v)) if bytes == v.as_bytes() => return None,
None | Some(Filter::NullIf(_)) => FieldValue::borrowed(bytes, self.hint),
Some(Filter::Lowercase) => FieldValue::owned(bytes.to_ascii_lowercase(), self.hint),
Some(Filter::Uppercase) => FieldValue::owned(bytes.to_ascii_uppercase(), self.hint),
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Expanded {
pub regex: String,
pub captures: Vec<Capture>,
}
#[derive(Debug, Clone, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum GrokError {
#[error("no grok definition named {0:?}")]
Unknown(String),
#[error("grok definition {0:?} refers to itself")]
Cycle(String),
#[error("grok definitions nest deeper than 64 at {0:?}")]
TooDeep(String),
#[error("malformed grok reference {0:?}")]
Malformed(String),
#[error("date format {0}")]
Date(String),
#[error("grok definitions as JSON: {0}")]
Json(String),
}
pub fn expand(pattern: &str, library: &Library, dialect: Dialect) -> Result<Expanded, GrokError> {
expand_as(pattern, library, dialect, Span::Part, Possessive::Greedy)
}
pub(super) fn expand_as(
pattern: &str,
library: &Library,
dialect: Dialect,
span: Span,
possessive: Possessive,
) -> Result<Expanded, GrokError> {
let pattern = &*as_rust(pattern, dialect, possessive);
let new = |keep_groups| Expander {
library,
out: String::with_capacity(pattern.len() * 4),
captures: Vec::new(),
stack: Vec::new(),
onig: dialect == Dialect::Oniguruma,
names: Vec::new(),
keep_groups,
numbered: false,
};
let mut e = new(false);
e.text(pattern)?;
if e.numbered {
e = new(true);
e.text(pattern)?;
}
let out = match span {
Span::Part => e.out,
Span::Whole => format!("(?s)\\A(?:{})\\z", e.out),
};
let regex = match dialect {
Dialect::Rust | Dialect::Pcre => out,
Dialect::Oniguruma => oniguruma(&out),
};
Ok(Expanded {
regex,
captures: e.captures,
})
}
struct Expander<'l> {
library: &'l Library,
out: String,
captures: Vec<Capture>,
stack: Vec<String>,
onig: bool,
names: Vec<(String, usize)>,
keep_groups: bool,
numbered: bool,
}
impl Expander<'_> {
fn text(&mut self, text: &str) -> Result<(), GrokError> {
let mut rest = text;
let mut class = 0_usize;
while let Some(c) = rest.chars().next() {
let w = c.len_utf8();
if let Some(name) = backreference(rest)
&& let Some(&(_, i)) = self.names.iter().rev().find(|(n, _)| n == name)
{
self.out.push_str("\\k<g");
self.out.push_str(&i.to_string());
self.out.push('>');
rest = &rest[name.len() + 4..];
continue;
}
if c == '\\' {
self.numbered |= matches!(rest.as_bytes().get(1), Some(b'1'..=b'9'));
let n = rest[1..].chars().next().map_or(0, char::len_utf8);
self.out.push_str(&rest[..w + n]);
rest = &rest[w + n..];
continue;
}
if class > 0 {
match c {
'[' => class += 1,
']' => class -= 1,
_ => {}
}
self.out.push(c);
rest = &rest[w..];
continue;
}
if c == '[' {
class = 1;
self.out.push('[');
rest = &rest[1..];
for lead in ["^]", "^", "]"] {
if let Some(after) = rest.strip_prefix(lead) {
self.out.push_str(lead);
rest = after;
break;
}
}
continue;
}
if let Some(after) = rest.strip_prefix("%{") {
let end = after
.find('}')
.ok_or_else(|| GrokError::Malformed(rest.to_owned()))?;
self.reference(&after[..end])?;
rest = &after[end + 1..];
continue;
}
let group = if self.onig {
onig_group(rest).map(|(raw, after)| (raw, capture_name(raw), after))
} else {
named_group(rest).map(|(raw, after)| (raw, (raw, Hint::Text), after))
};
if let Some((raw, (name, hint), after)) = group {
let i = self.capture(name.to_owned(), hint);
self.names.push((raw.to_owned(), i));
self.group(i);
rest = after;
continue;
}
if c == '(' && !self.keep_groups && !rest[1..].starts_with(['?', '*']) {
self.out.push_str("(?:");
rest = &rest[1..];
continue;
}
self.out.push(c);
rest = &rest[w..];
}
Ok(())
}
fn reference(&mut self, inner: &str) -> Result<(), GrokError> {
let mut parts = inner.splitn(3, ':');
let name = parts.next().unwrap_or_default();
let field = parts.next().filter(|f| !f.is_empty());
let suffix = parts.next();
let filter = suffix.and_then(filter_of);
let date = suffix.and_then(date_format);
let hint = match suffix.map(hint_of) {
None => Hint::Text,
Some(Some(hint)) => hint,
Some(None) if date.is_some() => Hint::Timestamp,
Some(None) if self.onig || filter.is_some() => Hint::Text,
Some(None) => return Err(GrokError::Malformed(format!("%{{{inner}}}"))),
};
let generated;
let def = match date {
Some(format) if name.is_empty() => {
generated = date_pattern(format)?;
generated.as_str()
}
_ => self
.library
.get(name)
.ok_or_else(|| GrokError::Unknown(name.to_owned()))?,
};
if self.stack.iter().any(|s| s == name) {
return Err(GrokError::Cycle(name.to_owned()));
}
if self.stack.len() == MAX_DEPTH {
return Err(GrokError::TooDeep(name.to_owned()));
}
match field {
Some(field) => {
let i = self.capture(field_path(field), hint);
self.captures[i].filter = filter;
self.group(i);
}
None => self.out.push_str("(?:"),
}
self.stack.push(name.to_owned());
self.text(def)?;
self.stack.pop();
self.out.push(')');
Ok(())
}
fn group(&mut self, i: usize) {
self.out.push_str("(?P<g");
self.out.push_str(&i.to_string());
self.out.push('>');
}
fn capture(&mut self, field: String, hint: Hint) -> usize {
self.captures.push(Capture {
field,
hint,
filter: None,
});
self.captures.len() - 1
}
}
fn named_group(rest: &str) -> Option<(&str, &str)> {
let body = rest
.strip_prefix("(?P<")
.or_else(|| rest.strip_prefix("(?<"))?;
let end = body.find('>')?;
let name = &body[..end];
let valid = !name.is_empty()
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'[' | b']'));
valid.then(|| (name, &body[end + 1..]))
}
fn date_format(suffix: &str) -> Option<&str> {
suffix.strip_prefix("date(")?.strip_suffix(')')
}
fn filter_of(suffix: &str) -> Option<Filter> {
match suffix {
"lowercase" => Some(Filter::Lowercase),
"uppercase" => Some(Filter::Uppercase),
_ => suffix
.strip_prefix("nullif(")
.and_then(|v| v.strip_suffix(')'))
.map(|v| Filter::NullIf(v.to_owned())),
}
}
fn hint_of(suffix: &str) -> Option<Hint> {
match suffix {
"string" => Some(Hint::Text),
"int" | "long" | "integer" => Some(Hint::Int),
"float" | "double" | "number" => Some(Hint::Float),
"boolean" => Some(Hint::Bool),
_ => None,
}
}
fn onig_group(rest: &str) -> Option<(&str, &str)> {
let (name, after) = if let Some(name) = quoted_name(rest) {
(name, &rest[name.len() + 4..])
} else {
let body = rest
.strip_prefix("(?P<")
.or_else(|| rest.strip_prefix("(?<"))?;
let end = body.find('>')?;
(&body[..end], &body[end + 1..])
};
let valid = !name.is_empty()
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b'[' | b']' | b':'));
valid.then_some((name, after))
}
fn capture_name(name: &str) -> (&str, Hint) {
let parts: Vec<&str> = name.split(':').collect();
match parts.as_slice() {
[_, field, suffix] => (field, hint_of(suffix).unwrap_or(Hint::Text)),
[field, suffix] => hint_of(suffix).map_or((name, Hint::Text), |hint| (field, hint)),
_ => (name, Hint::Text),
}
}
fn field_path(field: &str) -> String {
if !field.starts_with('[') {
return field.to_owned();
}
field
.split(['[', ']'])
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join(".")
}
fn oniguruma(expanded: &str) -> String {
let mut out = String::with_capacity(expanded.len() + 24);
out.push_str("(?m)");
let mut rest = expanded;
let mut class = false;
while let Some(c) = rest.chars().next() {
let w = c.len_utf8();
match c {
'\\' => {
let next = rest[1..].chars().next();
match next {
Some(angle @ ('<' | '>')) => out.push(angle),
Some('h') => out.push_str(if class { "0-9A-Fa-f" } else { "[0-9A-Fa-f]" }),
Some('H') if !class => out.push_str("[^0-9A-Fa-f]"),
Some(n) => {
out.push('\\');
out.push(n);
}
None => out.push('\\'),
}
rest = &rest[w + next.map_or(0, char::len_utf8)..];
continue;
}
'[' if !class => class = true,
']' if class => class = false,
'{' if !class => {
let len = match interval(rest) {
Some((len, true)) => {
out.push_str("{0");
out.push_str(&rest[1..len]);
len
}
Some((len, false)) => {
out.push_str(&rest[..len]);
len
}
None => {
out.push_str("\\{");
1
}
};
rest = &rest[len..];
continue;
}
'(' if !class && rest.starts_with("(?m)") => {
out.push_str("(?s)");
rest = &rest[4..];
continue;
}
_ => {}
}
out.push(c);
rest = &rest[w..];
}
if out.ends_with('$') && !out.ends_with("\\$") {
out.pop();
out.push_str("(?:\\r\\n|\\n|\\r)?$");
}
out
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Possessive {
Kept,
Greedy,
}
fn as_rust(pattern: &str, dialect: Dialect, possessive: Possessive) -> std::borrow::Cow<'_, str> {
match dialect {
Dialect::Pcre => pcre(pattern, possessive).into(),
Dialect::Rust | Dialect::Oniguruma => pattern.into(),
}
}
pub(super) fn has_possessive(pattern: &str, dialect: Dialect) -> bool {
dialect == Dialect::Pcre && pcre(pattern, Possessive::Kept) != pcre(pattern, Possessive::Greedy)
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Last {
Open,
Atom,
Repeat,
}
fn pcre(pattern: &str, possessive: Possessive) -> String {
let mut out = String::with_capacity(pattern.len() + 8);
let mut rest = pattern;
let mut class = false;
let mut last = Last::Open;
while let Some(c) = rest.chars().next() {
let mut len = c.len_utf8();
let before = std::mem::replace(&mut last, Last::Atom);
match c {
'\\' => {
let next = rest[1..].chars().next();
len += next.map_or(0, char::len_utf8);
match next {
Some(angle @ ('<' | '>')) => out.push(angle),
_ => out.push_str(&rest[..len]),
}
}
'[' if class => match rest[2..].find(":]").filter(|_| rest.starts_with("[:")) {
Some(end) => {
len = end + 4;
out.push_str(&rest[..len]);
}
None => out.push_str("\\["),
},
'[' => {
class = true;
let lead = ["^]", "^", "]"]
.into_iter()
.find(|lead| rest[1..].starts_with(lead));
len += lead.map_or(0, str::len);
out.push_str(&rest[..len]);
}
']' if class => {
class = false;
out.push(']');
}
'%' if !class && rest.starts_with("%{") => {
len = rest.find('}').map_or(rest.len(), |end| end + 1);
out.push_str(&rest[..len]);
}
'(' if !class && rest.starts_with("(?|") => {
len = 3;
out.push_str("(?:");
last = Last::Open;
}
'{' if !class => match interval(rest) {
Some((end, low_left_out)) => {
out.push_str(if low_left_out { "{0" } else { "{" });
out.push_str(&rest[1..end]);
len = end;
last = Last::Repeat;
}
None => out.push_str("\\{"),
},
'+' | '?' if !class && before == Last::Repeat => {
if c == '?' || possessive == Possessive::Kept {
out.push(c);
}
}
'*' | '+' | '?' if !class => {
out.push(c);
last = match before {
Last::Open => Last::Open,
Last::Atom | Last::Repeat => Last::Repeat,
};
}
'(' | '|' if !class => {
out.push(c);
last = Last::Open;
}
_ => out.push(c),
}
rest = &rest[len..];
}
out
}
pub(super) fn inline_definitions(pattern: &str, library: &mut Library) -> String {
let mut out = String::with_capacity(pattern.len());
let mut rest = pattern;
while let Some(at) = rest.find("%{") {
out.push_str(&rest[..at]);
let body = &rest[at + 2..];
let mut depth = 0_usize;
let end = body.char_indices().find_map(|(k, c)| match c {
'{' => {
depth += 1;
None
}
'}' if depth == 0 => Some(k),
'}' => {
depth -= 1;
None
}
_ => None,
});
let Some(end) = end else {
out.push_str(&rest[at..]);
return out;
};
let inner = &body[..end];
let head = if let Some((head, definition)) = inner.split_once('=') {
library.add(head.split(':').next().unwrap_or(head), definition);
head.trim_end_matches(':')
} else {
inner
};
out.push_str("%{");
out.push_str(head);
out.push('}');
rest = &body[end + 1..];
}
out.push_str(rest);
out
}
const ALIAS_MARK: char = '\u{1}';
fn reference_names(text: &str) -> impl Iterator<Item = (usize, &str)> {
text.match_indices("%{").filter_map(move |(at, _)| {
let body = &text[at + 2..];
let end = body.find([':', '}', '='])?;
Some((at + 2, &body[..end]))
})
}
pub(super) fn layer_aliases(
patterns: &[String],
aliases: &Library,
library: &mut Library,
) -> Vec<String> {
let point = |text: &str| {
let mut out = String::with_capacity(text.len() + 4);
let mut from = 0;
for (at, name) in reference_names(text) {
if aliases.get(name).is_some() {
out.push_str(&text[from..at]);
out.push(ALIAS_MARK);
from = at;
}
}
out.push_str(&text[from..]);
out
};
for (name, def) in &aliases.defs {
library.add(format!("{ALIAS_MARK}{name}"), point(def));
}
patterns.iter().map(|p| point(p)).collect()
}
pub(super) fn define_unknown(patterns: &[String], library: &mut Library, definition: &str) {
let mut todo: Vec<String> = patterns.to_vec();
let mut seen = std::collections::HashSet::new();
let mut missing = Vec::new();
while let Some(text) = todo.pop() {
for (_, name) in reference_names(&text) {
if name.is_empty() || !seen.insert(name.to_owned()) {
continue;
}
match library.get(name) {
Some(def) => todo.push(def.to_owned()),
None => missing.push(name.to_owned()),
}
}
}
for name in missing {
library.add(name, definition);
}
}
pub(super) fn unmark(error: GrokError) -> GrokError {
let named = |name: String| name.trim_start_matches(ALIAS_MARK).to_owned();
match error {
GrokError::Unknown(name) => GrokError::Unknown(named(name)),
GrokError::Cycle(name) => GrokError::Cycle(named(name)),
GrokError::TooDeep(name) => GrokError::TooDeep(named(name)),
other => other,
}
}
fn interval(rest: &str) -> Option<(usize, bool)> {
let b = rest.as_bytes();
let digits = |from: usize| b[from..].iter().take_while(|c| c.is_ascii_digit()).count();
let lo = digits(1);
let mut end = 1 + lo;
if b.get(end) == Some(&b',') {
let hi = digits(end + 1);
end += 1 + hi;
if lo == 0 && hi == 0 {
return None;
}
} else if lo == 0 {
return None;
}
(b.get(end) == Some(&b'}')).then_some((end + 1, lo == 0))
}
fn backreference(rest: &str) -> Option<&str> {
let (tail, close) = rest
.strip_prefix("\\k<")
.map(|t| (t, '>'))
.or_else(|| rest.strip_prefix("\\k'").map(|t| (t, '\'')))?;
tail.find(close).map(|end| &tail[..end])
}
fn quoted_name(rest: &str) -> Option<&str> {
let tail = rest.strip_prefix("(?'")?;
let end = tail.find('\'')?;
Some(&tail[..end])
}
#[cfg(test)]
mod cover_tests;
#[cfg(test)]
mod plan_tests;
#[cfg(test)]
mod tests;