use std::ops::Range;
use memchr::memchr;
use thiserror::Error;
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
const AWS_ALB: &[&str] = &[
"type",
"time",
"elb",
"client",
"target",
"request_processing_time",
"target_processing_time",
"response_processing_time",
"elb_status_code",
"target_status_code",
"received_bytes",
"sent_bytes",
"request",
"user_agent",
"ssl_cipher",
"ssl_protocol",
"target_group_arn",
"trace_id",
"domain_name",
"chosen_cert_arn",
"matched_rule_priority",
"request_creation_time",
"actions_executed",
"redirect_url",
"error_reason",
"target_port_list",
"target_status_code_list",
"classification",
"classification_reason",
"conn_trace_id",
"transformed_host",
"transformed_uri",
"request_transform_status",
"ip_address",
"target_error_code",
"elb_error_code",
];
const AWS_NLB: &[&str] = &[
"type",
"version",
"time",
"elb",
"listener",
"client",
"destination",
"connection_time",
"tls_handshake_time",
"received_bytes",
"sent_bytes",
"incoming_tls_alert",
"chosen_cert_arn",
"chosen_cert_serial",
"tls_cipher",
"tls_protocol_version",
"tls_keyexchange",
"domain_name",
"alpn_fe_protocol",
"alpn_be_protocol",
"alpn_client_preference_list",
"tls_connection_creation_time",
"tls_verify_status",
"leaf_client_cert_subject",
"leaf_client_cert_validity",
"leaf_client_cert_serial_number",
];
const AWS_ELB: &[&str] = &[
"time",
"elb",
"client",
"backend",
"request_processing_time",
"backend_processing_time",
"response_processing_time",
"elb_status_code",
"backend_status_code",
"received_bytes",
"sent_bytes",
"request",
"user_agent",
"ssl_cipher",
"ssl_protocol",
];
const AWS_S3: &[&str] = &[
"bucket_owner",
"bucket",
"time",
"remote_ip",
"requester",
"request_id",
"operation",
"key",
"request_uri",
"http_status",
"error_code",
"bytes_sent",
"object_size",
"total_time",
"turn_around_time",
"referer",
"user_agent",
"version_id",
"host_id",
"signature_version",
"cipher_suite",
"authentication_type",
"host_header",
"tls_version",
"access_point_arn",
"acl_required",
"source_region",
];
const AWS_VPC_FLOW: &[&str] = &[
"version",
"account_id",
"interface_id",
"srcaddr",
"dstaddr",
"srcport",
"dstport",
"protocol",
"packets",
"bytes",
"start",
"end",
"action",
"log_status",
];
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum CloudLogError {
#[error("the flow log format names no field")]
Empty,
#[error("{0:?} in a flow log format is not ${{field}}")]
Word(String),
}
#[derive(Debug, Clone)]
pub struct CloudLog {
name: &'static str,
fields: Box<[Box<str>]>,
least: usize,
signature: Signature,
}
impl CloudLog {
fn of(name: &'static str, fields: &[&str], least: usize) -> Self {
let signature = Signature::builder()
.build()
.unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
Self {
name,
fields: fields.iter().map(|&f| Box::from(f)).collect(),
least,
signature,
}
}
#[must_use]
pub fn aws_alb() -> Self {
Self::of("aws_alb", AWS_ALB, 16)
}
#[must_use]
pub fn aws_nlb() -> Self {
Self::of("aws_nlb", AWS_NLB, 16)
}
#[must_use]
pub fn aws_elb() -> Self {
Self::of("aws_elb", AWS_ELB, AWS_ELB.len())
}
#[must_use]
pub fn aws_s3() -> Self {
Self::of("aws_s3", AWS_S3, 18)
}
#[must_use]
pub fn aws_vpc_flow() -> Self {
Self::of("aws_vpc_flow", AWS_VPC_FLOW, AWS_VPC_FLOW.len())
}
pub fn aws_vpc_flow_format(format: &str) -> Result<Self, CloudLogError> {
let fields: Vec<String> = format
.split_ascii_whitespace()
.map(|word| {
word.strip_prefix("${")
.and_then(|w| w.strip_suffix('}'))
.filter(|w| !w.is_empty() && !w.contains(['$', '{', '}']))
.map(|w| w.replace('-', "_"))
.ok_or_else(|| CloudLogError::Word(word.to_owned()))
})
.collect::<Result<_, _>>()?;
if fields.is_empty() {
return Err(CloudLogError::Empty);
}
let names: Vec<&str> = fields.iter().map(String::as_str).collect();
Ok(Self::of("aws_vpc_flow", &names, names.len()))
}
pub fn fields(&self) -> impl Iterator<Item = &str> {
self.fields.iter().map(|f| &**f)
}
}
fn value(line: &[u8], i: usize) -> Option<(Range<usize>, usize)> {
let close = match line[i] {
b'"' => b'"',
b'[' => b']',
_ => {
let end = memchr(b' ', &line[i..]).map_or(line.len(), |at| i + at);
return Some((i..end, end));
}
};
let mut at = i + 1;
loop {
let end = at + memchr(close, &line[at..])?;
if matches!(line.get(end + 1), None | Some(b' ')) {
return Some((i + 1..end, end + 1));
}
at = end + 1;
}
}
impl Parser for CloudLog {
fn hands_on_body(&self) -> bool {
false
}
fn name(&self) -> &str {
self.name
}
fn tier(&self) -> MatcherTier {
MatcherTier::Field
}
fn signature(&self) -> &Signature {
&self.signature
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let line = input.strip_suffix(b"\r").unwrap_or(input);
let mark = out.mark();
let mut i = 0;
let mut written = 0;
for name in &*self.fields {
while line.get(i) == Some(&b' ') {
i += 1;
}
if i >= line.len() {
break;
}
let Some((span, next)) = value(line, i) else {
out.rollback(mark);
return Err(ParseError::Malformed {
offset: i,
reason: "a quote or bracket with no close",
});
};
out.field(name, FieldValue::borrowed(&line[span], Hint::Text));
written += 1;
i = next;
}
if written < self.least {
out.rollback(mark);
return Err(ParseError::Malformed {
offset: line.len(),
reason: "fewer fields than the format holds",
});
}
Ok(Parsed::Done)
}
}
#[cfg(test)]
mod tests;