Skip to main content

blazingly_wire/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Framework-independent HTTP/1 parsing and response framing.
4//!
5//! This crate owns no socket runtime and has no dependency on Blazingly
6//! contracts, routing, execution, `OpenAPI`, or `MCP`. Adapters provide bytes and
7//! choose how reads, writes, scheduling, and application dispatch happen.
8
9use std::fmt;
10use std::io;
11
12pub const DEFAULT_MAX_BODY_BYTES: usize = 1024 * 1024;
13pub const DEFAULT_MAX_HEADER_BYTES: usize = 32 * 1024;
14pub const DEFAULT_MAX_HEADERS: usize = 64;
15pub const DEFAULT_MAX_CHUNKS: usize = 8 * 1024;
16pub const MAX_HEADER_CAPACITY: usize = 128;
17const INLINE_REQUEST_HEADERS: usize = 16;
18
19/// Limits enforced while decoding one HTTP/1 request.
20#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21pub struct Limits {
22    header_bytes: usize,
23    headers: usize,
24    body_bytes: usize,
25    chunks: usize,
26}
27
28impl Limits {
29    #[must_use]
30    pub const fn new() -> Self {
31        Self {
32            header_bytes: DEFAULT_MAX_HEADER_BYTES,
33            headers: DEFAULT_MAX_HEADERS,
34            body_bytes: DEFAULT_MAX_BODY_BYTES,
35            chunks: DEFAULT_MAX_CHUNKS,
36        }
37    }
38
39    #[must_use]
40    pub const fn with_max_header_bytes(mut self, bytes: usize) -> Self {
41        assert!(bytes > 0, "max_header_bytes must be greater than zero");
42        self.header_bytes = bytes;
43        self
44    }
45
46    #[must_use]
47    pub const fn with_max_headers(mut self, count: usize) -> Self {
48        assert!(count > 0, "max_headers must be greater than zero");
49        assert!(
50            count <= MAX_HEADER_CAPACITY,
51            "max_headers cannot exceed the parser stack capacity"
52        );
53        self.headers = count;
54        self
55    }
56
57    #[must_use]
58    pub const fn with_max_body_bytes(mut self, bytes: usize) -> Self {
59        self.body_bytes = bytes;
60        self
61    }
62
63    #[must_use]
64    pub const fn with_max_chunks(mut self, count: usize) -> Self {
65        assert!(count > 0, "max_chunks must be greater than zero");
66        self.chunks = count;
67        self
68    }
69}
70
71impl Default for Limits {
72    fn default() -> Self {
73        Self::new()
74    }
75}
76
77/// Standard HTTP methods accepted by the current parser.
78#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
79pub enum Method {
80    Get,
81    Head,
82    Post,
83    Put,
84    Patch,
85    Delete,
86    Options,
87    Trace,
88    Connect,
89}
90
91impl Method {
92    #[must_use]
93    pub const fn as_str(self) -> &'static str {
94        match self {
95            Self::Get => "GET",
96            Self::Head => "HEAD",
97            Self::Post => "POST",
98            Self::Put => "PUT",
99            Self::Patch => "PATCH",
100            Self::Delete => "DELETE",
101            Self::Options => "OPTIONS",
102            Self::Trace => "TRACE",
103            Self::Connect => "CONNECT",
104        }
105    }
106
107    /// Parses one standard HTTP method token.
108    ///
109    /// # Errors
110    ///
111    /// Returns a method-not-allowed protocol rejection for unsupported tokens.
112    pub fn parse(method: &str) -> Result<Self, ParseError> {
113        match method {
114            "GET" => Ok(Self::Get),
115            "HEAD" => Ok(Self::Head),
116            "POST" => Ok(Self::Post),
117            "PUT" => Ok(Self::Put),
118            "PATCH" => Ok(Self::Patch),
119            "DELETE" => Ok(Self::Delete),
120            "OPTIONS" => Ok(Self::Options),
121            "TRACE" => Ok(Self::Trace),
122            "CONNECT" => Ok(Self::Connect),
123            _ => Err(ParseError {
124                status: 405,
125                code: "method_not_allowed",
126                message: "HTTP method is not supported by this build",
127            }),
128        }
129    }
130}
131
132/// Byte range referencing the caller-owned receive buffer.
133#[derive(Clone, Copy, Debug, Eq, PartialEq)]
134pub struct ByteRange {
135    pub start: usize,
136    pub end: usize,
137}
138
139impl ByteRange {
140    #[must_use]
141    pub fn bytes(self, buffer: &[u8]) -> Option<&[u8]> {
142        buffer.get(self.start..self.end)
143    }
144
145    #[must_use]
146    pub fn text(self, buffer: &[u8]) -> Option<&str> {
147        std::str::from_utf8(self.bytes(buffer)?).ok()
148    }
149}
150
151/// Header name and value ranges in the caller-owned receive buffer.
152#[derive(Clone, Copy, Debug, Eq, PartialEq)]
153pub struct HeaderPosition {
154    pub name: ByteRange,
155    pub value: ByteRange,
156}
157
158const EMPTY_HEADER_POSITION: HeaderPosition = HeaderPosition {
159    name: ByteRange { start: 0, end: 0 },
160    value: ByteRange { start: 0, end: 0 },
161};
162
163/// Inline-first header positions parsed without copying header bytes.
164#[derive(Clone, Debug)]
165pub struct HeaderPositions {
166    inline: [HeaderPosition; INLINE_REQUEST_HEADERS],
167    inline_len: usize,
168    overflow: Vec<HeaderPosition>,
169}
170
171impl HeaderPositions {
172    fn new() -> Self {
173        Self {
174            inline: [EMPTY_HEADER_POSITION; INLINE_REQUEST_HEADERS],
175            inline_len: 0,
176            overflow: Vec::new(),
177        }
178    }
179
180    fn push(&mut self, header: HeaderPosition) {
181        if self.inline_len < INLINE_REQUEST_HEADERS {
182            self.inline[self.inline_len] = header;
183            self.inline_len += 1;
184        } else {
185            self.overflow.push(header);
186        }
187    }
188
189    pub fn iter(&self) -> impl Iterator<Item = HeaderPosition> + '_ {
190        self.inline[..self.inline_len]
191            .iter()
192            .copied()
193            .chain(self.overflow.iter().copied())
194    }
195
196    #[must_use]
197    pub fn value<'buffer>(
198        &self,
199        buffer: &'buffer [u8],
200        name: &str,
201        index: usize,
202    ) -> Option<&'buffer str> {
203        self.iter()
204            .filter(|header| {
205                header
206                    .name
207                    .text(buffer)
208                    .is_some_and(|header| header_name_matches(header, name))
209            })
210            .nth(index)?
211            .value
212            .text(buffer)
213    }
214}
215
216/// Request body framing selected from validated HTTP/1 headers.
217#[derive(Clone, Copy, Debug, Eq, PartialEq)]
218pub enum BodyFraming {
219    ContentLength(usize),
220    Chunked,
221}
222
223/// Parsed request head borrowing all text through byte ranges.
224#[derive(Clone, Debug)]
225pub struct RequestHead {
226    pub method: Method,
227    pub target: ByteRange,
228    pub headers: HeaderPositions,
229    pub head_bytes: usize,
230    pub body: BodyFraming,
231    pub keep_alive: bool,
232}
233
234/// Stable protocol rejection suitable for an adapter error response.
235#[derive(Clone, Copy, Debug, Eq, PartialEq)]
236pub struct ParseError {
237    pub status: u16,
238    pub code: &'static str,
239    pub message: &'static str,
240}
241
242impl ParseError {
243    const fn bad_request() -> Self {
244        Self {
245            status: 400,
246            code: "bad_request",
247            message: "invalid HTTP/1 request",
248        }
249    }
250
251    const fn headers_too_large() -> Self {
252        Self {
253            status: 431,
254            code: "request_header_too_large",
255            message: "request headers exceed the configured limit",
256        }
257    }
258
259    const fn payload_too_large() -> Self {
260        Self {
261            status: 413,
262            code: "payload_too_large",
263            message: "request body exceeds the configured limit",
264        }
265    }
266}
267
268impl fmt::Display for ParseError {
269    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
270        write!(formatter, "{}: {}", self.code, self.message)
271    }
272}
273
274impl std::error::Error for ParseError {}
275
276/// Parses one complete HTTP/1 request head from the start of `buffer`.
277///
278/// `Ok(None)` means more bytes are required. Returned ranges remain valid only
279/// while the caller preserves the buffer prefix.
280///
281/// # Errors
282///
283/// Returns a bounded protocol rejection for malformed or oversized headers,
284/// conflicting framing fields, unsupported transfer encodings, and methods.
285pub fn parse_request_head(
286    buffer: &[u8],
287    limits: Limits,
288) -> Result<Option<RequestHead>, ParseError> {
289    let mut inline = [httparse::EMPTY_HEADER; INLINE_REQUEST_HEADERS];
290    let inline_limit = limits.headers.min(INLINE_REQUEST_HEADERS);
291    match parse_head_with_headers(buffer, limits, &mut inline[..inline_limit]) {
292        Err(rejection) if rejection.status == 431 && limits.headers > INLINE_REQUEST_HEADERS => {
293            let mut overflow = [httparse::EMPTY_HEADER; MAX_HEADER_CAPACITY];
294            parse_head_with_headers(buffer, limits, &mut overflow[..limits.headers])
295        }
296        result => result,
297    }
298}
299
300fn parse_head_with_headers<'buffer>(
301    buffer: &'buffer [u8],
302    limits: Limits,
303    headers: &mut [httparse::Header<'buffer>],
304) -> Result<Option<RequestHead>, ParseError> {
305    let mut request = httparse::Request::new(headers);
306    let status = request.parse(buffer).map_err(|error| match error {
307        httparse::Error::TooManyHeaders => ParseError::headers_too_large(),
308        _ => ParseError::bad_request(),
309    })?;
310    let httparse::Status::Complete(head_bytes) = status else {
311        if buffer.len() > limits.header_bytes {
312            return Err(ParseError::headers_too_large());
313        }
314        return Ok(None);
315    };
316    if head_bytes > limits.header_bytes {
317        return Err(ParseError::headers_too_large());
318    }
319    let method = Method::parse(request.method.ok_or_else(ParseError::bad_request)?)?;
320    let target = byte_range(
321        buffer,
322        request.path.ok_or_else(ParseError::bad_request)?.as_bytes(),
323    )?;
324    let version = request.version.ok_or_else(ParseError::bad_request)?;
325
326    let mut content_length = None;
327    let mut connection_close = false;
328    let mut connection_keep_alive = false;
329    let mut transfer_encoding_tokens = 0_usize;
330    let mut transfer_encoding_chunked = false;
331    let mut parsed_headers = HeaderPositions::new();
332    for header in request.headers.iter() {
333        parsed_headers.push(HeaderPosition {
334            name: byte_range(buffer, header.name.as_bytes())?,
335            value: byte_range(buffer, header.value)?,
336        });
337        // Length gate before case-insensitive comparison; values of framing
338        // headers stay fully validated, other values are validated lazily on
339        // lookup.
340        match header.name.len() {
341            14 if header.name.eq_ignore_ascii_case("content-length") => {
342                let length = parse_content_length(header.value)?;
343                if content_length.is_some_and(|previous| previous != length) {
344                    return Err(ParseError::bad_request());
345                }
346                content_length = Some(length);
347            }
348            17 if header.name.eq_ignore_ascii_case("transfer-encoding") => {
349                if header.value.eq_ignore_ascii_case(b"chunked") {
350                    transfer_encoding_tokens += 1;
351                    transfer_encoding_chunked = transfer_encoding_tokens == 1;
352                } else {
353                    let value =
354                        std::str::from_utf8(header.value).map_err(|_| ParseError::bad_request())?;
355                    for token in value.split(',').map(str::trim) {
356                        if token.is_empty() {
357                            continue;
358                        }
359                        transfer_encoding_tokens += 1;
360                        transfer_encoding_chunked =
361                            transfer_encoding_tokens == 1 && token.eq_ignore_ascii_case("chunked");
362                    }
363                }
364            }
365            10 if header.name.eq_ignore_ascii_case("connection") => {
366                if header.value.eq_ignore_ascii_case(b"keep-alive") {
367                    connection_keep_alive = true;
368                } else if header.value.eq_ignore_ascii_case(b"close") {
369                    connection_close = true;
370                } else {
371                    let value =
372                        std::str::from_utf8(header.value).map_err(|_| ParseError::bad_request())?;
373                    for token in value.split(',').map(str::trim) {
374                        connection_close |= token.eq_ignore_ascii_case("close");
375                        connection_keep_alive |= token.eq_ignore_ascii_case("keep-alive");
376                    }
377                }
378            }
379            _ => {}
380        }
381    }
382
383    if transfer_encoding_tokens > 0 && content_length.is_some() {
384        return Err(ParseError::bad_request());
385    }
386    let body = if transfer_encoding_tokens == 0 {
387        BodyFraming::ContentLength(content_length.unwrap_or(0))
388    } else if transfer_encoding_chunked {
389        BodyFraming::Chunked
390    } else {
391        return Err(ParseError {
392            status: 501,
393            code: "unsupported_transfer_encoding",
394            message: "only chunked transfer encoding is supported",
395        });
396    };
397
398    Ok(Some(RequestHead {
399        method,
400        target,
401        headers: parsed_headers,
402        head_bytes,
403        body,
404        keep_alive: if version == 1 {
405            !connection_close
406        } else {
407            connection_keep_alive && !connection_close
408        },
409    }))
410}
411
412/// Incremental decoder for a chunked request body and optional trailers.
413#[derive(Debug)]
414pub struct ChunkDecoder {
415    position: usize,
416    pending_size: Option<usize>,
417    body: Vec<u8>,
418    max_body_bytes: usize,
419    max_header_bytes: usize,
420    max_chunks: usize,
421    chunks: usize,
422}
423
424impl ChunkDecoder {
425    #[must_use]
426    pub fn new(position: usize, limits: Limits) -> Self {
427        Self {
428            position,
429            pending_size: None,
430            body: Vec::new(),
431            max_body_bytes: limits.body_bytes,
432            max_header_bytes: limits.header_bytes,
433            max_chunks: limits.chunks,
434            chunks: 0,
435        }
436    }
437
438    /// Advances decoding over the caller's accumulated receive buffer.
439    ///
440    /// # Errors
441    ///
442    /// Returns a protocol rejection for malformed chunks/trailers or configured
443    /// body, trailer, and chunk-count limit violations.
444    pub fn advance(&mut self, buffer: &[u8]) -> Result<Option<DecodedChunkedBody>, ParseError> {
445        loop {
446            if let Some(size) = self.pending_size {
447                let end = self
448                    .position
449                    .checked_add(size)
450                    .ok_or_else(ParseError::bad_request)?;
451                let chunk_end = end.checked_add(2).ok_or_else(ParseError::bad_request)?;
452                if buffer.len() < chunk_end {
453                    return Ok(None);
454                }
455                if buffer.get(end..chunk_end) != Some(b"\r\n") {
456                    return Err(ParseError::bad_request());
457                }
458                self.body.extend_from_slice(&buffer[self.position..end]);
459                self.position = chunk_end;
460                self.pending_size = None;
461                continue;
462            }
463
464            let Some(line_end) = find_bytes(buffer, b"\r\n", self.position) else {
465                if buffer.len().saturating_sub(self.position) > self.max_header_bytes {
466                    return Err(ParseError::bad_request());
467                }
468                return Ok(None);
469            };
470            let size_line = std::str::from_utf8(&buffer[self.position..line_end])
471                .map_err(|_| ParseError::bad_request())?;
472            let size = size_line
473                .split(';')
474                .next()
475                .map(str::trim)
476                .filter(|size| !size.is_empty())
477                .and_then(|size| usize::from_str_radix(size, 16).ok())
478                .ok_or_else(ParseError::bad_request)?;
479            self.position = line_end + 2;
480
481            if size == 0 {
482                let consumed = if buffer.get(self.position..self.position + 2) == Some(b"\r\n") {
483                    self.position + 2
484                } else {
485                    let Some(trailer_end) = find_bytes(buffer, b"\r\n\r\n", self.position) else {
486                        if buffer.len().saturating_sub(self.position) > self.max_header_bytes {
487                            return Err(ParseError::headers_too_large());
488                        }
489                        return Ok(None);
490                    };
491                    if trailer_end - self.position > self.max_header_bytes {
492                        return Err(ParseError::headers_too_large());
493                    }
494                    validate_trailers(&buffer[self.position..trailer_end])?;
495                    trailer_end + 4
496                };
497                return Ok(Some(DecodedChunkedBody {
498                    consumed,
499                    body: std::mem::take(&mut self.body),
500                }));
501            }
502
503            if size > self.max_body_bytes.saturating_sub(self.body.len()) {
504                return Err(ParseError::payload_too_large());
505            }
506            self.chunks += 1;
507            if self.chunks > self.max_chunks {
508                return Err(ParseError {
509                    status: 413,
510                    code: "too_many_chunks",
511                    message: "chunk count exceeds the configured limit",
512                });
513            }
514            self.pending_size = Some(size);
515        }
516    }
517}
518
519/// One incremental event from [`StreamingChunkDecoder`].
520#[derive(Clone, Copy, Debug, Eq, PartialEq)]
521pub enum StreamingChunk {
522    /// More receive bytes are required.
523    NeedMore,
524    /// One decoded data chunk referencing the caller-owned receive buffer.
525    Data(ByteRange),
526    /// Final chunk and trailers were validated.
527    Complete { consumed: usize },
528}
529
530/// Zero-aggregate incremental chunked decoder for streaming request bodies.
531///
532/// Unlike [`ChunkDecoder`], this decoder never builds a complete body. Each
533/// returned range can be copied into a bounded transport channel and released
534/// before reading the next network chunk.
535#[derive(Debug)]
536pub struct StreamingChunkDecoder {
537    position: usize,
538    pending_size: Option<usize>,
539    body_bytes: usize,
540    max_body_bytes: usize,
541    max_header_bytes: usize,
542    max_chunks: usize,
543    chunks: usize,
544}
545
546impl StreamingChunkDecoder {
547    #[must_use]
548    pub fn new(position: usize, limits: Limits) -> Self {
549        Self {
550            position,
551            pending_size: None,
552            body_bytes: 0,
553            max_body_bytes: limits.body_bytes,
554            max_header_bytes: limits.header_bytes,
555            max_chunks: limits.chunks,
556            chunks: 0,
557        }
558    }
559
560    /// Advances by at most one decoded data chunk.
561    ///
562    /// # Errors
563    ///
564    /// Returns a bounded protocol rejection for malformed chunks/trailers or
565    /// configured body and chunk-count limit violations.
566    pub fn advance(&mut self, buffer: &[u8]) -> Result<StreamingChunk, ParseError> {
567        loop {
568            if let Some(remaining) = self.pending_size {
569                if remaining > 0 {
570                    let available = buffer.len().saturating_sub(self.position).min(remaining);
571                    if available == 0 {
572                        return Ok(StreamingChunk::NeedMore);
573                    }
574                    let end = self
575                        .position
576                        .checked_add(available)
577                        .ok_or_else(ParseError::bad_request)?;
578                    let data = ByteRange {
579                        start: self.position,
580                        end,
581                    };
582                    self.position = end;
583                    self.pending_size = Some(remaining - available);
584                    return Ok(StreamingChunk::Data(data));
585                }
586                let chunk_end = self
587                    .position
588                    .checked_add(2)
589                    .ok_or_else(ParseError::bad_request)?;
590                if buffer.len() < chunk_end {
591                    return Ok(StreamingChunk::NeedMore);
592                }
593                if buffer.get(self.position..chunk_end) != Some(b"\r\n") {
594                    return Err(ParseError::bad_request());
595                }
596                self.position = chunk_end;
597                self.pending_size = None;
598                continue;
599            }
600
601            let Some(line_end) = find_bytes(buffer, b"\r\n", self.position) else {
602                if buffer.len().saturating_sub(self.position) > self.max_header_bytes {
603                    return Err(ParseError::bad_request());
604                }
605                return Ok(StreamingChunk::NeedMore);
606            };
607            let size_line = std::str::from_utf8(&buffer[self.position..line_end])
608                .map_err(|_| ParseError::bad_request())?;
609            let size = size_line
610                .split(';')
611                .next()
612                .map(str::trim)
613                .filter(|size| !size.is_empty())
614                .and_then(|size| usize::from_str_radix(size, 16).ok())
615                .ok_or_else(ParseError::bad_request)?;
616            self.position = line_end + 2;
617
618            if size == 0 {
619                let consumed = if buffer.get(self.position..self.position + 2) == Some(b"\r\n") {
620                    self.position + 2
621                } else {
622                    let Some(trailer_end) = find_bytes(buffer, b"\r\n\r\n", self.position) else {
623                        if buffer.len().saturating_sub(self.position) > self.max_header_bytes {
624                            return Err(ParseError::headers_too_large());
625                        }
626                        return Ok(StreamingChunk::NeedMore);
627                    };
628                    if trailer_end - self.position > self.max_header_bytes {
629                        return Err(ParseError::headers_too_large());
630                    }
631                    validate_trailers(&buffer[self.position..trailer_end])?;
632                    trailer_end + 4
633                };
634                return Ok(StreamingChunk::Complete { consumed });
635            }
636
637            if size > self.max_body_bytes.saturating_sub(self.body_bytes) {
638                return Err(ParseError::payload_too_large());
639            }
640            self.body_bytes += size;
641            self.chunks += 1;
642            if self.chunks > self.max_chunks {
643                return Err(ParseError {
644                    status: 413,
645                    code: "too_many_chunks",
646                    message: "chunk count exceeds the configured limit",
647                });
648            }
649            self.pending_size = Some(size);
650        }
651    }
652
653    #[must_use]
654    pub const fn body_bytes(&self) -> usize {
655        self.body_bytes
656    }
657
658    /// Wire prefix fully consumed by emitted events.
659    #[must_use]
660    pub const fn consumed_prefix(&self) -> usize {
661        self.position
662    }
663
664    /// Rebases decoder offsets after the caller discards a consumed prefix.
665    ///
666    /// # Panics
667    ///
668    /// Panics when `bytes` exceeds [`Self::consumed_prefix`].
669    pub fn discard_prefix(&mut self, bytes: usize) {
670        assert!(
671            bytes <= self.position,
672            "cannot discard bytes the decoder has not consumed"
673        );
674        self.position -= bytes;
675    }
676}
677
678/// Complete decoded chunked body and total consumed wire bytes.
679#[derive(Debug, Eq, PartialEq)]
680pub struct DecodedChunkedBody {
681    pub consumed: usize,
682    pub body: Vec<u8>,
683}
684
685/// Encodes an HTTP/1 response head while filtering caller-supplied framing
686/// fields. The adapter remains responsible for writing buffered/streaming body
687/// bytes and chunk terminators.
688///
689/// # Errors
690///
691/// Returns an invalid-input error for unsafe header names, values, or date.
692#[allow(clippy::too_many_arguments)]
693pub fn encode_response_head<'headers>(
694    output: &mut Vec<u8>,
695    status: u16,
696    headers: impl IntoIterator<Item = (&'headers str, &'headers str)>,
697    content_length: Option<u64>,
698    chunked: bool,
699    keep_alive: bool,
700    date: &str,
701) -> io::Result<()> {
702    push_status_line(output, status);
703    let mut has_date = false;
704    for (name, value) in headers {
705        if is_framing_header(name) {
706            continue;
707        }
708        if !valid_header(name, value) {
709            return Err(io::Error::new(
710                io::ErrorKind::InvalidInput,
711                "response contains an invalid header",
712            ));
713        }
714        has_date |= name.len() == 4 && name.eq_ignore_ascii_case("date");
715        push_header(output, name, value);
716    }
717    push_framing_tail(output, content_length, chunked, keep_alive, date, has_date)
718}
719
720/// Response headers validated and encoded once for reuse across responses.
721///
722/// [`encode_response_head`] re-validates every header on every call, which is
723/// the right default for uncontrolled input. When the same header set is sent
724/// many times, prepare it once and encode each response with
725/// [`encode_response_head_prepared`].
726#[derive(Clone, Debug)]
727pub struct PreparedHeaders {
728    encoded: Vec<u8>,
729    has_date: bool,
730}
731
732impl PreparedHeaders {
733    /// Validates response headers once, filtering caller-supplied framing
734    /// fields exactly like [`encode_response_head`].
735    ///
736    /// # Errors
737    ///
738    /// Returns an invalid-input error for unsafe header names/values.
739    pub fn new<'headers>(
740        headers: impl IntoIterator<Item = (&'headers str, &'headers str)>,
741    ) -> io::Result<Self> {
742        let mut encoded = Vec::new();
743        let mut has_date = false;
744        for (name, value) in headers {
745            if is_framing_header(name) {
746                continue;
747            }
748            if !valid_header(name, value) {
749                return Err(io::Error::new(
750                    io::ErrorKind::InvalidInput,
751                    "response contains an invalid header",
752                ));
753            }
754            has_date |= name.len() == 4 && name.eq_ignore_ascii_case("date");
755            push_header(&mut encoded, name, value);
756        }
757        Ok(Self { encoded, has_date })
758    }
759}
760
761/// Encodes an HTTP/1 response head from pre-validated headers.
762///
763/// Framing behavior matches [`encode_response_head`]; per-header validation
764/// was already paid once in [`PreparedHeaders::new`].
765///
766/// # Errors
767///
768/// Returns an invalid-input error for an unsafe `date` value.
769pub fn encode_response_head_prepared(
770    output: &mut Vec<u8>,
771    status: u16,
772    headers: &PreparedHeaders,
773    content_length: Option<u64>,
774    chunked: bool,
775    keep_alive: bool,
776    date: &str,
777) -> io::Result<()> {
778    push_status_line(output, status);
779    output.extend_from_slice(&headers.encoded);
780    push_framing_tail(
781        output,
782        content_length,
783        chunked,
784        keep_alive,
785        date,
786        headers.has_date,
787    )
788}
789
790fn push_status_line(output: &mut Vec<u8>, status: u16) {
791    let reason = reason_phrase(status).as_bytes();
792    let mut digits = [0_u8; 20];
793    let start = write_decimal(u64::from(status), &mut digits);
794    let count = digits.len() - start;
795    // Longest reason phrase is 31 bytes; 64 leaves headroom for new phrases.
796    let mut line = [0_u8; 64];
797    line[..9].copy_from_slice(b"HTTP/1.1 ");
798    let mut cursor = 9;
799    line[cursor..cursor + count].copy_from_slice(&digits[start..]);
800    cursor += count;
801    line[cursor] = b' ';
802    cursor += 1;
803    line[cursor..cursor + reason.len()].copy_from_slice(reason);
804    cursor += reason.len();
805    line[cursor] = b'\r';
806    line[cursor + 1] = b'\n';
807    output.extend_from_slice(&line[..cursor + 2]);
808}
809
810fn push_framing_tail(
811    output: &mut Vec<u8>,
812    content_length: Option<u64>,
813    chunked: bool,
814    keep_alive: bool,
815    date: &str,
816    has_date: bool,
817) -> io::Result<()> {
818    if let Some(length) = content_length {
819        push_content_length_line(output, length);
820    } else if chunked {
821        output.extend_from_slice(b"transfer-encoding: chunked\r\n");
822    }
823    if !has_date {
824        if !valid_header_value(date) {
825            return Err(io::Error::new(
826                io::ErrorKind::InvalidInput,
827                "response date is invalid",
828            ));
829        }
830        push_date_line(output, date);
831    }
832    if !keep_alive {
833        output.extend_from_slice(b"connection: close\r\n");
834    }
835    output.extend_from_slice(b"\r\n");
836    Ok(())
837}
838
839fn push_date_line(output: &mut Vec<u8>, date: &str) {
840    const PREFIX: &[u8; 6] = b"date: ";
841    let date = date.as_bytes();
842    let mut line = [0_u8; 64];
843    if date.len() <= line.len() - PREFIX.len() - 2 {
844        let mut cursor = append(&mut line, 0, PREFIX);
845        cursor = append(&mut line, cursor, date);
846        cursor = append(&mut line, cursor, b"\r\n");
847        output.extend_from_slice(&line[..cursor]);
848    } else {
849        output.extend_from_slice(PREFIX);
850        output.extend_from_slice(date);
851        output.extend_from_slice(b"\r\n");
852    }
853}
854
855fn is_framing_header(name: &str) -> bool {
856    match name.len() {
857        10 => name.eq_ignore_ascii_case("connection"),
858        14 => name.eq_ignore_ascii_case("content-length"),
859        17 => name.eq_ignore_ascii_case("transfer-encoding"),
860        _ => false,
861    }
862}
863
864fn push_header(output: &mut Vec<u8>, name: &str, value: &str) {
865    output.extend_from_slice(name.as_bytes());
866    output.extend_from_slice(b": ");
867    output.extend_from_slice(value.as_bytes());
868    output.extend_from_slice(b"\r\n");
869}
870
871fn append<const CAPACITY: usize>(
872    buffer: &mut [u8; CAPACITY],
873    cursor: usize,
874    bytes: &[u8],
875) -> usize {
876    buffer[cursor..cursor + bytes.len()].copy_from_slice(bytes);
877    cursor + bytes.len()
878}
879
880/// Writes `value` right-aligned into `digits`; returns the first used index.
881fn write_decimal(mut value: u64, digits: &mut [u8; 20]) -> usize {
882    let mut cursor = digits.len();
883    loop {
884        cursor -= 1;
885        #[allow(clippy::cast_possible_truncation)] // remainder < 10
886        {
887            digits[cursor] = b'0' + (value % 10) as u8;
888        }
889        value /= 10;
890        if value == 0 {
891            break;
892        }
893    }
894    cursor
895}
896
897fn push_content_length_line(output: &mut Vec<u8>, length: u64) {
898    const PREFIX: &[u8; 16] = b"content-length: ";
899    let mut digits = [0_u8; 20];
900    let start = write_decimal(length, &mut digits);
901    let count = digits.len() - start;
902    let mut line = [0_u8; PREFIX.len() + 20 + 2];
903    line[..PREFIX.len()].copy_from_slice(PREFIX);
904    line[PREFIX.len()..PREFIX.len() + count].copy_from_slice(&digits[start..]);
905    line[PREFIX.len() + count] = b'\r';
906    line[PREFIX.len() + count + 1] = b'\n';
907    output.extend_from_slice(&line[..PREFIX.len() + count + 2]);
908}
909
910fn push_hex(output: &mut Vec<u8>, mut value: usize) {
911    const HEX: &[u8; 16] = b"0123456789ABCDEF";
912    let mut digits = [0_u8; usize::BITS as usize / 4];
913    let mut cursor = digits.len();
914    loop {
915        cursor -= 1;
916        digits[cursor] = HEX[value & 0xF];
917        value >>= 4;
918        if value == 0 {
919            break;
920        }
921    }
922    output.extend_from_slice(&digits[cursor..]);
923}
924
925/// Encodes a `101 Switching Protocols` response without HTTP body framing.
926///
927/// # Errors
928///
929/// Returns an invalid-input error unless safe `Connection: Upgrade` and
930/// `Upgrade` headers are present.
931pub fn encode_upgrade_response<'headers>(
932    output: &mut Vec<u8>,
933    headers: impl IntoIterator<Item = (&'headers str, &'headers str)>,
934    date: &str,
935) -> io::Result<()> {
936    output.extend_from_slice(b"HTTP/1.1 101 Switching Protocols\r\n");
937    let mut has_connection_upgrade = false;
938    let mut has_upgrade = false;
939    let mut has_date = false;
940    for (name, value) in headers {
941        if name.eq_ignore_ascii_case("content-length")
942            || name.eq_ignore_ascii_case("transfer-encoding")
943        {
944            continue;
945        }
946        if !valid_header(name, value) {
947            return Err(io::Error::new(
948                io::ErrorKind::InvalidInput,
949                "upgrade response contains an invalid header",
950            ));
951        }
952        if name.eq_ignore_ascii_case("connection") {
953            has_connection_upgrade |= value
954                .split(',')
955                .map(str::trim)
956                .any(|token| token.eq_ignore_ascii_case("upgrade"));
957        }
958        has_upgrade |= name.eq_ignore_ascii_case("upgrade") && !value.trim().is_empty();
959        has_date |= name.eq_ignore_ascii_case("date");
960        push_header(output, name, value);
961    }
962    if !has_connection_upgrade || !has_upgrade {
963        return Err(io::Error::new(
964            io::ErrorKind::InvalidInput,
965            "upgrade response is missing required protocol switch headers",
966        ));
967    }
968    if !has_date {
969        if !valid_header_value(date) {
970            return Err(io::Error::new(
971                io::ErrorKind::InvalidInput,
972                "response date is invalid",
973            ));
974        }
975        push_header(output, "date", date);
976    }
977    output.extend_from_slice(b"\r\n");
978    Ok(())
979}
980
981/// Appends one HTTP/1 chunk frame to `output`.
982///
983/// # Errors
984///
985/// Never fails today; the `io::Result` return is kept for API stability.
986pub fn encode_chunk(output: &mut Vec<u8>, chunk: &[u8]) -> io::Result<()> {
987    push_hex(output, chunk.len());
988    output.extend_from_slice(b"\r\n");
989    output.extend_from_slice(chunk);
990    output.extend_from_slice(b"\r\n");
991    Ok(())
992}
993
994pub const LAST_CHUNK: &[u8] = b"0\r\n\r\n";
995
996#[must_use]
997pub const fn reason_phrase(status: u16) -> &'static str {
998    match status {
999        200 => "OK",
1000        201 => "Created",
1001        202 => "Accepted",
1002        204 => "No Content",
1003        206 => "Partial Content",
1004        400 => "Bad Request",
1005        401 => "Unauthorized",
1006        403 => "Forbidden",
1007        404 => "Not Found",
1008        405 => "Method Not Allowed",
1009        409 => "Conflict",
1010        413 => "Payload Too Large",
1011        415 => "Unsupported Media Type",
1012        422 => "Unprocessable Content",
1013        429 => "Too Many Requests",
1014        431 => "Request Header Fields Too Large",
1015        499 => "Client Closed Request",
1016        500 => "Internal Server Error",
1017        501 => "Not Implemented",
1018        503 => "Service Unavailable",
1019        504 => "Gateway Timeout",
1020        _ => "Unknown",
1021    }
1022}
1023
1024fn byte_range(buffer: &[u8], slice: &[u8]) -> Result<ByteRange, ParseError> {
1025    let start = (slice.as_ptr() as usize)
1026        .checked_sub(buffer.as_ptr() as usize)
1027        .ok_or_else(ParseError::bad_request)?;
1028    let end = start
1029        .checked_add(slice.len())
1030        .filter(|end| *end <= buffer.len())
1031        .ok_or_else(ParseError::bad_request)?;
1032    Ok(ByteRange { start, end })
1033}
1034
1035fn parse_content_length(value: &[u8]) -> Result<usize, ParseError> {
1036    // Digits-only fast path; whitespace-padded values take the tolerant path.
1037    if !value.is_empty() && value.len() <= 19 && value.iter().all(u8::is_ascii_digit) {
1038        let mut length = 0_u64;
1039        for &byte in value {
1040            length = length * 10 + u64::from(byte - b'0');
1041        }
1042        return usize::try_from(length).map_err(|_| ParseError::bad_request());
1043    }
1044    std::str::from_utf8(value)
1045        .map_err(|_| ParseError::bad_request())?
1046        .trim()
1047        .parse::<usize>()
1048        .map_err(|_| ParseError::bad_request())
1049}
1050
1051fn validate_trailers(trailers: &[u8]) -> Result<(), ParseError> {
1052    let trailers = std::str::from_utf8(trailers).map_err(|_| ParseError::bad_request())?;
1053    for line in trailers.split("\r\n") {
1054        let (name, value) = line.split_once(':').ok_or_else(ParseError::bad_request)?;
1055        if name.is_empty() || !name.bytes().all(is_header_name_byte) || !valid_header_value(value) {
1056            return Err(ParseError::bad_request());
1057        }
1058    }
1059    Ok(())
1060}
1061
1062fn find_bytes(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
1063    haystack
1064        .get(from..)?
1065        .windows(needle.len())
1066        .position(|window| window == needle)
1067        .map(|position| from + position)
1068}
1069
1070static HEADER_NAME_BYTES: [bool; 256] = {
1071    let mut table = [false; 256];
1072    let mut index = 0_usize;
1073    while index < 256 {
1074        #[allow(clippy::cast_possible_truncation)] // index < 256
1075        {
1076            table[index] = is_header_name_byte(index as u8);
1077        }
1078        index += 1;
1079    }
1080    table
1081};
1082
1083fn valid_header(name: &str, value: &str) -> bool {
1084    !name.is_empty()
1085        && name
1086            .bytes()
1087            .all(|byte| HEADER_NAME_BYTES[usize::from(byte)])
1088        && valid_header_value(value)
1089}
1090
1091/// Word-at-a-time scan flagging bytes below 0x20 (except HTAB) and DEL.
1092fn valid_header_value(value: &str) -> bool {
1093    const LOW: u64 = 0x0101_0101_0101_0101;
1094    const HIGH: u64 = 0x8080_8080_8080_8080;
1095    let mut chunks = value.as_bytes().chunks_exact(8);
1096    for chunk in chunks.by_ref() {
1097        let word = u64::from_le_bytes(chunk.try_into().expect("8-byte chunk"));
1098        let below_space = word.wrapping_sub(LOW * 0x20) & !word & HIGH;
1099        let tab = word ^ (LOW * u64::from(b'\t'));
1100        let tab = tab.wrapping_sub(LOW) & !tab & HIGH;
1101        let del = word ^ (LOW * 0x7F);
1102        let del = del.wrapping_sub(LOW) & !del & HIGH;
1103        if ((below_space & !tab) | del) != 0 {
1104            return false;
1105        }
1106    }
1107    chunks
1108        .remainder()
1109        .iter()
1110        .all(|&byte| byte == b'\t' || (byte >= b' ' && byte != 127))
1111}
1112
1113const fn is_header_name_byte(byte: u8) -> bool {
1114    byte.is_ascii_alphanumeric()
1115        || matches!(
1116            byte,
1117            b'!' | b'#'
1118                | b'$'
1119                | b'%'
1120                | b'&'
1121                | b'\''
1122                | b'*'
1123                | b'+'
1124                | b'-'
1125                | b'.'
1126                | b'^'
1127                | b'_'
1128                | b'`'
1129                | b'|'
1130                | b'~'
1131        )
1132}
1133
1134fn header_name_matches(header: &str, argument: &str) -> bool {
1135    header
1136        .bytes()
1137        .map(|byte| byte.to_ascii_lowercase())
1138        .eq(argument
1139            .bytes()
1140            .map(|byte| if byte == b'_' { b'-' } else { byte })
1141            .map(|byte| byte.to_ascii_lowercase()))
1142}
1143
1144#[cfg(test)]
1145mod tests {
1146    use super::{
1147        BodyFraming, ChunkDecoder, Limits, Method, PreparedHeaders, StreamingChunk,
1148        StreamingChunkDecoder, encode_chunk, encode_response_head, encode_response_head_prepared,
1149        encode_upgrade_response, parse_request_head,
1150    };
1151
1152    #[test]
1153    fn parses_borrowed_keep_alive_request_head() {
1154        let bytes =
1155            b"POST /items?x=1 HTTP/1.1\r\nHost: api.example\r\nContent-Length: 4\r\n\r\ntest";
1156        let head = parse_request_head(bytes, Limits::new())
1157            .expect("valid request")
1158            .expect("complete head");
1159        assert_eq!(head.method, Method::Post);
1160        assert_eq!(head.target.text(bytes), Some("/items?x=1"));
1161        assert_eq!(head.headers.value(bytes, "host", 0), Some("api.example"));
1162        assert_eq!(head.body, BodyFraming::ContentLength(4));
1163        assert!(head.keep_alive);
1164    }
1165
1166    #[test]
1167    fn rejects_content_length_transfer_encoding_smuggling() {
1168        let bytes = b"POST / HTTP/1.1\r\nContent-Length: 4\r\nTransfer-Encoding: chunked\r\n\r\n";
1169        let error = parse_request_head(bytes, Limits::new()).expect_err("must reject");
1170        assert_eq!(error.status, 400);
1171    }
1172
1173    #[test]
1174    fn incrementally_decodes_chunked_body_and_trailers() {
1175        let bytes = b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ntest\r\n0\r\nx-id: 7\r\n\r\n";
1176        let head = parse_request_head(bytes, Limits::new())
1177            .expect("valid request")
1178            .expect("complete head");
1179        let mut decoder = ChunkDecoder::new(head.head_bytes, Limits::new());
1180        let body = decoder
1181            .advance(bytes)
1182            .expect("valid chunks")
1183            .expect("complete body");
1184        assert_eq!(body.body, b"test");
1185        assert_eq!(body.consumed, bytes.len());
1186    }
1187
1188    #[test]
1189    fn streaming_decoder_yields_chunks_without_aggregating_the_body() {
1190        let bytes =
1191            b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n4\r\ntest\r\n3\r\ning\r\n0\r\n\r\n";
1192        let head = parse_request_head(bytes, Limits::default())
1193            .expect("request")
1194            .expect("head");
1195        let mut decoder = StreamingChunkDecoder::new(head.head_bytes, Limits::default());
1196        let first = decoder.advance(bytes).expect("first");
1197        let StreamingChunk::Data(first) = first else {
1198            panic!("expected first chunk");
1199        };
1200        assert_eq!(first.bytes(bytes), Some(b"test".as_slice()));
1201        let second = decoder.advance(bytes).expect("second");
1202        let StreamingChunk::Data(second) = second else {
1203            panic!("expected second chunk");
1204        };
1205        assert_eq!(second.bytes(bytes), Some(b"ing".as_slice()));
1206        assert_eq!(
1207            decoder.advance(bytes).expect("complete"),
1208            StreamingChunk::Complete {
1209                consumed: bytes.len()
1210            }
1211        );
1212        assert_eq!(decoder.body_bytes(), 7);
1213    }
1214
1215    #[test]
1216    fn response_head_owns_framing_and_blocks_header_injection() {
1217        let mut output = Vec::new();
1218        encode_response_head(
1219            &mut output,
1220            200,
1221            [("content-type", "application/json")],
1222            Some(2),
1223            false,
1224            true,
1225            "Mon, 27 Jul 2026 00:00:00 GMT",
1226        )
1227        .expect("valid response");
1228        let text = String::from_utf8(output).expect("HTTP text");
1229        assert!(text.starts_with("HTTP/1.1 200 OK\r\n"));
1230        assert!(text.contains("content-length: 2\r\n"));
1231
1232        let mut invalid = Vec::new();
1233        assert!(
1234            encode_response_head(
1235                &mut invalid,
1236                200,
1237                [("x-value", "ok\r\ninjected: true")],
1238                Some(0),
1239                false,
1240                true,
1241                "Mon, 27 Jul 2026 00:00:00 GMT",
1242            )
1243            .is_err()
1244        );
1245    }
1246
1247    #[test]
1248    fn rejects_multi_token_transfer_encoding() {
1249        let bytes = b"POST / HTTP/1.1\r\nTransfer-Encoding: gzip, chunked\r\n\r\n";
1250        let error = parse_request_head(bytes, Limits::new()).expect_err("must reject");
1251        assert_eq!(error.status, 501);
1252    }
1253
1254    #[test]
1255    fn parses_more_than_inline_headers_via_overflow() {
1256        let mut bytes = b"GET / HTTP/1.1\r\n".to_vec();
1257        for index in 0..20 {
1258            bytes.extend_from_slice(format!("x-h{index}: v{index}\r\n").as_bytes());
1259        }
1260        bytes.extend_from_slice(b"\r\n");
1261        let head = parse_request_head(&bytes, Limits::new().with_max_headers(32))
1262            .expect("valid request")
1263            .expect("complete head");
1264        assert_eq!(head.headers.iter().count(), 20);
1265        assert_eq!(head.headers.value(&bytes, "x-h0", 0), Some("v0"));
1266        assert_eq!(head.headers.value(&bytes, "x-h19", 0), Some("v19"));
1267    }
1268
1269    #[test]
1270    fn prepared_headers_match_the_validating_path_and_stay_filtered() {
1271        let headers = [
1272            ("content-type", "application/json"),
1273            ("content-length", "999"),
1274            ("x-request-id", "abc123"),
1275        ];
1276        let date = "Mon, 27 Jul 2026 00:00:00 GMT";
1277        let mut per_call = Vec::new();
1278        encode_response_head(&mut per_call, 200, headers, Some(2), false, true, date)
1279            .expect("valid response");
1280        let prepared = PreparedHeaders::new(headers).expect("valid headers");
1281        let mut reused = Vec::new();
1282        encode_response_head_prepared(&mut reused, 200, &prepared, Some(2), false, true, date)
1283            .expect("valid response");
1284        assert_eq!(per_call, reused);
1285        assert!(
1286            !String::from_utf8(reused)
1287                .expect("HTTP text")
1288                .contains("999")
1289        );
1290        assert!(PreparedHeaders::new([("x-bad", "ok\r\ninjected: true")]).is_err());
1291    }
1292
1293    #[test]
1294    fn prepared_caller_date_suppresses_the_generated_date() {
1295        let prepared =
1296            PreparedHeaders::new([("Date", "Mon, 27 Jul 2026 00:00:00 GMT")]).expect("valid");
1297        let mut output = Vec::new();
1298        encode_response_head_prepared(&mut output, 204, &prepared, None, false, true, "ignored")
1299            .expect("valid response");
1300        let text = String::from_utf8(output).expect("HTTP text");
1301        assert_eq!(text.matches("ate:").count(), 1);
1302    }
1303
1304    #[test]
1305    fn value_validation_scans_full_words_and_remainders() {
1306        let accepts = |value: &str| {
1307            let mut output = Vec::new();
1308            encode_response_head(
1309                &mut output,
1310                200,
1311                [("x-v", value)],
1312                Some(0),
1313                false,
1314                true,
1315                "Mon, 27 Jul 2026 00:00:00 GMT",
1316            )
1317            .is_ok()
1318        };
1319        assert!(accepts("exactly-eight!!!"));
1320        assert!(accepts("tab\tinside a longer value"));
1321        assert!(accepts("caf\u{e9} obs-text value"));
1322        assert!(!accepts("bad\u{7f}in first word"));
1323        assert!(!accepts("eightpad\u{7f}tail"));
1324        assert!(!accepts("eightpadx\u{1f}"));
1325        assert!(!accepts("\u{1}"));
1326    }
1327
1328    #[test]
1329    fn encodes_chunk_frames_with_uppercase_hex_sizes() {
1330        let mut output = Vec::new();
1331        encode_chunk(&mut output, &[b'x'; 26]).expect("chunk frame");
1332        assert!(output.starts_with(b"1A\r\n"));
1333        assert!(output.ends_with(b"\r\n"));
1334        assert_eq!(output.len(), 4 + 26 + 2);
1335    }
1336
1337    #[test]
1338    fn switching_protocols_preserves_required_upgrade_headers() {
1339        let mut output = Vec::new();
1340        encode_upgrade_response(
1341            &mut output,
1342            [
1343                ("connection", "Upgrade"),
1344                ("upgrade", "websocket"),
1345                ("sec-websocket-accept", "accepted"),
1346            ],
1347            "Sun, 06 Nov 1994 08:49:37 GMT",
1348        )
1349        .expect("upgrade response");
1350        let output = String::from_utf8(output).expect("UTF-8");
1351        assert!(output.starts_with("HTTP/1.1 101 Switching Protocols\r\n"));
1352        assert!(output.contains("connection: Upgrade\r\n"));
1353        assert!(!output.contains("content-length"));
1354    }
1355}