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