HTTP

HTTP :: # (opaque)

Parse HTTP/1.x requests and responses, following the message syntax of RFC 9112 and the field syntax of RFC 9110.

HTTP.Request.parse_bytes and HTTP.Response.parse_bytes read one complete message from a byte list and reject trailing input. Their .parser({}).run(bytes) forms read a message prefix and return the unconsumed rest. HTTP.parse_requests reads a complete pipeline. Native failures use InvalidHttp(Error); parser runners use the shared ParseError diagnostic envelope.

expect {
    bytes = "GET /hello HTTP/1.1\r\nHost: example.com\r\n\r\n".to_utf8()
    match HTTP.Request.parse_bytes(bytes, {}) {
        Ok(request) => request.method == Get and request.target == "/hello"
        Err(InvalidHttp(_)) => False
    }
}

Message framing (RFC 9112 section 6.3):

  • Transfer-Encoding: chunked bodies are decoded; chunk extensions and trailer fields are validated and discarded.
  • Content-Length bodies are exactly that many bytes.
  • A request with neither has no body. A response with neither runs to the end of the input (the connection close). Responses with a 1xx, 204 or 304 status never have a body. Responses to HEAD and 2xx responses to CONNECT also have no body, but this parser cannot see the request: parse those heads with a status that implies no body or strip the framing fields.

Messages whose framing is ambiguous are rejected rather than guessed at, because a parser that disagrees with a proxy about where a message ends is open to request smuggling: both Transfer-Encoding and Content-Length, conflicting or malformed Content-Length values, any transfer coding other than a single chunked, Transfer-Encoding in an HTTP/1.0 message, line folding (obs-fold), whitespace between a field name and its colon, control characters in field values, and line endings other than CRLF.

HTTP/1.1 requests must have exactly one Host field. Field names keep their case; field values have surrounding whitespace removed. Field values and reason phrases must be valid UTF-8 to be represented as Str; other obs-text bytes are rejected.

parse_requests : List(U8), ParseProps -> Try(List(Request), [InvalidHttp(Error)])

Parse every request in a complete byte source without collecting events.

requests_parser : ParseProps -> Parser(Bytes, List(Request), Problem)

Compose a complete request pipeline with generic parsers.

Lints

:= { repeated_content_length : Bool ?? True }

Reject repeated identical Content-Length values, including comma lists.

ValidationProps

:= { source : Str, name : Str ?? "<literal>", lints : Lints ?? {} }

A complete source message and its quotation validation options.

ParseProps

:= {}

Complete-message parser configuration.

Method : [Options, Get, Post, Put, Delete, Head, Trace, Connect, Patch, Extension(Str)]

A request method (RFC 9110 section 9).

The methods RFC 9110 and RFC 5789 define get their own tags. Any other method token is kept as Extension(name). Method names are case-sensitive, so get is Extension("get"), not Get.

Version : { major : U8, minor : U8 }

An HTTP protocol version such as HTTP/1.1, as { major: 1, minor: 1 }.

Each part is a single digit, as RFC 9112 requires.

Header : { name : Str, value : Str }

One header field: the name as written (case preserved) and the value with surrounding whitespace removed.

Fields keep their order in the message, and repeated fields are kept. Use message.header(name) to look one up by name.

Request

:= {
    method : Method,
    target : Str,
    version : Version,
    headers : List(Header),
    body : List(U8),
}

A parsed HTTP request message.

target is the request-target exactly as written (it is not decoded or normalized). body is the message body after any chunked transfer coding has been removed.

parse_bytes : List(U8), ParseProps -> Try(Request, [InvalidHttp(Error)])

Parse exactly one complete HTTP message, rejecting trailing bytes.

parser : ParseProps -> Parser(Bytes, Request, Problem)

Read one message prefix through the generic parser runner.

header : Request, Str -> Try(Str, [Missing])

Look up a header case-insensitively on this message.

validate : ValidationProps -> Try(Request, [InvalidHttp(Error)])

Check a named message using the selected lint profile.

from_quote : Str -> Try(Request, [BadQuotedBytes(Str)])

Checked source literals construct the actual message type.

decoder : ReadProps -> Decoder(IncrementalState, Event, [InvalidHttp(Error)])

Read bounded request events using the common descriptor methods.

Response

