Skip to main content

weida_http_codec/
h1.rs

1//! HTTP/1.1 message syntax (RFC 9112): heads, framing, chunked bodies.
2//!
3//! A head is decoded whole or not at all: [`decode_request`] and
4//! [`decode_response`] first find the empty line that ends it, within
5//! [`Limits::max_head_bytes`], and only then parse, so every proper prefix of
6//! a valid head is [`DecodeError::Incomplete`] and a head that never ends is
7//! [`DecodeError::TooLarge`] once the cap's worth of octets has been searched.
8//!
9//! The body's framing is decided from the head by [`request_framing`] and
10//! [`response_framing`] (RFC 9112 §6.3); a chunked body is decoded step by
11//! step by [`ChunkedDecoder`], which hands out slices of the caller's buffer.
12
13use crate::error::{DecodeError, EncodeError};
14use crate::fields::{Field, is_field_value, is_token, trim_ows};
15use crate::limits::Limits;
16
17/// A decoded request head, borrowing from the input.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct RequestHead<'a> {
20    /// The method, a token, case as written (methods are case-sensitive).
21    pub method: &'a [u8],
22    /// The request target as written: origin, absolute, authority or
23    /// asterisk form (RFC 9112 §3.2).
24    pub target: &'a [u8],
25    /// The minor version: 1 for `HTTP/1.1`, 0 for `HTTP/1.0`.
26    pub minor: u8,
27    /// The field lines in order.
28    pub fields: Vec<Field<'a>>,
29}
30
31/// A decoded response head, borrowing from the input.
32#[derive(Clone, Debug, PartialEq, Eq)]
33pub struct ResponseHead<'a> {
34    /// The minor version: 1 for `HTTP/1.1`, 0 for `HTTP/1.0`.
35    pub minor: u8,
36    /// The status code, `100..=999`.
37    pub status: u16,
38    /// The reason phrase, possibly empty; a client ignores it (RFC 9112 §4).
39    pub reason: &'a [u8],
40    /// The field lines in order.
41    pub fields: Vec<Field<'a>>,
42}
43
44/// How a message body is delimited (RFC 9112 §6.3).
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub enum Framing {
47    /// No body.
48    Empty,
49    /// Exactly this many octets.
50    Length(u64),
51    /// `Transfer-Encoding: chunked`.
52    Chunked,
53    /// Until the connection closes (responses only).
54    UntilClose,
55}
56
57const fn malformed(what: &'static str) -> DecodeError {
58    DecodeError::Malformed { what }
59}
60
61/// Finds the empty line that ends a field section starting at `start`,
62/// searching no further than `cap` octets from `start`. Returns the index just
63/// past it.
64fn find_section_end(
65    input: &[u8],
66    start: usize,
67    cap: usize,
68    what: &'static str,
69) -> Result<usize, DecodeError> {
70    let limit = start.saturating_add(cap).min(input.len());
71    let window = &input[..limit];
72    // The section's first line may itself be empty: `start` is the start of a
73    // line, so treat it as following a line feed.
74    let mut line_start = start;
75    loop {
76        match &window[line_start..] {
77            [b'\n', ..] => return Ok(line_start + 1),
78            [b'\r', b'\n', ..] => return Ok(line_start + 2),
79            _ => {}
80        }
81        match window[line_start..].iter().position(|&b| b == b'\n') {
82            Some(lf) => line_start += lf + 1,
83            None => break,
84        }
85    }
86    if input.len() - start >= cap {
87        Err(DecodeError::TooLarge {
88            what,
89            declared: (input.len() - start) as u64,
90            cap: cap as u64,
91        })
92    } else {
93        Err(DecodeError::Incomplete { needed: 1 })
94    }
95}
96
97/// The lines of `section` without their line endings; a bare LF ends a line
98/// as CRLF does (RFC 9112 §2.2). The final empty line is not yielded.
99fn lines(section: &[u8]) -> impl Iterator<Item = &[u8]> {
100    section
101        .split(|&b| b == b'\n')
102        .map(|line| line.strip_suffix(b"\r").unwrap_or(line))
103        .take_while(|line| !line.is_empty())
104}
105
106/// Parses field lines (RFC 9112 §5) with the rules every section shares.
107fn parse_fields<'a>(
108    lines: impl Iterator<Item = &'a [u8]>,
109    limits: Limits,
110) -> Result<Vec<Field<'a>>, DecodeError> {
111    let mut fields = Vec::new();
112    for line in lines {
113        if matches!(line.first(), Some(b' ' | b'\t')) {
114            return Err(malformed("obsolete line folding"));
115        }
116        let colon = line
117            .iter()
118            .position(|&b| b == b':')
119            .ok_or(malformed("field line without a colon"))?;
120        let name = &line[..colon];
121        if matches!(name.last(), Some(b' ' | b'\t')) {
122            return Err(malformed("whitespace before the colon"));
123        }
124        if !is_token(name) {
125            return Err(malformed("field name"));
126        }
127        let value = trim_ows(&line[colon + 1..]);
128        if !is_field_value(value) {
129            return Err(malformed("field value"));
130        }
131        if fields.len() == limits.max_fields {
132            return Err(DecodeError::TooLarge {
133                what: "field count",
134                declared: fields.len() as u64 + 1,
135                cap: limits.max_fields as u64,
136            });
137        }
138        fields.push(Field { name, value });
139    }
140    Ok(fields)
141}
142
143fn parse_version(v: &[u8]) -> Result<u8, DecodeError> {
144    match v {
145        b"HTTP/1.1" => Ok(1),
146        b"HTTP/1.0" => Ok(0),
147        _ => Err(malformed("version")),
148    }
149}
150
151fn is_visible(b: &[u8]) -> bool {
152    b.iter().all(|c| (0x21..=0x7e).contains(c))
153}
154
155fn is_reason(b: &[u8]) -> bool {
156    b.iter()
157        .all(|&c| c == b' ' || c == b'\t' || (0x21..=0x7e).contains(&c) || c >= 0x80)
158}
159
160/// Decodes a request head. Returns it and the octets it used, the empty line
161/// included; the body, if any, starts there.
162///
163/// Empty lines before the request line are skipped (RFC 9112 §2.2).
164///
165/// # Errors
166///
167/// [`DecodeError::Incomplete`] before the empty line; `TooLarge` `"head"`
168/// when none is found within [`Limits::max_head_bytes`] (leading empty lines
169/// count), `TooLarge` `"field count"` past [`Limits::max_fields`];
170/// `Malformed` naming the rule otherwise (`"version"` for a version other
171/// than HTTP/1.1 and HTTP/1.0).
172pub fn decode_request(
173    input: &[u8],
174    limits: Limits,
175) -> Result<(RequestHead<'_>, usize), DecodeError> {
176    let mut start = 0;
177    loop {
178        if start >= limits.max_head_bytes {
179            return Err(DecodeError::TooLarge {
180                what: "head",
181                declared: input.len() as u64,
182                cap: limits.max_head_bytes as u64,
183            });
184        }
185        match &input[start..] {
186            [b'\r', b'\n', ..] => start += 2,
187            [b'\n', ..] => start += 1,
188            [] | [b'\r'] => return Err(DecodeError::Incomplete { needed: 1 }),
189            _ => break,
190        }
191    }
192    let cap = limits.max_head_bytes.saturating_sub(start);
193    let end = find_section_end(input, start, cap, "head")?;
194    let mut it = lines(&input[start..end]);
195    let line = it.next().ok_or(malformed("request line"))?;
196    let mut parts = line.split(|&b| b == b' ');
197    let (Some(method), Some(target), Some(version), None) =
198        (parts.next(), parts.next(), parts.next(), parts.next())
199    else {
200        return Err(malformed("request line"));
201    };
202    if !is_token(method) {
203        return Err(malformed("method"));
204    }
205    if target.is_empty() || !is_visible(target) {
206        return Err(malformed("request target"));
207    }
208    let minor = parse_version(version)?;
209    let fields = parse_fields(it, limits)?;
210    Ok((
211        RequestHead {
212            method,
213            target,
214            minor,
215            fields,
216        },
217        end,
218    ))
219}
220
221/// Decodes a response head. Returns it and the octets it used.
222///
223/// # Errors
224///
225/// As [`decode_request`], with `"status line"`, `"status"` and
226/// `"reason phrase"` for the first line.
227pub fn decode_response(
228    input: &[u8],
229    limits: Limits,
230) -> Result<(ResponseHead<'_>, usize), DecodeError> {
231    let end = find_section_end(input, 0, limits.max_head_bytes, "head")?;
232    let mut it = lines(&input[..end]);
233    let line = it.next().ok_or(malformed("status line"))?;
234    let sp = line
235        .iter()
236        .position(|&b| b == b' ')
237        .ok_or(malformed("status line"))?;
238    let minor = parse_version(&line[..sp])?;
239    let rest = &line[sp + 1..];
240    let (code, reason) = match rest {
241        [a, b, c] => ([*a, *b, *c], &rest[3..]),
242        [a, b, c, b' ', reason @ ..] => ([*a, *b, *c], reason),
243        _ => return Err(malformed("status")),
244    };
245    if !(b'1'..=b'9').contains(&code[0]) || !code.iter().all(u8::is_ascii_digit) {
246        return Err(malformed("status"));
247    }
248    let status = code
249        .iter()
250        .fold(0u16, |acc, d| acc * 10 + u16::from(d - b'0'));
251    if !is_reason(reason) {
252        return Err(malformed("reason phrase"));
253    }
254    let fields = parse_fields(it, limits)?;
255    Ok((
256        ResponseHead {
257            minor,
258            status,
259            reason,
260            fields,
261        },
262        end,
263    ))
264}
265
266fn values<'a, 'f>(
267    fields: &'f [Field<'a>],
268    name: &'static str,
269) -> impl Iterator<Item = &'a [u8]> + 'f {
270    fields
271        .iter()
272        .filter(move |f| f.name.eq_ignore_ascii_case(name.as_bytes()))
273        .flat_map(|f| f.value.split(|&b| b == b','))
274        .map(trim_ows)
275        .filter(|v| !v.is_empty())
276}
277
278fn has(fields: &[Field<'_>], name: &'static str) -> bool {
279    fields
280        .iter()
281        .any(|f| f.name.eq_ignore_ascii_case(name.as_bytes()))
282}
283
284/// The value of `Content-Length`, if present: a list of equal values is one
285/// value (RFC 9110 §8.6).
286///
287/// # Errors
288///
289/// `Malformed` `"Content-Length"` for a value that is not digits, overflows
290/// `u64`, or differs from another.
291pub fn content_length(fields: &[Field<'_>]) -> Result<Option<u64>, DecodeError> {
292    let mut found = None;
293    let mut present = false;
294    for v in values(fields, "content-length") {
295        present = true;
296        if !v.iter().all(u8::is_ascii_digit) {
297            return Err(malformed("Content-Length"));
298        }
299        let n = v.iter().try_fold(0u64, |acc, d| {
300            acc.checked_mul(10)?.checked_add(u64::from(d - b'0'))
301        });
302        let n = n.ok_or(malformed("Content-Length"))?;
303        match found {
304            None => found = Some(n),
305            Some(m) if m == n => {}
306            Some(_) => return Err(malformed("Content-Length")),
307        }
308    }
309    if present || !has(fields, "content-length") {
310        Ok(found)
311    } else {
312        Err(malformed("Content-Length"))
313    }
314}
315
316/// Whether `Transfer-Encoding` is present; `Ok(true)` only for exactly
317/// `chunked`.
318fn chunked(fields: &[Field<'_>]) -> Result<bool, DecodeError> {
319    if !has(fields, "transfer-encoding") {
320        return Ok(false);
321    }
322    let mut codings = values(fields, "transfer-encoding");
323    match (codings.next(), codings.next()) {
324        (Some(c), None) if c.eq_ignore_ascii_case(b"chunked") => Ok(true),
325        _ => Err(malformed("transfer coding")),
326    }
327}
328
329/// Whether the `Connection` field lists `option`, ignoring ASCII case
330/// (RFC 9110 §7.6.1).
331#[must_use]
332pub fn connection_has(fields: &[Field<'_>], option: &str) -> bool {
333    values(fields, "connection").any(|v| v.eq_ignore_ascii_case(option.as_bytes()))
334}
335
336/// The framing of a request body (RFC 9112 §6.3 rules 3 to 7).
337///
338/// # Errors
339///
340/// `Malformed`: `"both Transfer-Encoding and Content-Length"` (a smuggling
341/// vector a server must not guess at, RFC 9112 §6.1); `"transfer coding"` for
342/// any coding list other than exactly `chunked`; `"Content-Length"`.
343pub fn request_framing(fields: &[Field<'_>]) -> Result<Framing, DecodeError> {
344    if has(fields, "transfer-encoding") && has(fields, "content-length") {
345        return Err(malformed("both Transfer-Encoding and Content-Length"));
346    }
347    if chunked(fields)? {
348        return Ok(Framing::Chunked);
349    }
350    Ok(match content_length(fields)? {
351        Some(n) => Framing::Length(n),
352        None => Framing::Empty,
353    })
354}
355
356/// The framing of a response body (RFC 9112 §6.3 rules 1 to 7), given the
357/// method of the request it answers.
358///
359/// # Errors
360///
361/// `Malformed` `"transfer coding"` or `"Content-Length"`.
362pub fn response_framing(
363    request_method: &[u8],
364    status: u16,
365    fields: &[Field<'_>],
366) -> Result<Framing, DecodeError> {
367    if request_method == b"HEAD" || (100..200).contains(&status) || status == 204 || status == 304 {
368        return Ok(Framing::Empty);
369    }
370    if chunked(fields)? {
371        return Ok(Framing::Chunked);
372    }
373    Ok(match content_length(fields)? {
374        Some(n) => Framing::Length(n),
375        None => Framing::UntilClose,
376    })
377}
378
379/// One step of a chunked body.
380#[derive(Clone, Debug, PartialEq, Eq)]
381pub enum Chunk<'a> {
382    /// Body octets, never empty.
383    Data(&'a [u8]),
384    /// The last chunk and its trailer fields; the body has ended.
385    End(Vec<Field<'a>>),
386}
387
388#[derive(Clone, Copy, Debug, PartialEq, Eq)]
389enum State {
390    Size,
391    Data(u64),
392    DataEnd,
393    Trailers,
394    Done,
395}
396
397/// The state of a chunked body decode (RFC 9112 §7.1).
398///
399/// The decoder owns no buffer: [`ChunkedDecoder::step`] reads the caller's
400/// input and returns slices of it. On an error the state is unchanged, so a
401/// caller that got [`DecodeError::Incomplete`] calls again with more input.
402#[derive(Clone, Debug, PartialEq, Eq)]
403pub struct ChunkedDecoder {
404    state: State,
405}
406
407impl Default for ChunkedDecoder {
408    fn default() -> Self {
409        Self::new()
410    }
411}
412
413impl ChunkedDecoder {
414    /// A decoder at the start of a body.
415    #[must_use]
416    pub const fn new() -> Self {
417        Self { state: State::Size }
418    }
419
420    /// Whether the last chunk and the trailers have been decoded.
421    #[must_use]
422    pub fn is_done(&self) -> bool {
423        self.state == State::Done
424    }
425
426    /// Decodes the next piece of the body from `input`. Returns it and the
427    /// octets it used.
428    ///
429    /// [`Chunk::Data`] is at most the rest of the current chunk that `input`
430    /// holds. Chunk extensions are stepped over but count toward
431    /// [`Limits::max_chunk_line`]; trailers follow the head's field rules and
432    /// [`Limits::max_head_bytes`].
433    ///
434    /// # Errors
435    ///
436    /// `Incomplete`; `TooLarge` `"chunk line"` or `"trailer section"`;
437    /// `Malformed` `"chunk size"`, `"chunk data terminator"`, or a field rule;
438    /// `Malformed` `"chunked body already ended"` after [`Chunk::End`].
439    pub fn step<'a>(
440        &mut self,
441        input: &'a [u8],
442        limits: Limits,
443    ) -> Result<(Chunk<'a>, usize), DecodeError> {
444        let mut pos = 0;
445        let mut state = self.state;
446        loop {
447            match state {
448                State::Size => {
449                    let (size, used) = chunk_size_line(&input[pos..], limits)?;
450                    pos += used;
451                    state = if size == 0 {
452                        State::Trailers
453                    } else {
454                        State::Data(size)
455                    };
456                }
457                State::Data(remaining) => {
458                    let available = input.len() - pos;
459                    if available == 0 {
460                        return Err(DecodeError::Incomplete { needed: 1 });
461                    }
462                    let n = remaining.min(available as u64) as usize;
463                    let data = &input[pos..pos + n];
464                    let left = remaining - n as u64;
465                    self.state = if left == 0 {
466                        State::DataEnd
467                    } else {
468                        State::Data(left)
469                    };
470                    return Ok((Chunk::Data(data), pos + n));
471                }
472                State::DataEnd => {
473                    match &input[pos..] {
474                        [b'\r', b'\n', ..] => pos += 2,
475                        [b'\n', ..] => pos += 1,
476                        [] | [b'\r'] => return Err(DecodeError::Incomplete { needed: 1 }),
477                        _ => return Err(malformed("chunk data terminator")),
478                    }
479                    state = State::Size;
480                }
481                State::Trailers => {
482                    let end =
483                        find_section_end(input, pos, limits.max_head_bytes, "trailer section")?;
484                    let fields = parse_fields(lines(&input[pos..end]), limits)?;
485                    self.state = State::Done;
486                    return Ok((Chunk::End(fields), end));
487                }
488                State::Done => return Err(malformed("chunked body already ended")),
489            }
490        }
491    }
492}
493
494/// `chunk-size [ chunk-ext ] CRLF`: the size and the octets used.
495fn chunk_size_line(input: &[u8], limits: Limits) -> Result<(u64, usize), DecodeError> {
496    let window = &input[..input.len().min(limits.max_chunk_line)];
497    let Some(lf) = window.iter().position(|&b| b == b'\n') else {
498        return if input.len() >= limits.max_chunk_line {
499            Err(DecodeError::TooLarge {
500                what: "chunk line",
501                declared: input.len() as u64,
502                cap: limits.max_chunk_line as u64,
503            })
504        } else {
505            Err(DecodeError::Incomplete { needed: 1 })
506        };
507    };
508    let line = &window[..lf];
509    let line = line.strip_suffix(b"\r").unwrap_or(line);
510    let digits = line.iter().take_while(|b| b.is_ascii_hexdigit()).count();
511    if digits == 0 {
512        return Err(malformed("chunk size"));
513    }
514    let size = line[..digits].iter().try_fold(0u64, |acc, &d| {
515        let v = (d as char).to_digit(16)?;
516        acc.checked_mul(16)?.checked_add(u64::from(v))
517    });
518    let size = size.ok_or(malformed("chunk size"))?;
519    match line.get(digits) {
520        None | Some(b';' | b' ' | b'\t') => Ok((size, lf + 1)),
521        Some(_) => Err(malformed("chunk size")),
522    }
523}
524
525fn check_fields(fields: &[(&[u8], &[u8])]) -> Result<(), EncodeError> {
526    for (name, value) in fields {
527        if !is_token(name) {
528            return Err(EncodeError::InvalidName { what: "field name" });
529        }
530        if !is_field_value(value) {
531            return Err(EncodeError::InvalidValue {
532                what: "field value",
533            });
534        }
535    }
536    Ok(())
537}
538
539fn write_fields(fields: &[(&[u8], &[u8])], out: &mut Vec<u8>) {
540    for (name, value) in fields {
541        out.extend_from_slice(name);
542        out.extend_from_slice(b": ");
543        out.extend_from_slice(value);
544        out.extend_from_slice(b"\r\n");
545    }
546    out.extend_from_slice(b"\r\n");
547}
548
549/// Writes an `HTTP/1.1` request head, the empty line included.
550///
551/// # Errors
552///
553/// `InvalidName` `"method"` or `"field name"`; `InvalidValue`
554/// `"request target"` or `"field value"`. Nothing is written on error.
555pub fn encode_request_head(
556    method: &[u8],
557    target: &[u8],
558    fields: &[(&[u8], &[u8])],
559    out: &mut Vec<u8>,
560) -> Result<(), EncodeError> {
561    if !is_token(method) {
562        return Err(EncodeError::InvalidName { what: "method" });
563    }
564    if target.is_empty() || !is_visible(target) {
565        return Err(EncodeError::InvalidValue {
566            what: "request target",
567        });
568    }
569    check_fields(fields)?;
570    out.extend_from_slice(method);
571    out.push(b' ');
572    out.extend_from_slice(target);
573    out.extend_from_slice(b" HTTP/1.1\r\n");
574    write_fields(fields, out);
575    Ok(())
576}
577
578/// Writes a response head with version `HTTP/1.<minor>`, the empty line
579/// included.
580///
581/// # Errors
582///
583/// `InvalidValue` `"version"` (minor not 0 or 1), `"status"` (outside
584/// `100..=999`), `"reason phrase"`, `"field value"`; `InvalidName`
585/// `"field name"`. Nothing is written on error.
586pub fn encode_response_head(
587    minor: u8,
588    status: u16,
589    reason: &[u8],
590    fields: &[(&[u8], &[u8])],
591    out: &mut Vec<u8>,
592) -> Result<(), EncodeError> {
593    if minor > 1 {
594        return Err(EncodeError::InvalidValue { what: "version" });
595    }
596    if !(100..=999).contains(&status) {
597        return Err(EncodeError::InvalidValue { what: "status" });
598    }
599    if !is_reason(reason) {
600        return Err(EncodeError::InvalidValue {
601            what: "reason phrase",
602        });
603    }
604    check_fields(fields)?;
605    out.extend_from_slice(b"HTTP/1.");
606    out.push(b'0' + minor);
607    out.push(b' ');
608    out.extend_from_slice(status.to_string().as_bytes());
609    out.push(b' ');
610    out.extend_from_slice(reason);
611    out.extend_from_slice(b"\r\n");
612    write_fields(fields, out);
613    Ok(())
614}
615
616/// Writes one chunk: the size in uppercase hex, CRLF, the data, CRLF. Empty
617/// data writes nothing, because a zero-size chunk is the last chunk.
618pub fn encode_chunk(data: &[u8], out: &mut Vec<u8>) {
619    if data.is_empty() {
620        return;
621    }
622    out.extend_from_slice(format!("{:X}\r\n", data.len()).as_bytes());
623    out.extend_from_slice(data);
624    out.extend_from_slice(b"\r\n");
625}
626
627/// Writes the last chunk and the trailer section.
628///
629/// # Errors
630///
631/// As [`encode_request_head`] for the fields. Nothing is written on error.
632pub fn encode_last_chunk(
633    trailers: &[(&[u8], &[u8])],
634    out: &mut Vec<u8>,
635) -> Result<(), EncodeError> {
636    check_fields(trailers)?;
637    out.extend_from_slice(b"0\r\n");
638    write_fields(trailers, out);
639    Ok(())
640}
641
642#[cfg(test)]
643mod tests {
644    use super::*;
645
646    const L: Limits = Limits::DEFAULT;
647
648    #[test]
649    fn a_head_of_exactly_the_cap_is_accepted_and_one_more_is_not() {
650        let head = b"GET / HTTP/1.1\r\nHost: a\r\n\r\n";
651        let limits = Limits {
652            max_head_bytes: head.len(),
653            ..L
654        };
655        assert_eq!(decode_request(head, limits).unwrap().1, head.len());
656        let limits = Limits {
657            max_head_bytes: head.len() - 1,
658            ..L
659        };
660        assert!(matches!(
661            decode_request(head, limits),
662            Err(DecodeError::TooLarge { what: "head", .. })
663        ));
664    }
665
666    #[test]
667    fn leading_empty_lines_before_a_request_are_skipped() {
668        let (head, used) = decode_request(b"\r\n\nGET / HTTP/1.0\r\n\r\nrest", L).unwrap();
669        assert_eq!(head.method, b"GET");
670        assert_eq!(head.minor, 0);
671        assert_eq!(used, 21);
672    }
673
674    #[test]
675    fn a_bare_lf_ends_a_line() {
676        let (head, _) = decode_request(b"GET / HTTP/1.1\nHost: a\n\n", L).unwrap();
677        assert_eq!(
678            head.fields,
679            vec![Field {
680                name: b"Host",
681                value: b"a"
682            }]
683        );
684    }
685
686    #[test]
687    fn a_status_line_may_omit_the_reason() {
688        let (head, _) = decode_response(b"HTTP/1.1 204\r\n\r\n", L).unwrap();
689        assert_eq!(head.status, 204);
690        assert_eq!(head.reason, b"");
691    }
692
693    #[test]
694    fn the_field_count_is_capped() {
695        let limits = Limits { max_fields: 1, ..L };
696        assert!(matches!(
697            decode_request(b"GET / HTTP/1.1\r\na: 1\r\nb: 2\r\n\r\n", limits),
698            Err(DecodeError::TooLarge {
699                what: "field count",
700                declared: 2,
701                cap: 1
702            })
703        ));
704    }
705
706    #[test]
707    fn chunked_data_is_handed_out_as_it_arrives() {
708        let mut d = ChunkedDecoder::new();
709        let input = b"5\r\nhel";
710        let (chunk, used) = d.step(input, L).unwrap();
711        assert_eq!(chunk, Chunk::Data(b"hel"));
712        assert_eq!(used, 6);
713        let (chunk, used) = d.step(b"lo\r\n0\r\n\r\n", L).unwrap();
714        assert_eq!(chunk, Chunk::Data(b"lo"));
715        assert_eq!(used, 2);
716        let (chunk, used) = d.step(b"\r\n0\r\n\r\n", L).unwrap();
717        assert_eq!(chunk, Chunk::End(vec![]));
718        assert_eq!(used, 7);
719        assert!(d.is_done());
720    }
721
722    #[test]
723    fn an_incomplete_step_leaves_the_state_alone() {
724        let mut d = ChunkedDecoder::new();
725        assert_eq!(
726            d.step(b"5\r\n", L),
727            Err(DecodeError::Incomplete { needed: 1 })
728        );
729        assert_eq!(d.step(b"5\r\nab", L).unwrap(), (Chunk::Data(b"ab"), 5));
730    }
731
732    #[test]
733    fn chunk_extensions_are_skipped_but_bounded() {
734        let mut d = ChunkedDecoder::new();
735        let (chunk, _) = d.step(b"1;name=\"v\"\r\nx", L).unwrap();
736        assert_eq!(chunk, Chunk::Data(b"x"));
737        let limits = Limits {
738            max_chunk_line: 8,
739            ..L
740        };
741        assert!(matches!(
742            ChunkedDecoder::new().step(b"1;aaaaaaaaaa\r\nx", limits),
743            Err(DecodeError::TooLarge {
744                what: "chunk line",
745                ..
746            })
747        ));
748    }
749
750    #[test]
751    fn a_chunk_size_beyond_u64_is_malformed() {
752        assert_eq!(
753            ChunkedDecoder::new().step(b"10000000000000000\r\n", L),
754            Err(DecodeError::Malformed { what: "chunk size" })
755        );
756        assert!(
757            ChunkedDecoder::new()
758                .step(b"FFFFFFFFFFFFFFFF\r\nx", L)
759                .is_ok()
760        );
761    }
762
763    #[test]
764    fn content_length_lists_of_equal_values_are_one_value() {
765        let f = [
766            Field {
767                name: b"Content-Length",
768                value: b"5, 5",
769            },
770            Field {
771                name: b"content-length",
772                value: b"5",
773            },
774        ];
775        assert_eq!(request_framing(&f), Ok(Framing::Length(5)));
776        let f = [Field {
777            name: b"Content-Length",
778            value: b"",
779        }];
780        assert_eq!(
781            request_framing(&f),
782            Err(DecodeError::Malformed {
783                what: "Content-Length"
784            })
785        );
786    }
787
788    #[test]
789    fn response_framing_follows_the_method_and_status() {
790        let cl = [Field {
791            name: b"Content-Length",
792            value: b"9",
793        }];
794        assert_eq!(response_framing(b"HEAD", 200, &cl), Ok(Framing::Empty));
795        assert_eq!(response_framing(b"GET", 204, &cl), Ok(Framing::Empty));
796        assert_eq!(response_framing(b"GET", 304, &cl), Ok(Framing::Empty));
797        assert_eq!(response_framing(b"GET", 101, &cl), Ok(Framing::Empty));
798        assert_eq!(response_framing(b"GET", 200, &cl), Ok(Framing::Length(9)));
799        assert_eq!(response_framing(b"GET", 200, &[]), Ok(Framing::UntilClose));
800        let both = [
801            Field {
802                name: b"Transfer-Encoding",
803                value: b"chunked",
804            },
805            Field {
806                name: b"Content-Length",
807                value: b"9",
808            },
809        ];
810        assert_eq!(response_framing(b"GET", 200, &both), Ok(Framing::Chunked));
811    }
812
813    #[test]
814    fn connection_options_are_a_case_insensitive_list() {
815        let f = [Field {
816            name: b"Connection",
817            value: b"keep-alive, Close",
818        }];
819        assert!(connection_has(&f, "close"));
820        assert!(connection_has(&f, "keep-alive"));
821        assert!(!connection_has(&f, "upgrade"));
822    }
823
824    #[test]
825    fn encoders_write_nothing_on_error() {
826        let mut out = b"x".to_vec();
827        assert_eq!(
828            encode_request_head(b"GET", b"/", &[(b"a", b"ok"), (b"b", b"bad\n")], &mut out),
829            Err(EncodeError::InvalidValue {
830                what: "field value"
831            })
832        );
833        assert_eq!(
834            encode_response_head(2, 200, b"OK", &[], &mut out),
835            Err(EncodeError::InvalidValue { what: "version" })
836        );
837        assert_eq!(out, b"x");
838    }
839
840    #[test]
841    fn a_chunk_is_written_in_uppercase_hex() {
842        let mut out = Vec::new();
843        encode_chunk(&[0u8; 26], &mut out);
844        assert!(out.starts_with(b"1A\r\n"));
845        assert!(out.ends_with(b"\r\n"));
846        let before = out.len();
847        encode_chunk(b"", &mut out);
848        assert_eq!(out.len(), before);
849    }
850}