use crate::parse::{DECODE_MAX_BYTES, Decoded, FieldSink, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
#[cfg(feature = "decode-text")]
use crate::charset::{Charset, Malformed, Transcoder};
#[cfg(feature = "decode-rsyslog")]
mod rsyslog;
#[cfg(feature = "decode-rsyslog")]
pub use rsyslog::Escaped;
#[cfg(any(
feature = "decode-gzip",
feature = "decode-zlib",
feature = "decode-zstd",
feature = "decode-snappy"
))]
use std::io::Read;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Codec {
#[cfg(feature = "decode-base64")]
Base64 {
url_safe: bool,
skip_whitespace: bool,
},
#[cfg(feature = "decode-hex")]
Hex,
#[cfg(feature = "decode-gzip")]
Gzip,
#[cfg(feature = "decode-zlib")]
Zlib,
#[cfg(feature = "decode-zstd")]
Zstd,
#[cfg(feature = "decode-snappy")]
Snappy,
#[cfg(feature = "decode-snappy")]
SnappyRaw,
#[cfg(feature = "decode-text")]
Text(Charset),
#[cfg(feature = "decode-rsyslog")]
Rsyslog {
prefix: u8,
escaped: Escaped,
},
}
#[cfg(feature = "decode-text")]
fn text_name(charset: Charset) -> &'static str {
if charset == Charset::UTF_8 {
"utf8"
} else if charset == Charset::UTF_16LE {
"utf16le"
} else if charset == Charset::UTF_16BE {
"utf16be"
} else {
"charset"
}
}
impl Codec {
#[must_use]
#[allow(
clippy::missing_const_for_fn,
reason = "a charset's name reads from a table at run time"
)]
pub fn name(self) -> &'static str {
match self {
#[cfg(feature = "decode-text")]
Self::Text(charset) => text_name(charset),
#[cfg(feature = "decode-rsyslog")]
Self::Rsyslog { .. } => "rsyslog",
#[cfg(feature = "decode-base64")]
Self::Base64 {
url_safe: false, ..
} => "base64",
#[cfg(feature = "decode-base64")]
Self::Base64 { url_safe: true, .. } => "base64url",
#[cfg(feature = "decode-hex")]
Self::Hex => "hex",
#[cfg(feature = "decode-gzip")]
Self::Gzip => "gzip",
#[cfg(feature = "decode-zlib")]
Self::Zlib => "zlib",
#[cfg(feature = "decode-zstd")]
Self::Zstd => "zstd",
#[cfg(feature = "decode-snappy")]
Self::Snappy => "snappy",
#[cfg(feature = "decode-snappy")]
Self::SnappyRaw => "snappy_raw",
}
}
const fn broken(self) -> &'static str {
match self {
#[cfg(feature = "decode-base64")]
Self::Base64 { .. } => "not base64",
#[cfg(feature = "decode-hex")]
Self::Hex => "not hex",
#[cfg(feature = "decode-gzip")]
Self::Gzip => "not a whole gzip stream",
#[cfg(feature = "decode-zlib")]
Self::Zlib => "not a whole zlib stream",
#[cfg(feature = "decode-zstd")]
Self::Zstd => "not whole zstd frames, or a window over the cap",
#[cfg(feature = "decode-snappy")]
Self::Snappy => "not a whole snappy stream",
#[cfg(feature = "decode-snappy")]
Self::SnappyRaw => "not a whole snappy block",
#[cfg(feature = "decode-text")]
Self::Text(_) => "not text this charset reads",
#[cfg(feature = "decode-rsyslog")]
Self::Rsyslog { .. } => "not text rsyslog wrote",
}
}
const fn magic(self) -> Option<&'static [u8]> {
match self {
#[cfg(feature = "decode-gzip")]
Self::Gzip => Some(b"\x1f\x8b\x08"),
#[cfg(feature = "decode-zstd")]
Self::Zstd => Some(b"\x28\xb5\x2f\xfd"),
#[cfg(feature = "decode-snappy")]
Self::Snappy => Some(b"\xff\x06\x00\x00sNaPpY"),
#[allow(unreachable_patterns, reason = "every arm may be compiled out")]
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub struct Decoder {
codec: Codec,
name: String,
max_bytes: usize,
signature: Signature,
}
impl Decoder {
#[must_use]
pub fn new(codec: Codec) -> Self {
let builder = Signature::builder();
let builder = match codec.magic() {
Some(magic) => builder.anchored([magic]),
None => builder,
};
let signature = builder
.build()
.unwrap_or_else(|_| unreachable!("invariant: a fixed signature builds"));
Self {
codec,
name: registered_name(codec),
max_bytes: DECODE_MAX_BYTES,
signature,
}
}
#[must_use]
pub fn named(mut self, name: impl Into<String>) -> Self {
self.name = name.into();
self
}
#[must_use]
pub const fn with_max_bytes(mut self, max_bytes: usize) -> Self {
self.max_bytes = max_bytes;
self
}
#[must_use]
pub const fn codec(&self) -> Codec {
self.codec
}
#[must_use]
pub const fn max_bytes(&self) -> usize {
self.max_bytes
}
pub fn decode(&self, input: &[u8], out: &mut Vec<u8>) -> Result<(), ParseError> {
let cap = self.max_bytes;
if let Some(magic) = self.codec.magic()
&& !input.starts_with(magic)
{
return Err(malformed(self.codec));
}
match self.codec {
#[cfg(feature = "decode-base64")]
Codec::Base64 {
url_safe,
skip_whitespace,
} => {
use crate::kernel::base64::{Failure, STANDARD, URL_SAFE, decode};
let alphabet = if url_safe { &URL_SAFE } else { &STANDARD };
decode(alphabet, input, skip_whitespace, out, cap).map_err(|f| match f {
Failure::Malformed { offset, reason } => {
ParseError::Malformed { offset, reason }
}
Failure::Limit => limit(),
})
}
#[cfg(feature = "decode-hex")]
Codec::Hex => {
use crate::kernel::hex::{Failure, decode};
decode(input, out, cap).map_err(|f| match f {
Failure::Malformed { offset, reason } => {
ParseError::Malformed { offset, reason }
}
Failure::Limit => limit(),
})
}
#[cfg(feature = "decode-gzip")]
Codec::Gzip => read_capped(
flate2::bufread::MultiGzDecoder::new(input),
input.len(),
out,
cap,
self.codec,
),
#[cfg(feature = "decode-zlib")]
Codec::Zlib => read_capped(
flate2::bufread::ZlibDecoder::new(input),
input.len(),
out,
cap,
self.codec,
),
#[cfg(feature = "decode-zstd")]
Codec::Zstd => {
let mut reader = zstd::stream::read::Decoder::with_buffer(input)
.map_err(|_| malformed(self.codec))?;
reader
.window_log_max(window_log(cap))
.map_err(|_| malformed(self.codec))?;
read_capped(reader, input.len(), out, cap, self.codec)
}
#[cfg(feature = "decode-snappy")]
Codec::Snappy => read_capped(
snap::read::FrameDecoder::new(input),
input.len(),
out,
cap,
self.codec,
),
#[cfg(feature = "decode-snappy")]
Codec::SnappyRaw => {
let len = snap::raw::decompress_len(input).map_err(|_| malformed(self.codec))?;
if len > cap {
return Err(limit());
}
let start = out.len();
out.resize(start + len, 0);
let wrote = snap::raw::Decoder::new().decompress(input, &mut out[start..]);
out.truncate(start + wrote.as_ref().map_or(0, |n| *n));
wrote.map(|_| ()).map_err(|_| malformed(self.codec))
}
#[cfg(feature = "decode-text")]
Codec::Text(charset) => decode_text(charset, input, out, cap, self.codec),
#[cfg(feature = "decode-rsyslog")]
Codec::Rsyslog { prefix, escaped } => {
if rsyslog::decode(prefix, escaped, input, out, cap) {
Ok(())
} else {
Err(limit())
}
}
}
}
}
fn registered_name(codec: Codec) -> String {
#[cfg(feature = "decode-text")]
if let Codec::Text(charset) = codec
&& codec.name() == "charset"
{
return format!("charset:{}", charset.name().to_ascii_lowercase());
}
codec.name().to_owned()
}
#[cfg(feature = "decode-text")]
const TEXT_STEP: usize = 8192;
#[cfg(feature = "decode-text")]
fn decode_text(
charset: Charset,
input: &[u8],
out: &mut Vec<u8>,
cap: usize,
codec: Codec,
) -> Result<(), ParseError> {
let start = out.len();
let mut transcoder = Transcoder::new(charset, Malformed::Replace);
let mut steps = input.chunks(TEXT_STEP);
let mut next = steps.next();
loop {
let step = next.unwrap_or_default();
next = steps.next();
let last = next.is_none();
if transcoder.push(step, last, out).is_err() {
out.truncate(start);
return Err(malformed(codec));
}
if out.len() - start > cap {
out.truncate(start);
return Err(limit());
}
if last {
return Ok(());
}
}
}
const fn limit() -> ParseError {
ParseError::Limit {
what: "decoded bytes",
}
}
const fn malformed(codec: Codec) -> ParseError {
ParseError::Malformed {
offset: 0,
reason: codec.broken(),
}
}
#[cfg(feature = "decode-zstd")]
fn window_log(cap: usize) -> u32 {
cap.next_power_of_two().trailing_zeros().clamp(10, 31)
}
#[cfg(any(
feature = "decode-gzip",
feature = "decode-zlib",
feature = "decode-zstd",
feature = "decode-snappy"
))]
const FIRST_ROOM_PER_INPUT_BYTE: usize = 4;
#[cfg(any(
feature = "decode-gzip",
feature = "decode-zlib",
feature = "decode-zstd",
feature = "decode-snappy"
))]
fn read_capped(
mut reader: impl Read,
input_len: usize,
out: &mut Vec<u8>,
cap: usize,
codec: Codec,
) -> Result<(), ParseError> {
let start = out.len();
let end = start.saturating_add(cap).saturating_add(1);
let mut len = start;
loop {
if len == out.len() {
let room = (len - start)
.max(input_len.saturating_mul(FIRST_ROOM_PER_INPUT_BYTE))
.max(4096);
let grown = len.saturating_add(room).min(end);
if grown == len {
break;
}
out.reserve_exact(grown - len);
out.resize(grown, 0);
}
match reader.read(&mut out[len..]) {
Ok(0) => break,
Ok(n) => len += n,
Err(_) => {
out.truncate(start);
return Err(malformed(codec));
}
}
}
out.truncate(len);
if len - start > cap {
out.truncate(start);
return Err(limit());
}
Ok(())
}
impl Parser for Decoder {
fn name(&self) -> &str {
&self.name
}
fn tier(&self) -> MatcherTier {
MatcherTier::Fixed
}
fn signature(&self) -> &Signature {
&self.signature
}
fn decodes(&self) -> bool {
true
}
fn parse<'a>(
&self,
input: &'a [u8],
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
let _ = out;
if self.codec.magic().is_some_and(|m| !input.starts_with(m)) {
return Ok(Parsed::NoMatch);
}
let mut bytes = Vec::new();
self.decode(input, &mut bytes)?;
Ok(Parsed::Decoded(Decoded::new(bytes)))
}
}
#[must_use]
#[allow(
unused_mut,
clippy::vec_init_then_push,
reason = "each push sits behind its own feature"
)]
pub fn stock() -> Vec<Decoder> {
let mut all = Vec::new();
#[cfg(feature = "decode-base64")]
{
all.push(Decoder::new(Codec::Base64 {
url_safe: false,
skip_whitespace: false,
}));
all.push(Decoder::new(Codec::Base64 {
url_safe: true,
skip_whitespace: false,
}));
}
#[cfg(feature = "decode-hex")]
all.push(Decoder::new(Codec::Hex));
#[cfg(feature = "decode-gzip")]
all.push(Decoder::new(Codec::Gzip));
#[cfg(feature = "decode-zlib")]
all.push(Decoder::new(Codec::Zlib));
#[cfg(feature = "decode-zstd")]
all.push(Decoder::new(Codec::Zstd));
#[cfg(feature = "decode-snappy")]
{
all.push(Decoder::new(Codec::Snappy));
all.push(Decoder::new(Codec::SnappyRaw));
}
#[cfg(feature = "decode-text")]
{
for charset in [Charset::UTF_8, Charset::UTF_16LE, Charset::UTF_16BE] {
all.push(Decoder::new(Codec::Text(charset)));
}
if let Some(charset) = Charset::for_label("windows-1252") {
all.push(Decoder::new(Codec::Text(charset)));
}
}
#[cfg(feature = "decode-rsyslog")]
all.push(Decoder::new(Codec::Rsyslog {
prefix: b'#',
escaped: Escaped::Controls,
}));
all
}
#[cfg(test)]
#[cfg(any(
feature = "decode-base64",
feature = "decode-hex",
feature = "decode-gzip",
feature = "decode-zlib",
feature = "decode-zstd",
feature = "decode-snappy"
))]
mod tests;
#[cfg(test)]
#[cfg(any(feature = "decode-text", feature = "decode-rsyslog"))]
mod text_tests;