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
#![doc(html_root_url = "https://docs.rs/grok/0.3.0")]
extern crate onig;
mod patterns;
use onig::{Captures, Regex};
use std::collections::{HashMap, BTreeMap};
use std::fmt;
use std::error::Error as StdError;
use std::collections::hash_map::Iter as MapIter;
use std::iter::FromIterator;
const MAX_RECURSION: usize = 1024;
const GROK_PATTERN: &'static str = r"%\{(?<name>(?<pattern>[A-z0-9]+)(?::(?<alias>[A-z0-9_:;\/\s\.]+))?)(?:=(?<definition>(?:(?:[^{}]+|\.+)+)+))?\}";
const NAME_INDEX: usize = 1;
const PATTERN_INDEX: usize = 2;
const ALIAS_INDEX: usize = 3;
const DEFINITION_INDEX: usize = 4;
#[derive(Debug)]
pub struct Matches<'a> {
captures: Captures<'a>,
alias: &'a HashMap<String, String>,
names: &'a HashMap<String, u32>,
}
impl<'a> Matches<'a> {
pub fn new(captures: Captures<'a>, alias: &'a HashMap<String, String>, names: &'a HashMap<String, u32>) -> Self {
Matches { captures: captures, alias: alias, names: names }
}
pub fn get(&self, name_or_alias: &str) -> Option<&str> {
match self.alias.get(name_or_alias) {
Some(real) => {
self.captures.at(*self.names.get(real).unwrap() as usize)
},
None => None,
}
}
pub fn len(&self) -> usize {
self.captures.len() - 1
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn iter(&'a self) -> MatchesIter<'a> {
MatchesIter { captures: &self.captures, alias: self.alias.iter(), names: &self.names }
}
}
pub struct MatchesIter<'a> {
captures: &'a Captures<'a>,
alias: MapIter<'a, String, String>,
names: &'a HashMap<String, u32>,
}
impl<'a> Iterator for MatchesIter<'a> {
type Item = (&'a str, &'a str);
fn next(&mut self) -> Option<Self::Item> {
self.alias.next().map(|(k, v)| {
let key = k.as_str();
let value = match self.captures.at(*self.names.get(v).unwrap() as usize) {
Some(v) => v,
None => "",
};
(key, value)
})
}
}
#[derive(Debug)]
pub struct Pattern {
regex: Regex,
alias: HashMap<String, String>,
names: HashMap<String, u32>,
}
impl Pattern {
pub fn new(regex: &str, alias: HashMap<String, String>) -> Result<Self, Error> {
match Regex::new(regex) {
Ok(r) => Ok({
let names = HashMap::from_iter(r.capture_names().map(|(name, idx)| (String::from(name), idx[0])));
Pattern { regex: r, alias: alias, names: names }
}),
Err(_) => Err(Error::RegexCompilationFailed(regex.into())),
}
}
pub fn match_against<'a>(&'a self, text: &'a str) -> Option<Matches<'a>> {
self.regex.captures(text).map(|cap| Matches::new(cap, &self.alias, &self.names))
}
}
#[derive(Debug)]
pub struct Grok {
definitions: BTreeMap<String, String>,
}
impl Grok {
pub fn empty() -> Self {
Grok {
definitions: BTreeMap::new(),
}
}
pub fn with_patterns() -> Self {
let mut grok = Grok::empty();
for &(key, value) in patterns::PATTERNS {
grok.insert_definition(String::from(key), String::from(value));
}
grok
}
pub fn insert_definition<S: Into<String>>(&mut self, name: S, pattern: S) {
self.definitions.insert(name.into(), pattern.into());
}
pub fn compile(&mut self, pattern: &str, with_alias_only: bool) -> Result<Pattern, Error> {
let mut named_regex = String::from(pattern);
let mut alias: HashMap<String, String> = HashMap::new();
let mut index = 0;
let mut iteration_left = MAX_RECURSION;
let mut continue_iteration = true;
let grok_regex = match Regex::new(GROK_PATTERN) {
Ok(r) => r,
Err(_) => return Err(Error::RegexCompilationFailed(GROK_PATTERN.into())),
};
while continue_iteration {
continue_iteration = false;
if iteration_left <= 0 {
return Err(Error::RecursionTooDeep);
}
iteration_left -= 1;
if let Some(m) = grok_regex.captures(&named_regex.clone()) {
continue_iteration = true;
let raw_pattern = match m.at(PATTERN_INDEX) {
Some(p) => p,
None => return Err(Error::GenericCompilationFailure("Could not find pattern in matches".into())),
};
let mut name = match m.at(NAME_INDEX) {
Some(n) => String::from(n),
None => return Err(Error::GenericCompilationFailure("Could not find name in matches".into())),
};
if let Some(definition) = m.at(DEFINITION_INDEX) {
self.insert_definition(raw_pattern, definition);
name = format!("{}={}", name, definition);
}
for _ in 0..named_regex.matches(&format!("%{{{}}}", name)).count() {
let pattern_definition = match self.definitions.get(raw_pattern) {
Some(d) => d,
None => return Err(Error::DefinitionNotFound(raw_pattern.into())),
};
let replacement = if with_alias_only && m.at(ALIAS_INDEX).is_none() {
format!("(?:{})", pattern_definition)
} else {
alias.insert(match m.at(ALIAS_INDEX) {
Some(a) => a.into(),
None => name.clone(),
}, format!("name{}", index));
format!("(?<name{}>{})", index, pattern_definition)
};
named_regex = named_regex.replacen(&format!("%{{{}}}", name), &replacement, 1);
index += 1;
}
}
}
if named_regex.is_empty() {
Err(Error::CompiledPatternIsEmpty(pattern.into()))
} else {
Pattern::new(&named_regex, alias)
}
}
}
impl Default for Grok {
fn default() -> Grok {
Grok::with_patterns()
}
}
#[derive(Clone, Debug, PartialEq)]
pub enum Error {
RecursionTooDeep,
CompiledPatternIsEmpty(String),
DefinitionNotFound(String),
RegexCompilationFailed(String),
GenericCompilationFailure(String),
#[doc(hidden)]
__Nonexhaustive,
}
impl StdError for Error {
fn description(&self) -> &str {
match *self {
Error::RecursionTooDeep => "compilation recursion reached the limit",
Error::CompiledPatternIsEmpty(_) => "compiled pattern is empty",
Error::DefinitionNotFound(_) => "pattern definition not found while compiling",
Error::RegexCompilationFailed(_) => "regex compilation in the engine failed",
Error::GenericCompilationFailure(_) => "something happened during the compilation phase",
Error::__Nonexhaustive => unreachable!(),
}
}
fn cause(&self) -> Option<&StdError> {
None
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::RecursionTooDeep =>
write!(f, "Recursion while compiling reached the limit of {}", MAX_RECURSION),
Error::CompiledPatternIsEmpty(ref p) =>
write!(f, "The given pattern \"{}\" ended up compiling into an empty regex", p),
Error::DefinitionNotFound(ref d) =>
write!(f, "The given pattern definition name \"{}\" could not be found in the definition map", d),
Error::RegexCompilationFailed(ref r) =>
write!(f, "The given regex \"{}\" failed compilation in the underlying engine", r),
Error::GenericCompilationFailure(ref d) =>
write!(f, "Something unexpected happened during the compilation phase: \"{}\"", d),
Error::__Nonexhaustive => unreachable!(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_simple_anonymous_pattern() {
let mut grok = Grok::empty();
grok.insert_definition("USERNAME", r"[a-zA-Z0-9._-]+");
let pattern = grok.compile("%{USERNAME}", false).expect("Error while compiling!");
let matches = pattern.match_against("root").expect("No matches found!");
assert_eq!("root", matches.get("USERNAME").unwrap());
assert_eq!(1, matches.len());
let matches = pattern.match_against("john doe").expect("No matches found!");
assert_eq!("john", matches.get("USERNAME").unwrap());
assert_eq!(1, matches.len());
}
#[test]
fn test_simple_named_pattern() {
let mut grok = Grok::empty();
grok.insert_definition("USERNAME", r"[a-zA-Z0-9._-]+");
let pattern = grok.compile("%{USERNAME:usr}", false).expect("Error while compiling!");
let matches = pattern.match_against("root").expect("No matches found!");
assert_eq!("root", matches.get("usr").unwrap());
assert_eq!(1, matches.len());
let matches = pattern.match_against("john doe").expect("No matches found!");
assert_eq!("john", matches.get("usr").unwrap());
assert_eq!(1, matches.len());
}
#[test]
fn test_alias_anonymous_pattern() {
let mut grok = Grok::empty();
grok.insert_definition("USERNAME", r"[a-zA-Z0-9._-]+");
grok.insert_definition("USER", r"%{USERNAME}");
let pattern = grok.compile("%{USER}", false).expect("Error while compiling!");
let matches = pattern.match_against("root").expect("No matches found!");
assert_eq!("root", matches.get("USER").unwrap());
let matches = pattern.match_against("john doe").expect("No matches found!");
assert_eq!("john", matches.get("USER").unwrap());
}
#[test]
fn test_ailas_named_pattern() {
let mut grok = Grok::empty();
grok.insert_definition("USERNAME", r"[a-zA-Z0-9._-]+");
grok.insert_definition("USER", r"%{USERNAME}");
let pattern = grok.compile("%{USER:usr}", false).expect("Error while compiling!");
let matches = pattern.match_against("root").expect("No matches found!");
assert_eq!("root", matches.get("usr").unwrap());
let matches = pattern.match_against("john doe").expect("No matches found!");
assert_eq!("john", matches.get("usr").unwrap());
}
#[test]
fn test_composite_or_pattern() {
let mut grok = Grok::empty();
grok.insert_definition("MAC", r"(?:%{CISCOMAC}|%{WINDOWSMAC}|%{COMMONMAC})");
grok.insert_definition("CISCOMAC", r"(?:(?:[A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4})");
grok.insert_definition("WINDOWSMAC", r"(?:(?:[A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2})");
grok.insert_definition("COMMONMAC", r"(?:(?:[A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2})");
let pattern = grok.compile("%{MAC}", false).expect("Error while compiling!");
let matches = pattern.match_against("5E:FF:56:A2:AF:15").expect("No matches found!");
assert_eq!("5E:FF:56:A2:AF:15", matches.get("MAC").unwrap());
assert_eq!(4, matches.len());
let matches = pattern.match_against("hello! 5E:FF:56:A2:AF:15 what?").expect("No matches found!");
assert_eq!("5E:FF:56:A2:AF:15", matches.get("MAC").unwrap());
assert_eq!(true, pattern.match_against("5E:FF").is_none());
}
#[test]
fn test_multiple_patterns() {
let mut grok = Grok::empty();
grok.insert_definition("YEAR", r"(\d\d){1,2}");
grok.insert_definition("MONTH", r"\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\b");
grok.insert_definition("DAY", r"(?:Mon(?:day)?|Tue(?:sday)?|Wed(?:nesday)?|Thu(?:rsday)?|Fri(?:day)?|Sat(?:urday)?|Sun(?:day)?)");
let pattern = grok.compile("%{DAY} %{MONTH} %{YEAR}", false).expect("Error while compiling!");
let matches = pattern.match_against("Monday March 2012").expect("No matches found!");
assert_eq!("Monday", matches.get("DAY").unwrap());
assert_eq!("March", matches.get("MONTH").unwrap());
assert_eq!("2012", matches.get("YEAR").unwrap());
assert_eq!(None, matches.get("unknown"));
}
#[test]
fn test_with_alias_only() {
let mut grok = Grok::empty();
grok.insert_definition("MAC", r"(?:%{CISCOMAC}|%{WINDOWSMAC}|%{COMMONMAC})");
grok.insert_definition("CISCOMAC", r"(?:(?:[A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4})");
grok.insert_definition("WINDOWSMAC", r"(?:(?:[A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2})");
grok.insert_definition("COMMONMAC", r"(?:(?:[A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2})");
let pattern = grok.compile("%{MAC:macaddr}", true).expect("Error while compiling!");
let matches = pattern.match_against("5E:FF:56:A2:AF:15").expect("No matches found!");
assert_eq!("5E:FF:56:A2:AF:15", matches.get("macaddr").unwrap());
assert_eq!(1, matches.len());
let matches = pattern.match_against("hello! 5E:FF:56:A2:AF:15 what?").expect("No matches found!");
assert_eq!("5E:FF:56:A2:AF:15", matches.get("macaddr").unwrap());
assert_eq!(true, pattern.match_against("5E:FF").is_none());
}
#[test]
fn test_match_iterator() {
let mut grok = Grok::empty();
grok.insert_definition("YEAR", r"(\d\d){1,2}");
grok.insert_definition("MONTH", r"\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\b");
grok.insert_definition("DAY", r"(?:Mon(?:day)?|Tue(?:sday)?|Wed(?:nesday)?|Thu(?:rsday)?|Fri(?:day)?|Sat(?:urday)?|Sun(?:day)?)");
grok.insert_definition("USERNAME", r"[a-zA-Z0-9._-]+");
grok.insert_definition("SPACE", r"\s*");
let pattern = grok.compile("%{DAY:day} %{MONTH:month} %{YEAR:year}%{SPACE}%{USERNAME:user}?", true).expect("Error while compiling!");
let matches = pattern.match_against("Monday March 2012").expect("No matches found!");
let mut found = 0;
for (k, v) in matches.iter() {
match k {
"day" => assert_eq!("Monday", v),
"month" => assert_eq!("March", v),
"year" => assert_eq!("2012", v),
"user" => assert_eq!("", v),
e => panic!(format!("{:?}", e)),
}
found += 1;
}
assert_eq!(4, found);
}
#[test]
fn test_loaded_default_patterns() {
let mut grok = Grok::with_patterns();
let pattern = grok.compile("%{DAY} %{MONTH} %{YEAR}", false).expect("Error while compiling!");
let matches = pattern.match_against("Monday March 2012").expect("No matches found!");
assert_eq!("Monday", matches.get("DAY").unwrap());
assert_eq!("March", matches.get("MONTH").unwrap());
assert_eq!("2012", matches.get("YEAR").unwrap());
assert_eq!(None, matches.get("unknown"));
}
#[test]
fn test_compilation_of_all_default_patterns() {
let mut grok = Grok::default();
let mut num_checked = 0;
for &(key, _) in patterns::PATTERNS {
let pattern = format!("%{{{}}}", key);
grok.compile(&pattern, false).expect(&format!("Pattern {} key {} failed to compile!", pattern, key));
num_checked += 1;
}
assert!(num_checked > 0);
}
}