Skip to main content

HttpError

Enum HttpError 

Source
#[non_exhaustive]
pub enum HttpError {
Show 41 variants InvalidStartLine, InvalidMethod, InvalidTarget, InvalidVersion, UnsupportedVersion, InvalidStatus, StartLineTooLong, HeadersTooLarge, TooManyHeaders, FieldLineTooLong, BareCr, BareLf, ObsFold, InvalidHeaderName, WhitespaceBeforeColon, InvalidHeaderValue, MissingHost, InvalidHost, InvalidContentLength, DuplicateContentLength, ConflictingFraming, InvalidTransferEncoding, UnsupportedTransferEncoding, TransferEncodingInHttp10, InvalidChunkSize, InvalidChunkExtension, InvalidChunkTerminator, ChunkLineTooLong, ChunkExtensionsTooLarge, BodyTooLarge, UnexpectedEof, UnexpectedData, UnexpectedUpgrade, TooManyInterim, ReservedHeader, BodyNotAllowed, BodyLengthMismatch, UpgradeNotOffered, InterimNotAllowed, TrailerNotAllowed, InvalidState(&'static str),
}
Expand description

Why a message was refused, or why a call was out of order.

Parse errors are final for the connection: HTTP/1.1 framing cannot be resynchronised after a malformed message without risking request smuggling, so after any parse error the connection must be closed. A server should first answer with status (for example through ServerConn::respond, which still accepts one response after a parse error and marks it connection: close).

Builder errors (ReservedHeader, InvalidHeaderName on an outgoing message, and so on) and InvalidState are programming errors on the caller’s side and leave the connection usable.

§Examples

use http_net::{HttpError, ServerConn, ServerEvent};

let mut conn = ServerConn::new();
let n = conn.feed(b"GET / HTTP/1.1\r\nHost: a\r\nContent-Length: 1\r\nTransfer-Encoding: chunked\r\n\r\n");
assert!(n > 0);
let err = conn.poll().unwrap_err();
assert_eq!(err, HttpError::ConflictingFraming);
assert_eq!(err.status(), Some(400));

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

InvalidStartLine

The request line or status line does not have the shape method SP target SP version / version SP code SP reason.

§

InvalidMethod

The method is not a token.

§

InvalidTarget

The request target contains characters outside RFC 3986, a bad percent-encoding, or a form the method does not allow (* outside OPTIONS, authority-form outside CONNECT); or an absolute form without //authority, with userinfo, or with an empty host.

§

InvalidVersion

The protocol version is not of the form HTTP/DIGIT.DIGIT.

§

UnsupportedVersion

The version is well formed but not HTTP/1.0 or HTTP/1.1. Answer 505.

§

InvalidStatus

A status code outside 100..=599, or not three digits.

§

StartLineTooLong

The request line (or status line) exceeds Limits::max_start_line. Answer 414.

§

HeadersTooLarge

The header section exceeds Limits::max_header_bytes. Answer 431.

§

TooManyHeaders

More header fields than Limits::max_headers, or more trailer fields than Limits::max_trailer_fields. Answer 431.

§

FieldLineTooLong

One field line is longer than Limits::max_field_line. Answer 431.

§

BareCr

A carriage return that is not followed by a line feed. Refused because recipients disagree on what it means, which is a smuggling vector.

§

BareLf

A line feed not preceded by a carriage return. RFC 9112 permits accepting it; this crate refuses it so that every hop agrees on where lines end.

§

ObsFold

A field line begins with whitespace: obsolete line folding, or whitespace between the start line and the first field.

§

InvalidHeaderName

A field name is empty, contains a non-token character, or the line has no colon.

§

WhitespaceBeforeColon

Whitespace between a field name and its colon (RFC 9112 section 5.1 requires rejecting it).

§

InvalidHeaderValue

A field value contains a control character other than horizontal tab.

§

MissingHost

An HTTP/1.1 request without a Host field.

§

InvalidHost

More than one Host field, or a Host value that is not host [":" port]: also an empty host before a port (:80) and a % not followed by two hex digits.

§

InvalidContentLength

Content-Length is not a plain decimal number that fits in 64 bits (signs, lists, spaces, and empty values are all refused).

§

DuplicateContentLength

Content-Length appears more than once. Refused even when the values agree, so no intermediary can pick a different one.

§

ConflictingFraming

Both Content-Length and Transfer-Encoding are present: the classic request smuggling vector, refused outright.

§

InvalidTransferEncoding

Transfer-Encoding is empty, repeats chunked, or does not end in chunked.

§

UnsupportedTransferEncoding

A transfer coding other than chunked (for example gzip). Answer 501.

§

TransferEncodingInHttp10

Transfer-Encoding in an HTTP/1.0 message, whose framing is then faulty by RFC 9112 section 6.1.

§

InvalidChunkSize

A chunk-size line is not hexadecimal, or overflows 64 bits.

§

InvalidChunkExtension

A chunk extension does not follow the ;name[=value] grammar.

§

InvalidChunkTerminator

Chunk data is not followed by CRLF.

§

ChunkLineTooLong

A chunk-size line is longer than Limits::max_start_line.

§

ChunkExtensionsTooLarge

The chunk extensions of one message add up to more than Limits::max_header_bytes. Each line is short, but without a total a peer could make a small body cost an unbounded amount of input (the CVE-2024-22019 pattern).

§

BodyTooLarge

The body exceeds Limits::max_body, detected from the declared length before any of it is buffered. Answer 413.

§

UnexpectedEof

The peer closed the connection in the middle of a message.

§

UnexpectedData

Bytes arrived when no message was expected: a response with no request outstanding, or data after the connection finished.

§

UnexpectedUpgrade

A 101 Switching Protocols (or a 2xx to CONNECT) arrived for a request that did not ask to switch.

§

TooManyInterim

The client received more interim (1xx) responses to one request than Limits::max_interim: a server that never sends its final response. Close the connection.

§

ReservedHeader

An outgoing message tried to set a header the connection owns (content-length, transfer-encoding, connection, upgrade, trailer, keep-alive, proxy-connection, and te on a response); use the builder methods instead.

§

BodyNotAllowed

A body was given for a status that cannot carry one (1xx, 204, 304).

§

BodyLengthMismatch

A streamed body’s length differs from the content_length declared for it.

§

UpgradeNotOffered

A 101 Switching Protocols names a protocol the request’s Upgrade field did not offer (RFC 9110 section 7.8: a server MUST NOT switch to it), or names h2c, whose upgrade RFC 9113 section 3.1 deprecates. Also raised by Request::upgrade("h2c"). Answer with a protocol the client offered, or with a normal response.

§

InterimNotAllowed

An interim (1xx) response the connection may not send now: to an HTTP/1.0 request (RFC 9110 section 15.2 forbids it), after the final response started, or a 100 Continue after the body began or twice. Skip the interim response.

§

TrailerNotAllowed

An outgoing trailer field that RFC 9110 section 6.5.1 keeps out of trailers (framing, routing, authentication, request modifiers, response control, content handling), or trailers on a body that is not chunked. Send the field in the header section instead.

§

InvalidState(&'static str)

A call made in the wrong state, for example respond twice for one request. The text names the rule that was broken.

Implementations§

Source§

impl HttpError

Source

pub const fn status(&self) -> Option<u16>

The status code a server should answer with when this error came from parsing a request, or None for errors that are not about a request (response parsing, builder misuse, connection state).

§Examples
use http_net::HttpError;

assert_eq!(HttpError::BodyTooLarge.status(), Some(413));
assert_eq!(HttpError::TooManyHeaders.status(), Some(431));
assert_eq!(HttpError::InvalidState("x").status(), None);
Source

pub const fn is_peer_error(&self) -> bool

Whether parsing bytes from the peer can produce this error. After such an error from poll, the connection is finished: send at most one error response, then close.

Some variants are also usage errors (for example InvalidTarget comes from a bad request line or from Request::new with a bad target): the call that returned the error tells which it was, since poll returns only peer errors.

§Examples
use http_net::HttpError;

assert!(HttpError::ConflictingFraming.is_peer_error());
assert!(!HttpError::ReservedHeader.is_peer_error());
Source

pub const fn is_usage_error(&self) -> bool

Whether a caller mistake (builder misuse, a call in the wrong state) can produce this error. Such an error leaves the connection usable: nothing was written.

§Examples
use http_net::HttpError;

assert!(HttpError::ReservedHeader.is_usage_error());
assert!(!HttpError::BareLf.is_usage_error());
// Raised by parsing or by a builder: both.
assert!(HttpError::InvalidTarget.is_peer_error() && HttpError::InvalidTarget.is_usage_error());

Trait Implementations§

Source§

impl Clone for HttpError

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for HttpError

Source§

impl Debug for HttpError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for HttpError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for HttpError

Source§

impl Error for HttpError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl From<HttpError> for Error

Available on crate feature std only.
Source§

fn from(e: HttpError) -> Self

Converts to this type from the input type.
Source§

impl Hash for HttpError

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl PartialEq for HttpError

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for HttpError

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.