:= {
    version : Version,
    status_code : U16,
    reason : Str,
    headers : List(Header),
    body : List(U8),
}

A parsed HTTP response message.

status_code is the three-digit status code and reason the reason phrase, which may be empty. body is decoded like a request body.

parse_bytes : List(U8), ParseProps -> Try(Response, [InvalidHttp(Error)])

Parse exactly one complete HTTP message, rejecting trailing bytes.

parser : ParseProps -> Parser(Bytes, Response, Problem)

Read one message prefix through the generic parser runner.

header : Response, Str -> Try(Str, [Missing])

Look up a header case-insensitively on this message.

validate : ValidationProps -> Try(Response, [InvalidHttp(Error)])

Check a named message using the selected lint profile.

from_quote : Str -> Try(Response, [BadQuotedBytes(Str)])

Checked source literals construct the actual message type.

decoder : DecoderProps -> Decoder(IncrementalState, Event, [InvalidHttp(Error)])

DecoderProps

:= { methods : Iter(Method), reader : ReadLimits ?? {}, errors : RecoveryProps ?? {} }

Associate responses with methods; informational responses retain one.

Resource : [HeadBytes, TrailerBytes, LineBytes, Headers, Trailers]

Why a message was rejected: problem identifies the broken rule and location: ByteOffset(offset) identifies its original byte position.

Problems with the message as a whole, such as a missing Host field, are at offset 0, the start of the message.

Problem : [LimitExceeded({ resource : Resource, max : U64, observed : Observed }), DuplicateHost, MissingHost, CrWithoutLf, LfWithoutCr, MissingCrlf, MissingTarget, InvalidTarget, InvalidMethod, MissingMethod, InvalidVersion, InvalidStatusWidth, InvalidStatus, InvalidReasonCharacter, InvalidReasonEncoding, MissingStatus, InvalidFieldEncoding, ObsoleteFolding, WhitespaceBeforeColon, InvalidFieldCharacter, InvalidFieldName, TransferEncodingHttp10, ContentLengthOverflow, ConflictingFraming, UnsupportedTransferCoding, ConflictingContentLength, InvalidContentLength, IncompleteBody, IncompleteChunk, MissingChunkCrlf, InvalidChunkSize, ChunkSizeOverflow, WhitespaceAfterChunkSize, MissingExtensionName, InvalidExtension, MissingExtensionValue, InvalidQuotedPair, InvalidQuotedCharacter, UnclosedQuote, TrailingContent, RepeatedContentLength, RepeatedContentLengthValues, InvalidBodyChunkSize, SourceClosed, IncompleteSection, MissingRequestMethod, ForbiddenTrailer]
Error : Diagnostic(Problem)

ReadLimits

:= { max_head_bytes : U64 ?? default_max_head_bytes, max_line_bytes : U64 ?? default_max_line_bytes, max_headers : U64 ?? default_max_headers, max_trailer_bytes : U64 ?? default_max_trailer_bytes, max_trailers : U64 ?? default_max_trailers, max_body_chunk_bytes : U64 ?? default_max_body_chunk_bytes }

Bounds for incremental readers. Body fragments never exceed max_body_chunk_bytes; heads and trailer sections have independent bounds. Limits shared by request and response event readers.

ReadProps

:= { max_head_bytes : U64 ?? default_max_head_bytes, max_line_bytes : U64 ?? default_max_line_bytes, max_headers : U64 ?? default_max_headers, max_trailer_bytes : U64 ?? default_max_trailer_bytes, max_trailers : U64 ?? default_max_trailers, max_body_chunk_bytes : U64 ?? default_max_body_chunk_bytes, errors : RecoveryProps ?? {} }
RequestHead : { method : Method, target : Str, version : Version, headers : List(Header) }

A request head, emitted before any body bytes.

ResponseHead : { version : Version, status_code : U16, reason : Str, headers : List(Header) }

A response head, emitted before any body bytes.

Event : [RequestHead(RequestHead), ResponseHead(ResponseHead), Body(List(U8)), Trailer(Header), MessageEnd, ProtocolSwitch, ProtocolData(List(U8))]

MessageEnd completes one HTTP message, including informational responses. Finished from the shared reader completes the source. After a 101 response or a successful CONNECT, ProtocolSwitch precedes uninterpreted ProtocolData.