Skip to main content

ntex/http/h1/
decoder.rs

1use std::{cell::Cell, fmt, task::Poll};
2
3use ntex_http::header::{HeaderName, HeaderValue};
4use ntex_http::{Method, StatusCode, Version, header};
5use ntex_httparse::{self as httparse, HeaderParsed, Status};
6use urly::Url;
7
8use super::encoder::is_bodyless;
9use crate::http::config::HttpServiceConfig;
10use crate::http::message::{ConnectionType, ResponseHead};
11use crate::http::{HeaderItem, error::DecodeError, header::HeaderMap, request::Request};
12use crate::util::{ByteString, Bytes, BytesMut};
13use crate::{codec::Decoder, service::cfg::Cfg};
14
15/// Incoming message decoder
16pub(crate) struct MessageDecoder<T: MessageType> {
17    hdrs: Cell<bool>,
18    inner: Cell<Option<Box<Inner<T>>>>,
19}
20
21struct Inner<T: MessageType> {
22    st: State,
23    val: Option<T>,
24    hdr: httparse::Header,
25    hdr_st: httparse::State,
26    cfg: Cfg<HttpServiceConfig>,
27    consumed: usize,
28    /// number of parsed header lines of the current message
29    headers: u16,
30    /// start line parser, resumed after a partial start line
31    line: T::Parser,
32    line_st: httparse::State,
33}
34
35#[derive(Debug, PartialEq, Eq)]
36/// The payload framing and decoder selected for an incoming HTTP/1 message.
37pub enum PayloadType {
38    /// The message has no payload.
39    None,
40    /// The message has an HTTP body.
41    ///
42    /// Depending on the message headers and version, the decoder may use a
43    /// fixed length, chunked transfer coding, or connection close as the body
44    /// delimiter.
45    Payload(PayloadDecoder),
46    /// The message switches the connection away from HTTP framing.
47    ///
48    /// Subsequent bytes belong to the upgraded protocol or tunnel.
49    Stream(PayloadDecoder),
50}
51
52impl<T: MessageType> Default for MessageDecoder<T> {
53    fn default() -> Self {
54        MessageDecoder::new(Cfg::default())
55    }
56}
57
58impl<T: MessageType> MessageDecoder<T> {
59    pub(crate) fn new(cfg: Cfg<HttpServiceConfig>) -> Self {
60        MessageDecoder {
61            hdrs: Cell::new(false),
62            inner: Cell::new(Some(Box::new(Inner {
63                cfg,
64                st: State::default(),
65                val: None,
66                hdr: httparse::Header::default(),
67                hdr_st: httparse::State::default(),
68                consumed: 0,
69                headers: 0,
70                line: T::Parser::default(),
71                line_st: httparse::State::default(),
72            }))),
73        }
74    }
75
76    pub(super) fn is_reading_hdrs(&self) -> bool {
77        self.hdrs.get()
78    }
79}
80
81impl<T: MessageType> Clone for MessageDecoder<T> {
82    fn clone(&self) -> Self {
83        let inner = self.inner.take().unwrap();
84        let val = MessageDecoder {
85            hdrs: Cell::new(false),
86            inner: Cell::new(Some(Box::new(Inner {
87                st: State::default(),
88                val: None,
89                consumed: 0,
90                headers: 0,
91                line: T::Parser::default(),
92                line_st: httparse::State::default(),
93                hdr: httparse::Header::default(),
94                hdr_st: httparse::State::default(),
95                cfg: inner.cfg.clone(),
96            }))),
97        };
98        self.inner.set(Some(inner));
99        val
100    }
101}
102
103impl<T: MessageType> MessageDecoder<T> {
104    fn decode_headers(src: &mut BytesMut, inner: &mut Inner<T>) -> Poll<Result<(), DecodeError>> {
105        loop {
106            let result = match inner.hdr.parse_with_state(src, &mut inner.hdr_st)? {
107                Status::Complete(result) => result,
108                Status::Partial => return Poll::Pending,
109            };
110            match result {
111                HeaderParsed::Header(len) => {
112                    // repeated header names count separately
113                    if inner.headers >= inner.cfg.max_headers {
114                        return Poll::Ready(Err(DecodeError::MaxHeaders));
115                    }
116                    inner.headers += 1;
117                    let (n, v) = (inner.hdr.name, inner.hdr.value);
118                    // the parser validates name characters, but not its length
119                    let Ok(name) = HeaderName::from_bytes(&src[n.start..n.end]) else {
120                        return Poll::Ready(Err(DecodeError::Header));
121                    };
122
123                    // name and value are split off `src` directly, without
124                    // splitting the whole line first, `pos` is the number of
125                    // bytes of the line already removed from `src`
126                    let mut pos = 0;
127                    let origin = if inner.cfg.headers_vec {
128                        src.advance_to(n.start);
129                        pos = n.end;
130                        Some(src.split_to(n.end - n.start))
131                    } else {
132                        None
133                    };
134                    let value = if v.start == v.end {
135                        Bytes::new()
136                    } else {
137                        src.advance_to(v.start - pos);
138                        pos = v.end;
139                        src.split_to(v.end - v.start)
140                    };
141                    src.advance_to(len - pos);
142
143                    // SAFETY: ntex-httparse checks header value for validity
144                    let value = unsafe { HeaderValue::from_shared_unchecked(value) };
145
146                    if let Some(origin) = origin {
147                        // SAFETY: ntex-httparse checks header name validity
148                        let origin = unsafe { ByteString::from_bytes_unchecked(origin) };
149                        inner.val.as_mut().unwrap().set_headers_item(HeaderItem {
150                            origin,
151                            name: name.clone(),
152                            value: value.clone(),
153                        });
154                    }
155
156                    inner.hdr_st = httparse::State::default();
157                    inner
158                        .val
159                        .as_mut()
160                        .unwrap()
161                        .set_header(&mut inner.st, name, value)?;
162                }
163                HeaderParsed::Eof(len) => {
164                    src.advance_to(len);
165                    inner.hdr_st = httparse::State::default();
166                    break;
167                }
168            }
169        }
170        Poll::Ready(Ok(()))
171    }
172}
173
174impl<T: MessageType> Decoder for MessageDecoder<T> {
175    type Item = (T, PayloadType);
176    type Error = DecodeError;
177
178    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
179        let mut inner = self.inner.take().unwrap();
180        let result = self.decode_message(src, &mut inner);
181        if result.is_err() {
182            // start the next message from a clean state
183            inner.val = None;
184            inner.st = State::default();
185            inner.hdr_st = httparse::State::default();
186            inner.consumed = 0;
187            inner.headers = 0;
188            inner.line_st = httparse::State::default();
189            self.hdrs.set(false);
190        }
191        self.inner.set(Some(inner));
192        result
193    }
194}
195
196impl<T: MessageType> MessageDecoder<T> {
197    fn decode_message(
198        &self,
199        src: &mut BytesMut,
200        inner: &mut Inner<T>,
201    ) -> Result<Option<(T, PayloadType)>, DecodeError> {
202        if !src.is_empty() {
203            self.hdrs.set(true);
204        }
205
206        // leading empty lines are not part of the start line and its size
207        // limit, positions in `line_st` stay valid only while nothing is
208        // removed from `src`
209        if inner.val.is_none() && inner.line_st == httparse::State::default() {
210            let skip = empty_lines(src);
211            if skip > 0 {
212                src.advance_to(skip);
213                inner.consumed += skip;
214            }
215        }
216        let len = src.len();
217        let max_line = inner.cfg.max_start_line_size;
218        if inner.val.is_none() {
219            // RFC 9112 §3: a method that alone exceeds the start-line limit
220            // is rejected as an invalid method, not as a long target
221            if T::REQUEST && len > max_line && !src[..=max_line].contains(&b' ') {
222                return Err(DecodeError::Method);
223            }
224            // the parser resumes from `line_st`, so data of an incomplete
225            // start line is not scanned again on the next read
226            match T::decode(src, &mut inner.line, &mut inner.line_st, &inner.cfg)? {
227                Poll::Ready(_) if len - src.len() > max_line => {
228                    return Err(DecodeError::StartLineTooLong(len - src.len()));
229                }
230                Poll::Ready(val) => {
231                    inner.line_st = httparse::State::default();
232                    inner.st.version = val.msg_version();
233                    inner.st.validate_host = T::REQUEST && inner.cfg.validate_host;
234                    inner.val = Some(val);
235                }
236                Poll::Pending => {}
237            }
238        }
239        if inner.val.is_none() && len > max_line {
240            return Err(DecodeError::StartLineTooLong(len));
241        }
242
243        let (result, buf_size) = if inner.val.is_some() {
244            match MessageDecoder::<T>::decode_headers(src, inner) {
245                Poll::Ready(Ok(())) => {
246                    let mut val = inner.val.take().unwrap();
247                    if T::REQUEST {
248                        inner.st.check_upgrade();
249                    }
250                    let pl_len = inner.st.payload_length();
251                    let pl = val.set_payload_length(&mut inner.st, pl_len)?;
252                    let consumed = inner.consumed + len - src.len();
253                    inner.st = State::default();
254                    inner.consumed = 0;
255                    inner.headers = 0;
256                    self.hdrs.set(false);
257                    (Ok(Some((val, pl))), consumed)
258                }
259                Poll::Pending => {
260                    let buf_size = inner.consumed + len;
261                    inner.consumed = buf_size - src.len();
262                    (Ok(None), buf_size)
263                }
264                Poll::Ready(Err(e)) => (Err(e), 0),
265            }
266        } else {
267            (Ok(None), inner.consumed + len)
268        };
269
270        if buf_size > inner.cfg.max_buf_size {
271            log::trace!("MAX_BUFFER_SIZE of data reached, closing");
272            return Err(DecodeError::TooLarge(buf_size));
273        }
274        result
275    }
276}
277
278impl<T: MessageType> fmt::Debug for MessageDecoder<T> {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.debug_struct("MessageDecoder").finish()
281    }
282}
283
284#[derive(Debug, PartialEq, Eq)]
285pub(crate) enum PayloadLength {
286    Payload(PayloadType),
287    Upgrade,
288    None,
289}
290
291#[allow(clippy::declare_interior_mutable_const)]
292const ZERO: PayloadLength = PayloadLength::Payload(PayloadType::Payload(PayloadDecoder {
293    kind: Cell::new(Kind::Length(0)),
294    merged: Cell::new(0),
295}));
296
297impl PayloadLength {
298    /// Returns true if variant is `None`.
299    fn is_none(&self) -> bool {
300        matches!(self, Self::None)
301    }
302
303    #[allow(clippy::borrow_interior_mutable_const)]
304    /// Returns true if variant is represents zero-length (not none) payload.
305    fn is_zero(&self) -> bool {
306        self == &ZERO
307    }
308}
309
310bitflags::bitflags! {
311    #[derive(Copy, Clone, Debug, Eq, PartialEq, Default)]
312    struct Flags: u16 {
313        const HAS_UPGRADE  = 0b0001;
314        const EXPECT       = 0b0010;
315        const CHUNKED      = 0b0100;
316        const SEEN_TE      = 0b1000;
317        const CONN_CLOSE   = 0b0001_0000;
318        const CONN_KA      = 0b0010_0000;
319        const CONN_UPGRADE = 0b0100_0000;
320        const WS_UPGRADE   = 0b1000_0000;
321        const SEEN_HOST    = 0b0001_0000_0000;
322        const TE_OTHER     = 0b0010_0000_0000;
323        const EMPTY_HOST   = 0b0100_0000_0000;
324    }
325}
326
327#[derive(Default, Debug)]
328pub(crate) struct State {
329    flags: Flags,
330    content_length: Option<u64>,
331    version: Version,
332    validate_host: bool,
333}
334
335impl State {
336    fn connection_types(&self) -> impl Iterator<Item = ConnectionType> {
337        [
338            (Flags::CONN_CLOSE, ConnectionType::Close),
339            (Flags::CONN_KA, ConnectionType::KeepAlive),
340            (Flags::CONN_UPGRADE, ConnectionType::Upgrade),
341        ]
342        .into_iter()
343        .filter_map(|(flag, ctype)| self.flags.contains(flag).then_some(ctype))
344    }
345
346    /// An upgrade requires both `Upgrade` and the `upgrade` connection option,
347    /// see [RFC 9110 section 7.8](https://www.rfc-editor.org/rfc/rfc9110#section-7.8).
348    fn check_upgrade(&mut self) {
349        if !self
350            .flags
351            .contains(Flags::HAS_UPGRADE | Flags::CONN_UPGRADE)
352        {
353            self.flags
354                .remove(Flags::HAS_UPGRADE | Flags::WS_UPGRADE | Flags::CONN_UPGRADE);
355        }
356    }
357
358    fn payload_length(&self) -> PayloadLength {
359        // https://tools.ietf.org/html/rfc7230#section-3.3.3
360        if self.flags.contains(Flags::CHUNKED) {
361            // Chunked encoding
362            PayloadLength::Payload(PayloadType::Payload(PayloadDecoder::chunked()))
363        } else if let Some(len) = self.content_length
364            // some clients (dart) send "content-length: 0" with websocket upgrade
365            && !(len == 0 && self.flags.contains(Flags::WS_UPGRADE))
366        {
367            // Content-Length
368            PayloadLength::Payload(PayloadType::Payload(PayloadDecoder::length(len)))
369        } else if self.flags.contains(Flags::HAS_UPGRADE) {
370            PayloadLength::Upgrade
371        } else {
372            PayloadLength::None
373        }
374    }
375}
376
377pub(crate) trait MessageType: fmt::Debug + Sized {
378    /// `true` for request messages.
379    const REQUEST: bool;
380
381    /// Resumable start line parser.
382    type Parser: Default;
383
384    fn msg_version(&self) -> Version;
385
386    /// `Expect` and `Upgrade` must be ignored in HTTP/1.0 requests,
387    /// see [RFC 9110 section 10.1.1](https://www.rfc-editor.org/rfc/rfc9110#section-10.1.1)
388    /// and [section 7.8](https://www.rfc-editor.org/rfc/rfc9110#section-7.8).
389    fn ignore_http11_features(st: &State) -> bool {
390        Self::REQUEST && st.version < Version::HTTP_11
391    }
392
393    fn headers_mut(&mut self) -> &mut HeaderMap;
394
395    /// Decodes the start line, resuming from `st` saved by a previous
396    /// `Pending` result for the same buffer.
397    fn decode(
398        src: &mut BytesMut,
399        parser: &mut Self::Parser,
400        st: &mut httparse::State,
401        cfg: &HttpServiceConfig,
402    ) -> Result<Poll<Self>, DecodeError>;
403
404    fn set_payload_length(
405        &mut self,
406        st: &mut State,
407        length: PayloadLength,
408    ) -> Result<PayloadType, DecodeError>;
409
410    fn set_headers_item(&mut self, item: HeaderItem);
411
412    fn set_header(
413        &mut self,
414        st: &mut State,
415        name: HeaderName,
416        value: HeaderValue,
417    ) -> Result<(), DecodeError> {
418        match name {
419            header::CONTENT_LENGTH
420                if st.content_length.is_some()
421                    || st.flags.intersects(Flags::CHUNKED | Flags::TE_OTHER) =>
422            {
423                log::trace!("multiple Content-Length or Transfer-Encoding with Content-Length");
424                return Err(DecodeError::Header);
425            }
426            // digits only: no sign, whitespace or other bytes
427            header::CONTENT_LENGTH => {
428                if let Ok(len) = atoi_simd::parse::<u64, true, false>(value.as_bytes()) {
429                    // accept 0 lengths here and remove them in `decode` after all
430                    // headers have been processed to prevent request smuggling issues
431                    st.content_length = Some(len);
432                } else {
433                    log::trace!("illegal Content-Length: {value:?}");
434                    return Err(DecodeError::Header);
435                }
436            }
437            // transfer-encoding
438            header::TRANSFER_ENCODING if st.flags.contains(Flags::SEEN_TE) => {
439                log::trace!("Transfer-Encoding header usage is not allowed");
440                return Err(DecodeError::Header);
441            }
442            header::TRANSFER_ENCODING if st.version == Version::HTTP_11 => {
443                st.flags.insert(Flags::SEEN_TE);
444                let Some((chunked, other)) = transfer_codings(value.as_bytes()) else {
445                    log::trace!("illegal Transfer-Encoding: {value:?}");
446                    return Err(DecodeError::Header);
447                };
448                if st.content_length.is_some() && (chunked || other) {
449                    log::trace!("Transfer-Encoding with Content-Length not allowed");
450                    return Err(DecodeError::Header);
451                }
452                if chunked {
453                    st.flags.insert(Flags::CHUNKED);
454                } else if other {
455                    // a response without final chunked coding is delimited by
456                    // connection close, see https://www.rfc-editor.org/rfc/rfc9112#section-6.3
457                    st.flags.insert(Flags::TE_OTHER);
458                }
459                if Self::REQUEST {
460                    if !chunked {
461                        log::trace!("request without final chunked coding: {value:?}");
462                        return Err(DecodeError::Header);
463                    }
464                    if other {
465                        log::trace!("unsupported transfer coding: {value:?}");
466                        return Err(DecodeError::UnsupportedTransferCoding);
467                    }
468                }
469            }
470            header::TRANSFER_ENCODING if st.version == Version::HTTP_10 => {
471                return Err(DecodeError::InvalidInput(
472                    "Transfer-Encoding is not supported by HTTP/1.0",
473                ));
474            }
475            // connection keep-alive state
476            header::CONNECTION => {
477                let mut flags = connection_flags(value.as_bytes());
478                if Self::ignore_http11_features(st) {
479                    flags.remove(Flags::CONN_UPGRADE);
480                }
481                st.flags.insert(flags);
482            }
483            // https://www.rfc-editor.org/rfc/rfc9112#section-3.2
484            header::HOST if Self::REQUEST => {
485                if st.flags.contains(Flags::SEEN_HOST) {
486                    log::trace!("multiple Host headers not allowed");
487                    return Err(DecodeError::Header);
488                }
489                // `Host = uri-host [ ":" port ]`, an empty value is checked
490                // against the target once the request is complete
491                if value.as_bytes().trim_ascii().is_empty() {
492                    st.flags.insert(Flags::EMPTY_HOST);
493                } else if st.validate_host
494                    && !matches!(
495                        value.to_str().map(urly::Authority::new),
496                        Ok(Ok(host)) if host.userinfo().is_none()
497                    )
498                {
499                    log::trace!("illegal Host: {value:?}");
500                    return Err(DecodeError::Header);
501                }
502                st.flags.insert(Flags::SEEN_HOST);
503            }
504            header::UPGRADE | header::EXPECT if Self::ignore_http11_features(st) => (),
505            header::UPGRADE => {
506                st.flags.insert(Flags::HAS_UPGRADE);
507                if value
508                    .as_bytes()
509                    .trim_ascii()
510                    .eq_ignore_ascii_case(b"websocket")
511                {
512                    st.flags.insert(Flags::WS_UPGRADE);
513                }
514            }
515            // a list of case-insensitive expectations, only `100-continue`
516            // is defined, see RFC 9110 section 10.1.1
517            header::EXPECT
518                if value
519                    .as_bytes()
520                    .split(|&b| b == b',')
521                    .any(|e| e.trim_ascii().eq_ignore_ascii_case(b"100-continue")) =>
522            {
523                st.flags.insert(Flags::EXPECT);
524            }
525            _ => (),
526        }
527
528        self.headers_mut().append(name, value);
529        Ok(())
530    }
531}
532
533impl MessageType for Request {
534    const REQUEST: bool = true;
535
536    type Parser = httparse::Request;
537
538    fn msg_version(&self) -> Version {
539        self.version()
540    }
541
542    fn headers_mut(&mut self) -> &mut HeaderMap {
543        &mut self.head_mut().headers
544    }
545
546    fn decode(
547        src: &mut BytesMut,
548        req: &mut httparse::Request,
549        st: &mut httparse::State,
550        cfg: &HttpServiceConfig,
551    ) -> Result<Poll<Self>, DecodeError> {
552        match req.parse_with_state(src, st)? {
553            Status::Complete(pos) => {
554                let method = Method::from_bytes(&src[req.method.start..req.method.end])
555                    .map_err(|_| DecodeError::Method)?;
556                // RFC 9112 §3.2: request-target is ASCII only, raw UTF-8
557                // must be percent-encoded
558                if !req.path_ascii {
559                    return Err(DecodeError::InvalidInput("Non-ASCII request target"));
560                }
561                // the target is split off `src` directly, the rest of the
562                // request line is skipped
563                src.advance_to(req.path.start);
564                let target = src.split_to(req.path.end - req.path.start);
565                src.advance_to(pos - req.path.end);
566                // the parser found the first `?` during its scan
567                let query = req.query.map(|q| q - req.path.start);
568                // SAFETY: the parser checked that the target is ASCII
569                let target = unsafe { ByteString::from_bytes_unchecked(target) };
570                let mut uri = Url::parse_target_str(target, query)?;
571                let version = if req.version == 1 {
572                    Version::HTTP_11
573                } else {
574                    Version::HTTP_10
575                };
576                crate::http::helpers::process_request_target(
577                    cfg.target_policy(),
578                    &method,
579                    version,
580                    &mut uri,
581                )?;
582
583                let mut msg = Request::new();
584                let head = msg.head_mut();
585                head.uri = uri;
586                head.method = method;
587                head.version = version;
588                Ok(Poll::Ready(msg))
589            }
590            Status::Partial => Ok(Poll::Pending),
591        }
592    }
593
594    fn set_headers_item(&mut self, item: HeaderItem) {
595        self.head_mut().headers_vec.push(item);
596    }
597
598    fn set_payload_length(
599        &mut self,
600        st: &mut State,
601        mut length: PayloadLength,
602    ) -> Result<PayloadType, DecodeError> {
603        // disallow HTTP/1.0 POST requests that do not contain a Content-Length headers
604        // see https://datatracker.ietf.org/doc/html/rfc1945#section-7.2.2
605        if self.version() == Version::HTTP_10 && self.method() == Method::POST && length.is_none() {
606            log::trace!("no Content-Length specified for HTTP/1.0 POST request");
607            return Err(DecodeError::Header);
608        }
609        // https://www.rfc-editor.org/rfc/rfc9112#section-3.2
610        if self.version() >= Version::HTTP_11 && !st.flags.contains(Flags::SEEN_HOST) {
611            log::trace!("no Host header specified for HTTP/1.1 request");
612            return Err(DecodeError::Header);
613        }
614        // RFC 9110 §4.2.1: an `http` URI with an empty host is invalid, an
615        // empty Host is accepted only when the target carries the authority
616        if st.flags.contains(Flags::EMPTY_HOST) && self.uri().authority().is_none() {
617            log::trace!("empty Host header for a target without authority");
618            return Err(DecodeError::Header);
619        }
620        // RFC 6455 §4.1: the websocket opening handshake must be a GET request
621        if st.flags.contains(Flags::WS_UPGRADE) && self.method() != Method::GET {
622            log::trace!("websocket upgrade with {} method", self.method());
623            return Err(DecodeError::InvalidInput(
624                "WebSocket upgrade requires GET method",
625            ));
626        }
627
628        for ctype in st.connection_types() {
629            self.head_mut().set_connection_type(ctype);
630        }
631        if st.flags.contains(Flags::EXPECT) {
632            self.head_mut().set_expect();
633        }
634
635        // Remove CL value if 0 now that all headers and HTTP/1.0 special cases are processed.
636        // Protects against some request smuggling attacks.
637        // See https://github.com/actix/actix-web/issues/2767.
638        if length.is_zero() {
639            length = PayloadLength::None;
640        }
641
642        // payload decoder
643        let decoder = match length {
644            PayloadLength::Payload(pl) => pl,
645            PayloadLength::Upgrade => {
646                // upgrade(websocket)
647                self.head_mut().set_upgrade();
648                PayloadType::Stream(PayloadDecoder::eof())
649            }
650            PayloadLength::None => {
651                if self.method() == Method::CONNECT {
652                    self.head_mut().set_upgrade();
653                    PayloadType::Stream(PayloadDecoder::eof())
654                } else {
655                    PayloadType::None
656                }
657            }
658        };
659
660        Ok(decoder)
661    }
662}
663
664impl MessageType for ResponseHead {
665    const REQUEST: bool = false;
666
667    type Parser = httparse::Response;
668
669    fn msg_version(&self) -> Version {
670        self.version
671    }
672
673    fn headers_mut(&mut self) -> &mut HeaderMap {
674        &mut self.headers
675    }
676
677    fn decode(
678        src: &mut BytesMut,
679        res: &mut httparse::Response,
680        st: &mut httparse::State,
681        _: &HttpServiceConfig,
682    ) -> Result<Poll<Self>, DecodeError> {
683        match res.parse_with_state(src, st)? {
684            Status::Complete(pos) => {
685                let version = if res.version == 1 {
686                    Version::HTTP_11
687                } else {
688                    Version::HTTP_10
689                };
690                let status = StatusCode::from_u16(res.code).map_err(|_| DecodeError::Status)?;
691
692                src.advance_to(pos);
693                Ok(Poll::Ready(ResponseHead::new(status, version)))
694            }
695            Status::Partial => Ok(Poll::Pending),
696        }
697    }
698
699    fn set_headers_item(&mut self, item: HeaderItem) {
700        self.headers_vec.push(item);
701    }
702
703    fn set_payload_length(
704        &mut self,
705        st: &mut State,
706        length: PayloadLength,
707    ) -> Result<PayloadType, DecodeError> {
708        for ctype in st.connection_types() {
709            self.set_connection_type(ctype);
710        }
711
712        // `1xx` (except `101`), `204` and `304` responses never have a body,
713        // `Content-Length` of `304` describes the selected representation
714        if is_bodyless(self.status) {
715            return Ok(PayloadType::None);
716        }
717
718        // message payload
719        let decoder = if self.status == StatusCode::SWITCHING_PROTOCOLS
720            && (length.is_zero() || !matches!(length, PayloadLength::Payload(_)))
721        {
722            // switching protocol
723            PayloadType::Stream(PayloadDecoder::eof())
724        } else if length.is_zero() {
725            PayloadType::None
726        } else if let PayloadLength::Payload(pl) = length {
727            pl
728        } else {
729            // no declared length, read to eof and close connection
730            // see https://www.rfc-editor.org/rfc/rfc9112#section-6.3
731            self.set_connection_type(ConnectionType::Close);
732            PayloadType::Payload(PayloadDecoder::eof())
733        };
734
735        Ok(decoder)
736    }
737}
738
739/// Parses a `Transfer-Encoding` value.
740///
741/// Returns whether `chunked` is the final transfer coding, and whether other
742/// codings are applied, the obsolete `identity` coding is ignored. `None` if
743/// the value is malformed or `chunked` is applied more than once, see
744/// [RFC 9112 section 6.1](https://www.rfc-editor.org/rfc/rfc9112#section-6.1).
745fn transfer_codings(val: &[u8]) -> Option<(bool, bool)> {
746    let mut chunked = false;
747    let mut seen_chunked = false;
748    let mut other = false;
749    // empty list elements are allowed, see RFC 9110 section 5.6.1
750    for coding in val.split(|&b| b == b',').map(<[u8]>::trim_ascii) {
751        if coding.is_empty() {
752            continue;
753        }
754        let name = coding.split(|&b| b == b';').next().unwrap_or_default();
755        let name = name.trim_ascii();
756        if name.is_empty() || !name.iter().copied().all(is_tchar) {
757            return None;
758        }
759        if name.eq_ignore_ascii_case(b"chunked") {
760            // chunked has no parameters
761            if seen_chunked || name.len() != coding.len() {
762                return None;
763            }
764            chunked = true;
765            seen_chunked = true;
766        } else if chunked {
767            // chunked is not the final coding
768            chunked = false;
769            other = true;
770        } else if !name.eq_ignore_ascii_case(b"identity") {
771            other = true;
772        }
773    }
774    Some((chunked, other))
775}
776
777fn connection_flags(val: &[u8]) -> Flags {
778    let mut flags = Flags::empty();
779    for token in val.split(|&b| b == b',') {
780        let token = token.trim_ascii();
781        if token.eq_ignore_ascii_case(b"close") {
782            flags.insert(Flags::CONN_CLOSE);
783        } else if token.eq_ignore_ascii_case(b"keep-alive") {
784            flags.insert(Flags::CONN_KA);
785        } else if token.eq_ignore_ascii_case(b"upgrade") {
786            flags.insert(Flags::CONN_UPGRADE);
787        }
788    }
789    flags
790}
791
792#[derive(Debug, Clone, PartialEq, Eq)]
793/// A decoded HTTP/1 payload item.
794pub enum PayloadItem {
795    /// A payload data chunk.
796    Chunk(Bytes),
797    /// Trailer fields of a chunked payload, [`PayloadItem::Eof`] follows.
798    Trailers(HeaderMap),
799    /// The end of the payload.
800    Eof,
801}
802
803/// Incremental decoder for an HTTP/1 message body.
804///
805/// The decoder handles fixed `Content-Length`, chunked transfer coding, and
806/// bodies delimited by connection EOF. It implements [`Decoder`] and retains
807/// framing state between calls.
808///
809/// Fixed-length and chunked decoders emit [`PayloadItem::Eof`] when their wire
810/// framing completes. An EOF-delimited decoder emits every available byte as a
811/// chunk but cannot infer completion from an empty input buffer; the transport
812/// owner must treat connection closure as the end of that payload.
813///
814/// `Ok(None)` means that more bytes or transport EOF are required. A
815/// [`DecodeError`] reports malformed payload framing, such as an invalid
816/// chunk-size or chunk terminator. Cloning preserves the current payload
817/// framing state.
818///
819/// Chunk extensions are validated and skipped. Trailer fields are buffered
820/// until the trailer section is complete and emitted as
821/// [`PayloadItem::Trailers`]. A chunked payload is rejected with
822/// [`DecodeError::InvalidInput`] if its chunk extensions exceed 16 KiB in
823/// total, or if its trailer section, including line terminators, exceeds
824/// 4 KiB.
825#[derive(Debug, Clone, PartialEq, Eq)]
826pub struct PayloadDecoder {
827    kind: Cell<Kind>,
828    /// number of chunks merged into the last decoded item
829    merged: Cell<u32>,
830}
831
832impl PayloadDecoder {
833    pub(super) fn length(x: u64) -> PayloadDecoder {
834        PayloadDecoder {
835            kind: Cell::new(Kind::Length(x)),
836            merged: Cell::new(0),
837        }
838    }
839
840    pub(super) fn chunked() -> PayloadDecoder {
841        let limits = ChunkedLimits {
842            ext: 0,
843            trailers: 0,
844            line: 0,
845            line_state: SizeLine::Unknown,
846        };
847        PayloadDecoder {
848            kind: Cell::new(Kind::Chunked(ChunkedState::Size, 0, limits)),
849            merged: Cell::new(0),
850        }
851    }
852
853    pub(crate) fn eof() -> PayloadDecoder {
854        PayloadDecoder {
855            kind: Cell::new(Kind::Eof),
856            merged: Cell::new(0),
857        }
858    }
859
860    /// Returns the number of chunks merged into the last decoded data item,
861    /// zero if the item holds a single chunk.
862    pub(super) fn merged_chunks(&self) -> usize {
863        self.merged.get() as usize
864    }
865
866    /// Returns `true` if the payload is delimited by connection close.
867    pub(crate) fn is_eof(&self) -> bool {
868        self.kind.get() == Kind::Eof
869    }
870
871    /// Returns the remaining size of a `Content-Length` delimited payload.
872    pub(super) fn fixed_length(&self) -> Option<u64> {
873        if let Kind::Length(len) = self.kind.get() {
874            Some(len)
875        } else {
876            None
877        }
878    }
879}
880
881#[derive(Debug, Copy, Clone, PartialEq, Eq)]
882enum Kind {
883    /// A Reader used when a Content-Length header is passed with a positive
884    /// integer.
885    Length(u64),
886    /// A Reader used when Transfer-Encoding is `chunked`.
887    ///
888    /// Holds the chunked state, the remaining size of the current chunk and
889    /// the size limits.
890    Chunked(ChunkedState, u64, ChunkedLimits),
891    /// A Reader used for responses that don't indicate a length or chunked.
892    ///
893    /// Note: This should only used for `Response`s. It is illegal for a
894    /// `Request` to be made with both `Content-Length` and
895    /// `Transfer-Encoding: chunked` missing, as explained from the spec:
896    ///
897    /// > If a Transfer-Encoding header field is present in a response and
898    /// > the chunked transfer coding is not the final encoding, the
899    /// > message body length is determined by reading the connection until
900    /// > it is closed by the server.  If a Transfer-Encoding header field
901    /// > is present in a request and the chunked transfer coding is not
902    /// > the final encoding, the message body length cannot be determined
903    /// > reliably; the server MUST respond with the 400 (Bad Request)
904    /// > status code and then close the connection.
905    Eof,
906}
907
908/// Maximum number of chunk-size line bytes beyond the size digits, such as
909/// chunk extensions, accepted for a chunked payload.
910const MAX_CHUNK_EXTENSIONS: u32 = 16 * 1024;
911
912/// Maximum size of the trailer section, including line terminators, accepted
913/// for a chunked payload.
914const MAX_CHUNK_TRAILERS: u32 = 4 * 1024;
915
916/// Chunks smaller than this are merged with the following chunks.
917const SMALL_CHUNK: usize = 1024;
918
919/// Maximum size of merged chunks.
920const MAX_MERGED_CHUNKS: usize = 16 * 1024;
921
922/// Maximum number of chunks merged into one item, it bounds the decoding work
923/// of one call for tiny chunks.
924const MAX_MERGED_COUNT: usize = 1024;
925
926#[derive(Debug, Copy, Clone, PartialEq, Eq)]
927struct ChunkedLimits {
928    /// chunk-size line bytes beyond the size digits received so far
929    ext: u32,
930    /// trailer section bytes of complete field lines, they are validated
931    trailers: u32,
932    /// bytes of a partially received chunk-size line that are validated
933    line: u32,
934    /// parser state at the end of the validated bytes
935    line_state: SizeLine,
936}
937
938/// Parser state of a partially received chunk-size line.
939#[derive(Debug, Copy, Clone, PartialEq, Eq)]
940enum SizeLine {
941    /// the line must be parsed from the start
942    Unknown,
943    /// whitespace after the chunk size
944    Lws,
945    /// chunk extensions
946    Ext,
947}
948
949impl SizeLine {
950    /// Returns `true` if bytes do not change the parser state.
951    fn is_neutral(self, bytes: &[u8]) -> bool {
952        match self {
953            SizeLine::Unknown => false,
954            SizeLine::Lws => bytes.iter().all(|&b| b == b' ' || b == b'\t'),
955            // any octet except control characters other than HTAB, `\r` ends the line
956            // and the complete line, with the extension grammar, is parsed again
957            SizeLine::Ext => bytes
958                .iter()
959                .all(|&b| b == b'\t' || (b >= 0x20 && b != 0x7f)),
960        }
961    }
962}
963
964#[derive(Debug, PartialEq, Eq, Copy, Clone)]
965enum ChunkedState {
966    Size,
967    Body,
968    BodyCr,
969    BodyLf,
970    EndCr,
971    EndLf,
972    Trailers,
973    End,
974}
975
976impl Decoder for PayloadDecoder {
977    type Item = PayloadItem;
978    type Error = DecodeError;
979
980    fn decode(&self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
981        let mut kind = self.kind.get();
982
983        match kind {
984            Kind::Length(ref mut remaining) => {
985                if *remaining == 0 {
986                    Ok(Some(PayloadItem::Eof))
987                } else {
988                    if src.is_empty() {
989                        return Ok(None);
990                    }
991                    let len = src.len() as u64;
992                    let buf;
993                    if *remaining > len {
994                        buf = src.take();
995                        *remaining -= len;
996                    } else {
997                        buf = src.split_to(*remaining as usize);
998                        *remaining = 0;
999                    }
1000                    self.kind.set(kind);
1001                    log::trace!("Length read: {}", buf.len());
1002                    Ok(Some(PayloadItem::Chunk(buf)))
1003                }
1004            }
1005            Kind::Chunked(ref mut state, ref mut size, ref mut limits) => {
1006                // small chunks are merged into one item, the payload of tiny
1007                // chunks would be buffered as many items
1008                let mut data: Option<Bytes> = None;
1009                let mut merged: Option<BytesMut> = None;
1010                let mut count = 0;
1011                let mut trailers: Option<HeaderMap> = None;
1012                let result = loop {
1013                    // complete small chunks are read without the state machine
1014                    if *state == ChunkedState::Size
1015                        && limits.line == 0
1016                        && (ChunkedState::read_small_chunks(
1017                            src,
1018                            &mut data,
1019                            &mut merged,
1020                            &mut count,
1021                        ) || src.is_empty())
1022                    {
1023                        break Ok(None);
1024                    }
1025
1026                    // a large chunk is not copied into merged chunks
1027                    if *state == ChunkedState::Body && *size >= SMALL_CHUNK as u64 && data.is_some()
1028                    {
1029                        break Ok(None);
1030                    }
1031                    // data is returned before trailers
1032                    if *state == ChunkedState::Trailers && data.is_some() {
1033                        break Ok(None);
1034                    }
1035
1036                    let mut buf = None;
1037                    // advances the chunked state
1038                    *state = match state.step(src, size, limits, &mut buf, &mut trailers) {
1039                        Poll::Pending => break Ok(None),
1040                        Poll::Ready(Ok(state)) => state,
1041                        Poll::Ready(Err(e)) => break Err(e),
1042                    };
1043
1044                    if *state == ChunkedState::End {
1045                        log::trace!("End of chunked stream");
1046                        break Ok(Some(
1047                            trailers
1048                                .take()
1049                                .map_or(PayloadItem::Eof, PayloadItem::Trailers),
1050                        ));
1051                    }
1052
1053                    if let Some(buf) = buf {
1054                        count += 1;
1055                        let len = if let Some(first) = &data {
1056                            let m = merged
1057                                .get_or_insert_with(|| merge_buf(first, buf.len() + src.len()));
1058                            m.extend_from_slice(&buf);
1059                            m.len()
1060                        } else {
1061                            let len = buf.len();
1062                            data = Some(buf);
1063                            len
1064                        };
1065                        if count >= MAX_MERGED_COUNT
1066                            || (len >= SMALL_CHUNK
1067                                && (merged.is_none() || len >= MAX_MERGED_CHUNKS))
1068                        {
1069                            break Ok(None);
1070                        }
1071                    }
1072                    if src.is_empty() {
1073                        break Ok(None);
1074                    }
1075                };
1076                self.kind.set(kind);
1077
1078                // the end of the payload is reported on the next call
1079                match result {
1080                    Ok(_) if data.is_some() => {
1081                        let data = if let Some(merged) = merged {
1082                            self.merged.set(count as u32);
1083                            merged.freeze()
1084                        } else {
1085                            self.merged.set(0);
1086                            data.unwrap()
1087                        };
1088                        Ok(Some(PayloadItem::Chunk(data)))
1089                    }
1090                    result => result,
1091                }
1092            }
1093            Kind::Eof => {
1094                if src.is_empty() {
1095                    Ok(None)
1096                } else {
1097                    Ok(Some(PayloadItem::Chunk(src.take())))
1098                }
1099            }
1100        }
1101    }
1102}
1103
1104/// Parses a complete chunk smaller than [`SMALL_CHUNK`], without chunk
1105/// extensions or whitespace: `HEXDIG{1,16} CRLF data CRLF`.
1106///
1107/// Returns the data offset and size. Other input, including invalid input,
1108/// returns `None` and is left to the chunked state machine.
1109#[inline]
1110fn small_chunk(buf: &[u8]) -> Option<(usize, usize)> {
1111    let mut size = 0;
1112    let mut pos = 0;
1113    loop {
1114        let digit = match *buf.get(pos)? {
1115            b @ b'0'..=b'9' => b - b'0',
1116            b @ b'a'..=b'f' => b - b'a' + 10,
1117            b @ b'A'..=b'F' => b - b'A' + 10,
1118            b'\r' => break,
1119            _ => return None,
1120        };
1121        // the chunk size has at most 16 digits
1122        if pos == 16 {
1123            return None;
1124        }
1125        size = size * 16 + usize::from(digit);
1126        if size >= SMALL_CHUNK {
1127            return None;
1128        }
1129        pos += 1;
1130    }
1131    let start = pos + 2;
1132    let end = start + size;
1133    if size == 0
1134        || buf.get(pos + 1) != Some(&b'\n')
1135        || buf.get(end..end + 2) != Some(b"\r\n".as_slice())
1136    {
1137        return None;
1138    }
1139    Some((start, size))
1140}
1141
1142/// Creates the merged data of chunks, starting with `first` and followed by at
1143/// most `more` bytes of input.
1144fn merge_buf(first: &[u8], more: usize) -> BytesMut {
1145    // the following chunks are expected to be of a similar size
1146    let cap = (first.len() + more)
1147        .min(MAX_MERGED_CHUNKS)
1148        .min(first.len() * MAX_MERGED_COUNT);
1149    let mut m = BytesMut::with_capacity(cap);
1150    m.extend_from_slice(first);
1151    m
1152}
1153
1154macro_rules! byte (
1155    ($rdr:ident) => ({
1156        if $rdr.len() > 0 {
1157            let b = $rdr[0];
1158            $rdr.advance_to(1);
1159            b
1160        } else {
1161            return Poll::Pending
1162        }
1163    })
1164);
1165
1166impl ChunkedState {
1167    fn step(
1168        self,
1169        body: &mut BytesMut,
1170        size: &mut u64,
1171        limits: &mut ChunkedLimits,
1172        buf: &mut Option<Bytes>,
1173        trailers: &mut Option<HeaderMap>,
1174    ) -> Poll<Result<ChunkedState, DecodeError>> {
1175        match self {
1176            ChunkedState::Size => ChunkedState::read_size(body, size, limits),
1177            ChunkedState::Body => ChunkedState::read_body(body, size, buf),
1178            ChunkedState::BodyCr => ChunkedState::read_body_cr(body),
1179            ChunkedState::BodyLf => ChunkedState::read_body_lf(body),
1180            ChunkedState::EndCr => ChunkedState::read_end_cr(body),
1181            ChunkedState::EndLf => ChunkedState::read_end_lf(body),
1182            ChunkedState::Trailers => ChunkedState::read_trailers(body, limits, trailers),
1183            ChunkedState::End => Poll::Ready(Ok(ChunkedState::End)),
1184        }
1185    }
1186
1187    /// Reads complete small chunks, a fast path of [`ChunkedState::Size`].
1188    ///
1189    /// The first chunk is not copied, the following chunks are merged until
1190    /// [`MAX_MERGED_CHUNKS`] bytes or [`MAX_MERGED_COUNT`] chunks. Returns
1191    /// `true` if the merged data is full.
1192    fn read_small_chunks(
1193        src: &mut BytesMut,
1194        data: &mut Option<Bytes>,
1195        merged: &mut Option<BytesMut>,
1196        count: &mut usize,
1197    ) -> bool {
1198        if data.is_none() {
1199            let Some((start, size)) = small_chunk(src) else {
1200                return false;
1201            };
1202            src.advance_to(start);
1203            *data = Some(src.split_to(size));
1204            src.advance_to(2);
1205            *count += 1;
1206        }
1207        let Some(first) = data.as_ref() else {
1208            return false;
1209        };
1210
1211        let mut len = merged.as_ref().map_or(first.len(), BytesMut::len);
1212        let mut pos = 0;
1213        while len < MAX_MERGED_CHUNKS && *count < MAX_MERGED_COUNT {
1214            let Some((start, size)) = small_chunk(&src[pos..]) else {
1215                break;
1216            };
1217            let m = merged.get_or_insert_with(|| merge_buf(first, src.len()));
1218            m.extend_from_slice(&src[pos + start..pos + start + size]);
1219            len = m.len();
1220            pos += start + size + 2;
1221            *count += 1;
1222        }
1223        if pos != 0 {
1224            src.advance_to(pos);
1225        }
1226        len >= MAX_MERGED_CHUNKS || *count >= MAX_MERGED_COUNT
1227    }
1228
1229    /// Reads a chunk-size line.
1230    ///
1231    /// Bytes beyond the size digits, chunk extensions and whitespace, are
1232    /// ignored but count against [`MAX_CHUNK_EXTENSIONS`] for the whole
1233    /// payload, which also bounds a partially received line.
1234    fn read_size(
1235        rdr: &mut BytesMut,
1236        size: &mut u64,
1237        limits: &mut ChunkedLimits,
1238    ) -> Poll<Result<ChunkedState, DecodeError>> {
1239        // at most 16 size digits and CRLF
1240        let max = (MAX_CHUNK_EXTENSIONS - limits.ext) as usize + 18;
1241
1242        // bytes of a partial line are validated once, new bytes that do
1243        // not change the parser state do not need to parse the line again
1244        let line = limits.line as usize;
1245        if line != 0 && line <= rdr.len() && limits.line_state.is_neutral(&rdr[line..]) {
1246            return if rdr.len() > max {
1247                Poll::Ready(Err(DecodeError::InvalidInput(
1248                    "Chunk extensions are too large",
1249                )))
1250            } else {
1251                limits.line = rdr.len() as u32;
1252                Poll::Pending
1253            };
1254        }
1255
1256        match httparse::parse_chunk_size(rdr) {
1257            Ok(httparse::Status::Complete((pos, sz))) => {
1258                limits.line = 0;
1259                limits.line_state = SizeLine::Unknown;
1260
1261                let digits = rdr.iter().take_while(|b| b.is_ascii_hexdigit()).count();
1262                // the line ends with CRLF
1263                limits.ext = limits.ext.saturating_add((pos - digits - 2) as u32);
1264                if limits.ext > MAX_CHUNK_EXTENSIONS {
1265                    return Poll::Ready(Err(DecodeError::InvalidInput(
1266                        "Chunk extensions are too large",
1267                    )));
1268                }
1269                rdr.advance_to(pos);
1270                *size = sz;
1271                if sz > 0 {
1272                    Poll::Ready(Ok(ChunkedState::Body))
1273                } else {
1274                    Poll::Ready(Ok(ChunkedState::EndCr))
1275                }
1276            }
1277            Ok(httparse::Status::Partial) => {
1278                if rdr.len() > max {
1279                    return Poll::Ready(Err(DecodeError::InvalidInput(
1280                        "Chunk extensions are too large",
1281                    )));
1282                }
1283                limits.line = rdr.len() as u32;
1284                limits.line_state = if rdr.last() == Some(&b'\r') {
1285                    // `\n` must follow
1286                    SizeLine::Unknown
1287                } else if rdr.contains(&b';') {
1288                    SizeLine::Ext
1289                } else if rdr.iter().any(|&b| b == b' ' || b == b'\t') {
1290                    SizeLine::Lws
1291                } else {
1292                    SizeLine::Unknown
1293                };
1294                Poll::Pending
1295            }
1296            Err(_) => Poll::Ready(Err(DecodeError::InvalidInput(
1297                "Invalid chunk size line: Invalid Size",
1298            ))),
1299        }
1300    }
1301
1302    fn read_body(
1303        rdr: &mut BytesMut,
1304        rem: &mut u64,
1305        buf: &mut Option<Bytes>,
1306    ) -> Poll<Result<ChunkedState, DecodeError>> {
1307        log::trace!("Chunked read, remaining={rem:?}");
1308
1309        let len = rdr.len() as u64;
1310        if len == 0 {
1311            Poll::Ready(Ok(ChunkedState::Body))
1312        } else {
1313            let slice;
1314            if *rem > len {
1315                slice = rdr.take();
1316                *rem -= len;
1317            } else {
1318                slice = rdr.split_to(*rem as usize);
1319                *rem = 0;
1320            }
1321            *buf = Some(slice);
1322            if *rem > 0 {
1323                Poll::Ready(Ok(ChunkedState::Body))
1324            } else {
1325                Poll::Ready(Ok(ChunkedState::BodyCr))
1326            }
1327        }
1328    }
1329
1330    fn read_body_cr(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, DecodeError>> {
1331        match byte!(rdr) {
1332            b'\r' => Poll::Ready(Ok(ChunkedState::BodyLf)),
1333            _ => Poll::Ready(Err(DecodeError::InvalidInput("Invalid chunk body CR"))),
1334        }
1335    }
1336
1337    fn read_body_lf(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, DecodeError>> {
1338        match byte!(rdr) {
1339            b'\n' => Poll::Ready(Ok(ChunkedState::Size)),
1340            _ => Poll::Ready(Err(DecodeError::InvalidInput("Invalid chunk body LF"))),
1341        }
1342    }
1343
1344    fn read_end_cr(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, DecodeError>> {
1345        match rdr.first() {
1346            None => Poll::Pending,
1347            Some(b'\r') => {
1348                rdr.advance_to(1);
1349                Poll::Ready(Ok(ChunkedState::EndLf))
1350            }
1351            // trailer field, must start with a field name character
1352            Some(&b) if is_tchar(b) => Poll::Ready(Ok(ChunkedState::Trailers)),
1353            Some(_) => Poll::Ready(Err(DecodeError::InvalidInput("Invalid chunk end CR"))),
1354        }
1355    }
1356
1357    /// Reads the trailer section, it is buffered until the section is complete.
1358    ///
1359    /// Field lines, including line terminators, count against
1360    /// [`MAX_CHUNK_TRAILERS`]. Complete field lines are validated once.
1361    fn read_trailers(
1362        rdr: &mut BytesMut,
1363        limits: &mut ChunkedLimits,
1364        trailers: &mut Option<HeaderMap>,
1365    ) -> Poll<Result<ChunkedState, DecodeError>> {
1366        const TOO_LARGE: DecodeError = DecodeError::InvalidInput("Chunked trailers are too large");
1367        const INVALID: DecodeError = DecodeError::InvalidInput("Invalid chunked trailer field");
1368
1369        let mut pos = limits.trailers as usize;
1370        while pos < rdr.len() {
1371            if rdr[pos] == b'\r' {
1372                // the end of the trailer section
1373                return match rdr.get(pos + 1) {
1374                    None => break,
1375                    Some(b'\n') => {
1376                        let section = rdr.split_to(pos + 2);
1377                        let mut hdrs = HeaderMap::new();
1378                        for line in section[..pos].split(|&b| b == b'\n') {
1379                            let Some(line) = line.strip_suffix(b"\r") else {
1380                                continue;
1381                            };
1382                            let (name, value) = trailer_field(line).ok_or(INVALID)?;
1383                            hdrs.append(
1384                                HeaderName::from_bytes(name).map_err(|_| INVALID)?,
1385                                HeaderValue::from_bytes(value).map_err(|_| INVALID)?,
1386                            );
1387                        }
1388                        *trailers = Some(hdrs);
1389                        Poll::Ready(Ok(ChunkedState::End))
1390                    }
1391                    Some(_) => Poll::Ready(Err(DecodeError::InvalidInput("Invalid chunk end LF"))),
1392                };
1393            }
1394            if !is_tchar(rdr[pos]) {
1395                return Poll::Ready(Err(INVALID));
1396            }
1397
1398            // a field line
1399            let Some(end) = rdr[pos..].iter().position(|&b| b == b'\r') else {
1400                break;
1401            };
1402            if trailer_field(&rdr[pos..pos + end]).is_none() {
1403                return Poll::Ready(Err(INVALID));
1404            }
1405            match rdr.get(pos + end + 1) {
1406                None => break,
1407                Some(b'\n') => {
1408                    pos += end + 2;
1409                    if pos > MAX_CHUNK_TRAILERS as usize {
1410                        return Poll::Ready(Err(TOO_LARGE));
1411                    }
1412                }
1413                Some(_) => {
1414                    return Poll::Ready(Err(DecodeError::InvalidInput(
1415                        "Invalid chunked trailer field LF",
1416                    )));
1417                }
1418            }
1419        }
1420        limits.trailers = pos as u32;
1421
1422        // an incomplete field line
1423        if rdr.len() > MAX_CHUNK_TRAILERS as usize && rdr.get(pos) != Some(&b'\r') {
1424            Poll::Ready(Err(TOO_LARGE))
1425        } else {
1426            Poll::Pending
1427        }
1428    }
1429
1430    fn read_end_lf(rdr: &mut BytesMut) -> Poll<Result<ChunkedState, DecodeError>> {
1431        match byte!(rdr) {
1432            b'\n' => Poll::Ready(Ok(ChunkedState::End)),
1433            _ => Poll::Ready(Err(DecodeError::InvalidInput("Invalid chunk end LF"))),
1434        }
1435    }
1436}
1437
1438/// Returns the length of complete empty lines at the start of `buf`.
1439fn empty_lines(buf: &[u8]) -> usize {
1440    let mut pos = 0;
1441    loop {
1442        match &buf[pos..] {
1443            [b'\n', ..] => pos += 1,
1444            [b'\r', b'\n', ..] => pos += 2,
1445            _ => return pos,
1446        }
1447    }
1448}
1449
1450/// Splits a trailer field line into its name and value.
1451fn trailer_field(line: &[u8]) -> Option<(&[u8], &[u8])> {
1452    let colon = line.iter().position(|&b| b == b':')?;
1453    let (name, value) = (&line[..colon], &line[colon + 1..]);
1454    let valid = !name.is_empty()
1455        && name.iter().all(|&b| is_tchar(b))
1456        && value
1457            .iter()
1458            .all(|&b| b == b'\t' || (b' '..=b'~').contains(&b) || b >= 0x80);
1459    valid.then(|| (name, value.trim_ascii()))
1460}
1461
1462/// Checks for a `tchar`, see [RFC 9110 section 5.6.2](https://www.rfc-editor.org/rfc/rfc9110#section-5.6.2).
1463fn is_tchar(b: u8) -> bool {
1464    b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
1465}
1466
1467#[cfg(test)]
1468mod tests {
1469    use super::*;
1470    use crate::http::{HttpMessage, header, header::SET_COOKIE};
1471    use crate::service::cfg::SharedCfg;
1472
1473    impl PayloadType {
1474        fn unwrap(self) -> PayloadDecoder {
1475            if let PayloadType::Payload(pl) = self {
1476                pl
1477            } else {
1478                panic!()
1479            }
1480        }
1481
1482        fn is_unhandled(&self) -> bool {
1483            matches!(self, PayloadType::Stream(_))
1484        }
1485    }
1486
1487    impl PayloadItem {
1488        fn chunk(self) -> Bytes {
1489            match self {
1490                PayloadItem::Chunk(chunk) => chunk,
1491                PayloadItem::Trailers(_) | PayloadItem::Eof => panic!("error"),
1492            }
1493        }
1494        fn eof(&self) -> bool {
1495            matches!(*self, PayloadItem::Eof)
1496        }
1497    }
1498
1499    macro_rules! parse_ready {
1500        ($e:expr) => {{
1501            match MessageDecoder::<Request>::default().decode($e) {
1502                Ok(Some((msg, _))) => msg,
1503                Ok(_) => unreachable!("Eof during parsing http request"),
1504                Err(err) => unreachable!("Error during parsing http request: {:?}", err),
1505            }
1506        }};
1507    }
1508
1509    macro_rules! expect_parse_err {
1510        ($e:expr) => {{
1511            match MessageDecoder::<Request>::default().decode($e) {
1512                Err(_) => (),
1513                _ => unreachable!("Error expected"),
1514            }
1515        }};
1516    }
1517
1518    /// STATEMENT: Asterisk-form is accepted only for OPTIONS, with or without target processing.
1519    ///
1520    /// HOW:
1521    /// - Decode `OPTIONS *` with the default and the normalizing decoder and check `*` is kept.
1522    /// - Decode `*` with other methods and require both decoders to reject it.
1523    #[test]
1524    fn test_asterisk_form_options_only() {
1525        let cfg: SharedCfg = SharedCfg::new("test")
1526            .add(HttpServiceConfig::new().set_request_target_normalization(true))
1527            .into();
1528        let reader = MessageDecoder::<Request>::new(cfg.get());
1529        let mut buf = BytesMut::from("OPTIONS * HTTP/1.1\r\nhost: a\r\n\r\n");
1530        let req = parse_ready!(&mut buf.clone());
1531        assert_eq!(req.path(), "*");
1532        assert_eq!(reader.decode(&mut buf).unwrap().unwrap().0.path(), "*");
1533
1534        for method in ["GET", "POST", "HEAD", "CONNECT"] {
1535            let mut buf =
1536                BytesMut::from(format!("{method} * HTTP/1.1\r\nhost: a\r\n\r\n").as_str());
1537            expect_parse_err!(&mut buf.clone());
1538            assert!(reader.decode(&mut buf).is_err(), "{method}");
1539        }
1540    }
1541
1542    /// STATEMENT: Authority-form restrictions and syntax are checked by opt-in decoding.
1543    ///
1544    /// HOW:
1545    /// - Decode CONNECT, absolute targets, userinfo and invalid CONNECT forms.
1546    /// - Check opt-in decoding rejects inappropriate methods and malformed authorities.
1547    #[test]
1548    fn test_authority_form_validation_opt_in() {
1549        let cfg: SharedCfg = SharedCfg::new("test")
1550            .add(HttpServiceConfig::new().set_request_target_normalization(true))
1551            .into();
1552        let reader = MessageDecoder::<Request>::new(cfg.get());
1553        let mut buf = BytesMut::from("CONNECT example.com:443 HTTP/1.1\r\nhost: a\r\n\r\n");
1554        let req = parse_ready!(&mut buf.clone());
1555        assert_eq!(req.uri().authority().unwrap(), "example.com:443");
1556        assert!(reader.decode(&mut buf).unwrap().is_some());
1557
1558        let mut buf = BytesMut::from("GET http://example.com/ HTTP/1.1\r\nhost: a\r\n\r\n");
1559        let req = reader.decode(&mut buf).unwrap().unwrap().0;
1560        assert_eq!(req.path(), "/");
1561
1562        // userinfo is rejected only with validation enabled
1563        let mut buf = BytesMut::from("GET http://[email protected]/ HTTP/1.1\r\nhost: a\r\n\r\n");
1564        let _ = parse_ready!(&mut buf.clone());
1565        assert!(reader.decode(&mut buf).is_err());
1566
1567        for method in ["GET", "POST", "HEAD", "OPTIONS"] {
1568            let mut buf = BytesMut::from(
1569                format!("{method} example.com:443 HTTP/1.1\r\nhost: a\r\n\r\n").as_str(),
1570            );
1571            let _ = parse_ready!(&mut buf.clone());
1572            assert!(reader.decode(&mut buf).is_err(), "{method}");
1573        }
1574
1575        let mut buf = BytesMut::from("CONNECT [::1]:443 HTTP/1.1\r\nhost: a\r\n\r\n");
1576        let req = reader.decode(&mut buf).unwrap().unwrap().0;
1577        assert_eq!(req.uri().authority().unwrap(), "[::1]:443");
1578
1579        for target in [
1580            "/",
1581            "/test",
1582            "http://example.com:443/",
1583            "u@h:1",
1584            ":443",
1585            "h:1?q",
1586        ] {
1587            let mut buf =
1588                BytesMut::from(format!("CONNECT {target} HTTP/1.1\r\nhost: a\r\n\r\n").as_str());
1589            let _ = parse_ready!(&mut buf.clone());
1590            assert!(reader.decode(&mut buf).is_err(), "{target}");
1591        }
1592    }
1593
1594    /// STATEMENT: HTTP/1 preserves raw targets by default and optionally validates them while decoding.
1595    ///
1596    /// HOW:
1597    /// - Decode dot segments, escapes, browser-compatible characters and double-slash paths.
1598    /// - Check raw path/query values and check malformed targets fail only with processing enabled.
1599    #[test]
1600    fn test_request_target() {
1601        let cfg: SharedCfg = SharedCfg::new("test")
1602            .add(HttpServiceConfig::new().set_request_target_normalization(true))
1603            .into();
1604        let reader = MessageDecoder::<Request>::new(cfg.get());
1605        for (target, path_and_query) in [
1606            ("/a/../b", "/a/../b"),
1607            ("/a/%2e%2E/b", "/a/%2e%2E/b"),
1608            ("/%7e%3b%2f?%7E%3d", "/%7e%3b%2f?%7E%3d"),
1609            ("/a[0]|^`{}?a[]=1&b=%00", "/a[0]|^`{}?a[]=1&b=%00"),
1610            ("//a//b?c", "//a//b?c"),
1611            ("http://example.com//a", "//a"),
1612            ("HTTP://Example.COM/a/../%7e?x=%41", "/a/../%7e?x=%41"),
1613        ] {
1614            let mut buf =
1615                BytesMut::from(format!("GET {target} HTTP/1.1\r\nhost: a\r\n\r\n").as_str());
1616            let req = parse_ready!(&mut buf.clone());
1617            assert_eq!(req.uri().path_and_query(), path_and_query, "{target}");
1618            assert!(reader.decode(&mut buf).unwrap().is_some(), "{target}");
1619        }
1620
1621        for target in [
1622            "http:///x",
1623            "a/b",
1624            "http://[::1/",
1625            "/a#frag",
1626            "/a?b=c#frag",
1627            "/a%zz",
1628            "/a%",
1629            "/a\"",
1630            "/a<b>",
1631            "/a\\b",
1632            "/a%00b",
1633            "http://example.com/%00",
1634        ] {
1635            let mut buf =
1636                BytesMut::from(format!("GET {target} HTTP/1.1\r\nhost: a\r\n\r\n").as_str());
1637            let _ = parse_ready!(&mut buf.clone());
1638            assert!(reader.decode(&mut buf).is_err(), "{target}");
1639        }
1640    }
1641
1642    /// STATEMENT: Opt-in target normalization handles partial reads and rejects expanding URLs.
1643    ///
1644    /// HOW:
1645    /// - Decode a split request line and check normalized scheme, host, port, path and query.
1646    /// - Reject a target exceeding the URL limit after encoding, then reuse the decoder successfully.
1647    #[test]
1648    fn test_request_target_normalization() {
1649        let cfg: SharedCfg = SharedCfg::new("test")
1650            .add(
1651                HttpServiceConfig::new()
1652                    .set_request_target_normalization(true)
1653                    .set_max_start_line_size(32 * 1024),
1654            )
1655            .into();
1656        let reader = MessageDecoder::<Request>::new(cfg.get());
1657        let mut buf = BytesMut::from("GET HTTPS://Example.COM:00443/a/../");
1658        assert!(reader.decode(&mut buf).unwrap().is_none());
1659        buf.extend_from_slice(b"%74est?q=%7e HTTP/1.1\r\nhost: a\r\n\r\n");
1660        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
1661        assert_eq!(req.uri().as_str(), "https://example.com/test?q=~");
1662
1663        let target = format!("/{}", "[".repeat(22000));
1664        let mut buf = BytesMut::from(format!("GET {target} HTTP/1.1\r\n\r\n").as_str());
1665        assert!(matches!(reader.decode(&mut buf), Err(DecodeError::Uri)));
1666
1667        let mut buf = BytesMut::from("GET /.//%74est HTTP/1.1\r\nhost: a\r\n\r\n");
1668        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
1669        assert_eq!(req.path(), "//test");
1670        assert!(req.uri().authority().is_none());
1671    }
1672
1673    /// STATEMENT: Validation-only target processing rejects malformed targets without rewriting valid ones.
1674    ///
1675    /// HOW:
1676    /// - Enable `set_request_target_validation` and decode unnormalized origin and absolute targets.
1677    /// - Check the decoded URI keeps the exact spelling, including escapes, dot segments and case.
1678    /// - Check malformed escapes, fragments, misplaced asterisk-form and userinfo are rejected.
1679    /// - Check validation stays enabled when normalization is explicitly disabled and
1680    ///   normalization still rewrites when both options are enabled.
1681    #[test]
1682    fn test_request_target_validation_only() {
1683        let cfg: SharedCfg = SharedCfg::new("test")
1684            .add(
1685                HttpServiceConfig::new()
1686                    .set_request_target_validation(true)
1687                    .set_request_target_normalization(false),
1688            )
1689            .into();
1690        let reader = MessageDecoder::<Request>::new(cfg.get());
1691        for target in [
1692            "/%41/../b?x=%7e",
1693            "/a/./b//c",
1694            "HTTPS://Example.COM:00443/a/../%7e",
1695        ] {
1696            let mut buf =
1697                BytesMut::from(format!("GET {target} HTTP/1.1\r\nhost: a\r\n\r\n").as_str());
1698            let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
1699            assert_eq!(req.uri().to_string(), target);
1700        }
1701        let mut buf = BytesMut::from("OPTIONS * HTTP/1.1\r\nhost: a\r\n\r\n");
1702        assert_eq!(reader.decode(&mut buf).unwrap().unwrap().0.path(), "*");
1703
1704        for (method, target) in [
1705            ("GET", "/a%zz"),
1706            ("GET", "/a#frag"),
1707            ("GET", "*"),
1708            ("GET", "http://[email protected]/"),
1709            ("GET", "example.com:443"),
1710        ] {
1711            let mut buf =
1712                BytesMut::from(format!("{method} {target} HTTP/1.1\r\nhost: a\r\n\r\n").as_str());
1713            assert!(reader.decode(&mut buf).is_err(), "{target}");
1714        }
1715
1716        let cfg: SharedCfg = SharedCfg::new("test")
1717            .add(
1718                HttpServiceConfig::new()
1719                    .set_request_target_validation(true)
1720                    .set_request_target_normalization(true),
1721            )
1722            .into();
1723        let reader = MessageDecoder::<Request>::new(cfg.get());
1724        let mut buf = BytesMut::from("GET /%41/../b?x=%7e HTTP/1.1\r\nhost: a\r\n\r\n");
1725        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
1726        assert_eq!(req.uri().path_and_query(), "/b?x=~");
1727    }
1728
1729    /// STATEMENT: Incremental parsing rejects a header name exceeding its representable length.
1730    ///
1731    /// HOW:
1732    /// - Feed a request line and near-limit partial name, then finish an oversized name and check the header error.
1733    #[test]
1734    fn test_too_long_header_name() {
1735        let mut buf = BytesMut::from("GET / HTTP/1.1\r\n");
1736        let reader = MessageDecoder::<Request>::default();
1737        assert!(reader.decode(&mut buf).unwrap().is_none());
1738
1739        // the partial name stays within the buffer limit
1740        buf.extend_from_slice("a".repeat(64 * 1024 - 16).as_bytes());
1741        assert!(reader.decode(&mut buf).unwrap().is_none());
1742
1743        buf.extend_from_slice(b"aaaaaaaaaaaaaaaaaaaa: v\r\n\r\n");
1744        assert!(matches!(reader.decode(&mut buf), Err(DecodeError::Header)));
1745    }
1746
1747    /// STATEMENT: Partial start-line parsing resumes independently per decoder and resets after errors.
1748    ///
1749    /// HOW:
1750    /// - Reject an invalid byte immediately, reuse that decoder, and decode request/response heads bytewise.
1751    /// - Interleave two partial requests and verify their methods and paths remain independent.
1752    #[test]
1753    fn test_partial_start_line_is_resumed() {
1754        let reader = MessageDecoder::<Request>::default();
1755        let mut buf = BytesMut::from("GET /");
1756        assert!(reader.decode(&mut buf).unwrap().is_none());
1757
1758        // an invalid byte is rejected without waiting for the line end
1759        buf.extend_from_slice(b"\x01");
1760        assert!(reader.decode(&mut buf).is_err());
1761
1762        // the decoder starts over after an error
1763        let mut buf = BytesMut::from("GET /a HTTP/1.1\r\nhost: a\r\n\r\n");
1764        assert_eq!(reader.decode(&mut buf).unwrap().unwrap().0.path(), "/a");
1765
1766        // byte by byte
1767        let reader = MessageDecoder::<Request>::default();
1768        let mut buf = BytesMut::new();
1769        for b in b"\r\nGET  /test/path HTTP/1.1\r\nhost: a\r\n\r" {
1770            buf.extend_from_slice(&[*b]);
1771            assert!(reader.decode(&mut buf).unwrap().is_none());
1772        }
1773        buf.extend_from_slice(b"\n");
1774        let req = reader.decode(&mut buf).unwrap().unwrap().0;
1775        assert_eq!(req.path(), "/test/path");
1776        assert_eq!(req.headers().get("host").unwrap(), "a");
1777
1778        let reader = MessageDecoder::<ResponseHead>::default();
1779        let mut buf = BytesMut::new();
1780        for b in b"HTTP/1.1 404 Not Found\r\n\r" {
1781            buf.extend_from_slice(&[*b]);
1782            assert!(reader.decode(&mut buf).unwrap().is_none());
1783        }
1784        buf.extend_from_slice(b"\n");
1785        let res = reader.decode(&mut buf).unwrap().unwrap().0;
1786        assert_eq!(res.status, StatusCode::NOT_FOUND);
1787
1788        // partial start lines of different connections on one thread
1789        let r1 = MessageDecoder::<Request>::default();
1790        let r2 = MessageDecoder::<Request>::default();
1791        let mut b1 = BytesMut::from("PUT /one HT");
1792        let mut b2 = BytesMut::from("DELETE /two HT");
1793        assert!(r1.decode(&mut b1).unwrap().is_none());
1794        assert!(r2.decode(&mut b2).unwrap().is_none());
1795        b1.extend_from_slice(b"TP/1.1\r\nhost: a\r\n\r\n");
1796        b2.extend_from_slice(b"TP/1.0\r\n\r\n");
1797        let req = r1.decode(&mut b1).unwrap().unwrap().0;
1798        assert_eq!((req.method(), req.path()), (&Method::PUT, "/one"));
1799        let req = r2.decode(&mut b2).unwrap().unwrap().0;
1800        assert_eq!((req.method(), req.path()), (&Method::DELETE, "/two"));
1801    }
1802
1803    /// STATEMENT: Leading empty lines are discarded but still count toward the request-buffer limit.
1804    ///
1805    /// HOW:
1806    /// - Feed repeated blank lines before a valid request and inspect buffer consumption and decoded path.
1807    /// - Exceed a small buffer budget using blank lines alone and check the reported size.
1808    #[test]
1809    fn test_leading_empty_lines() {
1810        let reader = MessageDecoder::<Request>::default();
1811        let mut buf = BytesMut::new();
1812        for _ in 0..10 {
1813            buf.extend_from_slice(b"\r\n");
1814            assert!(reader.decode(&mut buf).unwrap().is_none());
1815            assert!(buf.is_empty());
1816        }
1817        buf.extend_from_slice(b"\nGET /test HTTP/1.1\r\nhost: a\r\n\r\n");
1818        let req = reader.decode(&mut buf).unwrap().unwrap().0;
1819        assert_eq!(req.path(), "/test");
1820
1821        // empty lines count towards the buffer limit
1822        let cfg: SharedCfg = SharedCfg::new("test")
1823            .add(HttpServiceConfig::new().set_max_buf_size(10))
1824            .into();
1825        let reader = MessageDecoder::<Request>::new(cfg.get());
1826        let mut buf = BytesMut::new();
1827        let mut res = Ok(None);
1828        for _ in 0..6 {
1829            buf.extend_from_slice(b"\r\n");
1830            res = reader.decode(&mut buf);
1831            if res.is_err() {
1832                break;
1833            }
1834        }
1835        assert_eq!(res.err(), Some(DecodeError::TooLarge(12)));
1836    }
1837
1838    /// STATEMENT: Start-line limits include line endings, reject oversized partial input, and do not limit header lengths.
1839    ///
1840    /// HOW:
1841    /// - Decode at-limit and oversized complete/partial lines, inspect exact errors, and accept a longer header.
1842    /// - Verify the default limit also rejects a large incomplete request target.
1843    /// - Check a method longer than the limit fails with `DecodeError::Method`, while a
1844    ///   shorter method followed by a long target keeps `StartLineTooLong`.
1845    #[test]
1846    fn test_max_start_line_size() {
1847        let cfg: SharedCfg = SharedCfg::new("test")
1848            .add(HttpServiceConfig::new().set_max_start_line_size(32))
1849            .into();
1850
1851        // the limit includes the line end
1852        let line = format!("GET /{} HTTP/1.1\r\n", "a".repeat(16));
1853        assert_eq!(line.len(), 32);
1854        let reader = MessageDecoder::<Request>::new(cfg.get());
1855        let mut buf = BytesMut::from(format!("{line}host: a\r\n\r\n").as_str());
1856        assert!(reader.decode(&mut buf).unwrap().is_some());
1857
1858        let reader = MessageDecoder::<Request>::new(cfg.get());
1859        let mut buf = BytesMut::from(format!("GET /{} HTTP/1.1\r\n\r\n", "a".repeat(17)).as_str());
1860        assert_eq!(
1861            reader.decode(&mut buf).err(),
1862            Some(DecodeError::StartLineTooLong(33))
1863        );
1864
1865        // incomplete line
1866        let reader = MessageDecoder::<Request>::new(cfg.get());
1867        let mut buf = BytesMut::from("GET /");
1868        assert!(reader.decode(&mut buf).unwrap().is_none());
1869        buf.extend_from_slice("a".repeat(27).as_bytes());
1870        assert!(reader.decode(&mut buf).unwrap().is_none());
1871        buf.extend_from_slice(b"a");
1872        assert_eq!(
1873            reader.decode(&mut buf).err(),
1874            Some(DecodeError::StartLineTooLong(33))
1875        );
1876
1877        // headers are not limited
1878        let reader = MessageDecoder::<Request>::new(cfg.get());
1879        let mut buf = BytesMut::from(
1880            format!("GET / HTTP/1.1\r\nhost: a\r\nx: {}\r\n\r\n", "a".repeat(64)).as_str(),
1881        );
1882        assert!(reader.decode(&mut buf).unwrap().is_some());
1883
1884        // default limit
1885        let reader = MessageDecoder::<Request>::default();
1886        let mut buf = BytesMut::from(format!("GET /{}", "a".repeat(16 * 1024)).as_str());
1887        assert!(matches!(
1888            reader.decode(&mut buf),
1889            Err(DecodeError::StartLineTooLong(_))
1890        ));
1891
1892        // a method longer than the limit is an invalid method, complete or not
1893        for line in [
1894            format!("{} / HTTP/1.1\r\nhost: a\r\n\r\n", "A".repeat(33)),
1895            "A".repeat(33),
1896        ] {
1897            let reader = MessageDecoder::<Request>::new(cfg.get());
1898            let mut buf = BytesMut::from(line.as_str());
1899            assert_eq!(reader.decode(&mut buf).err(), Some(DecodeError::Method));
1900        }
1901        // a method that fits leaves the overflow to the target
1902        let reader = MessageDecoder::<Request>::new(cfg.get());
1903        let mut buf = BytesMut::from(format!("{} /aaa HTTP/1.1\r\n", "A".repeat(20)).as_str());
1904        assert_eq!(
1905            reader.decode(&mut buf).err(),
1906            Some(DecodeError::StartLineTooLong(36))
1907        );
1908    }
1909
1910    /// STATEMENT: Request-head decoding preserves HTTP version, method, and path with or without body framing.
1911    ///
1912    /// HOW:
1913    /// - Decode ordinary and content-length-bearing GET heads and compare their parsed metadata.
1914    #[test]
1915    fn test_parse() {
1916        let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
1917
1918        let reader = MessageDecoder::<Request>::default();
1919        match reader.decode(&mut buf) {
1920            Ok(Some((req, _))) => {
1921                assert_eq!(req.version(), Version::HTTP_11);
1922                assert_eq!(*req.method(), Method::GET);
1923                assert_eq!(req.path(), "/test");
1924            }
1925            Ok(_) | Err(_) => unreachable!("Error during parsing http request"),
1926        }
1927
1928        let mut buf =
1929            BytesMut::from("GET /test HTTP/1.1\r\nhost: localhost\r\ncontent-length:512\r\n\r\n");
1930        let reader = MessageDecoder::<Request>::default();
1931        let req = reader.decode(&mut buf).unwrap().unwrap().0;
1932        assert_eq!(req.version(), Version::HTTP_11);
1933        assert_eq!(*req.method(), Method::GET);
1934        assert_eq!(req.path(), "/test");
1935    }
1936
1937    /// STATEMENT: Connection options are matched as case-insensitive tokens rather than substrings.
1938    ///
1939    /// HOW:
1940    /// - Parse whitespace/comma/case variants, misleading prefixes/suffixes, and combined options.
1941    /// - Compare exact close, upgrade, keepalive, and combined flags.
1942    #[test]
1943    fn test_connection_flags() {
1944        for s in ["Close", "close,", "close ", " close", "\tclose"] {
1945            assert_eq!(connection_flags(s.as_bytes()), Flags::CONN_CLOSE);
1946        }
1947        for s in ["upgrade", "upGrade", "upgrade,", "upgrade "] {
1948            assert_eq!(connection_flags(s.as_bytes()), Flags::CONN_UPGRADE);
1949        }
1950        for s in ["keep-alive", "keep-Alive", "keep-alive,", "Keep-alive "] {
1951            assert_eq!(connection_flags(s.as_bytes()), Flags::CONN_KA);
1952        }
1953        for s in [
1954            "keep-aliv",
1955            "clos",
1956            "upgrad",
1957            "closed",
1958            "close-x",
1959            "upgrades",
1960            "x-close",
1961            "keep-alivex",
1962            "",
1963        ] {
1964            assert_eq!(connection_flags(s.as_bytes()), Flags::empty(), "{s:?}");
1965        }
1966        // tokens past the first 5 bytes
1967        assert_eq!(connection_flags(b"te, trailers, close"), Flags::CONN_CLOSE);
1968        assert_eq!(
1969            connection_flags(b"keep-alive, Upgrade"),
1970            Flags::CONN_KA | Flags::CONN_UPGRADE
1971        );
1972    }
1973
1974    /// STATEMENT: Connection decoding combines token lists and repeated headers without overriding an earlier close.
1975    ///
1976    /// HOW:
1977    /// - Decode embedded close tokens, a nonmatching token, repeated close/keepalive headers, and combined upgrade.
1978    /// - Inspect connection type and upgrade state.
1979    #[test]
1980    fn test_conn_multiple_tokens() {
1981        let mut buf = BytesMut::from(
1982            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
1983             connection: te, trailers, close\r\n\r\n",
1984        );
1985        let req = parse_ready!(&mut buf);
1986        assert_eq!(req.head().connection_type(), ConnectionType::Close);
1987
1988        let mut buf = BytesMut::from(
1989            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
1990             connection: closed\r\n\r\n",
1991        );
1992        let req = parse_ready!(&mut buf);
1993        assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
1994
1995        // `close` in an earlier header is not overridden by a later one
1996        let mut buf = BytesMut::from(
1997            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
1998             connection: close\r\n\
1999             connection: keep-alive\r\n\r\n",
2000        );
2001        let req = parse_ready!(&mut buf);
2002        assert_eq!(req.head().connection_type(), ConnectionType::Close);
2003
2004        let mut buf = BytesMut::from(
2005            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2006             upgrade: websocket\r\n\
2007             connection: keep-alive, Upgrade\r\n\r\n",
2008        );
2009        let req = parse_ready!(&mut buf);
2010        assert!(req.upgrade());
2011    }
2012
2013    /// STATEMENT: A request split within its HTTP version resumes into the correct head.
2014    ///
2015    /// HOW:
2016    /// - Decode an incomplete PUT line, append the remaining version and headers, and check method/path/version.
2017    #[test]
2018    fn test_parse_partial() {
2019        let mut buf = BytesMut::from("PUT /test HTTP/1");
2020
2021        let reader = MessageDecoder::<Request>::default();
2022        assert!(reader.decode(&mut buf).unwrap().is_none());
2023
2024        buf.extend(b".1\r\nhost: localhost\r\n\r\n");
2025        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2026        assert_eq!(req.version(), Version::HTTP_11);
2027        assert_eq!(*req.method(), Method::PUT);
2028        assert_eq!(req.path(), "/test");
2029    }
2030
2031    /// STATEMENT: Optional header vectors retain original casing and repeated values for requests and responses.
2032    ///
2033    /// HOW:
2034    /// - Decode mixed-case headers with vectors disabled and enabled.
2035    /// - Compare normalized names, original spellings, and repeated response values.
2036    #[test]
2037    fn parse_header_name_origins() {
2038        // request
2039        let mut buf = BytesMut::from(
2040            "GET /test2 HTTP/1.0\r\n\
2041            Test: 123\r\n\
2042            Content-Length: 0\r\n\
2043            \r\n",
2044        );
2045
2046        let reader = MessageDecoder::<Request>::new(Cfg::default());
2047        let (req, _) = reader.decode(&mut buf.clone()).unwrap().unwrap();
2048        assert_eq!(req.head().headers_vec().len(), 0);
2049
2050        let cfg: SharedCfg = SharedCfg::new("dbg")
2051            .add(HttpServiceConfig::default().set_headers_vec(true))
2052            .into();
2053        let reader = MessageDecoder::<Request>::new(cfg.get());
2054        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2055        assert_eq!(
2056            req.head().headers_vec()[0].name,
2057            HeaderName::try_from("test").unwrap()
2058        );
2059        assert_eq!(req.head().headers_vec()[0].origin, "Test");
2060        assert_eq!(req.head().headers_vec()[1].name, header::CONTENT_LENGTH);
2061        assert_eq!(req.head().headers_vec()[1].origin, "Content-Length");
2062
2063        // response
2064        let mut buf = BytesMut::from(
2065            "HTTP/1.0 200 Ok\r\n\
2066            TEST: 123\r\n\
2067            Content-Length: 0\r\n\
2068            tesT: 456\r\n\
2069            \r\n",
2070        );
2071
2072        let reader = MessageDecoder::<ResponseHead>::new(Cfg::default());
2073        let (res, _) = reader.decode(&mut buf.clone()).unwrap().unwrap();
2074        assert_eq!(res.headers_vec().len(), 0);
2075
2076        let cfg: SharedCfg = SharedCfg::new("dbg")
2077            .add(HttpServiceConfig::default().set_headers_vec(true))
2078            .into();
2079        let reader = MessageDecoder::<ResponseHead>::new(cfg.get());
2080        let (res, _) = reader.decode(&mut buf).unwrap().unwrap();
2081        assert_eq!(
2082            res.headers_vec()[0].name,
2083            HeaderName::try_from("test").unwrap()
2084        );
2085        assert_eq!(res.headers_vec()[0].origin, "TEST");
2086        assert_eq!(res.headers_vec()[0].value, "123");
2087        assert_eq!(res.headers_vec()[1].name, header::CONTENT_LENGTH);
2088        assert_eq!(res.headers_vec()[1].origin, "Content-Length");
2089        assert_eq!(res.headers_vec()[2].origin, "tesT");
2090        assert_eq!(res.headers_vec()[2].value, "456");
2091    }
2092
2093    /// STATEMENT: Header extraction trims whitespace, preserves long values and optional origins, and leaves body bytes untouched.
2094    ///
2095    /// HOW:
2096    /// - Decode whole and bytewise requests with empty, whitespace-only, long, and short headers.
2097    /// - Compare header maps, optional ordered vectors, and the remaining body buffer.
2098    #[test]
2099    fn parse_header_values_split_from_buffer() {
2100        const LONG_NAME: &str = "X-A-Very-Long-Header-Name-Over-Inline";
2101        const LONG_VALUE: &str = "a value longer than the inline capacity of bytes";
2102        let text = format!(
2103            "POST /test HTTP/1.1\r\n\
2104            Host: a\r\n\
2105            X-Empty:\r\n\
2106            X-Ws: \t \r\n\
2107            {LONG_NAME}: \t{LONG_VALUE} \t\r\n\
2108            Short: v\r\n\
2109            Content-Length: 4\r\n\
2110            \r\n\
2111            body"
2112        );
2113
2114        for headers_vec in [false, true] {
2115            let cfg: SharedCfg = SharedCfg::new("dbg")
2116                .add(HttpServiceConfig::default().set_headers_vec(headers_vec))
2117                .into();
2118            for chunk in [text.len(), 1] {
2119                let reader = MessageDecoder::<Request>::new(cfg.get());
2120                let mut buf = BytesMut::new();
2121                let mut req = None;
2122                let mut fed = 0;
2123                for part in text.as_bytes().chunks(chunk) {
2124                    buf.extend_from_slice(part);
2125                    fed += part.len();
2126                    if let Some((r, _)) = reader.decode(&mut buf).unwrap() {
2127                        req = Some(r);
2128                        break;
2129                    }
2130                }
2131                buf.extend_from_slice(&text.as_bytes()[fed..]);
2132                let req = req.unwrap();
2133                let ctx = format!("headers_vec {headers_vec} chunk {chunk}");
2134                assert_eq!(&buf[..], b"body", "{ctx}");
2135
2136                let h = req.headers();
2137                assert_eq!(h.get("x-empty").unwrap(), "", "{ctx}");
2138                assert_eq!(h.get("x-ws").unwrap(), "", "{ctx}");
2139                assert_eq!(h.get(LONG_NAME).unwrap(), LONG_VALUE, "{ctx}");
2140                assert_eq!(h.get("short").unwrap(), "v", "{ctx}");
2141                assert_eq!(h.get(header::CONTENT_LENGTH).unwrap(), "4", "{ctx}");
2142
2143                let items = req.head().headers_vec();
2144                if headers_vec {
2145                    let origins: Vec<_> = items.iter().map(|i| &i.origin[..]).collect();
2146                    assert_eq!(
2147                        origins,
2148                        [
2149                            "Host",
2150                            "X-Empty",
2151                            "X-Ws",
2152                            LONG_NAME,
2153                            "Short",
2154                            "Content-Length"
2155                        ],
2156                        "{ctx}"
2157                    );
2158                    let values: Vec<_> = items.iter().map(|i| i.value.as_bytes()).collect();
2159                    let expected: [&[u8]; 6] = [b"a", b"", b"", LONG_VALUE.as_bytes(), b"v", b"4"];
2160                    assert_eq!(values, expected, "{ctx}");
2161                } else {
2162                    assert!(items.is_empty(), "{ctx}");
2163                }
2164            }
2165        }
2166    }
2167
2168    /// STATEMENT: HTTP/1.0 GET parsing supports paths, queries, and content lengths but rejects chunked transfer encoding.
2169    ///
2170    /// HOW:
2171    /// - Decode bodyless and length-framed requests, inspect metadata/query, and reject a chunked HTTP/1.0 head.
2172    #[test]
2173    fn parse_h10_get() {
2174        let mut buf = BytesMut::from(
2175            "GET /test1 HTTP/1.0\r\n\
2176            \r\n\
2177            abc",
2178        );
2179
2180        let reader = MessageDecoder::<Request>::default();
2181        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2182        assert_eq!(req.version(), Version::HTTP_10);
2183        assert_eq!(*req.method(), Method::GET);
2184        assert_eq!(req.path(), "/test1");
2185
2186        let mut buf = BytesMut::from(
2187            "GET /test2 HTTP/1.0\r\n\
2188            Test: 123\r\n\
2189            Content-Length: 0\r\n\
2190            \r\n",
2191        );
2192
2193        let reader = MessageDecoder::<Request>::default();
2194        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2195        assert_eq!(req.version(), Version::HTTP_10);
2196        assert_eq!(*req.method(), Method::GET);
2197        assert_eq!(req.path(), "/test2");
2198
2199        let mut buf = BytesMut::from(
2200            "GET /test3?test=1 HTTP/1.0\r\n\
2201            Content-Length: 3\r\n\
2202            \r\n
2203            abc",
2204        );
2205
2206        let reader = MessageDecoder::<Request>::default();
2207        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2208        assert_eq!(req.version(), Version::HTTP_10);
2209        assert_eq!(*req.method(), Method::GET);
2210        assert_eq!(req.path(), "/test3");
2211        assert_eq!(req.uri().query().unwrap(), "test=1");
2212
2213        // transfer-encoding is not supported for http1.0
2214        let mut buf =
2215            BytesMut::from("GET /test3?test=1 HTTP/1.0\r\nTransfer-Encoding: chunked\r\n\r\n");
2216        expect_parse_err!(&mut buf);
2217    }
2218
2219    /// STATEMENT: HTTP/1.0 POST requests require explicit body length, including zero for an empty body.
2220    ///
2221    /// HOW:
2222    /// - Decode positive/zero-length requests and inspect metadata, then reject a POST without length.
2223    #[test]
2224    fn parse_h10_post() {
2225        let mut buf = BytesMut::from(
2226            "POST /test1 HTTP/1.0\r\n\
2227            Content-Length: 3\r\n\
2228            \r\n\
2229            abc",
2230        );
2231
2232        let reader = MessageDecoder::<Request>::default();
2233        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2234        assert_eq!(req.version(), Version::HTTP_10);
2235        assert_eq!(*req.method(), Method::POST);
2236        assert_eq!(req.path(), "/test1");
2237
2238        let mut buf = BytesMut::from(
2239            "POST /test2 HTTP/1.0\r\n\
2240            Content-Length: 0\r\n\
2241            \r\n",
2242        );
2243
2244        let reader = MessageDecoder::<Request>::default();
2245        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2246        assert_eq!(req.version(), Version::HTTP_10);
2247        assert_eq!(*req.method(), Method::POST);
2248        assert_eq!(req.path(), "/test2");
2249
2250        let mut buf = BytesMut::from(
2251            "POST /test3 HTTP/1.0\r\n\
2252            \r\n",
2253        );
2254        let reader = MessageDecoder::<Request>::default();
2255        let err = reader.decode(&mut buf).unwrap_err();
2256        assert!(err.to_string().contains("Header"));
2257    }
2258
2259    /// STATEMENT: A content-length request separates head metadata from its fixed-length payload.
2260    ///
2261    /// HOW:
2262    /// - Decode a complete GET with four body bytes and compare both request metadata and payload output.
2263    #[test]
2264    fn test_parse_body() {
2265        let mut buf = BytesMut::from(
2266            "GET /test HTTP/1.1\r\nhost: localhost\r\nContent-Length: 4\r\n\r\nbody",
2267        );
2268
2269        let reader = MessageDecoder::<Request>::default();
2270        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2271        let pl = pl.unwrap();
2272        assert_eq!(req.version(), Version::HTTP_11);
2273        assert_eq!(*req.method(), Method::GET);
2274        assert_eq!(req.path(), "/test");
2275        assert_eq!(
2276            pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(),
2277            b"body"
2278        );
2279    }
2280
2281    /// STATEMENT: Leading CRLF does not alter a request's metadata or fixed-length body.
2282    ///
2283    /// HOW:
2284    /// - Decode a length-framed GET preceded by an empty line and compare the parsed head and body bytes.
2285    #[test]
2286    fn test_parse_body_crlf() {
2287        let mut buf = BytesMut::from(
2288            "\r\nGET /test HTTP/1.1\r\nhost: localhost\r\nContent-Length: 4\r\n\r\nbody",
2289        );
2290
2291        let reader = MessageDecoder::<Request>::default();
2292        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2293        let pl = pl.unwrap();
2294        assert_eq!(req.version(), Version::HTTP_11);
2295        assert_eq!(*req.method(), Method::GET);
2296        assert_eq!(req.path(), "/test");
2297        assert_eq!(
2298            pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(),
2299            b"body"
2300        );
2301    }
2302
2303    /// STATEMENT: Request-head parsing waits for the final blank line.
2304    ///
2305    /// HOW:
2306    /// - Supply complete headers without their terminator, append CRLF, and inspect the resulting request metadata.
2307    #[test]
2308    fn test_parse_partial_eof() {
2309        let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nhost: localhost\r\n");
2310        let reader = MessageDecoder::<Request>::default();
2311        assert!(reader.decode(&mut buf).unwrap().is_none());
2312
2313        buf.extend(b"\r\n");
2314        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2315        assert_eq!(req.version(), Version::HTTP_11);
2316        assert_eq!(*req.method(), Method::GET);
2317        assert_eq!(req.path(), "/test");
2318    }
2319
2320    /// STATEMENT: A header name split across multiple reads is assembled without losing its value.
2321    ///
2322    /// HOW:
2323    /// - Feed pieces of a header name before its value and final terminator.
2324    /// - Verify pending results until completion, then inspect request metadata and header bytes.
2325    #[test]
2326    fn test_headers_split_field() {
2327        let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nhost: localhost\r\n");
2328
2329        let reader = MessageDecoder::<Request>::default();
2330        assert! { reader.decode(&mut buf).unwrap().is_none() }
2331
2332        buf.extend(b"t");
2333        assert! { reader.decode(&mut buf).unwrap().is_none() }
2334
2335        buf.extend(b"es");
2336        assert! { reader.decode(&mut buf).unwrap().is_none() }
2337
2338        buf.extend(b"t: value\r\n\r\n");
2339        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2340        assert_eq!(req.version(), Version::HTTP_11);
2341        assert_eq!(*req.method(), Method::GET);
2342        assert_eq!(req.path(), "/test");
2343        assert_eq!(
2344            req.headers()
2345                .get(HeaderName::try_from("test").unwrap())
2346                .unwrap()
2347                .as_bytes(),
2348            b"value"
2349        );
2350    }
2351
2352    /// STATEMENT: Repeated headers retain their separate values in input order.
2353    ///
2354    /// HOW:
2355    /// - Decode two Set-Cookie lines and compare both values from the resulting header map.
2356    #[test]
2357    fn test_headers_multi_value() {
2358        let mut buf = BytesMut::from(
2359            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2360             Set-Cookie: c1=cookie1\r\n\
2361             Set-Cookie: c2=cookie2\r\n\r\n",
2362        );
2363        let reader = MessageDecoder::<Request>::default();
2364        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2365
2366        let val: Vec<_> = req
2367            .headers()
2368            .get_all(SET_COOKIE)
2369            .map(|v| v.to_str().unwrap().to_owned())
2370            .collect();
2371        assert_eq!(val[0], "c1=cookie1");
2372        assert_eq!(val[1], "c2=cookie2");
2373    }
2374
2375    /// STATEMENT: HTTP/1.0 requests default to closing the connection.
2376    ///
2377    /// HOW:
2378    /// - Decode a request without connection options and inspect its connection type.
2379    #[test]
2380    fn test_conn_default_1_0() {
2381        let mut buf = BytesMut::from("GET /test HTTP/1.0\r\n\r\n");
2382        let req = parse_ready!(&mut buf);
2383
2384        assert_eq!(req.head().connection_type(), ConnectionType::Close);
2385    }
2386
2387    /// STATEMENT: HTTP/1.1 requests default to persistent connections.
2388    ///
2389    /// HOW:
2390    /// - Decode a request without connection options and inspect its keepalive connection type.
2391    #[test]
2392    fn test_conn_default_1_1() {
2393        let mut buf = BytesMut::from("GET /test HTTP/1.1\r\nhost: localhost\r\n\r\n");
2394        let req = parse_ready!(&mut buf);
2395
2396        assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
2397    }
2398
2399    /// STATEMENT: Explicit close options disable HTTP/1.1 persistence regardless of case.
2400    ///
2401    /// HOW:
2402    /// - Decode lowercase and capitalized close options and compare their connection types.
2403    #[test]
2404    fn test_conn_close() {
2405        let mut buf = BytesMut::from(
2406            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2407             connection: close\r\n\r\n",
2408        );
2409        let req = parse_ready!(&mut buf);
2410
2411        assert_eq!(req.head().connection_type(), ConnectionType::Close);
2412
2413        let mut buf = BytesMut::from(
2414            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2415             connection: Close\r\n\r\n",
2416        );
2417        let req = parse_ready!(&mut buf);
2418
2419        assert_eq!(req.head().connection_type(), ConnectionType::Close);
2420    }
2421
2422    /// STATEMENT: An explicit close option retains HTTP/1.0 nonpersistent behavior.
2423    ///
2424    /// HOW:
2425    /// - Decode an HTTP/1.0 request with the close option and inspect its connection type.
2426    #[test]
2427    fn test_conn_close_1_0() {
2428        let mut buf = BytesMut::from(
2429            "GET /test HTTP/1.0\r\n\
2430             connection: close\r\n\r\n",
2431        );
2432
2433        let req = parse_ready!(&mut buf);
2434
2435        assert_eq!(req.head().connection_type(), ConnectionType::Close);
2436    }
2437
2438    /// STATEMENT: HTTP/1.0 keepalive options enable persistence case-insensitively.
2439    ///
2440    /// HOW:
2441    /// - Decode lowercase and mixed-case keepalive options and inspect persistent connection types.
2442    #[test]
2443    fn test_conn_keep_alive_1_0() {
2444        let mut buf = BytesMut::from(
2445            "GET /test HTTP/1.0\r\n\
2446             connection: keep-alive\r\n\r\n",
2447        );
2448        let req = parse_ready!(&mut buf);
2449
2450        assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
2451
2452        let mut buf = BytesMut::from(
2453            "GET /test HTTP/1.0\r\n\
2454             connection: Keep-Alive\r\n\r\n",
2455        );
2456        let req = parse_ready!(&mut buf);
2457
2458        assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
2459    }
2460
2461    /// STATEMENT: An explicit HTTP/1.1 keepalive option preserves persistence.
2462    ///
2463    /// HOW:
2464    /// - Decode a keepalive-bearing request and inspect its connection type.
2465    #[test]
2466    fn test_conn_keep_alive_1_1() {
2467        let mut buf = BytesMut::from(
2468            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2469             connection: keep-alive\r\n\r\n",
2470        );
2471        let req = parse_ready!(&mut buf);
2472
2473        assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
2474    }
2475
2476    /// STATEMENT: Unknown connection options do not enable HTTP/1.0 persistence.
2477    ///
2478    /// HOW:
2479    /// - Decode an unknown option and verify the connection still closes.
2480    #[test]
2481    fn test_conn_other_1_0() {
2482        let mut buf = BytesMut::from(
2483            "GET /test HTTP/1.0\r\n\
2484             connection: other\r\n\r\n",
2485        );
2486        let req = parse_ready!(&mut buf);
2487
2488        assert_eq!(req.head().connection_type(), ConnectionType::Close);
2489    }
2490
2491    /// STATEMENT: Unknown connection options do not disable default HTTP/1.1 persistence.
2492    ///
2493    /// HOW:
2494    /// - Decode an unknown option and verify the connection remains keepalive.
2495    #[test]
2496    fn test_conn_other_1_1() {
2497        let mut buf = BytesMut::from(
2498            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2499             connection: other\r\n\r\n",
2500        );
2501        let req = parse_ready!(&mut buf);
2502
2503        assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
2504    }
2505
2506    /// STATEMENT: Matching upgrade headers select upgrade connection state case-insensitively.
2507    ///
2508    /// HOW:
2509    /// - Decode lowercase and mixed-case upgrade requests and inspect both upgrade predicates and connection types.
2510    #[test]
2511    fn test_conn_upgrade() {
2512        let mut buf = BytesMut::from(
2513            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2514             upgrade: websockets\r\n\
2515             connection: upgrade\r\n\r\n",
2516        );
2517        let req = parse_ready!(&mut buf);
2518
2519        assert!(req.upgrade());
2520        assert_eq!(req.head().connection_type(), ConnectionType::Upgrade);
2521
2522        let mut buf = BytesMut::from(
2523            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2524             upgrade: Websockets\r\n\
2525             connection: Upgrade\r\n\r\n",
2526        );
2527        let req = parse_ready!(&mut buf);
2528
2529        assert!(req.upgrade());
2530        assert_eq!(req.head().connection_type(), ConnectionType::Upgrade);
2531    }
2532
2533    /// STATEMENT: Both upgrade and connection-upgrade headers are required to leave ordinary HTTP framing.
2534    ///
2535    /// HOW:
2536    /// - Decode incomplete upgrade combinations and verify the next pipelined request or fixed body remains ordinary HTTP.
2537    /// - Supply both headers and verify streaming upgrade payload classification.
2538    #[test]
2539    fn test_upgrade_requires_connection_option() {
2540        let reader = MessageDecoder::<Request>::default();
2541        for req in [
2542            "GET /test HTTP/1.1\r\nhost: a\r\nupgrade: websocket\r\n\r\n",
2543            "GET /test HTTP/1.1\r\nhost: a\r\nconnection: upgrade\r\n\r\n",
2544            "GET /test HTTP/1.1\r\nhost: a\r\nconnection: keep-alive\r\n\
2545             upgrade: websocket\r\ncontent-length: 0\r\n\r\n",
2546        ] {
2547            let mut buf =
2548                BytesMut::from(format!("{req}GET /next HTTP/1.1\r\nhost: a\r\n\r\n").as_str());
2549            let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2550            assert!(!req.upgrade(), "{req:?}");
2551            assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
2552            assert_eq!(pl, PayloadType::None);
2553            // the next request is not consumed as upgraded stream
2554            let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2555            assert_eq!(req.path(), "/next");
2556        }
2557
2558        // a body is not treated as an upgraded stream
2559        let mut buf = BytesMut::from(
2560            "POST /test HTTP/1.1\r\nhost: a\r\nupgrade: h2c\r\n\
2561             content-length: 4\r\n\r\nbody",
2562        );
2563        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2564        assert!(!req.upgrade());
2565        assert!(matches!(pl, PayloadType::Payload(_)));
2566        assert_eq!(req.headers().get(header::UPGRADE).unwrap(), "h2c");
2567
2568        // both are present
2569        let mut buf = BytesMut::from(
2570            "GET /test HTTP/1.1\r\nhost: a\r\nconnection: keep-alive, Upgrade\r\n\
2571             upgrade: websocket\r\n\r\n",
2572        );
2573        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2574        assert!(req.upgrade());
2575        assert!(matches!(pl, PayloadType::Stream(_)));
2576    }
2577
2578    /// STATEMENT: A websocket upgrade with a method other than `GET` is rejected,
2579    /// other upgrades and incomplete websocket upgrades are unaffected.
2580    ///
2581    /// HOW:
2582    /// - Decode `connection: upgrade` and `upgrade: websocket` with non-`GET`
2583    ///   methods, with and without a body length, and require `InvalidInput`.
2584    /// - Decode a `POST` with only `upgrade: websocket` and a `POST` `h2c`
2585    ///   upgrade and verify they still decode.
2586    #[test]
2587    fn test_ws_upgrade_requires_get() {
2588        let reader = MessageDecoder::<Request>::default();
2589        for (method, extra) in [
2590            ("POST", ""),
2591            ("POST", "content-length: 0\r\n"),
2592            ("POST", "content-length: 4\r\n"),
2593            ("PUT", ""),
2594            ("HEAD", ""),
2595            ("OPTIONS", ""),
2596        ] {
2597            let mut buf = BytesMut::from(
2598                format!(
2599                    "{method} /test HTTP/1.1\r\nhost: a\r\nconnection: Upgrade\r\n\
2600                     upgrade: WebSocket\r\n{extra}\r\ndata"
2601                )
2602                .as_str(),
2603            );
2604            assert_eq!(
2605                reader.decode(&mut buf).err(),
2606                Some(DecodeError::InvalidInput(
2607                    "WebSocket upgrade requires GET method"
2608                )),
2609                "{method} {extra:?}"
2610            );
2611        }
2612
2613        // without the connection option it is not an upgrade
2614        let mut buf =
2615            BytesMut::from("POST /test HTTP/1.1\r\nhost: a\r\nupgrade: websocket\r\n\r\n");
2616        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2617        assert!(!req.upgrade());
2618        assert_eq!(pl, PayloadType::None);
2619
2620        // other protocols are not restricted to GET
2621        let mut buf = BytesMut::from(
2622            "POST /test HTTP/1.1\r\nhost: a\r\nconnection: upgrade\r\nupgrade: h2c\r\n\r\n",
2623        );
2624        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2625        assert!(req.upgrade());
2626        assert!(matches!(pl, PayloadType::Stream(_)));
2627    }
2628
2629    /// STATEMENT: Expectation parsing recognizes a complete case-insensitive 100-continue token within lists.
2630    ///
2631    /// HOW:
2632    /// - Decode valid case/whitespace/list forms and misleading partial tokens, comparing each expectation flag.
2633    #[test]
2634    fn test_expect_100_continue() {
2635        let reader = MessageDecoder::<Request>::default();
2636        for (val, expect) in [
2637            ("100-continue", true),
2638            ("100-Continue", true),
2639            (" 100-CONTINUE ", true),
2640            ("foo, 100-continue", true),
2641            ("100-foo", false),
2642            ("100-continuex", false),
2643            ("100", false),
2644            ("", false),
2645        ] {
2646            let mut buf = BytesMut::from(
2647                format!(
2648                    "POST /test HTTP/1.1\r\nhost: a\r\nexpect: {val}\r\ncontent-length: 1\r\n\r\n"
2649                )
2650                .as_str(),
2651            );
2652            let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2653            assert_eq!(req.head().expect(), expect, "{val:?}");
2654        }
2655    }
2656
2657    /// STATEMENT: HTTP/1.0 retains expectation/upgrade headers without activating HTTP/1.1 protocol behavior.
2658    ///
2659    /// HOW:
2660    /// - Decode HTTP/1.0 with both headers and a following request, checking flags, preserved headers, and pipeline boundary.
2661    /// - Verify equivalent HTTP/1.1 headers activate expectation and upgrade streaming.
2662    #[test]
2663    fn test_http10_ignores_expect_and_upgrade() {
2664        let mut buf = BytesMut::from(
2665            "GET /test HTTP/1.0\r\n\
2666             connection: keep-alive, upgrade\r\n\
2667             upgrade: websocket\r\n\
2668             expect: 100-continue\r\n\r\n\
2669             GET /next HTTP/1.0\r\n\r\n",
2670        );
2671        let reader = MessageDecoder::<Request>::default();
2672        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2673        assert!(!req.upgrade());
2674        assert!(!req.head().expect());
2675        assert_eq!(req.head().connection_type(), ConnectionType::KeepAlive);
2676        assert_eq!(pl, PayloadType::None);
2677        // the headers are still available
2678        assert_eq!(req.headers().get(header::UPGRADE).unwrap(), "websocket");
2679        assert_eq!(req.headers().get(header::EXPECT).unwrap(), "100-continue");
2680        // the next request is not consumed as upgraded stream
2681        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2682        assert_eq!(req.path(), "/next");
2683
2684        // HTTP/1.1 is not affected
2685        let mut buf = BytesMut::from(
2686            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2687             connection: upgrade\r\n\
2688             upgrade: websocket\r\n\
2689             expect: 100-continue\r\n\r\n",
2690        );
2691        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2692        assert!(req.upgrade());
2693        assert!(req.head().expect());
2694        assert!(matches!(pl, PayloadType::Stream(_)));
2695    }
2696
2697    /// STATEMENT: HTTP/1.1 requests require exactly one `Host` header, any
2698    /// request rejects duplicates and an empty Host unless the target has an
2699    /// authority; other value checks are opt-in and responses are not affected.
2700    ///
2701    /// HOW:
2702    /// - Enable validation and check rejection of missing, duplicate, empty and invalid Host headers.
2703    /// - Check accepted Host forms with validation enabled, including an empty Host with
2704    ///   absolute-form and authority-form targets.
2705    /// - With validation disabled by default or explicitly, check a missing HTTP/1.1 Host,
2706    ///   duplicate Host lines in HTTP/1.1 and HTTP/1.0 and an empty Host with origin-form or
2707    ///   asterisk-form targets are still rejected, an HTTP/1.0
2708    ///   request without Host is accepted, and an invalid Host value is preserved.
2709    /// - Decode duplicate Host headers in a response with validation enabled.
2710    #[test]
2711    fn test_host_validation() {
2712        let cfg: SharedCfg = SharedCfg::new("test")
2713            .add(HttpServiceConfig::new().set_host_validation(true))
2714            .into();
2715        let reader = MessageDecoder::<Request>::new(cfg.get());
2716        for req in [
2717            "GET / HTTP/1.1\r\n\r\n",
2718            "GET / HTTP/1.1\r\nhost: a\r\nhost: a\r\n\r\n",
2719            "GET / HTTP/1.0\r\nhost: a\r\nhost: b\r\n\r\n",
2720            "GET / HTTP/1.1\r\nhost: [email protected]\r\n\r\n",
2721            "GET / HTTP/1.1\r\nhost: exa mple.com\r\n\r\n",
2722            "GET / HTTP/1.1\r\nhost: example.com/path\r\n\r\n",
2723            "GET / HTTP/1.1\r\nhost: example.com:port\r\n\r\n",
2724            "GET / HTTP/1.1\r\nhost: [::1]:x\r\n\r\n",
2725            "GET / HTTP/1.1\r\nhost: a:1:2\r\n\r\n",
2726            "GET / HTTP/1.1\r\nhost: @\r\n\r\n",
2727            "GET / HTTP/1.1\r\nhost: example.com:99999\r\n\r\n",
2728            "GET / HTTP/1.1\r\nhost: 256.0.0.1\r\n\r\n",
2729            "GET / HTTP/1.1\r\nhost: [::1\r\n\r\n",
2730            "GET / HTTP/1.1\r\nhost: [::1]]\r\n\r\n",
2731            "GET / HTTP/1.1\r\nhost: [1:2:3:4:5:6:7:8:9]\r\n\r\n",
2732            "GET / HTTP/1.1\r\nhost: a%\r\n\r\n",
2733            "GET / HTTP/1.1\r\nhost: a{b}\r\n\r\n",
2734            "GET / HTTP/1.1\r\nhost: \u{e9}\r\n\r\n",
2735            "GET / HTTP/1.1\r\nhost:\r\n\r\n",
2736        ] {
2737            let mut buf = BytesMut::from(req);
2738            assert_eq!(
2739                reader.decode(&mut buf).err(),
2740                Some(DecodeError::Header),
2741                "{req:?}"
2742            );
2743        }
2744
2745        for req in [
2746            "GET / HTTP/1.0\r\n\r\n",
2747            "GET http://example.com/ HTTP/1.1\r\nhost:\r\n\r\n",
2748            "CONNECT example.com:443 HTTP/1.1\r\nhost:\r\n\r\n",
2749            "GET / HTTP/1.1\r\nhost: example.com\r\n\r\n",
2750            "GET / HTTP/1.1\r\nHost: example.com:8080\r\n\r\n",
2751            "GET / HTTP/1.1\r\nhost: 127.0.0.1:80\r\n\r\n",
2752            "GET / HTTP/1.1\r\nhost: [::1]:80\r\n\r\n",
2753            "GET / HTTP/1.1\r\nhost: [::1]\r\n\r\n",
2754            "GET / HTTP/1.1\r\nhost: example.com:\r\n\r\n",
2755            "GET / HTTP/1.1\r\nhost: a-b_c~d!$&'()*+,;=\r\n\r\n",
2756            "GET http://example.com/ HTTP/1.1\r\nhost: example.com\r\n\r\n",
2757        ] {
2758            let mut buf = BytesMut::from(req);
2759            assert!(reader.decode(&mut buf).unwrap().is_some(), "{req:?}");
2760        }
2761
2762        let disabled_cfg: SharedCfg = SharedCfg::new("test")
2763            .add(HttpServiceConfig::new().set_host_validation(false))
2764            .into();
2765        for reader in [
2766            MessageDecoder::<Request>::default(),
2767            MessageDecoder::<Request>::new(disabled_cfg.get()),
2768        ] {
2769            for req in [
2770                "GET / HTTP/1.1\r\n\r\n",
2771                "GET / HTTP/1.1\r\nhost: a\r\nhost: a\r\n\r\n",
2772                "GET / HTTP/1.0\r\nhost: a\r\nhost: b\r\n\r\n",
2773                "GET / HTTP/1.1\r\nhost: \r\n\r\n",
2774                "OPTIONS * HTTP/1.0\r\nhost:\r\n\r\n",
2775            ] {
2776                let mut buf = BytesMut::from(req);
2777                assert_eq!(
2778                    reader.decode(&mut buf).err(),
2779                    Some(DecodeError::Header),
2780                    "{req:?}"
2781                );
2782            }
2783
2784            let mut buf = BytesMut::from(
2785                "GET / HTTP/1.0\r\n\r\n\
2786                 GET / HTTP/1.1\r\nhost: user@b, c\r\n\r\n",
2787            );
2788            assert!(reader.decode(&mut buf).unwrap().is_some());
2789            let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
2790            assert_eq!(req.headers().get(header::HOST).unwrap(), "user@b, c");
2791        }
2792
2793        // responses are not affected
2794        let reader = MessageDecoder::<ResponseHead>::new(cfg.get());
2795        let mut buf = BytesMut::from("HTTP/1.1 200 OK\r\nhost: a\r\nhost: b\r\n\r\n");
2796        assert!(reader.decode(&mut buf).unwrap().is_some());
2797    }
2798
2799    /// STATEMENT: CONNECT requests are classified as connection upgrades.
2800    ///
2801    /// HOW:
2802    /// - Decode an authority-target CONNECT request and inspect its upgrade predicate.
2803    #[test]
2804    fn test_conn_upgrade_connect_method() {
2805        let mut buf = BytesMut::from(
2806            "CONNECT localhost:443 HTTP/1.1\r\nhost: localhost\r\n\
2807             content-type: text/plain\r\n\r\n",
2808        );
2809        let req = parse_ready!(&mut buf);
2810
2811        assert!(req.upgrade());
2812    }
2813
2814    /// STATEMENT: Request framing recognizes chunked transfer encoding and rejects unsupported spellings.
2815    ///
2816    /// HOW:
2817    /// - Decode a chunked request and inspect its chunked predicate, then reject a misspelled coding.
2818    #[test]
2819    fn test_request_chunked() {
2820        let mut buf = BytesMut::from(
2821            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2822             transfer-encoding: chunked\r\n\r\n",
2823        );
2824        let req = parse_ready!(&mut buf);
2825
2826        if let Ok(val) = req.chunked() {
2827            assert!(val);
2828        } else {
2829            unreachable!("Error");
2830        }
2831
2832        // typo in chunked
2833        let mut buf = BytesMut::from(
2834            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2835             transfer-encoding: chnked\r\n\r\n",
2836        );
2837        expect_parse_err!(&mut buf);
2838    }
2839
2840    /// STATEMENT: Content length must be numeric.
2841    ///
2842    /// HOW:
2843    /// - Decode a request with an alphabetic content-length value and require a parse error.
2844    #[test]
2845    fn test_headers_content_length_err_1() {
2846        let mut buf = BytesMut::from(
2847            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2848             content-length: line\r\n\r\n",
2849        );
2850
2851        expect_parse_err!(&mut buf);
2852    }
2853
2854    /// STATEMENT: Negative content lengths are invalid.
2855    ///
2856    /// HOW:
2857    /// - Decode a request declaring length minus one and require a parse error.
2858    #[test]
2859    fn test_headers_content_length_err_2() {
2860        let mut buf = BytesMut::from(
2861            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2862             content-length: -1\r\n\r\n",
2863        );
2864
2865        expect_parse_err!(&mut buf);
2866    }
2867
2868    /// STATEMENT: Header lines require a field-name/value separator.
2869    ///
2870    /// HOW:
2871    /// - Decode a header line without a colon and require a parse error.
2872    #[test]
2873    fn test_invalid_header() {
2874        let mut buf = BytesMut::from(
2875            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2876             test line\r\n\r\n",
2877        );
2878
2879        expect_parse_err!(&mut buf);
2880    }
2881
2882    /// STATEMENT: Invalid token characters are rejected in header names.
2883    ///
2884    /// HOW:
2885    /// - Decode a header name containing square brackets and require a parse error.
2886    #[test]
2887    fn test_invalid_name() {
2888        let mut buf = BytesMut::from(
2889            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2890             test[]: line\r\n\r\n",
2891        );
2892
2893        expect_parse_err!(&mut buf);
2894    }
2895
2896    /// STATEMENT: Malformed request start lines are rejected.
2897    ///
2898    /// HOW:
2899    /// - Supply a combined method/path token without a valid target or version and require a parse error.
2900    #[test]
2901    fn test_http_request_bad_status_line() {
2902        let mut buf = BytesMut::from("getpath \r\n\r\n");
2903        expect_parse_err!(&mut buf);
2904    }
2905
2906    /// STATEMENT: A valid upgrade request exposes subsequent bytes as an upgraded stream rather than an HTTP body.
2907    ///
2908    /// HOW:
2909    /// - Decode upgrade headers followed by raw data and inspect upgrade flags and stream payload classification.
2910    #[test]
2911    fn test_http_request_upgrade() {
2912        let mut buf = BytesMut::from(
2913            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2914             connection: upgrade\r\n\
2915             upgrade: websocket\r\n\r\n\
2916             some raw data",
2917        );
2918        let reader = MessageDecoder::<Request>::default();
2919        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2920        assert_eq!(req.head().connection_type(), ConnectionType::Upgrade);
2921        assert!(req.upgrade());
2922        assert!(pl.is_unhandled());
2923    }
2924
2925    /// STATEMENT: Upgrade framing ignores zero length, respects nonzero body length, and rejects duplicate lengths.
2926    ///
2927    /// HOW:
2928    /// - Decode both header orders for zero/nonzero upgrade lengths and inspect stream or fixed-body behavior.
2929    /// - Verify duplicate content lengths still fail after an upgrade header.
2930    #[test]
2931    fn test_http_request_upgrade_content_length() {
2932        let reader = MessageDecoder::<Request>::default();
2933
2934        // zero content-length is ignored regardless of header order
2935        for hdrs in [
2936            "content-length: 0\r\nupgrade: websocket\r\n",
2937            "upgrade: websocket\r\ncontent-length: 0\r\n",
2938        ] {
2939            let mut buf = BytesMut::from(
2940                format!(
2941                    "GET /test HTTP/1.1\r\nhost: localhost\r\nconnection: upgrade\r\n{hdrs}\r\nraw"
2942                )
2943                .as_str(),
2944            );
2945            let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
2946            assert!(req.upgrade(), "{hdrs:?}");
2947            assert!(pl.is_unhandled(), "{hdrs:?}");
2948        }
2949
2950        // non-zero content-length delimits the body regardless of header order
2951        for hdrs in [
2952            "content-length: 4\r\nupgrade: websocket\r\n",
2953            "upgrade: websocket\r\ncontent-length: 4\r\n",
2954        ] {
2955            let mut buf = BytesMut::from(
2956                format!(
2957                    "GET /test HTTP/1.1\r\nhost: localhost\r\nconnection: upgrade\r\n{hdrs}\r\ndata"
2958                )
2959                .as_str(),
2960            );
2961            let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
2962            let pl = pl.unwrap();
2963            assert_eq!(
2964                pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(),
2965                b"data"
2966            );
2967            assert!(pl.decode(&mut buf).unwrap().unwrap().eof());
2968        }
2969
2970        // duplicate content-length is rejected even after websocket upgrade
2971        let mut buf = BytesMut::from(
2972            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2973             content-length: 4\r\n\
2974             upgrade: websocket\r\n\
2975             content-length: 10\r\n\r\n",
2976        );
2977        assert!(reader.decode(&mut buf).is_err());
2978    }
2979
2980    /// STATEMENT: Request header values preserve non-ASCII UTF-8 bytes.
2981    ///
2982    /// HOW:
2983    /// - Decode a Cyrillic header value and compare its original byte sequence.
2984    #[test]
2985    fn test_http_request_parser_utf8() {
2986        let mut buf = BytesMut::from(
2987            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
2988             x-test: тест\r\n\r\n",
2989        );
2990        let req = parse_ready!(&mut buf);
2991
2992        assert_eq!(
2993            req.headers().get("x-test").unwrap().as_bytes(),
2994            "тест".as_bytes()
2995        );
2996    }
2997
2998    /// STATEMENT: Request targets must be ASCII; raw non-ASCII bytes are
2999    /// rejected even when they form valid UTF-8.
3000    ///
3001    /// HOW:
3002    /// - Decode an ASCII target and compare its path and query.
3003    /// - Decode targets with valid UTF-8 (`é`) and invalid UTF-8 in the path
3004    ///   and the query and require a parse error for each.
3005    #[test]
3006    fn test_http_request_parser_target_utf8() {
3007        let mut buf = BytesMut::from("GET /a/b?c=1 HTTP/1.1\r\nhost: localhost\r\n\r\n");
3008        let req = parse_ready!(&mut buf);
3009        assert_eq!(req.uri().path_and_query(), "/a/b?c=1");
3010
3011        for target in [
3012            &b"/caf\xC3\xA9"[..],
3013            b"/a?q=caf\xC3\xA9",
3014            b"/caf\xC3",
3015            b"/a?q=\xFF",
3016        ] {
3017            let mut buf = BytesMut::copy_from_slice(
3018                [b"GET ", target, b" HTTP/1.1\r\nhost: localhost\r\n\r\n"].concat(),
3019            );
3020            expect_parse_err!(&mut buf);
3021        }
3022    }
3023
3024    /// STATEMENT: A request target beginning with two slashes remains a path, not an authority.
3025    ///
3026    /// HOW:
3027    /// - Decode a double-slash target and inspect its exact path and absent authority.
3028    #[test]
3029    fn test_http_request_parser_two_slashes() {
3030        let mut buf = BytesMut::from("GET //path HTTP/1.1\r\nhost: localhost\r\n\r\n");
3031        let req = parse_ready!(&mut buf);
3032
3033        assert_eq!(req.path(), "//path");
3034        assert!(req.uri().authority().is_none());
3035    }
3036
3037    /// STATEMENT: Invalid method-token characters are rejected.
3038    ///
3039    /// HOW:
3040    /// - Decode a method containing invalid punctuation and require a parse error.
3041    #[test]
3042    fn test_http_request_parser_bad_method() {
3043        let mut buf = BytesMut::from("!12%()+=~$ /get HTTP/1.1\r\nhost: localhost\r\n\r\n");
3044
3045        expect_parse_err!(&mut buf);
3046    }
3047
3048    /// STATEMENT: Malformed HTTP version syntax is rejected.
3049    ///
3050    /// HOW:
3051    /// - Decode a request with an invalid protocol/version token and require a parse error.
3052    #[test]
3053    fn test_http_request_parser_bad_version() {
3054        let mut buf = BytesMut::from("GET //get HT/11\r\n\r\n");
3055
3056        expect_parse_err!(&mut buf);
3057    }
3058
3059    /// STATEMENT: Chunked request bodies decode adjacent small chunks into payload bytes followed by EOF.
3060    ///
3061    /// HOW:
3062    /// - Decode a chunked head, append two chunks and a terminator, and compare merged data and EOF.
3063    #[test]
3064    fn test_http_request_chunked_payload() {
3065        let mut buf = BytesMut::from(
3066            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
3067             transfer-encoding: chunked\r\n\r\n",
3068        );
3069        let reader = MessageDecoder::<Request>::default();
3070        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
3071        let pl = pl.unwrap();
3072        assert!(req.chunked().unwrap());
3073
3074        buf.extend(b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n");
3075        assert_eq!(
3076            pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(),
3077            b"dataline"
3078        );
3079        assert!(pl.decode(&mut buf).unwrap().unwrap().eof());
3080    }
3081
3082    /// STATEMENT: Chunked payload decoding preserves the next pipelined request.
3083    ///
3084    /// HOW:
3085    /// - Append a two-chunk body and a following POST, consume body/EOF, and inspect the next request's method and framing.
3086    #[test]
3087    fn test_http_request_chunked_payload_and_next_message() {
3088        let mut buf = BytesMut::from(
3089            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
3090             transfer-encoding: chunked\r\n\r\n",
3091        );
3092        let reader = MessageDecoder::<Request>::default();
3093        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
3094        let pl = pl.unwrap();
3095        assert!(req.chunked().unwrap());
3096
3097        buf.extend(
3098            b"4\r\ndata\r\n4\r\nline\r\n0\r\n\r\n\
3099              POST /test2 HTTP/1.1\r\nhost: localhost\r\n\
3100              transfer-encoding: chunked\r\n\r\n"
3101                .iter(),
3102        );
3103        let msg = pl.decode(&mut buf).unwrap().unwrap();
3104        assert_eq!(msg.chunk().as_ref(), b"dataline");
3105        let msg = pl.decode(&mut buf).unwrap().unwrap();
3106        assert!(msg.eof());
3107
3108        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
3109        assert!(req.chunked().unwrap());
3110        assert_eq!(*req.method(), Method::POST);
3111        assert!(req.chunked().unwrap());
3112    }
3113
3114    /// STATEMENT: Chunked parsing resumes across split sizes, delimiters, and body data.
3115    ///
3116    /// HOW:
3117    /// - Feed a body in fragments crossing every framing boundary and compare emitted data or pending results.
3118    /// - Verify EOF appears only after the final blank line completes.
3119    #[test]
3120    fn test_http_request_chunked_payload_chunks() {
3121        let mut buf = BytesMut::from(
3122            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
3123             transfer-encoding: chunked\r\n\r\n",
3124        );
3125
3126        let reader = MessageDecoder::<Request>::default();
3127        let (req, pl) = reader.decode(&mut buf).unwrap().unwrap();
3128        let pl = pl.unwrap();
3129        assert!(req.chunked().unwrap());
3130
3131        buf.extend(b"4\r\n1111\r\n");
3132        let msg = pl.decode(&mut buf).unwrap().unwrap();
3133        assert_eq!(msg.chunk().as_ref(), b"1111");
3134
3135        buf.extend(b"4\r\ndata\r");
3136        let msg = pl.decode(&mut buf).unwrap().unwrap();
3137        assert_eq!(msg.chunk().as_ref(), b"data");
3138
3139        buf.extend(b"\n4");
3140        assert!(pl.decode(&mut buf).unwrap().is_none());
3141
3142        buf.extend(b"\r");
3143        assert!(pl.decode(&mut buf).unwrap().is_none());
3144        buf.extend(b"\n");
3145        assert!(pl.decode(&mut buf).unwrap().is_none());
3146
3147        buf.extend(b"li");
3148        let msg = pl.decode(&mut buf).unwrap().unwrap();
3149        assert_eq!(msg.chunk().as_ref(), b"li");
3150
3151        buf.extend(b"ne\r\n0\r\n");
3152        let msg = pl.decode(&mut buf).unwrap().unwrap();
3153        assert_eq!(msg.chunk().as_ref(), b"ne");
3154        assert!(pl.decode(&mut buf).unwrap().is_none());
3155
3156        buf.extend(b"\r\n");
3157        assert!(pl.decode(&mut buf).unwrap().unwrap().eof());
3158    }
3159
3160    /// STATEMENT: Trailer-size limits apply to single, repeated, and unfinished fields, including bytewise input.
3161    ///
3162    /// HOW:
3163    /// - Decode trailer fields at and above the limit as whole buffers and one byte at a time.
3164    /// - Check acceptance at the boundary and rejection of oversized or endless fields.
3165    #[test]
3166    fn test_chunked_trailers_limit() {
3167        let decode = |trailers: &[u8], split: bool| {
3168            let (pl, mut buf) = chunked_payload();
3169            buf.extend_from_slice(b"4\r\ndata\r\n0\r\n");
3170            assert_eq!(pl.decode(&mut buf).unwrap().unwrap().chunk().len(), 4);
3171
3172            let mut data = trailers.to_vec();
3173            data.extend_from_slice(b"\r\n");
3174            let step = if split { 1 } else { data.len() };
3175            for part in data.chunks(step) {
3176                buf.extend_from_slice(part);
3177                match pl.decode(&mut buf) {
3178                    Ok(None) => (),
3179                    Ok(Some(item)) => return Ok(matches!(item, PayloadItem::Trailers(_))),
3180                    Err(err) => return Err(err),
3181                }
3182            }
3183            Ok(false)
3184        };
3185        let max = MAX_CHUNK_TRAILERS as usize;
3186
3187        // a single field
3188        let field = |len: usize| format!("x: {}\r\n", "v".repeat(len - 5)).into_bytes();
3189        for split in [false, true] {
3190            assert_eq!(decode(&field(max), split), Ok(true), "{split}");
3191            assert!(
3192                matches!(
3193                    decode(&field(max + 1), split),
3194                    Err(DecodeError::InvalidInput(_))
3195                ),
3196                "{split}"
3197            );
3198            // an endless field line
3199            assert!(
3200                matches!(
3201                    decode(&[&b"x: "[..], &vec![b'v'; max * 2]].concat(), split),
3202                    Err(DecodeError::InvalidInput(_))
3203                ),
3204                "{split}"
3205            );
3206        }
3207
3208        // many small fields
3209        assert_eq!(decode(&b"x: y\r\n".repeat(max / 6), false), Ok(true));
3210        assert!(matches!(
3211            decode(&b"x: y\r\n".repeat(max / 6 + 1), false),
3212            Err(DecodeError::InvalidInput(_))
3213        ));
3214    }
3215
3216    /// STATEMENT: Chunked trailers preserve values and pipeline boundaries while rejecting malformed syntax.
3217    ///
3218    /// HOW:
3219    /// - Decode complete and fragmented trailers, including whitespace and repeated fields, then inspect EOF and the next request.
3220    /// - Feed invalid names, separators, line endings, and folded fields and require errors.
3221    #[test]
3222    fn test_parse_chunked_payload_trailers() {
3223        let mut buf = BytesMut::from(
3224            "POST /test HTTP/1.1\r\nhost: localhost\r\n\
3225             transfer-encoding: chunked\r\n\r\n\
3226             4\r\ndata\r\n0\r\n\
3227             test: test\r\n\
3228             x-checksum: \tabc 123\r\n\r\n\
3229             GET /next HTTP/1.1\r\nhost: localhost\r\n\r\n",
3230        );
3231        let reader = MessageDecoder::<Request>::default();
3232        let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3233        let pl = pl.unwrap();
3234        assert_eq!(
3235            pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(),
3236            b"data"
3237        );
3238        let Some(PayloadItem::Trailers(trailers)) = pl.decode(&mut buf).unwrap() else {
3239            panic!("trailers are expected")
3240        };
3241        assert_eq!(trailers.len(), 2);
3242        assert_eq!(trailers.get("test").unwrap(), "test");
3243        assert_eq!(trailers.get("x-checksum").unwrap(), "abc 123");
3244        assert!(pl.decode(&mut buf).unwrap().unwrap().eof());
3245        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
3246        assert_eq!(req.path(), "/next");
3247        assert!(buf.is_empty());
3248
3249        // trailers split across reads
3250        let mut buf = BytesMut::from(
3251            "POST /test HTTP/1.1\r\nhost: localhost\r\n\
3252             transfer-encoding: chunked\r\n\r\n",
3253        );
3254        let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3255        let pl = pl.unwrap();
3256        for part in [
3257            "0\r\n",
3258            "te",
3259            "st: te",
3260            "st\r",
3261            "\n",
3262            "a: 1\r\na: ",
3263            "2\r\n",
3264            "\r",
3265        ] {
3266            buf.extend(part.as_bytes());
3267            assert!(pl.decode(&mut buf).unwrap().is_none(), "{part:?}");
3268        }
3269        buf.extend(b"\n");
3270        let Some(PayloadItem::Trailers(trailers)) = pl.decode(&mut buf).unwrap() else {
3271            panic!("trailers are expected")
3272        };
3273        assert_eq!(trailers.get("test").unwrap(), "test");
3274        let values: Vec<_> = trailers.get_all("a").collect();
3275        assert_eq!(values, ["1", "2"]);
3276        assert!(pl.decode(&mut buf).unwrap().unwrap().eof());
3277        assert!(buf.is_empty());
3278
3279        // invalid trailers
3280        for trailer in [
3281            "test: te\nst\r\n\r\n",
3282            "test\x00\r\n\r\n",
3283            " test: v\r\n\r\n",
3284            "test: v\rx",
3285            "test\r\n\r\n",
3286            ": v\r\n\r\n",
3287            "te st: v\r\n\r\n",
3288            "test: v\r\n\rx",
3289            "test: v\r\n t\r\n\r\n",
3290        ] {
3291            let mut buf = BytesMut::from(
3292                "POST /test HTTP/1.1\r\nhost: localhost\r\n\
3293                 transfer-encoding: chunked\r\n\r\n0\r\n",
3294            );
3295            buf.extend(trailer.as_bytes());
3296            let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3297            assert!(pl.unwrap().decode(&mut buf).is_err(), "{trailer:?}");
3298        }
3299    }
3300
3301    /// STATEMENT: Chunked output orders data, trailers, and EOF without consuming following bytes.
3302    ///
3303    /// HOW:
3304    /// - Decode a buffered chunk/trailer sequence and compare each item plus the untouched trailing buffer.
3305    #[test]
3306    fn test_chunked_trailers_after_data() {
3307        let (pl, mut buf) = chunked_payload();
3308        buf.extend_from_slice(b"2\r\nab\r\n0\r\nx: 1\r\n\r\nnext");
3309        assert_eq!(
3310            pl.decode(&mut buf).unwrap(),
3311            Some(PayloadItem::Chunk("ab".into()))
3312        );
3313        let Some(PayloadItem::Trailers(trailers)) = pl.decode(&mut buf).unwrap() else {
3314            panic!("trailers are expected")
3315        };
3316        assert_eq!(trailers.get("x").unwrap(), "1");
3317        assert_eq!(pl.decode(&mut buf).unwrap(), Some(PayloadItem::Eof));
3318        assert_eq!(&buf[..], b"next");
3319    }
3320
3321    /// STATEMENT: Supported chunk extensions do not appear in decoded payload data.
3322    ///
3323    /// HOW:
3324    /// - Decode an extension-bearing chunk followed by ordinary data and compare merged body bytes and EOF.
3325    #[test]
3326    fn test_parse_chunked_payload_chunk_extension() {
3327        let mut buf = BytesMut::from(
3328            "GET /test HTTP/1.1\r\nhost: localhost\r\n\
3329              transfer-encoding: chunked\r\n\r\n",
3330        );
3331
3332        let reader = MessageDecoder::<Request>::default();
3333        let (msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
3334        let pl = pl.unwrap();
3335        assert!(msg.chunked().unwrap());
3336
3337        buf.extend(b"4;test\r\ndata\r\n4\r\nline\r\n0\r\n\r\n"); // test: test\r\n\r\n")
3338        let chunk = pl.decode(&mut buf).unwrap().unwrap().chunk();
3339        assert_eq!(chunk, Bytes::from_static(b"dataline"));
3340        let msg = pl.decode(&mut buf).unwrap().unwrap();
3341        assert!(msg.eof());
3342    }
3343
3344    fn decode_all(pl: &PayloadDecoder, buf: &mut BytesMut) -> Vec<Bytes> {
3345        let mut items = Vec::new();
3346        while let Some(item) = pl.decode(buf).unwrap() {
3347            match item {
3348                PayloadItem::Chunk(chunk) => items.push(chunk),
3349                PayloadItem::Trailers(_) => (),
3350                PayloadItem::Eof => break,
3351            }
3352        }
3353        items
3354    }
3355
3356    /// STATEMENT: Small chunk payloads merge up to a bounded output size and chunk count, and are released before final input arrives.
3357    ///
3358    /// HOW:
3359    /// - Decode many one-byte chunks, with and without extensions, and check that output lengths stop at `MAX_MERGED_COUNT` and contents match.
3360    /// - Decode many 64-byte chunks and check that output lengths stop at `MAX_MERGED_CHUNKS`.
3361    /// - Exercise a completed small body and a partial chunk, checking prompt output and final EOF.
3362    #[test]
3363    fn test_small_chunks_are_merged() {
3364        // extensions are decoded by the state machine, not the fast path
3365        for chunk in [&b"1\r\na\r\n"[..], b"1;e\r\na\r\n"] {
3366            let (pl, mut buf) = chunked_payload();
3367            for _ in 0..2_500 {
3368                buf.extend_from_slice(chunk);
3369            }
3370            buf.extend_from_slice(b"0\r\n\r\n");
3371            let items = decode_all(&pl, &mut buf);
3372            let lens: Vec<_> = items.iter().map(Bytes::len).collect();
3373            assert_eq!(
3374                lens,
3375                [
3376                    MAX_MERGED_COUNT,
3377                    MAX_MERGED_COUNT,
3378                    2_500 - 2 * MAX_MERGED_COUNT
3379                ],
3380                "{chunk:?}"
3381            );
3382            assert!(items.iter().all(|c| c.iter().all(|b| *b == b'a')));
3383            assert!(buf.is_empty());
3384        }
3385
3386        let (pl, mut buf) = chunked_payload();
3387        for _ in 0..600 {
3388            buf.extend_from_slice(format!("40\r\n{}\r\n", "b".repeat(64)).as_bytes());
3389        }
3390        buf.extend_from_slice(b"0\r\n\r\n");
3391        let lens: Vec<_> = decode_all(&pl, &mut buf).iter().map(Bytes::len).collect();
3392        assert_eq!(
3393            lens,
3394            [
3395                MAX_MERGED_CHUNKS,
3396                MAX_MERGED_CHUNKS,
3397                600 * 64 - 2 * MAX_MERGED_CHUNKS
3398            ]
3399        );
3400
3401        // merged chunks are returned before the end of the payload
3402        let (pl, mut buf) = chunked_payload();
3403        buf.extend_from_slice(b"2\r\nab\r\n2\r\ncd\r\n0\r\n\r\n");
3404        assert_eq!(
3405            pl.decode(&mut buf).unwrap(),
3406            Some(PayloadItem::Chunk("abcd".into()))
3407        );
3408        assert_eq!(pl.decode(&mut buf).unwrap(), Some(PayloadItem::Eof));
3409
3410        // incomplete chunk
3411        let (pl, mut buf) = chunked_payload();
3412        buf.extend_from_slice(b"2\r\nab\r\n5\r\ncd");
3413        assert_eq!(
3414            pl.decode(&mut buf).unwrap(),
3415            Some(PayloadItem::Chunk("abcd".into()))
3416        );
3417        assert_eq!(pl.decode(&mut buf).unwrap(), None);
3418        buf.extend_from_slice(b"efg\r\n0\r\n\r\n");
3419        assert_eq!(
3420            pl.decode(&mut buf).unwrap(),
3421            Some(PayloadItem::Chunk("efg".into()))
3422        );
3423        assert_eq!(pl.decode(&mut buf).unwrap(), Some(PayloadItem::Eof));
3424    }
3425
3426    /// STATEMENT: Complete small chunks read by the fast path decode exactly as the chunked state machine decodes them.
3427    ///
3428    /// HOW:
3429    /// - Decode valid, incomplete and invalid payloads from one buffer, where complete small chunks
3430    ///   take the fast path, and byte by byte, where only the state machine runs.
3431    /// - Compare data and the final result of valid and incomplete payloads, and the error of
3432    ///   invalid payloads, whose data before the error differs.
3433    #[test]
3434    fn test_small_chunk_fast_path() {
3435        fn decode(input: &[u8], bytewise: bool) -> (Vec<u8>, String) {
3436            let (pl, mut buf) = chunked_payload();
3437            let steps: Vec<&[u8]> = if bytewise {
3438                input.chunks(1).collect()
3439            } else {
3440                vec![input]
3441            };
3442            let mut data = Vec::new();
3443            for step in steps {
3444                buf.extend_from_slice(step);
3445                loop {
3446                    match pl.decode(&mut buf) {
3447                        Ok(Some(PayloadItem::Chunk(chunk))) => {
3448                            assert!(chunk.len() < MAX_MERGED_CHUNKS + SMALL_CHUNK);
3449                            data.extend_from_slice(&chunk);
3450                        }
3451                        Ok(None) => break,
3452                        res => return (data, format!("{res:?}")),
3453                    }
3454                }
3455            }
3456            (data, "incomplete".to_string())
3457        }
3458
3459        let valid = [
3460            format!("{}0\r\n\r\n", "1\r\na\r\n".repeat(3_000)),
3461            "3\r\nabc\r\nA\r\n0123456789\r\na\r\n0123456789\r\n0\r\n\r\n".to_string(),
3462            format!(
3463                "3FF\r\n{}\r\n400\r\n{}\r\n2\r\nab\r\n0\r\n\r\n",
3464                "x".repeat(0x3ff),
3465                "y".repeat(0x400)
3466            ),
3467            "000000000000000F\r\n0123456789abcde\r\n1\r\nf\r\n0\r\n\r\n".to_string(),
3468            "3;a=b\r\nabc\r\n3 ;x\r\ndef\r\n2\r\ngh\r\n0\r\n\r\n".to_string(),
3469            "2\r\nab\r\n1\r\nc\r\n0\r\nx-a: b\r\n\r\n".to_string(),
3470            "2\r\nab\r\n1\r\nc\r\n5\r\nabc".to_string(),
3471            "2\r\nab\r\n1\r\nc\r\n1".to_string(),
3472        ];
3473        for input in &valid {
3474            let whole = decode(input.as_bytes(), false);
3475            assert!(!whole.1.contains("Err"), "{input:?} {}", whole.1);
3476            assert_eq!(whole, decode(input.as_bytes(), true), "{input:?}");
3477        }
3478
3479        for input in [
3480            "2\r\nab\r\n00000000000000001\r\na\r\n",
3481            "2\r\nab\r\n1\r\naX\r\n",
3482            "2\r\nab\r\n1\r\na\rX",
3483            "2\r\nab\r\ng\r\na\r\n",
3484            "2\r\nab\r\n1g\r\na\r\n",
3485            "2\r\nab\r\n\r\n",
3486            "2\r\nab\r\n1\rX",
3487        ] {
3488            let whole = decode(input.as_bytes(), false);
3489            assert!(whole.1.contains("Err"), "{input:?} {}", whole.1);
3490            assert_eq!(whole.1, decode(input.as_bytes(), true).1, "{input:?}");
3491        }
3492    }
3493
3494    /// STATEMENT: Large payload chunks remain separate and borrow the original input allocation.
3495    ///
3496    /// HOW:
3497    /// - Decode alternating small/large chunks, compare item boundaries, and verify large-chunk pointers lie in the input buffer.
3498    #[test]
3499    fn test_large_chunks_are_not_merged() {
3500        let large = "x".repeat(SMALL_CHUNK);
3501        let (pl, mut buf) = chunked_payload();
3502        buf.extend_from_slice(format!("3\r\nabc\r\n{:X}\r\n{large}\r\n", large.len()).as_bytes());
3503        buf.extend_from_slice(
3504            format!("{:X}\r\n{large}\r\n2\r\nxy\r\n0\r\n\r\n", large.len()).as_bytes(),
3505        );
3506        let range = buf.as_ptr() as usize..buf.as_ptr() as usize + buf.len();
3507
3508        let items = decode_all(&pl, &mut buf);
3509        assert_eq!(
3510            items,
3511            [
3512                Bytes::from("abc"),
3513                large.clone().into(),
3514                large.into(),
3515                "xy".into()
3516            ]
3517        );
3518        // large chunks are not copied
3519        assert!(range.contains(&(items[1].as_ptr() as usize)));
3520        assert!(range.contains(&(items[2].as_ptr() as usize)));
3521    }
3522
3523    fn chunked_payload() -> (PayloadDecoder, BytesMut) {
3524        let mut buf = BytesMut::from(
3525            "POST /test HTTP/1.1\r\nhost: localhost\r\ntransfer-encoding: chunked\r\n\r\n",
3526        );
3527        let reader = MessageDecoder::<Request>::default();
3528        let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3529        (pl.unwrap(), buf)
3530    }
3531
3532    /// STATEMENT: Chunk extensions reject forbidden control bytes while tolerating allowed tab, spacing, and high bytes.
3533    ///
3534    /// HOW:
3535    /// - Feed malformed extension lines and require invalid-input errors, then decode an accepted quoted extension.
3536    #[test]
3537    fn test_chunk_extension_control_chars() {
3538        for line in [
3539            &b"4;a\nX\r\n"[..],
3540            b"4;a=\"\nX\"\r\n",
3541            b"4;a\x00\r\n",
3542            b"4;a\x7f\r\n",
3543            b"4 \n;a\r\n",
3544        ] {
3545            let (pl, mut buf) = chunked_payload();
3546            buf.extend_from_slice(line);
3547            buf.extend_from_slice(b"data\r\n0\r\n\r\n");
3548            assert!(
3549                matches!(pl.decode(&mut buf), Err(DecodeError::InvalidInput(_))),
3550                "{line:?}"
3551            );
3552        }
3553
3554        let (pl, mut buf) = chunked_payload();
3555        buf.extend_from_slice(b"4 ;a=\"b\tc \x80\" ;d\r\ndata\r\n0\r\n\r\n");
3556        let chunk = pl.decode(&mut buf).unwrap().unwrap().chunk();
3557        assert_eq!(chunk, Bytes::from_static(b"data"));
3558        assert!(pl.decode(&mut buf).unwrap().unwrap().eof());
3559    }
3560
3561    /// STATEMENT: Chunk-extension budgets bound unfinished lines and cumulative extensions across the payload.
3562    ///
3563    /// HOW:
3564    /// - Grow an unterminated extension and repeated extension-bearing chunks until rejection.
3565    /// - Check bounded buffering and acceptance of a single extension exactly at the budget.
3566    #[test]
3567    fn test_chunk_extensions_limit() {
3568        // a size line that never ends is not buffered without limit
3569        let (pl, mut buf) = chunked_payload();
3570        buf.extend(b"1;");
3571        let mut failed = false;
3572        for _ in 0..64 {
3573            buf.extend(&[b'a'; 1024]);
3574            match pl.decode(&mut buf) {
3575                Ok(None) => (),
3576                Err(_) => {
3577                    failed = true;
3578                    break;
3579                }
3580                Ok(Some(item)) => panic!("unexpected item {item:?}"),
3581            }
3582        }
3583        assert!(failed);
3584        assert!(buf.len() <= MAX_CHUNK_EXTENSIONS as usize + 1024 + 20);
3585
3586        // extensions are limited for the whole payload
3587        let (pl, mut buf) = chunked_payload();
3588        let ext = "a".repeat(1023);
3589        let mut result = Ok(());
3590        for _ in 0..32 {
3591            buf.extend(format!("1;{ext}\r\nx\r\n").as_bytes());
3592            match pl.decode(&mut buf) {
3593                Ok(Some(PayloadItem::Chunk(chunk))) => assert_eq!(chunk, "x"),
3594                Ok(item) => panic!("unexpected item {item:?}"),
3595                Err(err) => {
3596                    result = Err(err);
3597                    break;
3598                }
3599            }
3600        }
3601        assert!(result.is_err());
3602
3603        // extensions up to the limit are accepted
3604        let (pl, mut buf) = chunked_payload();
3605        let ext = "a".repeat(MAX_CHUNK_EXTENSIONS as usize - 1);
3606        buf.extend(format!("10;{ext}\r\n0123456789abcdef\r\n0\r\n\r\n").as_bytes());
3607        assert_eq!(
3608            pl.decode(&mut buf).unwrap().unwrap().chunk(),
3609            "0123456789abcdef"
3610        );
3611        assert!(pl.decode(&mut buf).unwrap().unwrap().eof());
3612    }
3613
3614    /// STATEMENT: Oversized partial extensions and invalid chunk delimiters produce specific framing errors.
3615    ///
3616    /// HOW:
3617    /// - Feed an already-oversized extension and corrupt body/end CRLF bytes.
3618    /// - Drain any preceding data and compare each invalid-input diagnostic.
3619    #[test]
3620    fn test_chunk_framing_errors() {
3621        // a partial size line larger than the limit, received at once
3622        let (pl, mut buf) = chunked_payload();
3623        buf.extend(b"1;");
3624        buf.extend("a".repeat(MAX_CHUNK_EXTENSIONS as usize + 64).as_bytes());
3625        assert!(matches!(
3626            pl.decode(&mut buf),
3627            Err(DecodeError::InvalidInput("Chunk extensions are too large"))
3628        ));
3629
3630        for (data, msg) in [
3631            (&b"4\r\ndataX\r\n"[..], "Invalid chunk body CR"),
3632            (b"4\r\ndata\rX", "Invalid chunk body LF"),
3633            (b"0\r\n\rX", "Invalid chunk end LF"),
3634        ] {
3635            let (pl, mut buf) = chunked_payload();
3636            buf.extend_from_slice(data);
3637            let mut res = pl.decode(&mut buf);
3638            while let Ok(Some(PayloadItem::Chunk(_))) = res {
3639                res = pl.decode(&mut buf);
3640            }
3641            assert!(
3642                matches!(res, Err(DecodeError::InvalidInput(m)) if m == msg),
3643                "{data:?} {res:?}"
3644            );
3645        }
3646    }
3647
3648    /// STATEMENT: Content-length parsing accepts only an in-range run of ASCII digits.
3649    ///
3650    /// HOW:
3651    /// - Decode trailing-letter, high-byte, empty, embedded-space, signed and
3652    ///   `u64`-overflowing length values and expect header errors.
3653    #[test]
3654    fn test_illegal_content_length() {
3655        for value in [
3656            &b"12a"[..],
3657            b"\xff1",
3658            b"1\xff",
3659            b"",
3660            b"1 2",
3661            b"-0",
3662            b"+0",
3663            b"18446744073709551616",
3664        ] {
3665            let mut buf = BytesMut::from(&b"GET /test HTTP/1.1\r\ncontent-length: "[..]);
3666            buf.extend_from_slice(value);
3667            buf.extend_from_slice(b"\r\n\r\n");
3668            let reader = MessageDecoder::<Request>::default();
3669            assert!(
3670                matches!(reader.decode(&mut buf), Err(DecodeError::Header)),
3671                "{value:?}"
3672            );
3673        }
3674    }
3675
3676    /// STATEMENT: Incremental chunk-size parsing validates each byte promptly and enforces extension budgets.
3677    ///
3678    /// HOW:
3679    /// - Feed valid spacing/extensions bytewise and compare decoded data.
3680    /// - Check exact rejection positions for invalid bytes and boundary behavior for long or endless extensions.
3681    #[test]
3682    fn test_chunk_size_line_byte_by_byte() {
3683        let feed = |line: &[u8]| {
3684            let (pl, mut buf) = chunked_payload();
3685            let mut data = Vec::new();
3686            for (idx, b) in line.iter().enumerate() {
3687                buf.extend_from_slice(&[*b]);
3688                match pl.decode(&mut buf) {
3689                    Ok(None) => (),
3690                    Ok(Some(item)) => data.extend_from_slice(&item.chunk()),
3691                    Err(_) => return Err(idx),
3692                }
3693            }
3694            Ok(data)
3695        };
3696
3697        // valid lines
3698        for line in [
3699            &b"4;a=b;c\r\ndata"[..],
3700            b"4 \t ;ext\t=\t\"\x80\"\r\ndata",
3701            b"4\r\ndata",
3702        ] {
3703            assert_eq!(feed(line).unwrap(), b"data", "{line:?}");
3704        }
3705
3706        // invalid lines fail at the invalid byte
3707        for (line, pos) in [
3708            (&b"4;aaaa\x01aaaa\r\n"[..], 6),
3709            (b"4;aa\x7f", 4),
3710            (b"4;aa\ra", 5),
3711            (b"4;aa\na", 4),
3712            (b"4   5", 4),
3713            (b"4  x", 3),
3714            (b"4\rx", 2),
3715        ] {
3716            assert_eq!(feed(line).map(|_| ()), Err(pos), "{line:?}");
3717        }
3718
3719        // long extension fed byte by byte
3720        let mut line = b"10;".to_vec();
3721        line.extend(std::iter::repeat_n(b'a', MAX_CHUNK_EXTENSIONS as usize - 1));
3722        line.extend_from_slice(b"\r\n0123456789abcdef");
3723        assert_eq!(feed(&line).unwrap(), b"0123456789abcdef");
3724
3725        let mut line = b"10;".to_vec();
3726        line.extend(std::iter::repeat_n(b'a', MAX_CHUNK_EXTENSIONS as usize + 1));
3727        line.extend_from_slice(b"\r\n");
3728        assert!(feed(&line).is_err());
3729
3730        // a line that never ends fails at the limit
3731        let line = vec![b'a'; MAX_CHUNK_EXTENSIONS as usize];
3732        let line = [&b"1;"[..], &line, &line].concat();
3733        assert!(feed(&line).is_err());
3734    }
3735
3736    /// STATEMENT: Bodyless response statuses ignore framing headers and preserve following response bytes.
3737    ///
3738    /// HOW:
3739    /// - Decode informational, no-content, and not-modified responses and inspect absent payloads and remaining buffers.
3740    /// - Verify an ordinary successful response still yields its declared body.
3741    #[test]
3742    fn test_response_bodyless_status() {
3743        for (head, rest) in [
3744            (
3745                "HTTP/1.1 304 Not Modified\r\ncontent-length: 10\r\n\r\n",
3746                "",
3747            ),
3748            ("HTTP/1.1 204 No Content\r\ncontent-length: 10\r\n\r\n", ""),
3749            (
3750                "HTTP/1.1 204 No Content\r\ntransfer-encoding: chunked\r\n\r\n",
3751                "",
3752            ),
3753            (
3754                "HTTP/1.1 100 Continue\r\ncontent-length: 2\r\n\r\n",
3755                "HTTP/1.1 200 OK\r\n\r\n",
3756            ),
3757            ("HTTP/1.0 304 Not Modified\r\n\r\n", "next"),
3758        ] {
3759            let mut buf = BytesMut::from(format!("{head}{rest}").as_str());
3760            let reader = MessageDecoder::<ResponseHead>::default();
3761            let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3762            assert!(matches!(pl, PayloadType::None), "{head:?}");
3763            assert_eq!(buf, rest.as_bytes(), "{head:?}");
3764        }
3765
3766        let mut buf = BytesMut::from("HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nok");
3767        let reader = MessageDecoder::<ResponseHead>::default();
3768        let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3769        let pl = pl.unwrap();
3770        assert_eq!(
3771            pl.decode(&mut buf).unwrap().unwrap().chunk().as_ref(),
3772            b"ok"
3773        );
3774    }
3775
3776    /// STATEMENT: Unframed ordinary responses read until close, explicit zero lengths are empty, and switching protocols yields a stream.
3777    ///
3778    /// HOW:
3779    /// - Decode HTTP/1.0 and HTTP/1.1 variants and inspect connection type, payload mode, and body bytes.
3780    /// - Compare zero-length ordinary responses with a zero-length upgrade response.
3781    #[test]
3782    fn test_response_read_until_eof() {
3783        for version in ["1.0", "1.1"] {
3784            let mut buf =
3785                BytesMut::from(format!("HTTP/{version} 200 OK\r\n\r\ntest data").as_str());
3786            let reader = MessageDecoder::<ResponseHead>::default();
3787            let (msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
3788            assert_eq!(msg.connection_type(), ConnectionType::Close, "{version}");
3789            let pl = pl.unwrap();
3790            assert!(pl.is_eof(), "{version}");
3791            let chunk = pl.decode(&mut buf).unwrap().unwrap();
3792            assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"test data")));
3793        }
3794
3795        // zero content-length has no payload
3796        for version in ["1.0", "1.1"] {
3797            let mut buf = BytesMut::from(
3798                format!("HTTP/{version} 200 OK\r\ncontent-length: 0\r\n\r\n").as_str(),
3799            );
3800            let reader = MessageDecoder::<ResponseHead>::default();
3801            let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3802            assert!(matches!(pl, PayloadType::None), "{version}");
3803        }
3804
3805        let mut buf =
3806            BytesMut::from("HTTP/1.1 101 Switching Protocols\r\ncontent-length: 0\r\n\r\n");
3807        let reader = MessageDecoder::<ResponseHead>::default();
3808        let (_, pl) = reader.decode(&mut buf).unwrap().unwrap();
3809        assert!(matches!(pl, PayloadType::Stream(_)));
3810    }
3811
3812    /// STATEMENT: HTTP/1.0 responses without length expose buffered data as close-delimited payload.
3813    ///
3814    /// HOW:
3815    /// - Decode a response without framing headers and compare its first payload chunk.
3816    #[test]
3817    fn test_response_http10_read_until_eof() {
3818        let mut buf = BytesMut::from("HTTP/1.0 200 Ok\r\n\r\ntest data");
3819
3820        let reader = MessageDecoder::<ResponseHead>::default();
3821        let res = reader.decode(&mut buf);
3822        let (_msg, pl) = res.unwrap().unwrap();
3823        let pl = pl.unwrap();
3824
3825        let chunk = pl.decode(&mut buf).unwrap().unwrap();
3826        assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"test data")));
3827    }
3828
3829    /// STATEMENT: Multiple content-length headers are rejected even when one declares zero.
3830    ///
3831    /// HOW:
3832    /// - Decode conflicting positive lengths and zero/positive lengths and require parse errors.
3833    #[test]
3834    fn test_multiple_content_length() {
3835        let mut buf = BytesMut::from(
3836            "GET / HTTP/1.1\r\n\
3837             Host: example.com\r\n\
3838             Content-Length: 4\r\n\
3839             Content-Length: 2\r\n\
3840             \r\n\
3841             abcd",
3842        );
3843        expect_parse_err!(&mut buf);
3844
3845        let mut buf = BytesMut::from(
3846            "GET / HTTP/1.1\r\n\
3847             Host: example.com\r\n\
3848             Content-Length: 0\r\n\
3849             Content-Length: 2\r\n\
3850             \r\n\
3851             ab",
3852        );
3853        expect_parse_err!(&mut buf);
3854    }
3855
3856    /// STATEMENT: HTTP/1.0 requests reject transfer encoding.
3857    ///
3858    /// HOW:
3859    /// - Decode an HTTP/1.0 POST with chunked framing and require a parse error.
3860    #[test]
3861    fn test_transfer_encoding_http10() {
3862        // in HTTP/1.0 transfer encoding is not supported
3863
3864        let mut buf = BytesMut::from(
3865            "POST / HTTP/1.0\r\n\
3866            Host: example.com\r\n\
3867            Transfer-Encoding: chunked\r\n\
3868            \r\n\
3869            3\r\n\
3870            aaa\r\n\
3871            0\r\n\
3872            ",
3873        );
3874
3875        expect_parse_err!(&mut buf);
3876    }
3877
3878    /// STATEMENT: A content length does not make HTTP/1.0 transfer encoding acceptable.
3879    ///
3880    /// HOW:
3881    /// - Decode a request containing both framing headers and require a parse error.
3882    #[test]
3883    fn test_content_length_and_te_http10() {
3884        // in HTTP/1.0 transfer encoding is not supported
3885
3886        let mut buf = BytesMut::from(
3887            "GET / HTTP/1.0\r\n\
3888            Host: example.com\r\n\
3889            Content-Length: 3\r\n\
3890            Transfer-Encoding: chunked\r\n\
3891            \r\n\
3892            000",
3893        );
3894
3895        expect_parse_err!(&mut buf);
3896    }
3897
3898    /// STATEMENT: Content lengths cannot carry a leading plus sign.
3899    ///
3900    /// HOW:
3901    /// - Decode a positive signed content-length value and require a parse error.
3902    #[test]
3903    fn test_content_length_plus() {
3904        let mut buf = BytesMut::from(
3905            "GET / HTTP/1.1\r\n\
3906             Host: example.com\r\n\
3907             Content-Length: +3\r\n\
3908             \r\n\
3909             000",
3910        );
3911        expect_parse_err!(&mut buf);
3912    }
3913
3914    /// STATEMENT: A later chunked header does not hide an earlier unsupported transfer encoding.
3915    ///
3916    /// HOW:
3917    /// - Decode unknown and chunked transfer headers together and require rejection.
3918    #[test]
3919    fn test_unknown_transfer_encoding() {
3920        let mut buf = BytesMut::from(
3921            "GET / HTTP/1.1\r\n\
3922             Host: example.com\r\n\
3923             Transfer-Encoding: JUNK\r\n\
3924             Transfer-Encoding: chunked\r\n\
3925             \r\n\
3926             5\r\n\
3927             hello\r\n\
3928             0",
3929        );
3930
3931        expect_parse_err!(&mut buf);
3932    }
3933
3934    /// STATEMENT: Ambiguous repeated transfer framing with content length is rejected before pipelined bytes are interpreted.
3935    ///
3936    /// HOW:
3937    /// - Decode identity/chunked headers plus a length and request-like body suffix and require a parse error.
3938    #[test]
3939    fn test_multiple_transfer_encoding() {
3940        let mut buf = BytesMut::from(
3941            "GET / HTTP/1.1\r\n\
3942             Host: example.com\r\n\
3943             Content-Length: 51\r\n\
3944             Transfer-Encoding: identity\r\n\
3945             Transfer-Encoding: chunked\r\n\
3946             \r\n\
3947             0\r\n\
3948             \r\n\
3949             GET /forbidden HTTP/1.1\r\n\
3950             Host: example.com\r\n\r\n",
3951        );
3952        expect_parse_err!(&mut buf);
3953    }
3954
3955    /// STATEMENT: Requests cannot combine content length with chunked transfer encoding in either header order.
3956    ///
3957    /// HOW:
3958    /// - Decode both framing-header orders and require parse errors.
3959    #[test]
3960    fn test_transfer_encoding_content_length_combination() {
3961        let mut buf = BytesMut::from(
3962            "GET /test HTTP/1.1\r\n\
3963             Host: example.com\r\n\
3964             Content-Length: 3\r\n\
3965             Transfer-Encoding: chunked\r\n\
3966             \r\n\
3967             0\r\n",
3968        );
3969        expect_parse_err!(&mut buf);
3970
3971        let mut buf = BytesMut::from(
3972            "GET /test HTTP/1.1\r\n\
3973             Host: example.com\r\n\
3974             Transfer-Encoding: chunked\r\n\
3975             Content-Length: 3\r\n\
3976             \r\n\
3977             0\r\n",
3978        );
3979        expect_parse_err!(&mut buf);
3980    }
3981
3982    /// STATEMENT: Transfer-coding lists distinguish final chunking and unsupported codings while rejecting invalid syntax.
3983    ///
3984    /// HOW:
3985    /// - Parse case, whitespace, empty-token, ordering, duplicate, and parameter variants.
3986    /// - Compare final-chunked/other-coding flags or invalid-list results.
3987    #[test]
3988    fn test_transfer_codings() {
3989        for (val, res) in [
3990            ("chunked", Some((true, false))),
3991            (" Chunked ", Some((true, false))),
3992            ("gzip, chunked", Some((true, true))),
3993            ("gzip;q=1 ,, chunked,", Some((true, true))),
3994            ("identity, chunked", Some((true, false))),
3995            ("identity", Some((false, false))),
3996            ("gzip", Some((false, true))),
3997            ("chunked, gzip", Some((false, true))),
3998            ("chunked, chunked", None),
3999            ("chunked, gzip, chunked", None),
4000            ("chunked;a=b", None),
4001            ("gz ip", None),
4002            (";a=b", None),
4003        ] {
4004            assert_eq!(transfer_codings(val.as_bytes()), res, "{val:?}");
4005        }
4006    }
4007
4008    /// STATEMENT: Requests require valid final chunking and distinguish unsupported codings from malformed framing.
4009    ///
4010    /// HOW:
4011    /// - Decode several coding lists and compare unsupported/header errors or valid chunked payload classification.
4012    #[test]
4013    fn test_request_transfer_codings() {
4014        for (val, res) in [
4015            ("gzip, chunked", Err(DecodeError::UnsupportedTransferCoding)),
4016            ("chunked, gzip", Err(DecodeError::Header)),
4017            ("gzip", Err(DecodeError::Header)),
4018            ("chunked, chunked", Err(DecodeError::Header)),
4019            ("identity, chunked", Ok(())),
4020            ("chunked,", Ok(())),
4021        ] {
4022            let mut buf = BytesMut::from(
4023                format!("POST / HTTP/1.1\r\nhost: a\r\ntransfer-encoding: {val}\r\n\r\n").as_str(),
4024            );
4025            let reader = MessageDecoder::<Request>::default();
4026            let result = reader.decode(&mut buf).map(|msg| {
4027                let (req, pl) = msg.unwrap();
4028                assert!(req.chunked().unwrap());
4029                assert_eq!(pl, PayloadType::Payload(PayloadDecoder::chunked()));
4030            });
4031            assert_eq!(result, res, "{val:?}");
4032        }
4033    }
4034
4035    /// STATEMENT: Responses use final chunking for framing, otherwise close-delimit unsupported codings, and reject conflicting lengths.
4036    ///
4037    /// HOW:
4038    /// - Decode final/nonfinal chunked lists and compare headers, connection modes, and undecoded body bytes.
4039    /// - Reject transfer coding combined with content length in either order.
4040    #[test]
4041    fn test_response_transfer_codings() {
4042        // final chunked coding frames the payload, other codings are not decoded
4043        let mut buf = BytesMut::from(
4044            "HTTP/1.1 200 OK\r\ntransfer-encoding: gzip, chunked\r\n\r\n3\r\nabc\r\n0\r\n\r\n",
4045        );
4046        let reader = MessageDecoder::<ResponseHead>::default();
4047        let (res, pl) = reader.decode(&mut buf).unwrap().unwrap();
4048        assert_eq!(
4049            res.headers.get(header::TRANSFER_ENCODING).unwrap(),
4050            "gzip, chunked"
4051        );
4052        let pl = pl.unwrap();
4053        assert_eq!(
4054            pl.decode(&mut buf).unwrap(),
4055            Some(PayloadItem::Chunk("abc".into()))
4056        );
4057        assert_eq!(pl.decode(&mut buf).unwrap(), Some(PayloadItem::Eof));
4058
4059        // without final chunked coding the payload is delimited by connection close
4060        for val in ["gzip", "chunked, gzip"] {
4061            let mut buf = BytesMut::from(
4062                format!("HTTP/1.1 200 OK\r\ntransfer-encoding: {val}\r\n\r\n3\r\nabc").as_str(),
4063            );
4064            let (res, pl) = reader.decode(&mut buf).unwrap().unwrap();
4065            assert_eq!(res.connection_type(), ConnectionType::Close, "{val:?}");
4066            let pl = pl.unwrap();
4067            assert!(pl.is_eof(), "{val:?}");
4068            assert_eq!(
4069                pl.decode(&mut buf).unwrap(),
4070                Some(PayloadItem::Chunk("3\r\nabc".into()))
4071            );
4072        }
4073
4074        // codings with Content-Length are rejected in either order
4075        for hdrs in [
4076            "content-length: 3\r\ntransfer-encoding: gzip\r\n",
4077            "transfer-encoding: gzip\r\ncontent-length: 3\r\n",
4078            "transfer-encoding: gzip, chunked\r\ncontent-length: 3\r\n",
4079        ] {
4080            let mut buf = BytesMut::from(format!("HTTP/1.1 200 OK\r\n{hdrs}\r\nabc").as_str());
4081            let reader = MessageDecoder::<ResponseHead>::default();
4082            assert_eq!(
4083                reader.decode(&mut buf).err(),
4084                Some(DecodeError::Header),
4085                "{hdrs:?}"
4086            );
4087        }
4088    }
4089
4090    /// STATEMENT: Identity transfer encoding is rejected in requests but tolerated with response content length.
4091    ///
4092    /// HOW:
4093    /// - Reject request variants with and without lengths and differing header order/case.
4094    /// - Decode a length-framed identity response and compare its body.
4095    #[test]
4096    fn test_transfer_encoding_identity() {
4097        for req in [
4098            "GET /test HTTP/1.1\r\nHost: a\r\n\
4099             Content-Length: 3\r\nTransfer-Encoding: identity\r\n\r\n0\r\n",
4100            "GET /test HTTP/1.1\r\nHost: a\r\n\
4101             Transfer-Encoding: identity\r\nContent-Length: 3\r\n\r\n0\r\n",
4102            "GET /test HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: identity\r\n\r\n",
4103            "GET /test HTTP/1.1\r\nHost: a\r\nTransfer-Encoding: Identity \r\n\r\n",
4104        ] {
4105            let mut buf = BytesMut::from(req);
4106            let reader = MessageDecoder::<Request>::default();
4107            assert_eq!(
4108                reader.decode(&mut buf).err(),
4109                Some(DecodeError::Header),
4110                "{req:?}"
4111            );
4112        }
4113
4114        // responses are tolerated
4115        let mut buf = BytesMut::from(
4116            "HTTP/1.1 200 OK\r\nContent-Length: 3\r\n\
4117             Transfer-Encoding: identity\r\n\r\n0\r\n",
4118        );
4119        let reader = MessageDecoder::<ResponseHead>::default();
4120        let (_msg, pl) = reader.decode(&mut buf).unwrap().unwrap();
4121        let pl = pl.unwrap();
4122        let chunk = pl.decode(&mut buf).unwrap().unwrap();
4123        assert_eq!(chunk, PayloadItem::Chunk(Bytes::from_static(b"0\r\n")));
4124    }
4125
4126    /// STATEMENT: Header decoding enforces buffer-size and field-count limits while supporting decoder reuse within limits.
4127    ///
4128    /// HOW:
4129    /// - Decode the same head under small/larger byte budgets and a one-field limit.
4130    /// - Compare exact errors and successful repeated decoder use.
4131    #[test]
4132    fn test_max_headers() {
4133        const TEXT: &str = "GET /test HTTP/1.1\r\n\
4134             Host: example.com\r\n\
4135             Content-Length: 3\r\n\
4136             Test-header: ****\r\n";
4137
4138        const TEXT_2: &str = "GET /test HTTP/1.1\r\n\
4139             Host: example.com\r\n\
4140             Content-Length: 3\r\n\
4141             Test-header: ****\r\n\
4142             \r\n";
4143
4144        let mut buf = BytesMut::from(TEXT);
4145        let cfg: SharedCfg = SharedCfg::new("test")
4146            .add(HttpServiceConfig::new().set_max_buf_size(10))
4147            .into();
4148        let reader = MessageDecoder::<Request>::new(cfg.get());
4149        let err = reader.decode(&mut buf).err().unwrap();
4150        assert_eq!(err, DecodeError::TooLarge(77));
4151
4152        let cfg: SharedCfg = SharedCfg::new("test")
4153            .add(HttpServiceConfig::new().set_max_buf_size(100))
4154            .into();
4155        let reader = MessageDecoder::<Request>::new(cfg.get());
4156        // decode one message
4157        let mut buf = BytesMut::from(TEXT_2);
4158        let res = reader.decode(&mut buf);
4159        assert!(res.is_ok());
4160
4161        // decode second message, same decoder
4162        let mut buf = BytesMut::from(TEXT);
4163        let res = reader.decode(&mut buf);
4164        assert!(res.is_ok());
4165
4166        // MAX HEADERS
4167        let cfg: SharedCfg = SharedCfg::new("test")
4168            .add(HttpServiceConfig::new().set_max_headers(1))
4169            .into();
4170        let reader = MessageDecoder::<Request>::new(cfg.get());
4171        let mut buf = BytesMut::from(TEXT);
4172        let err = reader.decode(&mut buf).err().unwrap();
4173        assert_eq!(err, DecodeError::MaxHeaders);
4174    }
4175
4176    /// STATEMENT: Header-count limits count repeated names, persist across partial reads, and reset per message.
4177    ///
4178    /// HOW:
4179    /// - Exceed the limit with repeated names in whole and split input.
4180    /// - Decode two at-limit pipelined messages and verify both succeed.
4181    #[test]
4182    fn test_max_headers_repeated_names() {
4183        let cfg: SharedCfg = SharedCfg::new("test")
4184            .add(
4185                HttpServiceConfig::new()
4186                    .set_max_headers(3)
4187                    .set_host_validation(false),
4188            )
4189            .into();
4190
4191        // repeated names count separately
4192        let reader = MessageDecoder::<Request>::new(cfg.get());
4193        let mut buf = BytesMut::from("GET / HTTP/1.1\r\nhost: a\r\nX: 1\r\nX: 2\r\nX: 3\r\n\r\n");
4194        assert_eq!(reader.decode(&mut buf).err(), Some(DecodeError::MaxHeaders));
4195
4196        // count is kept across partial reads
4197        let reader = MessageDecoder::<Request>::new(cfg.get());
4198        let mut buf = BytesMut::from("GET / HTTP/1.1\r\nhost: a\r\nX: 1\r\nX: 2\r\n");
4199        assert!(reader.decode(&mut buf).unwrap().is_none());
4200        buf.extend_from_slice(b"X: 3\r\n\r\n");
4201        assert_eq!(reader.decode(&mut buf).err(), Some(DecodeError::MaxHeaders));
4202
4203        // count is reset for the next message
4204        let reader = MessageDecoder::<Request>::new(cfg.get());
4205        let mut buf = BytesMut::from(
4206            "GET / HTTP/1.1\r\nhost: a\r\nX: 1\r\nX: 2\r\n\r\n\
4207             GET / HTTP/1.1\r\nhost: a\r\nX: 1\r\nX: 2\r\n\r\n",
4208        );
4209        let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
4210        assert_eq!(req.headers().get_all("x").count(), 2);
4211        assert!(reader.decode(&mut buf).unwrap().is_some());
4212    }
4213
4214    /// STATEMENT: Request decoders reset after syntax, framing, count, and size failures.
4215    ///
4216    /// HOW:
4217    /// - Feed each invalid head, then reuse the same decoder for a valid request.
4218    /// - Check its path and header count show no stale state.
4219    #[test]
4220    fn test_decoder_reusable_after_error() {
4221        const VALID: &str = "GET /ok HTTP/1.1\r\nHost: example.com\r\n\r\n";
4222
4223        let cfg: SharedCfg = SharedCfg::new("test")
4224            .add(
4225                HttpServiceConfig::new()
4226                    .set_max_headers(2)
4227                    .set_max_buf_size(128),
4228            )
4229            .into();
4230        let reader = MessageDecoder::<Request>::new(cfg.get());
4231
4232        let invalid = [
4233            // request line
4234            "G\x00T / HTTP/1.1\r\n\r\n".to_string(),
4235            // header
4236            "GET / HTTP/1.1\r\nContent-Length: x\r\n\r\n".to_string(),
4237            // partial head followed by too many headers
4238            "GET / HTTP/1.1\r\nA: 1\r\nB: 2\r\nC: 3\r\n".to_string(),
4239            // message head is too large
4240            format!("GET / HTTP/1.1\r\nA: {}\r\n", "a".repeat(200)),
4241        ];
4242        for text in invalid {
4243            let mut buf = BytesMut::from(text.as_str());
4244            assert!(reader.decode(&mut buf).is_err(), "{text:?}");
4245
4246            let mut buf = BytesMut::from(VALID);
4247            let (req, _) = reader.decode(&mut buf).unwrap().unwrap();
4248            assert_eq!(req.path(), "/ok");
4249            assert_eq!(req.headers().len(), 1);
4250        }
4251    }
4252
4253    /// STATEMENT: Request-head byte limits are inclusive and apply to both whole-buffer and split completion.
4254    ///
4255    /// HOW:
4256    /// - Decode an oversized head whole and split, comparing reported size.
4257    /// - Accept the same head with larger and exactly matching limits.
4258    #[test]
4259    fn test_max_buf_size_complete_message() {
4260        const TEXT: &str = "GET /test HTTP/1.1\r\n\
4261             Host: example.com\r\n\
4262             Content-Length: 3\r\n\
4263             Test-header: ****\r\n\
4264             \r\n";
4265
4266        // whole message head is available in one buffer
4267        let cfg: SharedCfg = SharedCfg::new("test")
4268            .add(HttpServiceConfig::new().set_max_buf_size(10))
4269            .into();
4270        let reader = MessageDecoder::<Request>::new(cfg.get());
4271        let mut buf = BytesMut::from(TEXT);
4272        let err = reader.decode(&mut buf).err().unwrap();
4273        assert_eq!(err, DecodeError::TooLarge(79));
4274
4275        // message head completes on the second read
4276        let cfg: SharedCfg = SharedCfg::new("test")
4277            .add(HttpServiceConfig::new().set_max_buf_size(78))
4278            .into();
4279        let reader = MessageDecoder::<Request>::new(cfg.get());
4280        let mut buf = BytesMut::from(&TEXT[..77]);
4281        assert!(reader.decode(&mut buf).unwrap().is_none());
4282        buf.extend_from_slice(&TEXT.as_bytes()[77..]);
4283        let err = reader.decode(&mut buf).err().unwrap();
4284        assert_eq!(err, DecodeError::TooLarge(79));
4285
4286        // message head size is within the limit
4287        let cfg: SharedCfg = SharedCfg::new("test")
4288            .add(HttpServiceConfig::new().set_max_buf_size(100))
4289            .into();
4290        let reader = MessageDecoder::<Request>::new(cfg.get());
4291        let mut buf = BytesMut::from(TEXT);
4292        assert!(reader.decode(&mut buf).unwrap().is_some());
4293
4294        // the configured maximum is inclusive
4295        let cfg: SharedCfg = SharedCfg::new("test")
4296            .add(HttpServiceConfig::new().set_max_buf_size(TEXT.len()))
4297            .into();
4298        let reader = MessageDecoder::<Request>::new(cfg.get());
4299        let mut buf = BytesMut::from(TEXT);
4300        assert!(reader.decode(&mut buf).unwrap().is_some());
4301    }
4302}