nhttp_multipart (nhttp_lib v2.2.0)

View Source

The multipart/* media types (RFC 2046 Section 5.1), for every subtype.

boundary/1 reads the boundary parameter from a Content-Type field value. The parameter is required. Its value is 1 to 70 bchars, and the last octet is not a space (RFC 2046 Section 5.1.1):

bchars := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" /
          "." / "/" / ":" / "=" / "?" / " "

A media type with two boundary parameters is invalid_boundary, because two recipients can select different values. A boundary in a quoted-string that holds a quoted-pair is invalid_boundary too. No bchar needs a quoted-pair, so no conforming sender writes one, and Go mime/multipart keeps the backslash where RFC 9110 Section 5.6.4 removes it.

Decoder

decoder/2, decode/2 and finish/1 read a body incrementally. Each call to decode/2 takes the next octets of the body and returns the events that they complete:

{ok, Boundary} = nhttp_multipart:boundary(ContentType),
{ok, D0} = nhttp_multipart:decoder(Boundary, #{max_header_size => 8192}),
{ok, Events, D1} = nhttp_multipart:decode(Chunk, D0),
ok = nhttp_multipart:finish(D1).

A part gives {headers, Headers}, zero or more {body, Octets} and end_of_part. The close-delimiter gives done. A {body, _} event is never empty, and an input that holds no delimiter gives two {body, _} events at most.

The decoder reads the grammar of RFC 2046 Section 5.1.1:

multipart-body := [preamble CRLF] dash-boundary transport-padding CRLF
                  body-part *encapsulation close-delimiter
                  transport-padding [CRLF epilogue]
encapsulation  := delimiter transport-padding CRLF body-part
delimiter      := CRLF dash-boundary
dash-boundary  := "--" boundary
close-delimiter := delimiter "--"
body-part      := MIME-part-headers [CRLF *OCTET]
  • The decoder skips the preamble. It accepts --B at offset 0, or after a CRLF. A --B in the middle of a line is preamble or body data.
  • -- directly after a delimiter makes it the close-delimiter. Otherwise the decoder skips SP and HTAB, then requires CRLF. Other octets are invalid_delimiter, because the delimiter must not be the prefix of a line (RFC 2046 Section 5.1). Padding before -- is invalid_delimiter.
  • After the close-delimiter, the decoder skips SP and HTAB, then requires CRLF or the end of the body. Other octets are invalid_delimiter, and a bare LF is bare_lf.
  • A part can have no headers, and it can have no body. --B directly after the empty line ends a part with no body.
  • After the CRLF of the close line, the decoder discards all input, which is the epilogue.
  • Line ends are CRLF. A bare LF where the grammar wants CRLF is bare_lf. LF--B without a CR before it is bare_lf in the preamble and in a body. A parser that also splits on LF--B finds a part there that a parser of CRLF only reads as data, so the decoder refuses both readings. Any other bare LF in a body is data.
  • Part header names are lowercase. A field without a colon, a name that is not a token, an obs-fold line, or a value with a control octet other than HTAB is invalid_header. Values keep octets 0x80 to 0xFF.
  • The decoder gives no part a default Content-Type. RFC 2046 Section 5.1 makes it text/plain, and Section 5.1.5 makes it message/rfc822 in multipart/digest. nhttp_form_data:part/1 applies the default of RFC 7578.

done is the event of the --, so a caller sees the end of the last part at once. The close line can still fail after it. A body is valid only when finish/1 returns ok. finish/1 returns ok after the close-delimiter and its padding, and after its CRLF. A CR of the close line without its LF at the end of the body is truncated, and so is a body that ends anywhere else.

The limits of limits/0 default to infinity. decoder/2 refuses a key outside limits/0 and a value that is not limit/0 with {invalid_limit, Key}. max_header_size counts the transport padding after a delimiter or a close-delimiter, and each field line with its CRLF. It also bounds the octets that the decoder keeps for a header block that is not complete. With infinity, the decoder keeps a header line without an LF whole. max_parts counts the parts that start. No limit applies to the preamble and the epilogue. The decoder keeps none of their octets, and the body size limit of the caller is their only bound.

A {body, _} event or a header value above 64 octets is a sub-binary of the input, so it keeps the input binary alive. A caller that stores one calls binary:copy/1 first. The runtime copies a slice of 64 octets or less into a heap binary. The decoder keeps at most byte_size(Boundary) + 3 octets of a body between two calls.

A decoder holds compiled patterns from binary:compile_pattern/1, so it is valid only on the node that made it.

Encoder

encode/2 writes a whole body. part_head/3 and close/1 write the octets around each body, for a caller that sends the bodies itself:

Boundary = nhttp_multipart:new_boundary(),
{ok, ContentType} = nhttp_multipart:content_type(<<"form-data">>, Boundary),
{ok, Size} = nhttp_multipart:encoded_size(Boundary, [{Headers, FileSize}]),
{ok, Head} = nhttp_multipart:part_head(Boundary, first, Headers),
{ok, Tail} = nhttp_multipart:close(Boundary).

The caller sends Head, the FileSize octets of the file, then Tail.

The first part starts with --B, every later part with CRLF--B, and the body ends with CRLF--B--CRLF (RFC 2046 Section 5.1.1). A part header name is a lowercase token (RFC 9110 Section 5.6.2). A value holds no control octet other than HTAB, no 0x7F, and no SP or HTAB at its edges (RFC 9110 Section 5.5). The encoder refuses any other field with {invalid_field, Reason, Name}. Every function of the encoder checks the boundary with the rule of boundary/1 and refuses it with invalid_boundary, and content_type/2 refuses a subtype that is not a token with invalid_subtype. No field and no boundary can thus end its line or its block early.

The encoder does not read the bodies. A body that holds the delimiter ends its part early, so the boundary must not occur in any body. new_boundary/0 gives 192 random bits, which makes that a matter of chance that a caller can ignore.

Summary

Functions

Read the boundary from a Content-Type field value.

The close-delimiter after the last body, with its CRLF.

The Content-Type field value of a multipart/Subtype body. The subtype is a token. The boundary is a token, or a quoted-string when it holds a bchar that is not a token octet (RFC 9110 Section 5.6.6). No bchar needs a quoted-pair.

Decode the next octets of the body.

Make a decoder for the body of a multipart/* message with Boundary.

Encode a whole body. An empty list of parts is no_parts.

The size of the body that encode/2 gives for parts of these sizes, for a Content-Length. An empty list of parts is no_parts.

Check that the body is valid. It ended with the close-delimiter, and no CR of the close line waits for its LF.

A new boundary: 24 octets of crypto:strong_rand_bytes/1 in base64url without padding. It has 32 octets, and each is a token octet and a bchar.

The delimiter line and the header block of one part, up to and with the empty line. first is the first part of the body, and next is every later part.

Types

boundary_error()

-type boundary_error() :: invalid_media_type | not_multipart | missing_boundary | invalid_boundary.

decode_error()

-type decode_error() ::
          invalid_delimiter | bare_lf | invalid_header | header_too_large | too_many_headers |
          too_many_parts | truncated.

decoder()

-opaque decoder()

decoder_error()

-type decoder_error() :: invalid_boundary | {invalid_limit, term()}.

encode_error()

-type encode_error() :: invalid_boundary | no_parts | field_error().

event()

-type event() :: {headers, nhttp_lib:headers()} | {body, binary()} | end_of_part | done.

field_error()

-type field_error() ::
          {invalid_field,
           nhttp_headers:field_name_error() | nhttp_headers:field_value_error(),
           binary()}.

limit()

-type limit() :: pos_integer() | infinity.

limits()

-type limits() :: #{max_header_size => limit(), max_headers_count => limit(), max_parts => limit()}.

part_headers()

-type part_headers() :: nhttp_lib:headers().

position()

-type position() :: first | next.

Functions

boundary(ContentType)

-spec boundary(binary()) -> {ok, binary()} | {error, boundary_error()}.

Read the boundary from a Content-Type field value.

The media type must be multipart/*. The boundary keeps its case.

close(Boundary)

-spec close(binary()) -> {ok, iodata()} | {error, invalid_boundary}.

The close-delimiter after the last body, with its CRLF.

content_type(Subtype, Boundary)

-spec content_type(Subtype :: binary(), Boundary :: binary()) ->
                      {ok, binary()} | {error, invalid_subtype | invalid_boundary}.

The Content-Type field value of a multipart/Subtype body. The subtype is a token. The boundary is a token, or a quoted-string when it holds a bchar that is not a token octet (RFC 9110 Section 5.6.6). No bchar needs a quoted-pair.

decode/2

-spec decode(binary(), decoder()) -> {ok, [event()], decoder()} | {error, decode_error()}.

Decode the next octets of the body.

The events are in the order of the body. On an error, the decoder is not usable any more.

decoder(Boundary, Limits)

-spec decoder(binary(), limits()) -> {ok, decoder()} | {error, decoder_error()}.

Make a decoder for the body of a multipart/* message with Boundary.

The boundary is checked again with the rule of boundary/1. A key outside limits/0 and a value that is not limit/0 are {invalid_limit, Key}.

encode(Boundary, Parts)

-spec encode(binary(), [{part_headers(), iodata()}]) -> {ok, iodata()} | {error, encode_error()}.

Encode a whole body. An empty list of parts is no_parts.

encoded_size(Boundary, Parts)

-spec encoded_size(binary(), [{part_headers(), non_neg_integer()}]) ->
                      {ok, non_neg_integer()} | {error, encode_error()}.

The size of the body that encode/2 gives for parts of these sizes, for a Content-Length. An empty list of parts is no_parts.

finish/1

-spec finish(decoder()) -> ok | {error, truncated}.

Check that the body is valid. It ended with the close-delimiter, and no CR of the close line waits for its LF.

new_boundary()

-spec new_boundary() -> binary().

A new boundary: 24 octets of crypto:strong_rand_bytes/1 in base64url without padding. It has 32 octets, and each is a token octet and a bchar.

part_head(Boundary, Position, Headers)

-spec part_head(binary(), position(), part_headers()) ->
                   {ok, iodata()} | {error, invalid_boundary | field_error()}.

The delimiter line and the header block of one part, up to and with the empty line. first is the first part of the body, and next is every later part.