use httparse::{EMPTY_HEADER, Header, Request, Response, Status};
use crate::parse::{FieldSink, FieldValue, Hint, ParseError, Parsed, Parser};
use crate::strmatch::Signature;
use crate::tier::MatcherTier;
pub const MAX_HEADERS: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HttpKind {
Message,
Headers,
}
#[derive(Debug, Clone)]
pub struct Http {
kind: HttpKind,
signature: Signature,
}
impl Http {
#[must_use]
pub fn new(kind: HttpKind) -> Self {
let signature = Signature::builder()
.build()
.unwrap_or_else(|_| unreachable!("invariant: an empty signature always builds"));
Self { kind, signature }
}
}
#[must_use]
pub fn body_format(content_type: &[u8]) -> Option<&'static str> {
let essence = content_type
.split(|&b| b == b';')
.next()
.unwrap_or_default()
.trim_ascii();
let essence = String::from_utf8_lossy(essence).to_ascii_lowercase();
let format = match essence.as_str() {
"application/json" | "application/x-ndjson" | "application/jsonl" => "ndjson",
"application/xml" | "text/xml" => "xml",
"text/csv" => "csv",
"application/yaml" | "application/x-yaml" | "text/yaml" => "yaml",
"application/toml" => "toml",
"application/msgpack" | "application/x-msgpack" | "application/vnd.msgpack" => "msgpack",
"application/x-protobuf" | "application/protobuf" => "protobuf",
e if e.ends_with("+json") => "ndjson",
e if e.ends_with("+xml") => "xml",
_ => return None,
};
Some(format)
}
fn opens_http(input: &[u8]) -> bool {
if input.starts_with(b"HTTP/") {
return true;
}
let method = input.iter().take_while(|b| b.is_ascii_uppercase()).count();
method > 0 && input.get(method) == Some(&b' ')
}
const fn malformed(reason: &'static str) -> ParseError {
ParseError::Malformed { offset: 0, reason }
}
const fn http_error(e: httparse::Error) -> ParseError {
match e {
httparse::Error::TooManyHeaders => ParseError::Limit {
what: "more than 128 headers in one message",
},
_ => malformed("an HTTP message or header block that doesn't parse"),
}
}
fn headers<'a>(
list: &[Header<'a>],
out: &mut dyn FieldSink<'a>,
) -> Result<(Option<&'static str>, bool, Option<usize>), ParseError> {
let (mut hint, mut chunked, mut length) = (None, false, None);
out.push_prefix("headers.");
for h in list {
let name = h.name.to_ascii_lowercase();
match name.as_str() {
"content-type" => hint = body_format(h.value),
"transfer-encoding" => {
chunked |= h
.value
.split(|&b| b == b',')
.any(|c| c.trim_ascii().eq_ignore_ascii_case(b"chunked"));
}
"content-length" => {
let n = std::str::from_utf8(h.value.trim_ascii())
.ok()
.and_then(|v| v.parse::<usize>().ok());
match (n, length) {
(Some(n), None) => length = Some(n),
(Some(n), Some(seen)) if n == seen => {}
_ => {
out.pop_prefix();
return Err(malformed("a Content-Length that isn't one number"));
}
}
}
_ => {}
}
out.field(&name, FieldValue::borrowed(h.value, Hint::Text));
}
out.pop_prefix();
Ok((hint, chunked, length))
}
fn body<'a>(
input: &'a [u8],
head: usize,
(hint, chunked, length): (Option<&'static str>, bool, Option<usize>),
out: &mut dyn FieldSink<'a>,
) -> Result<Parsed, ParseError> {
if chunked {
out.field("chunked", FieldValue::borrowed(b"true", Hint::Bool));
return Ok(Parsed::Done);
}
let end = match length {
Some(n) => head
.checked_add(n)
.filter(|&end| end <= input.len())
.ok_or_else(|| malformed("a body shorter than its Content-Length"))?,
None => input.len(),
};
if end == head {
return Ok(Parsed::Done);
}
Ok(Parsed::Body {
span: head..end,
hint,
})
}
fn message<'a>(input: &'a [u8], out: &mut dyn FieldSink<'a>) -> Result<Parsed, ParseError> {
let mut list = [EMPTY_HEADER; MAX_HEADERS];
if input.starts_with(b"HTTP/") {
let mut res = Response::new(&mut list);
let Status::Complete(head) = res.parse(input).map_err(http_error)? else {
return Err(malformed("an HTTP head with no blank line after it"));
};
write_version(res.version, out);
if let Some(code) = res.code {
out.field(
"status",
FieldValue::owned(code.to_string().into_bytes(), Hint::Int),
);
}
if let Some(reason) = res.reason {
out.field(
"reason",
FieldValue::borrowed(reason.as_bytes(), Hint::Text),
);
}
let found = headers(res.headers, out)?;
body(input, head, found, out)
} else {
let mut req = Request::new(&mut list);
let Status::Complete(head) = req.parse(input).map_err(http_error)? else {
return Err(malformed("an HTTP head with no blank line after it"));
};
for (name, value) in [("method", req.method), ("path", req.path)] {
if let Some(value) = value {
out.field(name, FieldValue::borrowed(value.as_bytes(), Hint::Text));
}
}
write_version(req.version, out);
let found = headers(req.headers, out)?;
body(input, head, found, out)
}
}
fn write_version(minor: Option<u8>, out: &mut dyn FieldSink<'_>) {
let version: &'static [u8] = match minor {
Some(0) => b"1.0",
Some(1) => b"1.1",
_ => return,
};
out.field("version", FieldValue::borrowed(version, Hint::Text));
}
fn block<'a>(input: &'a [u8], out: &mut dyn FieldSink<'a>) -> Result<Parsed, ParseError> {
let mut list = [EMPTY_HEADER; MAX_HEADERS];
if let Status::Complete((head, found)) =
httparse::parse_headers(input, &mut list).map_err(http_error)?
{
let found = headers(found, out)?;
return body(input, head, found, out);
}
let mut closed: Vec<u8> = Vec::with_capacity(input.len() + 2);
closed.extend_from_slice(input);
if !input.ends_with(b"\n") {
closed.push(b'\n');
}
closed.push(b'\n');
let mut list = [EMPTY_HEADER; MAX_HEADERS];
let Status::Complete((_, found)) =
httparse::parse_headers(&closed, &mut list).map_err(http_error)?
else {
return Err(malformed("a header block that doesn't end"));
};
let base = closed.as_ptr() as usize;
let lent: Vec<Header<'a>> = found
.iter()
.map(|h| {
let at = h.value.as_ptr() as usize - base;
let end = (at + h.value.len()).min(input.len());
Header {
name: lend_name(input, h.name.as_ptr() as usize - base, h.name.len()),
value: &input[at.min(end)..end],
}
})
.collect();
let found = headers(&lent, out)?;
body(input, input.len(), found, out)
}
fn lend_name(input: &[u8], at: usize, len: usize) -> &str {
input
.get(at..at + len)
.and_then(|n| std::str::from_utf8(n).ok())
.unwrap_or_default()
}
impl Parser for Http {
fn name(&self) -> &'static str {
match self.kind {
HttpKind::Message => "http",
HttpKind::Headers => "headers",
}
}
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> {
if self.kind == HttpKind::Message && !opens_http(input) {
return Ok(Parsed::NoMatch);
}
let mark = out.mark();
let read = match self.kind {
HttpKind::Message => message(input, out),
HttpKind::Headers => block(input, out),
};
if read.is_err() {
out.rollback(mark);
}
read
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use super::*;
use crate::parse::Fields;
fn is_borrowed(v: &FieldValue<'_>) -> bool {
matches!(v.bytes, Cow::Borrowed(_))
}
type Want = Result<
(
&'static [(&'static str, &'static str)],
Option<(&'static str, Option<&'static str>)>,
),
&'static str,
>;
fn read(kind: HttpKind, input: &[u8]) -> (Result<Parsed, ParseError>, Vec<(String, String)>) {
let mut out = Fields::new();
out.push_prefix("outer.");
let got = Http::new(kind).parse(input, &mut out);
out.pop_prefix();
out.field("after", FieldValue::borrowed(b"1", Hint::Int));
let mut rows: Vec<(String, String)> = out
.as_slice()
.iter()
.map(|(n, v)| {
assert!(is_borrowed(v) || n == "outer.status", "{n} copied");
(n.clone(), String::from_utf8_lossy(&v.bytes).into_owned())
})
.collect();
assert_eq!(rows.pop().map(|r| r.0), Some("after".to_owned()));
(got, rows)
}
#[test]
fn messages_write_their_head_and_hand_on_the_body() {
let cases: &[(HttpKind, &[u8], Want)] = &[
(
HttpKind::Message,
b"POST /api/v1?x=1 HTTP/1.1\r\nHost: web01\r\nContent-Type: application/json; charset=utf-8\r\nContent-Length: 7\r\nX-A: 1\r\nx-a: 2\r\n\r\n{\"a\":1}tail",
Ok((
&[
("outer.method", "POST"),
("outer.path", "/api/v1?x=1"),
("outer.version", "1.1"),
("outer.headers.host", "web01"),
("outer.headers.content-type", "application/json; charset=utf-8"),
("outer.headers.content-length", "7"),
("outer.headers.x-a", "1"),
("outer.headers.x-a", "2"),
],
Some(("{\"a\":1}", Some("ndjson"))),
)),
),
(
HttpKind::Message,
b"HTTP/1.0 404 Not Found\nContent-Type: text/xml\n\n<a/>",
Ok((
&[
("outer.version", "1.0"),
("outer.status", "404"),
("outer.reason", "Not Found"),
("outer.headers.content-type", "text/xml"),
],
Some(("<a/>", Some("xml"))),
)),
),
(
HttpKind::Message,
b"GET / HTTP/1.1\r\nHost: h\r\n\r\n",
Ok((
&[("outer.method", "GET"), ("outer.path", "/"), ("outer.version", "1.1"), ("outer.headers.host", "h")],
None,
)),
),
(
HttpKind::Message,
b"HTTP/1.1 200 OK\r\nTransfer-Encoding: gzip, chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n",
Ok((
&[
("outer.version", "1.1"),
("outer.status", "200"),
("outer.reason", "OK"),
("outer.headers.transfer-encoding", "gzip, chunked"),
("outer.chunked", "true"),
],
None,
)),
),
(
HttpKind::Headers,
b"From: a@example.com\r\nSubject: hi\r\nContent-Type: text/csv\r\n\r\na,b\r\n",
Ok((
&[
("outer.headers.from", "a@example.com"),
("outer.headers.subject", "hi"),
("outer.headers.content-type", "text/csv"),
],
Some(("a,b\r\n", Some("csv"))),
)),
),
(
HttpKind::Headers,
b"Received: by mx1\nX-Spam: no",
Ok((&[("outer.headers.received", "by mx1"), ("outer.headers.x-spam", "no")], None)),
),
(HttpKind::Message, b"hello world", Err("no match")),
(HttpKind::Message, b"get / HTTP/1.1\r\n\r\n", Err("no match")),
(HttpKind::Message, b"GET / HTTP/1.1\r\nHost: h\r\n", Err("malformed")),
(HttpKind::Message, b"GET / HTTP/9.9\r\n\r\n", Err("malformed")),
(HttpKind::Message, b"GET / HTTP/1.1\r\nBad Name: x\r\n\r\n", Err("malformed")),
(HttpKind::Message, b"POST / HTTP/1.1\r\nContent-Length: 10\r\n\r\nshort", Err("malformed")),
(HttpKind::Message, b"POST / HTTP/1.1\r\nContent-Length: 1\r\nContent-Length: 2\r\n\r\nab", Err("malformed")),
(HttpKind::Headers, b"Subject: a\r\n folded\r\n\r\n", Err("malformed")),
];
for &(kind, input, want) in cases {
let shown = String::from_utf8_lossy(input);
let (got, rows) = read(kind, input);
match (got, want) {
(Ok(parsed), Ok((fields, body))) => {
let rows: Vec<(&str, &str)> =
rows.iter().map(|(n, v)| (n.as_str(), v.as_str())).collect();
assert_eq!(rows, fields, "{shown}");
let got = match parsed {
Parsed::Body { span, hint } => {
Some((std::str::from_utf8(&input[span]).unwrap(), hint))
}
Parsed::Done => None,
other => panic!("{shown}: {other:?}"),
};
assert_eq!(got, body, "{shown}");
}
(Ok(Parsed::NoMatch), Err("no match"))
| (Err(ParseError::Malformed { .. }), Err("malformed")) => {
assert!(rows.is_empty(), "{shown} wrote {rows:?}");
}
(got, want) => panic!("{shown}: {got:?}, want {want:?}"),
}
}
}
#[test]
fn too_many_headers_is_a_limit() {
let mut msg = b"GET / HTTP/1.1\r\n".to_vec();
for i in 0..=MAX_HEADERS {
msg.extend_from_slice(format!("X-{i}: v\r\n").as_bytes());
}
msg.extend_from_slice(b"\r\n");
let (got, rows) = read(HttpKind::Message, &msg);
assert!(matches!(got, Err(ParseError::Limit { .. })), "{got:?}");
assert_eq!(rows.len(), 0);
}
#[test]
fn content_types_name_the_body_format() {
for (ct, want) in [
(&b"application/json"[..], Some("ndjson")),
(b"Application/Problem+JSON; charset=utf-8", Some("ndjson")),
(b"application/atom+xml", Some("xml")),
(b"application/x-msgpack", Some("msgpack")),
(b"text/plain", None),
(b"", None),
] {
assert_eq!(body_format(ct), want, "{}", String::from_utf8_lossy(ct));
}
}
}