Skip to main content

turnloop_http/
http1.rs

1//! Incremental RFC 9112 framing. The host retains unconsumed input and owns writes.
2//! `Body` borrows input; head/trailer allocations are the returned representation.
3use crate::{Error, Result};
4use std::io::Write;
5
6#[derive(Debug, Clone, Copy)]
7pub struct Limits {
8    pub headers: usize,
9    pub head_bytes: usize,
10    pub line_bytes: usize,
11}
12impl Default for Limits {
13    fn default() -> Self {
14        Self {
15            headers: 128,
16            head_bytes: 32768,
17            line_bytes: 8192,
18        }
19    }
20}
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct Header {
23    pub name: String,
24    pub value: Vec<u8>,
25}
26impl Header {
27    pub fn new(name: &str, value: impl AsRef<[u8]>) -> Self {
28        Self {
29            name: name.to_ascii_lowercase(),
30            value: value.as_ref().to_vec(),
31        }
32    }
33}
34#[derive(Debug, Clone)]
35pub struct Head {
36    pub method: String,
37    pub target: String,
38    pub status: u16,
39    pub version: u8,
40    pub headers: Vec<Header>,
41    pub keep_alive: bool,
42}
43impl Head {
44    pub fn get(&self, name: &str) -> Option<&[u8]> {
45        self.headers
46            .iter()
47            .find(|h| h.name.eq_ignore_ascii_case(name))
48            .map(|h| h.value.as_slice())
49    }
50    /// Every value of a header that may repeat, in wire order. [`get`](Self::get)
51    /// returns only the first line; a list-valued field such as
52    /// `Content-Encoding` needs all of them, for example
53    /// `StreamingDecoder::from_codings(head.values("content-encoding"), limit)`.
54    pub fn values<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a [u8]> + 'a {
55        self.headers
56            .iter()
57            .filter(move |h| h.name.eq_ignore_ascii_case(name))
58            .map(|h| h.value.as_slice())
59    }
60    pub fn token(&self, name: &str, token: &str) -> bool {
61        self.headers
62            .iter()
63            .filter(|h| h.name.eq_ignore_ascii_case(name))
64            .any(|h| tokens(&h.value).any(|t| t.eq_ignore_ascii_case(token.as_bytes())))
65    }
66}
67/// Which side of the connection a [`Decoder`] reads.
68///
69/// The two modes raise the same [`Event`]s, [`Event::Upgrade`] included: a
70/// server decoding an upgrade or CONNECT request sees it just as a client
71/// decoding the `101` or `2xx` does. What differs is who decides. In
72/// [`Mode::Response`] the peer has already switched protocols, so the decoder
73/// is finished with the connection. In [`Mode::Request`] the peer has only
74/// asked, and the host answers.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76pub enum Mode {
77    /// Server side: decode requests.
78    Request,
79    /// Client side: decode responses. Call [`Decoder::response_to`] first.
80    Response,
81}
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83enum State {
84    Head,
85    Fixed(u64),
86    ChunkSize,
87    Chunk(u64),
88    ChunkEnd,
89    Trailers,
90    Eof,
91    End,
92    Done,
93    Upgrade,
94    Failed,
95}
96#[derive(Debug)]
97pub enum Event<'a> {
98    Head(Head),
99    Informational(Head),
100    Body(&'a [u8]),
101    Trailers(Vec<Header>),
102    /// The message is complete. Reads no input: see [`Step`].
103    End,
104    /// The message is complete, and it leaves HTTP/1 or asks to. Raised
105    /// *instead of* [`Event::End`], with `consumed == 0`, as the last event of
106    /// the message. Every byte after it belongs to the next protocol, so the
107    /// host takes its retained input along.
108    ///
109    /// Both [`Mode`]s raise it:
110    ///
111    /// * [`Mode::Response`]: a `101 Switching Protocols`, or a `2xx` answer to a
112    ///   request passed to [`Decoder::response_to`] as `CONNECT`. The switch has
113    ///   happened, so the decoder is never [`reusable`](Decoder::reusable)
114    ///   afterwards.
115    /// * [`Mode::Request`]: an HTTP/1.1 request with an `Upgrade` header and
116    ///   the `upgrade` token in `Connection` (RFC 9110 section 7.8), or any
117    ///   `CONNECT` request. It follows the request body, if there is one. The
118    ///   switch has **not** happened: answering `101` (or `2xx` for CONNECT) is
119    ///   the host's decision. A host that accepts stops feeding this decoder.
120    ///   A host that declines sends an ordinary response and may carry on: the
121    ///   decoder is [`reusable`](Decoder::reusable) on the same terms as after
122    ///   [`Event::End`], and [`Decoder::reset`] resumes HTTP/1.
123    ///
124    /// An `Upgrade` header on an HTTP/1.0 request is ignored, as RFC 9110
125    /// section 7.8 requires, and that request ends with [`Event::End`].
126    Upgrade,
127}
128/// One decode step: how much of `input` was consumed, and the event it
129/// produced, if any. See the [step contract](crate#the-step-contract).
130///
131/// **`consumed` and `event` are independent.** All four shapes occur:
132///
133/// | `consumed` | `event` | meaning |
134/// |---|---|---|
135/// | `0` | `None` | **stop.** More input is needed - or the message is over and the decoder is done; the step does not say which. |
136/// | `> 0` | `None` | **keep going.** A chunk-size line, a chunk CRLF or an empty trailer block: progress with nothing for the host. |
137/// | `> 0` | `Some` | an event. |
138/// | `0` | `Some` | an event that reads no input: [`Event::End`] and [`Event::Upgrade`] both arrive this way. |
139///
140/// So the loop condition is `consumed > 0 || event.is_some()`, and a host that
141/// stops on either zero alone is wrong in one of the two directions:
142///
143/// ```
144/// # use turnloop_http::http1::{Decoder, Event, Mode};
145/// # let mut decoder = Decoder::new(Mode::Response, Default::default());
146/// # decoder.response_to("GET");
147/// # let mut input = b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nhi".to_vec();
148/// let mut ended = false;
149/// loop {
150///     let step = decoder.receive(&input)?;
151///     let consumed = step.consumed;
152///     let progressed = consumed > 0 || step.event.is_some();
153///     // Body borrows `input`, so handle the event before draining.
154///     ended |= matches!(step.event, Some(Event::End));
155///     input.drain(..consumed);
156///     if !progressed {
157///         break; // read more bytes from the transport, then continue
158///     }
159/// }
160/// // `End` came from a step after the last byte was consumed.
161/// assert!(ended && input.is_empty() && decoder.reusable());
162/// # Ok::<(), turnloop_http::Error>(())
163/// ```
164///
165/// **The zero-consumption event is the trap.** The step that consumes the last
166/// byte of a message does not carry `End`; the *next* call does, and it reads
167/// nothing. A host that loops while it has input - or stops when a step
168/// consumed nothing - never makes that call, and the finished message sits in
169/// the decoder until the peer's idle timeout closes the connection.
170/// [`Decoder::wants_step`] names the pending call for a host that keys its
171/// loop on input rather than on steps.
172#[derive(Debug)]
173pub struct Step<'a> {
174    pub consumed: usize,
175    pub event: Option<Event<'a>>,
176}
177#[derive(Debug)]
178pub struct Decoder {
179    mode: Mode,
180    limits: Limits,
181    state: State,
182    head_request: bool,
183    connect_request: bool,
184    keep_alive: bool,
185    /// The request being read asks to leave HTTP/1, so it ends in `Upgrade`.
186    upgrade_request: bool,
187}
188fn invalid(message: &'static str) -> Error {
189    Error::new("HPE_INVALID_HEADER_TOKEN", message)
190}
191fn tokens(v: &[u8]) -> impl Iterator<Item = &[u8]> {
192    v.split(|b| *b == b',').map(trim)
193}
194fn trim(v: &[u8]) -> &[u8] {
195    v.trim_ascii()
196}
197fn boundary(input: &[u8]) -> Option<usize> {
198    input
199        .windows(4)
200        .position(|b| b == b"\r\n\r\n")
201        .map(|n| n + 4)
202}
203fn lines_valid(input: &[u8], max: usize) -> Result<()> {
204    let mut start = 0;
205    for (i, b) in input.iter().enumerate() {
206        if *b == b'\n' {
207            if i == 0 || input[i - 1] != b'\r' {
208                return Err(invalid("bare LF"));
209            }
210            if i - start > max {
211                return Err(Error::new("HPE_HEADER_OVERFLOW", "line limit"));
212            }
213            start = i + 1;
214        } else if *b == b'\r' && i + 1 < input.len() && input[i + 1] != b'\n' {
215            return Err(invalid("bare CR"));
216        }
217    }
218    if input.len() - start > max {
219        return Err(Error::new("HPE_HEADER_OVERFLOW", "line limit"));
220    }
221    Ok(())
222}
223fn headers(raw: &[httparse::Header<'_>], limits: Limits) -> Result<Vec<Header>> {
224    if raw.len() > limits.headers {
225        return Err(Error::new("HPE_HEADER_OVERFLOW", "header count limit"));
226    }
227    Ok(raw.iter().map(|h| Header::new(h.name, h.value)).collect())
228}
229fn lengths(head: &Head) -> Result<(Option<u64>, bool)> {
230    let mut cl = None;
231    let mut te = false;
232    for h in &head.headers {
233        if h.name.eq_ignore_ascii_case("content-length") {
234            // Deliberately reject even identical duplicates: no downstream ambiguity.
235            if cl.is_some() || h.value.is_empty() || !h.value.iter().all(u8::is_ascii_digit) {
236                return Err(Error::new(
237                    "HPE_UNEXPECTED_CONTENT_LENGTH",
238                    "invalid or duplicate content-length",
239                ));
240            }
241            cl = Some(
242                h.value
243                    .iter()
244                    .try_fold(0u64, |n, b| {
245                        n.checked_mul(10)?.checked_add((b - b'0') as u64)
246                    })
247                    .ok_or(invalid("content-length overflow"))?,
248            );
249        }
250        if h.name.eq_ignore_ascii_case("transfer-encoding") {
251            if te || !h.value.eq_ignore_ascii_case(b"chunked") {
252                return Err(Error::new(
253                    "HPE_INVALID_TRANSFER_ENCODING",
254                    "unsupported or duplicate transfer coding",
255                ));
256            }
257            te = true;
258        }
259    }
260    if cl.is_some() && te {
261        return Err(Error::new(
262            "HPE_UNEXPECTED_CONTENT_LENGTH",
263            "transfer-encoding with content-length",
264        ));
265    }
266    if te && head.version == 0 {
267        return Err(invalid("transfer-encoding on HTTP/1.0"));
268    }
269    Ok((cl, te))
270}
271impl Decoder {
272    pub fn new(mode: Mode, limits: Limits) -> Self {
273        Self {
274            mode,
275            limits,
276            state: State::Head,
277            head_request: false,
278            connect_request: false,
279            keep_alive: false,
280            upgrade_request: false,
281        }
282    }
283    /// Must precede response parsing. Pipelining is intentionally not provided.
284    pub fn response_to(&mut self, method: &str) {
285        self.head_request = method == "HEAD";
286        self.connect_request = method == "CONNECT";
287    }
288    pub fn reusable(&self) -> bool {
289        self.state == State::Done && self.keep_alive
290    }
291    /// True when the decoder holds an event that reads no input, so the host
292    /// must call [`receive`](Self::receive) again even with nothing new to feed
293    /// it - an empty slice will do. That event is [`Event::End`] or
294    /// [`Event::Upgrade`]. It becomes pending when the last body byte, the
295    /// final chunk or the head of a bodiless message is consumed, and after
296    /// [`eof`](Self::eof) ends a close-delimited body.
297    ///
298    /// This is the signal a host that drives on "bytes to feed" is missing.
299    /// Such a host stops once its buffer is empty and never sees `End`: the
300    /// message sits finished inside the decoder, the connection is not
301    /// [`reusable`](Self::reusable), and only the peer's idle timeout ends the
302    /// exchange. Loop while `!input.is_empty() || decoder.wants_step()`, or use
303    /// the [`Step`] contract's condition, which covers the same case.
304    pub fn wants_step(&self) -> bool {
305        matches!(self.state, State::End | State::Upgrade)
306    }
307    /// True between a message's [`Event::Head`] and the point its end is
308    /// reached: the body, chunk framing or trailers are still being read. False
309    /// before the head (including after an [`Event::Informational`], which is
310    /// not the message), once `End` or `Upgrade` is owed or delivered, and after
311    /// a failure. Bytes of a head the host has buffered but not yet completed
312    /// are the host's to know; the decoder has not accepted them.
313    ///
314    /// A close-delimited body is mid-message too, though EOF is its legal end:
315    /// ask [`eof_is_clean`](Self::eof_is_clean) to tell the two apart.
316    pub fn is_mid_message(&self) -> bool {
317        matches!(
318            self.state,
319            State::Fixed(_)
320                | State::ChunkSize
321                | State::Chunk(_)
322                | State::ChunkEnd
323                | State::Trailers
324                | State::Eof
325        )
326    }
327    /// Whether the transport ending now would be a clean end rather than a
328    /// truncation: exactly the cases in which [`eof`](Self::eof) returns `Ok`,
329    /// answered without changing any state. True inside a close-delimited body
330    /// and once the message is complete; false inside a framed body, before a
331    /// head arrives and after a failure. So a host whose read returned zero can
332    /// choose what to do - retry, fail with its own diagnosis, log - before it
333    /// commits to `eof`.
334    ///
335    /// Before a head is always "not clean" here, because a client that sees EOF
336    /// there got no response. A server whose connection closes while idle
337    /// between requests (with no buffered head bytes) treats that as an
338    /// ordinary close on its own.
339    pub fn eof_is_clean(&self) -> bool {
340        matches!(self.state, State::Eof | State::End | State::Done)
341    }
342    pub fn reset(&mut self) -> Result<()> {
343        if !self.reusable() {
344            return Err(invalid("connection is not reusable"));
345        }
346        self.state = State::Head;
347        Ok(())
348    }
349    pub fn receive<'a>(&mut self, input: &'a [u8]) -> Result<Step<'a>> {
350        let result = self.receive_inner(input);
351        if result.is_err() {
352            self.state = State::Failed;
353        }
354        result
355    }
356    fn receive_inner<'a>(&mut self, input: &'a [u8]) -> Result<Step<'a>> {
357        let mut step = Step {
358            consumed: 0,
359            event: None,
360        };
361        match self.state {
362            State::Head => {
363                let end = boundary(input);
364                let n = end.unwrap_or(input.len());
365                if n > self.limits.head_bytes {
366                    return Err(Error::new("HPE_HEADER_OVERFLOW", "head size limit"));
367                }
368                lines_valid(&input[..n], self.limits.line_bytes)?;
369                let Some(end) = end else { return Ok(step) };
370                let mut slots = [httparse::EMPTY_HEADER; 256];
371                let mut head = if self.mode == Mode::Response {
372                    let mut parsed = httparse::Response::new(&mut slots);
373                    parsed
374                        .parse(&input[..end])
375                        .map_err(|_| invalid("invalid response head"))?;
376                    Head {
377                        method: String::new(),
378                        target: String::new(),
379                        status: parsed.code.ok_or(invalid("missing status"))?,
380                        version: parsed.version.unwrap_or(1),
381                        headers: headers(parsed.headers, self.limits)?,
382                        keep_alive: false,
383                    }
384                } else {
385                    let mut parsed = httparse::Request::new(&mut slots);
386                    parsed
387                        .parse(&input[..end])
388                        .map_err(|_| invalid("invalid request head"))?;
389                    Head {
390                        method: parsed.method.ok_or(invalid("missing method"))?.into(),
391                        target: parsed.path.ok_or(invalid("missing target"))?.into(),
392                        status: 0,
393                        version: parsed.version.unwrap_or(1),
394                        headers: headers(parsed.headers, self.limits)?,
395                        keep_alive: false,
396                    }
397                };
398                if self.mode == Mode::Request
399                    && head.version == 1
400                    && (head.headers.iter().filter(|h| h.name == "host").count() != 1
401                        || head.get("host").is_none_or(|v| v.is_empty()))
402                {
403                    return Err(invalid("HTTP/1.1 requires exactly one Host"));
404                }
405                // RFC 9112 6.3: successful CONNECT starts a tunnel regardless of
406                // message framing fields in its response.
407                let (cl, te) = if self.mode == Mode::Response
408                    && self.connect_request
409                    && (200..300).contains(&head.status)
410                {
411                    (None, false)
412                } else {
413                    lengths(&head)?
414                };
415                head.keep_alive = !head.token("connection", "close")
416                    && (head.version == 1 || head.token("connection", "keep-alive"));
417                self.keep_alive = head.keep_alive;
418                // RFC 9110 7.8: an Upgrade in an HTTP/1.0 request is ignored.
419                self.upgrade_request = self.mode == Mode::Request
420                    && (head.method == "CONNECT"
421                        || (head.version == 1
422                            && head.get("upgrade").is_some()
423                            && head.token("connection", "upgrade")));
424                step.consumed = end;
425                if self.mode == Mode::Response
426                    && (100..200).contains(&head.status)
427                    && head.status != 101
428                {
429                    if cl.is_some() || te {
430                        return Err(invalid("informational response has body framing"));
431                    }
432                    step.event = Some(Event::Informational(head));
433                    return Ok(step);
434                }
435                self.state = if self.mode == Mode::Response
436                    && (head.status == 101
437                        || (self.connect_request && (200..300).contains(&head.status)))
438                {
439                    self.keep_alive = false;
440                    State::Upgrade
441                } else if self.mode == Mode::Response
442                    && (self.head_request || head.status == 204 || head.status == 304)
443                {
444                    State::End
445                } else if te {
446                    State::ChunkSize
447                } else if let Some(n) = cl {
448                    if n == 0 { State::End } else { State::Fixed(n) }
449                } else if self.mode == Mode::Request {
450                    State::End
451                } else {
452                    self.keep_alive = false;
453                    State::Eof
454                };
455                if self.mode == Mode::Response && head.status == 204 && (cl.is_some() || te) {
456                    return Err(invalid("204 has body framing"));
457                }
458                step.event = Some(Event::Head(head));
459            }
460            State::Fixed(left) | State::Chunk(left) => {
461                let n = input.len().min(usize::try_from(left).unwrap_or(usize::MAX));
462                if n > 0 {
463                    step.consumed = n;
464                    step.event = Some(Event::Body(&input[..n]));
465                    self.state = match self.state {
466                        State::Fixed(_) => {
467                            if left == n as u64 {
468                                State::End
469                            } else {
470                                State::Fixed(left - n as u64)
471                            }
472                        }
473                        _ => {
474                            if left == n as u64 {
475                                State::ChunkEnd
476                            } else {
477                                State::Chunk(left - n as u64)
478                            }
479                        }
480                    };
481                }
482            }
483            State::ChunkSize => {
484                let end = input.windows(2).position(|w| w == b"\r\n");
485                let n = end.unwrap_or(input.len());
486                if n > self.limits.line_bytes {
487                    return Err(invalid("chunk line limit"));
488                }
489                let Some(n) = end else { return Ok(step) };
490                let digits = input[..n].split(|b| *b == b';').next().unwrap();
491                if digits.is_empty() || !digits.iter().all(u8::is_ascii_hexdigit) {
492                    return Err(invalid("invalid chunk size"));
493                }
494                if input[..n].iter().any(|b| *b < 32 || *b == 127) {
495                    return Err(invalid("invalid chunk extension"));
496                }
497                let size = digits
498                    .iter()
499                    .try_fold(0u64, |v, b| {
500                        v.checked_mul(16)?
501                            .checked_add((*b as char).to_digit(16)? as u64)
502                    })
503                    .ok_or(invalid("chunk overflow"))?;
504                self.state = if size == 0 {
505                    State::Trailers
506                } else {
507                    State::Chunk(size)
508                };
509                step.consumed = n + 2;
510            }
511            State::ChunkEnd => {
512                if input.len() >= 2 {
513                    if &input[..2] != b"\r\n" {
514                        return Err(invalid("missing chunk CRLF"));
515                    }
516                    step.consumed = 2;
517                    self.state = State::ChunkSize;
518                }
519            }
520            State::Trailers => {
521                if input.starts_with(b"\r\n") {
522                    step.consumed = 2;
523                    self.state = State::End;
524                    return Ok(step);
525                }
526                let end = boundary(input);
527                let n = end.unwrap_or(input.len());
528                if n > self.limits.head_bytes {
529                    return Err(invalid("trailer size limit"));
530                }
531                lines_valid(&input[..n], self.limits.line_bytes)?;
532                let Some(n) = end else { return Ok(step) };
533                let mut slots = [httparse::EMPTY_HEADER; 256];
534                let httparse::Status::Complete((_, raw)) =
535                    httparse::parse_headers(&input[..n], &mut slots)
536                        .map_err(|_| invalid("invalid trailers"))?
537                else {
538                    return Err(invalid("incomplete trailers"));
539                };
540                let trailers = headers(raw, self.limits)?;
541                if trailers.iter().any(|h| {
542                    matches!(
543                        h.name.as_str(),
544                        "content-length"
545                            | "transfer-encoding"
546                            | "host"
547                            | "connection"
548                            | "trailer"
549                            | "upgrade"
550                    )
551                }) {
552                    return Err(invalid("forbidden trailer"));
553                }
554                step.consumed = n;
555                step.event = Some(Event::Trailers(trailers));
556                self.state = State::End;
557            }
558            State::Eof => {
559                if !input.is_empty() {
560                    step.consumed = input.len();
561                    step.event = Some(Event::Body(input));
562                }
563            }
564            State::End => {
565                self.state = State::Done;
566                step.event = Some(if self.upgrade_request {
567                    Event::Upgrade
568                } else {
569                    Event::End
570                });
571            }
572            State::Upgrade => {
573                self.state = State::Done;
574                step.event = Some(Event::Upgrade);
575            }
576            State::Done => {}
577            State::Failed => return Err(invalid("failed connection")),
578        }
579        Ok(step)
580    }
581    /// Declare the end of input. Ends a close-delimited body (leaving
582    /// [`Event::End`] owed, see [`wants_step`](Self::wants_step)); anywhere
583    /// [`eof_is_clean`](Self::eof_is_clean) is false it fails the decoder.
584    pub fn eof(&mut self) -> Result<()> {
585        if !self.eof_is_clean() {
586            self.state = State::Failed;
587            return Err(Error::new("UND_ERR_SOCKET", "unexpected EOF"));
588        }
589        if self.state == State::Eof {
590            self.state = State::End;
591        }
592        Ok(())
593    }
594}
595/// How the body after an encoded head is framed.
596#[derive(Debug, Clone, Copy)]
597pub enum BodyLength {
598    /// No body. A `Content-Length` in the head, if any, must be `0`.
599    Empty,
600    /// Exactly this many bytes, framed by `Content-Length`.
601    Known(u64),
602    /// `Transfer-Encoding: chunked`; the only framing that carries trailers.
603    Chunked,
604    /// Responses only: no framing, the body ends when the connection closes
605    /// (RFC 9112 section 6.3, rule 8). The head must carry neither
606    /// `Content-Length` nor `Transfer-Encoding`, and after
607    /// [`finish`](Encoder::finish) the host closes the connection - that close
608    /// *is* the end of the body. Adding `connection: close` is the host's
609    /// choice; the peer reads to EOF either way.
610    CloseDelimited,
611    /// Responses only: the head's framing headers are sent exactly as given,
612    /// and no body follows them. This is a response to HEAD, which advertises
613    /// the `Content-Length` (or chunked coding) it *would* have sent, and a
614    /// `304`, which may do the same. A `204` or `1xx` may not advertise a length
615    /// at all (RFC 9110 sections 8.6 and 15.2), so either header is refused
616    /// there. The encoder cannot see the request method, so a HEAD response is
617    /// the host's word. No framing header is added, and [`body`](Encoder::body)
618    /// accepts only empty slices.
619    Omitted,
620}
621/// Caller-owned wire buffer, reused across commands. No body buffering.
622pub struct Encoder {
623    left: BodyLength,
624    finished: bool,
625}
626impl Encoder {
627    /// Encode a head. A response's status line uses the canonical reason
628    /// phrase; [`start_with_reason`](Self::start_with_reason) sets another one.
629    pub fn start(head: &Head, body: BodyLength, out: &mut Vec<u8>) -> Result<Self> {
630        Self::encode(head, None, body, out)
631    }
632    /// Encode a response head with a custom reason phrase, as Node's
633    /// `res.writeHead(404, "Nope")` puts `HTTP/1.1 404 Nope` on the wire. The
634    /// phrase may be empty, and may hold spaces, tabs, visible ASCII and
635    /// obs-text (RFC 9112 section 4); a request head or a control character is
636    /// refused before anything is written.
637    pub fn start_with_reason(
638        head: &Head,
639        reason: &str,
640        body: BodyLength,
641        out: &mut Vec<u8>,
642    ) -> Result<Self> {
643        if head.status == 0 {
644            return Err(invalid("reason phrase on a request"));
645        }
646        if reason.bytes().any(|b| (b < 32 && b != b'\t') || b == 127) {
647            return Err(invalid("invalid reason phrase"));
648        }
649        Self::encode(head, Some(reason), body, out)
650    }
651    fn encode(
652        head: &Head,
653        reason: Option<&str>,
654        body: BodyLength,
655        out: &mut Vec<u8>,
656    ) -> Result<Self> {
657        // Validate everything before mutating the output.
658        for h in &head.headers {
659            validate_field(h)?;
660        }
661        let (cl, te) = lengths(head)?;
662        let conflict = match body {
663            BodyLength::Known(n) => te || cl.is_some_and(|cl| cl != n),
664            BodyLength::Empty => te || cl.is_some_and(|cl| cl != 0),
665            BodyLength::Chunked => cl.is_some(),
666            BodyLength::CloseDelimited => te || cl.is_some(),
667            BodyLength::Omitted => {
668                (cl.is_some() || te) && (head.status < 200 || head.status == 204)
669            }
670        };
671        if conflict {
672            return Err(invalid("body length conflicts with headers"));
673        }
674        let response_only = matches!(body, BodyLength::CloseDelimited | BodyLength::Omitted);
675        if response_only && head.status == 0 {
676            return Err(invalid("body length is only valid for a response"));
677        }
678        if matches!(body, BodyLength::CloseDelimited)
679            && (head.status < 200 || matches!(head.status, 204 | 304))
680        {
681            return Err(invalid("status forbids a body"));
682        }
683        if head.status == 0 {
684            if !valid_token(head.method.as_bytes()) {
685                return Err(invalid("invalid method"));
686            }
687            if head.target.is_empty() || head.target.bytes().any(|b| b <= 32 || b == 127) {
688                return Err(invalid("invalid request target"));
689            }
690            write!(out, "{} {} HTTP/1.1\r\n", head.method, head.target).unwrap();
691        } else {
692            let status =
693                http::StatusCode::from_u16(head.status).map_err(|_| invalid("invalid status"))?;
694            let reason = reason.unwrap_or(status.canonical_reason().unwrap_or(""));
695            write!(out, "HTTP/1.1 {} {reason}\r\n", head.status).unwrap();
696        }
697        for h in &head.headers {
698            out.extend_from_slice(h.name.as_bytes());
699            out.extend_from_slice(b": ");
700            out.extend_from_slice(&h.value);
701            out.extend_from_slice(b"\r\n");
702        }
703        if cl.is_none() && !te {
704            match body {
705                BodyLength::Known(n) => write!(out, "content-length: {n}\r\n").unwrap(),
706                BodyLength::Chunked => out.extend_from_slice(b"transfer-encoding: chunked\r\n"),
707                BodyLength::Empty | BodyLength::CloseDelimited | BodyLength::Omitted => {}
708            }
709        }
710        out.extend_from_slice(b"\r\n");
711        Ok(Self {
712            left: body,
713            finished: false,
714        })
715    }
716    pub fn body(&mut self, bytes: &[u8], out: &mut Vec<u8>) -> Result<()> {
717        if self.finished {
718            return Err(invalid("body already finished"));
719        }
720        match self.left {
721            BodyLength::Empty | BodyLength::Omitted => {
722                if !bytes.is_empty() {
723                    return Err(invalid("unexpected body"));
724                }
725            }
726            BodyLength::CloseDelimited => out.extend_from_slice(bytes),
727            BodyLength::Known(n) => {
728                if bytes.len() as u64 > n {
729                    return Err(invalid("body exceeds content-length"));
730                }
731                out.extend_from_slice(bytes);
732                self.left = BodyLength::Known(n - bytes.len() as u64);
733            }
734            BodyLength::Chunked => {
735                if !bytes.is_empty() {
736                    write!(out, "{:x}\r\n", bytes.len()).unwrap();
737                    out.extend_from_slice(bytes);
738                    out.extend_from_slice(b"\r\n");
739                }
740            }
741        }
742        Ok(())
743    }
744    pub fn finish(&mut self, trailers: &[Header], out: &mut Vec<u8>) -> Result<()> {
745        if self.finished || matches!(self.left, BodyLength::Known(1..)) {
746            return Err(invalid("incomplete or already finished body"));
747        }
748        if !trailers.is_empty() && !matches!(self.left, BodyLength::Chunked) {
749            return Err(invalid("trailers require chunked body"));
750        }
751        for h in trailers {
752            if matches!(
753                h.name.as_str(),
754                "content-length"
755                    | "transfer-encoding"
756                    | "host"
757                    | "connection"
758                    | "trailer"
759                    | "upgrade"
760            ) {
761                return Err(invalid("forbidden trailer"));
762            }
763            validate_field(h)?;
764        }
765        if matches!(self.left, BodyLength::Chunked) {
766            out.extend_from_slice(b"0\r\n");
767            for h in trailers {
768                out.extend_from_slice(h.name.as_bytes());
769                out.extend_from_slice(b": ");
770                out.extend_from_slice(&h.value);
771                out.extend_from_slice(b"\r\n");
772            }
773            out.extend_from_slice(b"\r\n");
774        }
775        self.finished = true;
776        Ok(())
777    }
778}
779
780/// RFC token grammar, shared with HPACK field validation without temporary types.
781pub(crate) fn valid_token(value: &[u8]) -> bool {
782    !value.is_empty()
783        && value
784            .iter()
785            .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(b))
786}
787fn validate_field(h: &Header) -> Result<()> {
788    if !valid_token(h.name.as_bytes())
789        || h.value
790            .iter()
791            .any(|b| (*b < 32 && *b != b'\t') || *b == 127)
792    {
793        return Err(invalid("invalid header field"));
794    }
795    Ok(())
796}