use crate::parse::{DECODE_MAX_BYTES, Decoded, FieldSink, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
#[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,
}
impl Codec {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
#[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",
}
}
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: codec.name().to_owned(),
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))
}
}
}
}
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));
}
all
}
#[cfg(test)]
mod tests;