Skip to main content

http_net/
error.rs

1//! The crate-wide error type.
2
3use core::fmt;
4
5/// Why a message was refused, or why a call was out of order.
6///
7/// Parse errors are final for the connection: HTTP/1.1 framing cannot be
8/// resynchronised after a malformed message without risking request
9/// smuggling, so after any parse error the connection must be closed. A
10/// server should first answer with [`status`](HttpError::status) (for
11/// example through [`ServerConn::respond`](crate::ServerConn::respond),
12/// which still accepts one response after a parse error and marks it
13/// `connection: close`).
14///
15/// Builder errors ([`ReservedHeader`](HttpError::ReservedHeader),
16/// [`InvalidHeaderName`](HttpError::InvalidHeaderName) on an outgoing message,
17/// and so on) and [`InvalidState`](HttpError::InvalidState) are programming
18/// errors on the caller's side and leave the connection usable.
19///
20/// # Examples
21///
22/// ```
23/// use http_net::{HttpError, ServerConn, ServerEvent};
24///
25/// let mut conn = ServerConn::new();
26/// let n = conn.feed(b"GET / HTTP/1.1\r\nHost: a\r\nContent-Length: 1\r\nTransfer-Encoding: chunked\r\n\r\n");
27/// assert!(n > 0);
28/// let err = conn.poll().unwrap_err();
29/// assert_eq!(err, HttpError::ConflictingFraming);
30/// assert_eq!(err.status(), Some(400));
31/// ```
32#[non_exhaustive]
33#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
34pub enum HttpError {
35    /// The request line or status line does not have the shape
36    /// `method SP target SP version` / `version SP code SP reason`.
37    InvalidStartLine,
38    /// The method is not a token.
39    InvalidMethod,
40    /// The request target contains characters outside RFC 3986, a bad
41    /// percent-encoding, or a form the method does not allow (`*` outside
42    /// `OPTIONS`, authority-form outside `CONNECT`); or an absolute form
43    /// without `//authority`, with userinfo, or with an empty host.
44    InvalidTarget,
45    /// The protocol version is not of the form `HTTP/DIGIT.DIGIT`.
46    InvalidVersion,
47    /// The version is well formed but its major version is not 1
48    /// (`HTTP/1.2` to `HTTP/1.9` are accepted and read as HTTP/1.1). Answer
49    /// 505.
50    UnsupportedVersion,
51    /// The connection starts with the HTTP/2 connection preface
52    /// (`PRI * HTTP/2.0`, RFC 9113 section 3.4): a client speaking HTTP/2
53    /// with prior knowledge. Route the connection to an HTTP/2 engine if
54    /// the listener allows prior knowledge; otherwise answer 505 and close.
55    Http2Preface,
56    /// A received three-character status code that is not digits or is
57    /// outside `100..=599` (a code of another length is
58    /// [`InvalidStartLine`](HttpError::InvalidStartLine)); or a code the call
59    /// cannot send: outside `100..=599`, a 1xx other than 101 as a final
60    /// response, or a non-1xx (or 100 or 101) as an informational response.
61    InvalidStatus,
62    /// The request line (or status line) exceeds
63    /// [`Limits::max_start_line`](crate::Limits::max_start_line). Answer 414.
64    StartLineTooLong,
65    /// The header section exceeds
66    /// [`Limits::max_header_bytes`](crate::Limits::max_header_bytes), or a
67    /// trailer section exceeds
68    /// [`Limits::max_trailer_bytes`](crate::Limits::max_trailer_bytes); on the
69    /// client also interim heads that together exceed `max_header_bytes`.
70    /// Answer 431.
71    HeadersTooLarge,
72    /// More header fields than
73    /// [`Limits::max_headers`](crate::Limits::max_headers), or more trailer
74    /// fields than [`Limits::max_trailer_fields`](crate::Limits::max_trailer_fields).
75    /// Answer 431.
76    TooManyHeaders,
77    /// One field line is longer than
78    /// [`Limits::max_field_line`](crate::Limits::max_field_line). Answer 431.
79    FieldLineTooLong,
80    /// A carriage return that is not followed by a line feed in a received
81    /// message, or any carriage return in an outgoing field value. Refused
82    /// because recipients disagree on what it means, which is a smuggling
83    /// vector.
84    BareCr,
85    /// A line feed not preceded by a carriage return. RFC 9112 permits
86    /// accepting it; this crate refuses it so that every hop agrees on where
87    /// lines end.
88    BareLf,
89    /// A field line begins with whitespace: obsolete line folding, or
90    /// whitespace between the start line and the first field.
91    ObsFold,
92    /// A field name is empty, contains a non-token character, or the line
93    /// has no colon.
94    InvalidHeaderName,
95    /// Whitespace between a field name and its colon (RFC 9112 section 5.1
96    /// requires rejecting it).
97    WhitespaceBeforeColon,
98    /// A field value contains a control character other than horizontal tab
99    /// (a carriage return is [`BareCr`](HttpError::BareCr)); an outgoing
100    /// value has leading or trailing whitespace; or an upgrade protocol is
101    /// not a token.
102    InvalidHeaderValue,
103    /// An HTTP/1.1 request without a `Host` field.
104    MissingHost,
105    /// More than one `Host` field, or a `Host` value that is not
106    /// `host [":" port]`: also an empty host before a port (`:80`) and a
107    /// `%` not followed by two hex digits.
108    InvalidHost,
109    /// `Content-Length` is not a plain decimal number that fits in 64 bits
110    /// (signs, lists, spaces, and empty values are all refused).
111    InvalidContentLength,
112    /// `Content-Length` appears more than once. Refused even when the values
113    /// agree, so no intermediary can pick a different one.
114    DuplicateContentLength,
115    /// Both `Content-Length` and `Transfer-Encoding` are present: the classic
116    /// request smuggling vector, refused outright.
117    ConflictingFraming,
118    /// `Transfer-Encoding` is empty, repeats `chunked`, or does not end in
119    /// `chunked`.
120    InvalidTransferEncoding,
121    /// A transfer coding before the final `chunked` (for example
122    /// `gzip, chunked`). Answer 501. A `Transfer-Encoding` that does not end
123    /// in `chunked` is [`InvalidTransferEncoding`](HttpError::InvalidTransferEncoding).
124    UnsupportedTransferEncoding,
125    /// `Transfer-Encoding` in an HTTP/1.0 message, whose framing is then
126    /// faulty by RFC 9112 section 6.1.
127    TransferEncodingInHttp10,
128    /// A chunk-size line is not hexadecimal, has more than 16 hex digits
129    /// (even when the value fits, as in `00000000000000001`), or overflows
130    /// 64 bits.
131    InvalidChunkSize,
132    /// A chunk extension does not follow the `;name[=value]` grammar.
133    InvalidChunkExtension,
134    /// Chunk data is not followed by CRLF.
135    InvalidChunkTerminator,
136    /// A chunk-size line is longer than
137    /// [`Limits::max_start_line`](crate::Limits::max_start_line).
138    ChunkLineTooLong,
139    /// The chunk extensions of one message add up to more than
140    /// [`Limits::max_header_bytes`](crate::Limits::max_header_bytes). Each
141    /// line is short, but without a total a peer could make a small body
142    /// cost an unbounded amount of input (the CVE-2024-22019 pattern).
143    ChunkExtensionsTooLarge,
144    /// The body exceeds [`Limits::max_body`](crate::Limits::max_body): a
145    /// `Content-Length` or chunk size is checked before its data is buffered;
146    /// a read-until-close body is refused at the first byte past the budget.
147    /// Answer 413.
148    BodyTooLarge,
149    /// The peer closed the connection in the middle of a message.
150    UnexpectedEof,
151    /// Bytes arrived when no message was expected: a response with no
152    /// request outstanding, or data after the connection finished.
153    UnexpectedData,
154    /// A `101 Switching Protocols` (or a 2xx to `CONNECT`) arrived for a
155    /// request that did not ask to switch.
156    UnexpectedUpgrade,
157    /// The client received more interim (1xx) responses to one request
158    /// than [`Limits::max_interim`](crate::Limits::max_interim): a server
159    /// that never sends its final response. Close the connection.
160    TooManyInterim,
161    /// An outgoing message tried to set a header the connection owns
162    /// (`content-length`, `transfer-encoding`, `connection`, `upgrade`,
163    /// `trailer`, `keep-alive`, `proxy-connection`, and `te` on a response);
164    /// use the builder methods instead.
165    ReservedHeader,
166    /// A body was given for a status that cannot carry one (1xx, 204, 304,
167    /// or a 2xx to `CONNECT`).
168    BodyNotAllowed,
169    /// A streamed body's length differs from the `content_length` declared
170    /// for it.
171    BodyLengthMismatch,
172    /// A `101 Switching Protocols` names a protocol the request's `Upgrade`
173    /// field did not offer (RFC 9110 section 7.8: a server MUST NOT switch
174    /// to it), or names `h2c`, whose upgrade RFC 9113 section 3.1
175    /// deprecates. Also raised by `Request::upgrade("h2c")`. Answer with a
176    /// protocol the client offered, or with a normal response.
177    UpgradeNotOffered,
178    /// An interim (1xx) response the connection may not send now: to an
179    /// HTTP/1.0 request (RFC 9110 section 15.2 forbids it), after the final
180    /// response started, or a `100 Continue` after the body began or twice.
181    /// Skip the interim response.
182    InterimNotAllowed,
183    /// An outgoing trailer field that RFC 9110 section 6.5.1 keeps out of
184    /// trailers (framing, routing, authentication, request modifiers,
185    /// response control, content handling), or trailers on a body that is
186    /// not chunked. Send the field in the header section instead.
187    TrailerNotAllowed,
188    /// A call made in the wrong state, for example `respond` twice for one
189    /// request. The text names the rule that was broken.
190    InvalidState(&'static str),
191}
192
193impl HttpError {
194    /// The status code a server should answer with when this error came from
195    /// parsing a request, or `None` for errors that are not about a request
196    /// (response parsing, builder misuse, connection state).
197    ///
198    /// # Examples
199    ///
200    /// ```
201    /// use http_net::HttpError;
202    ///
203    /// assert_eq!(HttpError::BodyTooLarge.status(), Some(413));
204    /// assert_eq!(HttpError::TooManyHeaders.status(), Some(431));
205    /// assert_eq!(HttpError::InvalidState("x").status(), None);
206    /// ```
207    #[must_use]
208    pub const fn status(&self) -> Option<u16> {
209        match self {
210            Self::StartLineTooLong => Some(414),
211            Self::HeadersTooLarge | Self::TooManyHeaders | Self::FieldLineTooLong => Some(431),
212            Self::BodyTooLarge => Some(413),
213            Self::UnsupportedVersion | Self::Http2Preface => Some(505),
214            Self::UnsupportedTransferEncoding => Some(501),
215            Self::InvalidStartLine
216            | Self::InvalidMethod
217            | Self::InvalidTarget
218            | Self::InvalidVersion
219            | Self::BareCr
220            | Self::BareLf
221            | Self::ObsFold
222            | Self::InvalidHeaderName
223            | Self::WhitespaceBeforeColon
224            | Self::InvalidHeaderValue
225            | Self::MissingHost
226            | Self::InvalidHost
227            | Self::InvalidContentLength
228            | Self::DuplicateContentLength
229            | Self::ConflictingFraming
230            | Self::InvalidTransferEncoding
231            | Self::TransferEncodingInHttp10
232            | Self::InvalidChunkSize
233            | Self::InvalidChunkExtension
234            | Self::InvalidChunkTerminator
235            | Self::ChunkLineTooLong
236            | Self::ChunkExtensionsTooLarge => Some(400),
237            Self::InvalidStatus
238            | Self::UnexpectedEof
239            | Self::UnexpectedData
240            | Self::UnexpectedUpgrade
241            | Self::TooManyInterim
242            | Self::ReservedHeader
243            | Self::BodyNotAllowed
244            | Self::BodyLengthMismatch
245            | Self::UpgradeNotOffered
246            | Self::InterimNotAllowed
247            | Self::TrailerNotAllowed
248            | Self::InvalidState(_) => None,
249        }
250    }
251
252    /// Whether parsing bytes from the peer can produce this error. After
253    /// such an error from `poll`, the connection is finished: send at most
254    /// one error response, then close.
255    ///
256    /// Some variants are also usage errors (for example
257    /// [`InvalidTarget`](HttpError::InvalidTarget) comes from a bad request
258    /// line or from `Request::new` with a bad target): the call that
259    /// returned the error tells which it was, since `poll` returns only
260    /// peer errors.
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// use http_net::HttpError;
266    ///
267    /// assert!(HttpError::ConflictingFraming.is_peer_error());
268    /// assert!(!HttpError::ReservedHeader.is_peer_error());
269    /// ```
270    #[must_use]
271    pub const fn is_peer_error(&self) -> bool {
272        !matches!(
273            self,
274            Self::ReservedHeader
275                | Self::BodyNotAllowed
276                | Self::BodyLengthMismatch
277                | Self::UpgradeNotOffered
278                | Self::InterimNotAllowed
279                | Self::TrailerNotAllowed
280                | Self::InvalidState(_)
281        )
282    }
283
284    /// Whether a caller mistake (builder misuse, a call in the wrong state)
285    /// can produce this error. Such an error leaves the connection usable:
286    /// nothing was written.
287    ///
288    /// # Examples
289    ///
290    /// ```
291    /// use http_net::HttpError;
292    ///
293    /// assert!(HttpError::ReservedHeader.is_usage_error());
294    /// assert!(!HttpError::BareLf.is_usage_error());
295    /// // Raised by parsing or by a builder: both.
296    /// assert!(HttpError::InvalidTarget.is_peer_error() && HttpError::InvalidTarget.is_usage_error());
297    /// ```
298    #[must_use]
299    pub const fn is_usage_error(&self) -> bool {
300        matches!(
301            self,
302            Self::InvalidMethod
303                | Self::InvalidTarget
304                | Self::InvalidStatus
305                | Self::BareCr
306                | Self::InvalidHeaderName
307                | Self::InvalidHeaderValue
308                | Self::MissingHost
309                | Self::InvalidHost
310                | Self::UnexpectedData
311                | Self::ReservedHeader
312                | Self::BodyNotAllowed
313                | Self::BodyLengthMismatch
314                | Self::UpgradeNotOffered
315                | Self::InterimNotAllowed
316                | Self::TrailerNotAllowed
317                | Self::InvalidState(_)
318        )
319    }
320}
321
322impl fmt::Display for HttpError {
323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324        let msg = match self {
325            Self::InvalidStartLine => "malformed start line: expected three space-separated parts",
326            Self::InvalidMethod => "invalid method: must be a token",
327            Self::InvalidTarget => "invalid request target",
328            Self::InvalidVersion => "invalid HTTP version: expected HTTP/DIGIT.DIGIT",
329            Self::UnsupportedVersion => "unsupported HTTP version: only HTTP/1.0 and HTTP/1.1",
330            Self::Http2Preface => {
331                "HTTP/2 connection preface on an HTTP/1.1 connection: route it to an HTTP/2 \
332                 engine or answer 505"
333            }
334            Self::InvalidStatus => "invalid status code: expected three digits in 100..=599",
335            Self::StartLineTooLong => "start line exceeds the configured limit",
336            Self::HeadersTooLarge => "header section exceeds the configured byte limit",
337            Self::TooManyHeaders => "more header fields than the configured limit",
338            Self::FieldLineTooLong => "a field line exceeds the configured limit",
339            Self::BareCr => "carriage return not followed by line feed",
340            Self::BareLf => "line feed not preceded by carriage return",
341            Self::ObsFold => "field line starts with whitespace (obsolete line folding)",
342            Self::InvalidHeaderName => "invalid field name or missing colon",
343            Self::WhitespaceBeforeColon => "whitespace between field name and colon",
344            Self::InvalidHeaderValue => {
345                "control character in field value, or surrounding whitespace in an outgoing value"
346            }
347            Self::MissingHost => "HTTP/1.1 request without a Host field",
348            Self::InvalidHost => "duplicate or malformed Host field",
349            Self::InvalidContentLength => "Content-Length is not a single decimal number",
350            Self::DuplicateContentLength => "Content-Length appears more than once",
351            Self::ConflictingFraming => "both Content-Length and Transfer-Encoding are present",
352            Self::InvalidTransferEncoding => "Transfer-Encoding must end in a single chunked",
353            Self::UnsupportedTransferEncoding => "transfer coding other than chunked",
354            Self::TransferEncodingInHttp10 => "Transfer-Encoding in an HTTP/1.0 message",
355            Self::InvalidChunkSize => "invalid chunk size",
356            Self::InvalidChunkExtension => "invalid chunk extension",
357            Self::InvalidChunkTerminator => "chunk data not followed by CRLF",
358            Self::ChunkLineTooLong => "chunk-size line exceeds the configured limit",
359            Self::ChunkExtensionsTooLarge => {
360                "chunk extensions exceed the header byte limit for the message"
361            }
362            Self::BodyTooLarge => "body exceeds the configured limit",
363            Self::UnexpectedEof => "connection closed in the middle of a message",
364            Self::UnexpectedData => "data received when no message was expected",
365            Self::UnexpectedUpgrade => "protocol switch that the request did not ask for",
366            Self::TooManyInterim => "more interim responses than the configured limit",
367            Self::ReservedHeader => {
368                "header is managed by the connection; use the builder method instead"
369            }
370            Self::BodyNotAllowed => "this status code cannot carry a body",
371            Self::BodyLengthMismatch => "streamed body length differs from the declared length",
372            Self::InterimNotAllowed => {
373                "interim response not allowed now (HTTP/1.0 peer, after the final response, \
374                 or 100 Continue after the body began)"
375            }
376            Self::TrailerNotAllowed => {
377                "field not allowed in trailers, or trailers on a body that is not chunked"
378            }
379            Self::UpgradeNotOffered => {
380                "101 names a protocol the request did not offer (or h2c); \
381                 answer with an offered protocol or a normal response"
382            }
383            Self::InvalidState(rule) => return write!(f, "invalid call order: {rule}"),
384        };
385        f.write_str(msg)
386    }
387}
388
389impl core::error::Error for HttpError {}
390
391#[cfg(test)]
392mod tests {
393    use alloc::string::ToString;
394
395    use super::*;
396
397    #[test]
398    fn test_status_mapping_covers_request_errors() {
399        assert_eq!(HttpError::StartLineTooLong.status(), Some(414));
400        assert_eq!(HttpError::UnsupportedVersion.status(), Some(505));
401        assert_eq!(HttpError::UnsupportedTransferEncoding.status(), Some(501));
402        assert_eq!(HttpError::BareCr.status(), Some(400));
403        assert_eq!(HttpError::UnexpectedEof.status(), None);
404    }
405
406    /// Every variant, so the category and text tests cannot miss one.
407    const ALL: &[HttpError] = &[
408        HttpError::InvalidStartLine,
409        HttpError::InvalidMethod,
410        HttpError::InvalidTarget,
411        HttpError::InvalidVersion,
412        HttpError::UnsupportedVersion,
413        HttpError::Http2Preface,
414        HttpError::InvalidStatus,
415        HttpError::StartLineTooLong,
416        HttpError::HeadersTooLarge,
417        HttpError::TooManyHeaders,
418        HttpError::FieldLineTooLong,
419        HttpError::BareCr,
420        HttpError::BareLf,
421        HttpError::ObsFold,
422        HttpError::InvalidHeaderName,
423        HttpError::WhitespaceBeforeColon,
424        HttpError::InvalidHeaderValue,
425        HttpError::MissingHost,
426        HttpError::InvalidHost,
427        HttpError::InvalidContentLength,
428        HttpError::DuplicateContentLength,
429        HttpError::ConflictingFraming,
430        HttpError::InvalidTransferEncoding,
431        HttpError::UnsupportedTransferEncoding,
432        HttpError::TransferEncodingInHttp10,
433        HttpError::InvalidChunkSize,
434        HttpError::InvalidChunkExtension,
435        HttpError::InvalidChunkTerminator,
436        HttpError::ChunkLineTooLong,
437        HttpError::ChunkExtensionsTooLarge,
438        HttpError::BodyTooLarge,
439        HttpError::UnexpectedEof,
440        HttpError::UnexpectedData,
441        HttpError::UnexpectedUpgrade,
442        HttpError::TooManyInterim,
443        HttpError::ReservedHeader,
444        HttpError::BodyNotAllowed,
445        HttpError::BodyLengthMismatch,
446        HttpError::UpgradeNotOffered,
447        HttpError::InterimNotAllowed,
448        HttpError::TrailerNotAllowed,
449        HttpError::InvalidState("rule"),
450    ];
451
452    #[test]
453    fn test_every_variant_has_a_category() {
454        for e in ALL {
455            assert!(e.is_peer_error() || e.is_usage_error(), "{e:?}");
456            // A usage-only error never maps to a status: it is not about a request.
457            if !e.is_peer_error() {
458                assert_eq!(e.status(), None, "{e:?}");
459            }
460        }
461        assert!(HttpError::UpgradeNotOffered.is_usage_error());
462        assert!(!HttpError::UpgradeNotOffered.is_peer_error());
463        assert!(HttpError::BareLf.is_peer_error() && !HttpError::BareLf.is_usage_error());
464    }
465
466    /// Threat T-37: error text is static and never reflects input bytes.
467    #[test]
468    fn test_display_every_variant_is_static_ascii_text() {
469        for e in ALL {
470            let text = e.to_string();
471            assert!(!text.is_empty(), "{e:?}");
472            assert!(
473                text.bytes().all(|b| b.is_ascii_graphic() || b == b' '),
474                "{e:?}: {text}"
475            );
476            // A missing line continuation leaves a run of indentation.
477            assert!(!text.contains("  "), "{e:?}: {text}");
478            assert_eq!(text.trim(), text, "{e:?}");
479        }
480    }
481
482    #[test]
483    fn test_display_is_actionable() {
484        assert_eq!(
485            HttpError::InvalidState("respond called twice").to_string(),
486            "invalid call order: respond called twice"
487        );
488        assert!(
489            HttpError::ConflictingFraming
490                .to_string()
491                .contains("Content-Length")
492        );
493    }
494}