mod capture;
mod chain;
mod config;
mod driver;
mod frame;
mod number;
mod sink;
mod trace;
#[cfg(feature = "both-paths")]
pub mod both_paths;
use std::borrow::Cow;
use std::collections::HashMap;
use std::ops::Range;
use std::sync::Arc;
use thiserror::Error;
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
pub use chain::ChainError;
pub use config::{Chain, FallbackConfig, FormatChoice, HopConfig, ParseConfig, Settings};
#[cfg(test)]
#[allow(
unused_imports,
reason = "its test sits behind the stock parser features"
)]
pub(crate) use driver::gate_pays;
pub use driver::{Batch, CompileError, Outcome, ParsePlan, ParserCounts, SourceState, Status};
#[cfg(feature = "parse-grok")]
pub(crate) use driver::{Counter, counter};
#[cfg(feature = "framing")]
pub use frame::{
CarriageReturns, ContainerConfig, ContainerFormat, JsonPointer, JsonPointerConfig,
PointerError, StreamConfig, StreamEncoding, StreamSplit,
};
pub use frame::{Frame, FrameState, FramingConfig, MultiLineConfig};
#[cfg(feature = "framing")]
pub(crate) use frame::{RS, Scan, ScanStep, space};
pub use sink::{FieldSink, Fields, PrefixStack, SinkMark};
pub use trace::{Event, Failure, Input, Step, Trace};
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Hint {
Text,
Int,
Float,
Bool,
Ip,
Timestamp,
Json,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldValue<'a> {
pub bytes: Cow<'a, [u8]>,
pub hint: Hint,
}
impl<'a> FieldValue<'a> {
#[must_use]
pub const fn borrowed(bytes: &'a [u8], hint: Hint) -> Self {
Self {
bytes: Cow::Borrowed(bytes),
hint,
}
}
#[must_use]
pub const fn owned(bytes: Vec<u8>, hint: Hint) -> Self {
Self {
bytes: Cow::Owned(bytes),
hint,
}
}
#[must_use]
pub fn into_owned(self) -> FieldValue<'static> {
FieldValue {
bytes: Cow::Owned(self.bytes.into_owned()),
hint: self.hint,
}
}
}
pub const DECODE_MAX_BYTES: usize = 16 << 20;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Decoded {
bytes: Vec<u8>,
hint: Option<&'static str>,
}
impl Decoded {
#[must_use]
pub const fn new(bytes: Vec<u8>) -> Self {
Self { bytes, hint: None }
}
#[must_use]
pub const fn with_hint(mut self, hint: &'static str) -> Self {
self.hint = Some(hint);
self
}
#[must_use]
pub fn bytes(&self) -> &[u8] {
&self.bytes
}
#[must_use]
pub const fn hint(&self) -> Option<&'static str> {
self.hint
}
#[must_use]
pub fn into_vec(self) -> Vec<u8> {
self.bytes
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Parsed {
NoMatch,
Done,
Body {
span: Range<usize>,
hint: Option<&'static str>,
},
Decoded(Decoded),
}
#[non_exhaustive]
#[derive(Debug, Error)]
pub enum ParseError {
#[error("malformed at byte {offset}: {reason}")]
Malformed {
offset: usize,
reason: &'static str,
},
#[error("limit reached: {what}")]
Limit {
what: &'static str,
},
#[error("a frame of {len} bytes is over max_bytes {max}")]
FrameTooLong {
len: u64,
max: usize,
},
#[error(transparent)]
Other(Box<dyn std::error::Error + Send + Sync>),
}
pub trait Parser: Send + Sync {
fn name(&self) -> &str;
fn tier(&self) -> MatcherTier;
fn signature(&self) -> &Signature;
fn cost(&self) -> Option<crate::cost::Cost> {
crate::cost::of(&format!("parser.{}", self.name()))
}
fn parse_counted<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
counts: &mut ParserCounts,
) -> Result<Parsed, ParseError> {
let _ = counts;
self.parse(input, out)
}
fn decodes(&self) -> bool {
false
}
fn detectable(&self) -> bool {
!self.signature().is_literal_free()
}
fn hands_on_body(&self) -> bool {
true
}
fn escape_value(
&self,
input: &[u8],
field: usize,
at: Range<usize>,
value: &[u8],
out: &mut Vec<u8>,
) -> Option<Range<usize>> {
let _ = (input, field);
out.extend_from_slice(value);
Some(at)
}
fn parse<'a>(&self, input: &'a [u8], out: &mut dyn FieldSink<'a>)
-> Result<Parsed, ParseError>;
}
#[inline]
pub(crate) fn without_trailing_cr(bytes: &[u8]) -> &[u8] {
&bytes[..bytes.iter().rposition(|&b| b != b'\r').map_or(0, |i| i + 1)]
}
#[cfg(any(feature = "parse-kv", feature = "parse-csv", feature = "parse-gelf"))]
pub(crate) fn quoted_span(
input: &[u8],
at: &Range<usize>,
quote: impl Fn(u8) -> bool,
) -> Option<Range<usize>> {
let open = *input.get(at.start.checked_sub(1)?)?;
(quote(open) && input.get(at.end) == Some(&open)).then(|| at.start - 1..at.end + 1)
}
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ResolveError {
#[error("no parser named {0:?}")]
Unknown(String),
#[error("{name:?} needs grippo's `{feature}` feature, which this build left out")]
FeatureOff {
name: String,
feature: &'static str,
},
#[error("parser name {0:?} is not `format` or `format:instance` in lower case")]
BadName(String),
#[error("parser {name:?}: {reason}")]
Settings {
name: String,
reason: String,
},
}
const FORMAT_FEATURES: &[(&str, &str, bool)] = &[
("cef", "parse-cef", cfg!(feature = "parse-cef")),
("syslog", "parse-syslog", cfg!(feature = "parse-syslog")),
(
"syslog_nopri",
"parse-syslog",
cfg!(feature = "parse-syslog"),
),
("leef", "parse-leef", cfg!(feature = "parse-leef")),
("ndjson", "parse-ndjson", cfg!(feature = "parse-ndjson")),
("gelf", "parse-gelf", cfg!(feature = "parse-gelf")),
("csv", "parse-csv", cfg!(feature = "parse-csv")),
("kv", "parse-kv", cfg!(feature = "parse-kv")),
("logfmt", "parse-kv", cfg!(feature = "parse-kv")),
("dissect", "parse-dissect", cfg!(feature = "parse-dissect")),
("cri", "parse-cri", cfg!(feature = "parse-cri")),
("xml", "parse-xml", cfg!(feature = "parse-xml")),
("uri", "parse-uri", cfg!(feature = "parse-uri")),
("query", "parse-query", cfg!(feature = "parse-query")),
(
"prometheus",
"parse-prometheus",
cfg!(feature = "parse-prometheus"),
),
("aws_alb", "parse-cloud", cfg!(feature = "parse-cloud")),
("aws_nlb", "parse-cloud", cfg!(feature = "parse-cloud")),
("aws_elb", "parse-cloud", cfg!(feature = "parse-cloud")),
("aws_s3", "parse-cloud", cfg!(feature = "parse-cloud")),
("aws_vpc_flow", "parse-cloud", cfg!(feature = "parse-cloud")),
("ini", "parse-ini", cfg!(feature = "parse-ini")),
("properties", "parse-ini", cfg!(feature = "parse-ini")),
("dotenv", "parse-ini", cfg!(feature = "parse-ini")),
("yaml", "parse-yaml", cfg!(feature = "parse-yaml")),
("toml", "parse-toml", cfg!(feature = "parse-toml")),
("http", "parse-http", cfg!(feature = "parse-http")),
("headers", "parse-http", cfg!(feature = "parse-http")),
("msgpack", "parse-msgpack", cfg!(feature = "parse-msgpack")),
(
"protobuf",
"parse-protobuf",
cfg!(feature = "parse-protobuf"),
),
("otlp", "parse-otlp", cfg!(feature = "parse-otlp")),
("base64", "decode-base64", cfg!(feature = "decode-base64")),
(
"base64url",
"decode-base64",
cfg!(feature = "decode-base64"),
),
("hex", "decode-hex", cfg!(feature = "decode-hex")),
("gzip", "decode-gzip", cfg!(feature = "decode-gzip")),
("zlib", "decode-zlib", cfg!(feature = "decode-zlib")),
("zstd", "decode-zstd", cfg!(feature = "decode-zstd")),
("snappy", "decode-snappy", cfg!(feature = "decode-snappy")),
(
"snappy_raw",
"decode-snappy",
cfg!(feature = "decode-snappy"),
),
("utf8", "decode-text", cfg!(feature = "decode-text")),
("utf16le", "decode-text", cfg!(feature = "decode-text")),
("utf16be", "decode-text", cfg!(feature = "decode-text")),
("charset", "decode-text", cfg!(feature = "decode-text")),
(
"rsyslog",
"decode-rsyslog",
cfg!(feature = "decode-rsyslog"),
),
];
#[must_use]
pub fn missing_feature(name: &str) -> Option<&'static str> {
let format = name.split_once(':').map_or(name, |(f, _)| f);
FORMAT_FEATURES
.iter()
.find(|(n, _, _)| *n == format)
.and_then(|&(_, feature, on)| (!on).then_some(feature))
}
impl ResolveError {
#[must_use]
pub fn unknown(name: &str) -> Self {
missing_feature(name).map_or_else(
|| Self::Unknown(name.to_owned()),
|feature| Self::FeatureOff {
name: name.to_owned(),
feature,
},
)
}
}
pub trait Resolve {
fn resolve(
&self,
name: &str,
settings: Option<&serde_json::Value>,
) -> Result<Arc<dyn Parser>, ResolveError>;
fn candidates(&self) -> Vec<Arc<dyn Parser>>;
}
#[derive(Default, Clone)]
pub struct Parsers {
by_name: HashMap<String, Arc<dyn Parser>>,
order: Vec<Arc<dyn Parser>>,
}
impl std::fmt::Debug for Parsers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_list()
.entries(self.order.iter().map(|p| p.name()))
.finish()
}
}
impl Parsers {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn register(&mut self, parser: Arc<dyn Parser>) -> Result<(), ResolveError> {
let name = parser.name().to_owned();
if !valid_parser_name(&name) {
return Err(ResolveError::BadName(name));
}
if let Some(old) = self.by_name.insert(name, Arc::clone(&parser)) {
self.order.retain(|p| !Arc::ptr_eq(p, &old));
}
self.order.push(parser);
Ok(())
}
}
#[must_use]
pub fn valid_parser_name(name: &str) -> bool {
let (format, instance) = match name.split_once(':') {
Some((f, i)) => (f, Some(i)),
None => (name, None),
};
let mut fb = format.bytes();
let format_ok = fb.next().is_some_and(|b| b.is_ascii_lowercase())
&& fb.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
&& !chain::RESERVED.contains(&format);
let instance_ok = instance.is_none_or(|i| {
!i.is_empty()
&& i.bytes().all(|b| {
b.is_ascii_lowercase() || b.is_ascii_digit() || matches!(b, b'_' | b'.' | b'-')
})
});
format_ok && instance_ok
}
impl Resolve for Parsers {
fn resolve(
&self,
name: &str,
settings: Option<&serde_json::Value>,
) -> Result<Arc<dyn Parser>, ResolveError> {
let parser = self
.by_name
.get(name)
.ok_or_else(|| ResolveError::unknown(name))?;
if settings.is_some() {
return Err(ResolveError::Settings {
name: name.to_owned(),
reason: "this parser takes no settings".to_owned(),
});
}
Ok(Arc::clone(parser))
}
fn candidates(&self) -> Vec<Arc<dyn Parser>> {
self.order.clone()
}
}
#[cfg(test)]
mod tests;