grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// Project:   grippo
// File:      src/format/http.rs
// Purpose:   HTTP/1.x messages and RFC 822 header blocks: headers as fields, the body handed on
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! HTTP/1.x messages and RFC 822 header blocks, read with httparse.
//!
//! A message is an envelope: its start line and headers are fields, and its
//! body goes on to the next hop as [`Parsed::Body`], hinted with the format
//! its `Content-Type` names.
//!
//! - A request writes `method`, `path` and `version`, a response `version`,
//!   `status` and `reason`. Each header writes `headers.<name>`, the name in
//!   lower case, its value borrowed. A repeated header writes again.
//! - `Content-Length` bounds the body. One longer than the input is
//!   `Malformed`. With no length the body runs to the end of the input.
//! - A chunked body can't be handed on as one span: the headers are written,
//!   `chunked` is `true`, and the parser returns [`Parsed::Done`].
//! - `headers` reads a header block alone, a blank line or the end of the
//!   input closing it. A folded header line is `Malformed`.
//!
//! httparse is SIMD-tuned and well used, so grippo keeps no header scanner of
//! its own: headers are an envelope, read once a message.

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;

/// Most headers one message may hold.
pub const MAX_HEADERS: usize = 128;

/// What an [`Http`] parser reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum HttpKind {
    /// An HTTP/1.x request or response, registered as `http`.
    Message,
    /// A header block alone, registered as `headers`.
    Headers,
}

/// The HTTP message parser.
#[derive(Debug, Clone)]
pub struct Http {
    kind: HttpKind,
    signature: Signature,
}

impl Http {
    /// A parser for `kind`.
    ///
    /// # Panics
    ///
    /// Never: an empty signature always builds.
    #[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 }
    }
}

/// The grippo parser for a body of media type `content_type`, when it is one
/// a layer reads.
#[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)
}

/// Whether `input` opens as an HTTP/1.x message: `HTTP/` for a response, or
/// a method of capitals and a space for a request.
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"),
    }
}

/// Write each header under `headers.`, returning the body's hint and whether
/// it is chunked, and its declared length.
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))
}

/// The body after the head of `head` bytes, as [`Parsed`].
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));
}

/// A header block alone. One the input ends without a blank line after is
/// read from a copy with the blank line added, its values still borrowed
/// from the input at the same offsets.
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)
}

/// The header name at `at`, read back from the input.
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;

    /// Whether a value was lent by the input or copied.
    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));
        }
    }
}