Structured Field Values for HTTPFastlyPrahranVICAustraliamnot@mnot.nethttps://www.mnot.net/The Varnish Cache Projectphk@varnish-cache.org
Applications and Real-Time
HTTPThis document describes a set of data types and associated algorithms
that are intended to make it easier and safer to define and handle HTTP
header and trailer fields, known as "Structured Fields", "Structured
Headers", or "Structured Trailers". It is intended for use by
specifications of new HTTP fields that wish to use a common syntax that
is more restrictive than traditional HTTP field values.Status of This Memo
This is an Internet Standards Track document.
This document is a product of the Internet Engineering Task Force
(IETF). It represents the consensus of the IETF community. It has
received public review and has been approved for publication by
the Internet Engineering Steering Group (IESG). Further
information on Internet Standards is available in Section 2 of
RFC 7841.
Information about the current status of this document, any
errata, and how to provide feedback on it may be obtained at
.
Copyright Notice
Copyright (c) 2021 IETF Trust and the persons identified as the
document authors. All rights reserved.
This document is subject to BCP 78 and the IETF Trust's Legal
Provisions Relating to IETF Documents
() in effect on the date of
publication of this document. Please review these documents
carefully, as they describe your rights and restrictions with
respect to this document. Code Components extracted from this
document must include Simplified BSD License text as described in
Section 4.e of the Trust Legal Provisions and are provided without
warranty as described in the Simplified BSD License.
Table of Contents
. Introduction
. Intentionally Strict Processing
. Notational Conventions
. Defining New Structured Fields
. Structured Data Types
. Lists
. Inner Lists
. Parameters
. Dictionaries
. Items
. Integers
. Decimals
. Strings
. Tokens
. Byte Sequences
. Booleans
. Working with Structured Fields in HTTP
. Serializing Structured Fields
. Serializing a List
. Serializing a Dictionary
. Serializing an Item
. Serializing an Integer
. Serializing a Decimal
. Serializing a String
. Serializing a Token
. Serializing a Byte Sequence
. Serializing a Boolean
. Parsing Structured Fields
. Parsing a List
. Parsing a Dictionary
. Parsing an Item
. Parsing an Integer or Decimal
. Parsing a String
. Parsing a Token
. Parsing a Byte Sequence
. Parsing a Boolean
. IANA Considerations
. Security Considerations
. References
. Normative References
. Informative References
. Frequently Asked Questions
. Why Not JSON?
. Implementation Notes
Acknowledgements
Authors' Addresses
IntroductionSpecifying the syntax of new HTTP header (and trailer) fields is an
onerous task; even with the guidance in , there are many decisions -- and
pitfalls -- for a prospective HTTP field author.Once a field is defined, bespoke parsers and serializers often need
to be written, because each field value has a slightly different handling
of what looks like common syntax.This document introduces a set of common data structures for use in
definitions of new HTTP field values to address these problems. In
particular, it defines a generic, abstract model for them, along with a
concrete serialization for expressing that model in HTTP header and trailer fields.An HTTP field that is defined as a "Structured Header" or "Structured
Trailer" (if the field can be either, it is a "Structured Field") uses
the types defined in this specification to define its syntax and basic
handling rules, thereby simplifying both its definition by specification
writers and handling by implementations.Additionally, future versions of HTTP can define alternative
serializations of the abstract model of these structures, allowing
fields that use that model to be transmitted more efficiently without
being redefined.Note that it is not a goal of this document to redefine the syntax of
existing HTTP fields; the mechanisms described herein are only intended
to be used with fields that explicitly opt into them. describes how to specify a
Structured Field. defines a number of abstract
data types that can be used in Structured Fields.Those abstract types can be serialized into and parsed from HTTP
field values using the algorithms described in .Intentionally Strict ProcessingThis specification intentionally defines strict parsing and
serialization behaviors using step-by-step algorithms; the only error
handling defined is to fail the operation altogether.It is designed to encourage faithful implementation and
good interoperability. Therefore, an implementation that tried to be
helpful by being more tolerant of input would make interoperability
worse, since that would create pressure on other implementations to
implement similar (but likely subtly different) workarounds.In other words, strict processing is an intentional feature of this
specification; it allows non-conformant input to be discovered and
corrected by the producer early and avoids both interoperability and
security issues that might otherwise result.Note that as a result of this strictness, if a field is appended to
by multiple parties (e.g., intermediaries or different components in
the sender), an error in one party's value is likely to cause the
entire field value to fail parsing.Notational Conventions
The key words "MUST", "MUST NOT",
"REQUIRED", "SHALL", "SHALL NOT", "SHOULD", "SHOULD NOT",
"RECOMMENDED", "NOT RECOMMENDED",
"MAY", and "OPTIONAL" in this document are
to be interpreted as
described in BCP 14
when, and only when, they appear in all capitals, as shown here.
This document uses algorithms to specify parsing and serialization
behaviors and the Augmented Backus-Naur Form (ABNF) notation of to illustrate expected syntax in
HTTP header fields. In doing so, it uses the VCHAR, SP, DIGIT, ALPHA,
and DQUOTE rules from . It
also includes the tchar and OWS rules from .When parsing from HTTP fields, implementations MUST have behavior
that is indistinguishable from following the algorithms. If there is
disagreement between the parsing algorithms and ABNF, the specified
algorithms take precedence.For serialization to HTTP fields, the ABNF illustrates their
expected wire representations, and the algorithms define the
recommended way to produce them. Implementations MAY vary from the
specified behavior so long as the output is still correctly handled by
the parsing algorithm described in .Defining New Structured FieldsTo specify an HTTP field as a Structured Field, its authors need to:
Normatively reference this specification. Recipients and
generators of the field need to know that the requirements of this
document are in effect.
Identify whether the field is a Structured Header (i.e., it can
only be used in the header section -- the common case), a Structured
Trailer (only in the trailer section), or a Structured Field
(both).
Specify the type of the field value; either List (), Dictionary (), or Item ().
Define the semantics of the field value.
Specify any additional constraints upon the field value, as well
as the consequences when those constraints are violated.
Typically, this means that a field definition will specify the
top-level type -- List, Dictionary, or Item -- and then define its
allowable types and constraints upon them. For example, a header
defined as a List might have all Integer members, or a mix of types; a
header defined as an Item might allow only Strings, and additionally
only strings beginning with the letter "Q", or strings in
lowercase. Likewise, Inner Lists () are only valid when a field definition explicitly
allows them.When parsing fails, the entire field is ignored (see ); in most situations, violating
field-specific constraints should have the same effect. Thus, if a
header is defined as an Item and required to be an Integer, but a String
is received, the field will by default be ignored. If the field requires
different error handling, this should be explicitly specified.Both Items and Inner Lists allow parameters as an extensibility
mechanism; this means that values can later be extended to accommodate
more information, if need be. To preserve forward compatibility, field
specifications are discouraged from defining the presence of an
unrecognized parameter as an error condition.To further assure that this extensibility is available in the future,
and to encourage consumers to use a complete parser implementation, a
field definition can specify that "grease" parameters be added by
senders. A specification could stipulate that all parameters that fit a
defined pattern are reserved for this use and then encourage them to be
sent on some portion of requests. This helps to discourage recipients
from writing a parser that does not account for Parameters.Specifications that use Dictionaries can also allow for forward
compatibility by requiring that the presence of -- as well as value and
type associated with -- unknown members be ignored. Subsequent specifications
can then add additional members, specifying constraints on them as
appropriate.An extension to a Structured Field can then require that an entire
field value be ignored by a recipient that understands the extension if
constraints on the value it defines are not met.A field definition cannot relax the requirements of this
specification because doing so would preclude handling by generic
software; they can only add additional constraints (for example, on the
numeric range of Integers and Decimals, the format of Strings and
Tokens, the types allowed in a Dictionary's values, or the number of
Items in a List). Likewise, field definitions can only use this
specification for the entire field value, not a portion thereof.This specification defines minimums for the length or number of
various structures supported by implementations. It does not specify
maximum sizes in most cases, but authors should be aware that HTTP
implementations do impose various limits on the size of individual
fields, the total number of fields, and/or the size of the entire header
or trailer section.Specifications can refer to a field name as a "structured header
name", "structured trailer name", or "structured field name" as
appropriate. Likewise, they can refer its field value as a "structured
header value", "structured trailer value", or "structured field value" as
necessary.
Field definitions are encouraged to use the ABNF rules
beginning with "sf-" defined in this specification; other rules in this
specification are not intended to be used in field definitions.For example, a fictitious Foo-Example header field might be specified
as:
42. Foo-Example HeaderThe Foo-Example HTTP header field conveys information about how
much Foo the message has.Foo-Example is an Item Structured Header [RFC8941]. Its value MUST be
an Integer (Section 3.3.1 of [RFC8941]). Its ABNF is:
Foo-Example = sf-integer
Its value indicates the amount of Foo in the message, and it MUST
be between 0 and 10, inclusive; other values MUST cause
the entire header field to be ignored.The following parameter is defined:
A parameter whose key is "foourl", and whose value is a String
(Section 3.3.3 of [RFC8941]), conveying the Foo URL
for the message. See below for processing requirements.
"foourl" contains a URI-reference (Section 4.1 of [RFC3986]). If
its value is not a valid URI-reference, the entire header field
MUST be ignored. If its value is a relative reference (Section 4.2
of [RFC3986]), it MUST be resolved (Section 5 of [RFC3986]) before
being used.For example:
Foo-Example: 2; foourl="https://foo.example.com/"
Structured Data TypesThis section defines the abstract types for Structured Fields. The
ABNF provided represents the on-wire format in HTTP field values.In summary:
There are three top-level types that an HTTP field can be defined
as: Lists, Dictionaries, and Items.
Lists and Dictionaries are containers; their members can be Items
or Inner Lists (which are themselves arrays of Items).
Both Items and Inner Lists can be Parameterized with key/value pairs.
ListsLists are arrays of zero or more members, each of which can be an
Item () or an Inner List (), both of which can be
Parameterized ().The ABNF for Lists in HTTP fields is:
sf-list = list-member *( OWS "," OWS list-member )
list-member = sf-item / inner-list
Each member is separated by a comma and optional whitespace. For
example, a field whose value is defined as a List of Tokens could
look like:
Example-List: sugar, tea, rum
An empty List is denoted by not serializing the field at all. This
implies that fields defined as Lists have a default empty value.Note that Lists can have their members split across multiple lines
of the same header or trailer section, as per ; for example, the following are
equivalent:
Example-List: sugar, tea, rum
and
Example-List: sugar, tea
Example-List: rum
However, individual members of a List cannot be safely split
between lines; see
for details.Parsers MUST support Lists containing at least 1024 members. Field
specifications can constrain the types and cardinality of individual
List values as they require.Inner ListsAn Inner List is an array of zero or more Items (). Both the individual Items and the
Inner List itself can be Parameterized ().The ABNF for Inner Lists is:
inner-list = "(" *SP [ sf-item *( 1*SP sf-item ) *SP ] ")"
parameters
Inner Lists are denoted by surrounding parenthesis, and
their values are delimited by one or more spaces. A field whose value is
defined as a List of Inner Lists of Strings could look like:
Example-List: ("foo" "bar"), ("baz"), ("bat" "one"), ()
Note that the last member in this example is an empty Inner List.A header field whose value is defined as a List of Inner Lists
with Parameters at both levels could look like:
Example-List: ("foo"; a=1;b=2);lvl=5, ("bar" "baz");lvl=1
Parsers MUST support Inner Lists containing at least 256
members. Field specifications can constrain the types and
cardinality of individual Inner List members as they require.ParametersParameters are an ordered map of key-value pairs that are
associated with an Item () or
Inner List ().
The keys
are unique within the scope of the Parameters they occur within, and
the values are bare items (i.e., they themselves cannot be
parameterized; see ).Implementations MUST provide access to Parameters both by index and
by key. Specifications MAY use either means of accessing them.The ABNF for Parameters is:
parameters = *( ";" *SP parameter )
parameter = param-key [ "=" param-value ]
param-key = key
key = ( lcalpha / "*" )
*( lcalpha / DIGIT / "_" / "-" / "." / "*" )
lcalpha = %x61-7A ; a-z
param-value = bare-item
Note that parameters are ordered as serialized, and parameter
keys cannot contain uppercase letters. A parameter is separated from
its Item or Inner List and other parameters by a semicolon. For
example:
Example-List: abc;a=1;b=2; cde_456, (ghi;jk=4 l);q="9";r=w
Parameters whose value is Boolean (see ) true MUST omit that value when serialized. For
example, the "a" parameter here is true, while the "b" parameter is
false:
Example-Integer: 1; a; b=?0
Note that this requirement is only on serialization; parsers are
still required to correctly handle the true value when it appears in
a parameter.Parsers MUST support at least 256 parameters on an Item or Inner
List, and support parameter keys with at least 64 characters. Field
specifications can constrain the order of individual parameters, as
well as their values' types as required.DictionariesDictionaries are ordered maps of key-value pairs, where the keys
are short textual strings and the values are Items () or arrays of Items, both of which
can be Parameterized (). There
can be zero or more members, and their keys are unique in the scope
of the Dictionary they occur within.Implementations MUST provide access to Dictionaries both by index
and by key. Specifications MAY use either means of accessing the
members.The ABNF for Dictionaries is:
sf-dictionary = dict-member *( OWS "," OWS dict-member )
dict-member = member-key ( parameters / ( "=" member-value ))
member-key = key
member-value = sf-item / inner-list
Members are ordered as serialized and separated by a comma with
optional whitespace. Member keys cannot contain uppercase
characters. Keys and values are separated by "=" (without
whitespace). For example:
Example-Dict: en="Applepie", da=:w4ZibGV0w6ZydGU=:
Note that in this example, the final "=" is due to the inclusion of
a Byte Sequence; see .Members whose value is Boolean (see ) true MUST omit that value when serialized. For
example, here both "b" and "c" are true:
Example-Dict: a=?0, b, c; foo=bar
Note that this requirement is only on serialization; parsers are
still required to correctly handle the true Boolean value when it
appears in Dictionary values.A Dictionary with a member whose value is an Inner List of Tokens:
Example-Dict: rating=1.5, feelings=(joy sadness)
A Dictionary with a mix of Items and Inner Lists, some with parameters:
Example-Dict: a=(1 2), b=3, c=4;aa=bb, d=(5 6);valid
As with Lists, an empty Dictionary is represented by omitting the
entire field. This implies that fields defined as Dictionaries have a
default empty value.Typically, a field specification will define the semantics of
Dictionaries by specifying the allowed type(s) for individual members
by their keys, as well as whether their presence is required or
optional. Recipients MUST ignore members whose keys that are undefined or unknown,
unless the field's specification specifically disallows them.Note that Dictionaries can have their members split across multiple
lines of the same header or trailer section; for example, the following
are equivalent:
Example-Dict: foo=1, bar=2
and
Example-Dict: foo=1
Example-Dict: bar=2
However, individual members of a Dictionary cannot be safely split
between lines; see for
details.Parsers MUST support Dictionaries containing at least 1024
key/value pairs and keys with at least 64 characters. Field
specifications can constrain the order of individual Dictionary
members, as well as their values' types as required.ItemsAn Item can be an Integer (), a Decimal (), a String (), a Token (),
a Byte Sequence (), or a Boolean
(). It can have associated
parameters ().The ABNF for Items is:
sf-item = bare-item parameters
bare-item = sf-integer / sf-decimal / sf-string / sf-token
/ sf-binary / sf-boolean
For example, a header field that is defined to be an Item that is
an Integer might look like:
Example-Integer: 5
or with parameters:
Example-Integer: 5; foo=bar
IntegersIntegers have a range of -999,999,999,999,999 to
999,999,999,999,999 inclusive (i.e., up to fifteen digits, signed),
for IEEE 754 compatibility .The ABNF for Integers is:
sf-integer = ["-"] 1*15DIGIT
For example:
Example-Integer: 42
Integers larger than 15 digits can be supported in a variety of
ways; for example, by using a String (), a Byte Sequence (), or a parameter on an Integer that acts as a
scaling factor.While it is possible to serialize Integers with leading zeros
(e.g., "0002", "-01") and signed zero ("-0"), these distinctions may
not be preserved by implementations.Note that commas in Integers are used in this section's prose
only for readability; they are not valid in the wire format.DecimalsDecimals are numbers with an integer and a fractional
component. The integer component has at most 12 digits; the
fractional component has at most three digits.The ABNF for decimals is:
sf-decimal = ["-"] 1*12DIGIT "." 1*3DIGIT
For example, a header whose value is defined as a Decimal could
look like:
Example-Decimal: 4.5
While it is possible to serialize Decimals with leading zeros
(e.g., "0002.5", "-01.334"), trailing zeros (e.g., "5.230",
"-0.40"), and signed zero (e.g., "-0.0"), these distinctions may not
be preserved by implementations.Note that the serialization algorithm () rounds input with more than three digits of
precision in the fractional component. If an alternative rounding
strategy is desired, this should be specified by the header
definition to occur before serialization.StringsStrings are zero or more printable ASCII characters (i.e., the range %x20 to %x7E). Note
that this excludes tabs, newlines, carriage returns, etc.The ABNF for Strings is:
sf-string = DQUOTE *chr DQUOTE
chr = unescaped / escaped
unescaped = %x20-21 / %x23-5B / %x5D-7E
escaped = "\" ( DQUOTE / "\" )
Strings are delimited with double quotes, using a backslash ("\")
to escape double quotes and backslashes. For example:
Example-String: "hello world"
Note that Strings only use DQUOTE as a delimiter; single quotes
do not delimit Strings. Furthermore, only DQUOTE and "\" can be
escaped; other characters after "\" MUST cause parsing to fail.Unicode is not directly supported in Strings, because it causes a
number of interoperability issues, and -- with few exceptions -- field
values do not require it.When it is necessary for a field value to convey non-ASCII
content, a Byte Sequence ()
can be specified, along with a character encoding (preferably UTF-8 ).Parsers MUST support Strings (after any decoding) with at least
1024 characters.TokensTokens are short textual words; their abstract model is identical
to their expression in the HTTP field value serialization.The ABNF for Tokens is:
sf-token = ( ALPHA / "*" ) *( tchar / ":" / "/" )
For example:
Example-Token: foo123/456
Parsers MUST support Tokens with at least 512 characters.Note that Token allows the same characters as the "token" ABNF
rule defined in , with the
exceptions that the first character is required to be either ALPHA
or "*", and ":" and "/" are also allowed in subsequent
characters.Byte SequencesByte Sequences can be conveyed in Structured Fields.The ABNF for a Byte Sequence is:
sf-binary = ":" *(base64) ":"
base64 = ALPHA / DIGIT / "+" / "/" / "="
A Byte Sequence is delimited with colons and encoded using base64
(). For
example:
Example-ByteSequence: :cHJldGVuZCB0aGlzIGlzIGJpbmFyeSBjb250ZW50Lg==:
Parsers MUST support Byte Sequences with at least 16384 octets
after decoding.BooleansBoolean values can be conveyed in Structured Fields.The ABNF for a Boolean is:
sf-boolean = "?" boolean
boolean = "0" / "1"
A Boolean is indicated with a leading "?" character followed by a
"1" for a true value or "0" for false. For example:
Example-Boolean: ?1
Note that in Dictionary () and Parameter () values, Boolean true is indicated by omitting
the value.Working with Structured Fields in HTTPThis section defines how to serialize and parse Structured Fields in
textual HTTP field values and other encodings compatible with them
(e.g., in HTTP/2 before
compression with HPACK ).Serializing Structured FieldsGiven a structure defined in this specification, return an ASCII
string suitable for use in an HTTP field value.
If the structure is a Dictionary or List and its value is empty
(i.e., it has no members), do not serialize the field at all (i.e.,
omit both the field-name and field-value).
If the structure is a List, let output_string be the result of
running Serializing a List () with the structure.
Else, if the structure is a Dictionary, let output_string be the
result of running Serializing a Dictionary () with the structure.
Else, if the structure is an Item, let output_string be the
result of running Serializing an Item () with the structure.
Else, fail serialization.
Return output_string converted into an array of bytes, using
ASCII encoding .
Serializing a ListGiven an array of (member_value, parameters) tuples as
input_list, return an ASCII string suitable for use in an HTTP field
value.
Let output be an empty string.
For each (member_value, parameters) of input_list:
If member_value is an array, append the result of running
Serializing an Inner List () with (member_value, parameters) to
output.
Otherwise, append the result of running Serializing an
Item () with
(member_value, parameters) to output.
If more member_values remain in input_list:
Append "," to output.
Append a single SP to output.
Return output.
Serializing an Inner ListGiven an array of (member_value, parameters) tuples as
inner_list, and parameters as list_parameters, return an ASCII
string suitable for use in an HTTP field value.
Let output be the string "(".
For each (member_value, parameters) of inner_list:
Append the result of running Serializing an Item () with (member_value,
parameters) to output.
If more values remain in inner_list, append a single SP to output.
Append ")" to output.
Append the result of running Serializing Parameters () with list_parameters to
output.
Return output.
Serializing ParametersGiven an ordered Dictionary as input_parameters (each member
having a param_key and a param_value), return an ASCII string
suitable for use in an HTTP field value.
Let output be an empty string.
For each param_key with a value of param_value in input_parameters:
Append ";" to output.
Append the result of running Serializing a Key () with param_key to
output.
If param_value is not Boolean true:
Append "=" to output.
Append the result of running Serializing a bare Item
() with
param_value to output.
Return output.
Serializing a KeyGiven a key as input_key, return an ASCII string suitable for
use in an HTTP field value.
Convert input_key into a sequence of ASCII characters; if
conversion fails, fail serialization.
If input_key contains characters not in lcalpha, DIGIT, "_",
"-", ".", or "*", fail serialization.
If the first character of input_key is not lcalpha or "*",
fail serialization.
Let output be an empty string.
Append input_key to output.
Return output.
Serializing a DictionaryGiven an ordered Dictionary as input_dictionary (each member
having a member_key and a tuple value of (member_value,
parameters)), return an ASCII string suitable for use in an HTTP
field value.
Let output be an empty string.
For each member_key with a value of (member_value, parameters) in input_dictionary:
Append the result of running Serializing a Key () with member's member_key
to output.
If member_value is Boolean true:
Append the result of running Serializing Parameters
() with
parameters to output.
Otherwise:
Append "=" to output.
If member_value is an array, append the result of
running Serializing an Inner List () with
(member_value, parameters) to output.
Otherwise, append the result of running Serializing an
Item () with
(member_value, parameters) to output.
If more members remain in input_dictionary:
Append "," to output.
Append a single SP to output.
Return output.
Serializing an ItemGiven an Item as bare_item and Parameters as item_parameters,
return an ASCII string suitable for use in an HTTP field value.
Let output be an empty string.
Append the result of running Serializing a Bare Item () with bare_item to
output.
Append the result of running Serializing Parameters () with item_parameters to
output.
Return output.
Serializing a Bare ItemGiven an Item as input_item, return an ASCII string suitable
for use in an HTTP field value.
If input_item is an Integer, return the result of running
Serializing an Integer () with input_item.
If input_item is a Decimal, return the result of running
Serializing a Decimal () with input_item.
If input_item is a String, return the result of running
Serializing a String () with input_item.
If input_item is a Token, return the result of running
Serializing a Token () with input_item.
If input_item is a Byte Sequence, return the result of
running Serializing a Byte Sequence () with input_item.
If input_item is a Boolean, return the result of running
Serializing a Boolean () with
input_item.
Otherwise, fail serialization.
Serializing an IntegerGiven an Integer as input_integer, return an ASCII string
suitable for use in an HTTP field value.
If input_integer is not an integer in the range of
-999,999,999,999,999 to 999,999,999,999,999 inclusive, fail
serialization.
Let output be an empty string.
If input_integer is less than (but not equal to) 0, append "-"
to output.
Append input_integer's numeric value represented in base 10
using only decimal digits to output.
Return output.
Serializing a DecimalGiven a decimal number as input_decimal, return an ASCII string
suitable for use in an HTTP field value.
If input_decimal is not a decimal number, fail serialization.
If input_decimal has more than three significant digits to the
right of the decimal point, round it to three decimal places,
rounding the final digit to the nearest value, or to the even
value if it is equidistant.
If input_decimal has more than 12 significant digits to the
left of the decimal point after rounding, fail serialization.
Let output be an empty string.
If input_decimal is less than (but not equal to) 0, append "-"
to output.
Append input_decimal's integer component represented in base
10 (using only decimal digits) to output; if it is zero, append
"0".
Append "." to output.
If input_decimal's fractional component is zero, append "0" to
output.
Otherwise, append the significant digits of input_decimal's
fractional component represented in base 10 (using only decimal
digits) to output.
Return output.
Serializing a StringGiven a String as input_string, return an ASCII string suitable
for use in an HTTP field value.
Convert input_string into a sequence of ASCII characters; if
conversion fails, fail serialization.
If input_string contains characters in the range %x00-1f or
%x7f-ff (i.e., not in VCHAR or SP), fail serialization.
Let output be the string DQUOTE.
For each character char in input_string:
If char is "\" or DQUOTE:
Append "\" to output.
Append char to output.
Append DQUOTE to output.
Return output.
Serializing a TokenGiven a Token as input_token, return an ASCII string suitable for
use in an HTTP field value.
Convert input_token into a sequence of ASCII characters; if
conversion fails, fail serialization.
If the first character of input_token is not ALPHA or "*", or
the remaining portion contains a character not in tchar, ":", or
"/", fail serialization.
Let output be an empty string.
Append input_token to output.
Return output.
Serializing a Byte SequenceGiven a Byte Sequence as input_bytes, return an ASCII string
suitable for use in an HTTP field value.
If input_bytes is not a sequence of bytes, fail serialization.
Let output be an empty string.
Append ":" to output.
Append the result of base64-encoding input_bytes as per , taking account of
the requirements below.
Append ":" to output.
Return output.
The encoded data is required to be padded with "=", as per .Likewise, encoded data SHOULD have pad bits set to zero, as per
, unless it is
not possible to do so due to implementation constraints.Serializing a BooleanGiven a Boolean as input_boolean, return an ASCII string suitable
for use in an HTTP field value.
If input_boolean is not a boolean, fail serialization.
Let output be an empty string.
Append "?" to output.
If input_boolean is true, append "1" to output.
If input_boolean is false, append "0" to output.
Return output.
Parsing Structured FieldsWhen a receiving implementation parses HTTP fields that are known
to be Structured Fields, it is important that care be taken, as there
are a number of edge cases that can cause interoperability or even
security problems. This section specifies the algorithm for doing
so.Given an array of bytes as input_bytes that represent the chosen
field's field-value (which is empty if that field is not present) and
field_type (one of "dictionary", "list", or "item"), return the parsed
header value.
Convert input_bytes into an ASCII string input_string; if
conversion fails, fail parsing.
Discard any leading SP characters from input_string.
If field_type is "list", let output be the result of running
Parsing a List () with
input_string.
If field_type is "dictionary", let output be the result of
running Parsing a Dictionary () with input_string.
If field_type is "item", let output be the result of running
Parsing an Item () with
input_string.
Discard any leading SP characters from input_string.
If input_string is not empty, fail parsing.
Otherwise, return output.
When generating input_bytes, parsers MUST combine all field lines
in the same section (header or trailer) that case-insensitively match
the field name into one comma-separated field-value, as per ; this assures that
the entire field value is processed correctly.For Lists and Dictionaries, this has the effect of correctly
concatenating all of the field's lines, as long as individual members
of the top-level data structure are not split across multiple header
instances. The parsing algorithms for both types allow tab characters,
since these might be used to combine field lines by some
implementations.Strings split across multiple field lines will have unpredictable
results, because one or more commas (with optional whitespace)
will become part of the string output by the parser. Since
concatenation might be done by an upstream intermediary, the results
are not under the control of the serializer or the parser, even when
they are both under the control of the same party.Tokens, Integers, Decimals, and Byte Sequences cannot be split
across multiple field lines because the inserted commas will cause
parsing to fail.Parsers MAY fail when processing a field value spread across
multiple field lines, when one of those lines does not parse as that
field. For example, a parsing handling an Example-String field that's
defined as an sf-string is allowed to fail when processing this field
section:
Example-String: "foo
Example-String: bar"
If parsing fails -- including when calling another algorithm -- the
entire field value MUST be ignored (i.e., treated as if the field were
not present in the section). This is intentionally strict, to improve
interoperability and safety, and specifications referencing this
document are not allowed to loosen this requirement.Note that this requirement does not apply to an implementation that
is not parsing the field; for example, an intermediary is not required
to strip a failing field from a message before forwarding it.Parsing a ListGiven an ASCII string as input_string, return an array of
(item_or_inner_list, parameters) tuples. input_string is modified to
remove the parsed value.
Let members be an empty array.
While input_string is not empty:
Append the result of running Parsing an Item or Inner List
() with
input_string to members.
Discard any leading OWS characters from input_string.
If input_string is empty, return members.
Consume the first character of input_string; if it is not
",", fail parsing.
Discard any leading OWS characters from input_string.
If input_string is empty, there is a trailing comma; fail parsing.
No structured data has been found; return members (which is empty).
Parsing an Item or Inner ListGiven an ASCII string as input_string, return the tuple
(item_or_inner_list, parameters), where item_or_inner_list can be
either a single bare item or an array of (bare_item, parameters)
tuples. input_string is modified to remove the parsed value.
If the first character of input_string is "(", return the
result of running Parsing an Inner List () with
input_string.
Return the result of running Parsing an Item () with input_string.
Parsing an Inner ListGiven an ASCII string as input_string, return the tuple
(inner_list, parameters), where inner_list is an array of
(bare_item, parameters) tuples. input_string is modified to remove
the parsed value.
Consume the first character of input_string; if it is not
"(", fail parsing.
Let inner_list be an empty array.
While input_string is not empty:
Discard any leading SP characters from input_string.
If the first character of input_string is ")":
Consume the first character of input_string.
Let parameters be the result of running Parsing
Parameters () with input_string.
Return the tuple (inner_list, parameters).
Let item be the result of running Parsing an Item () with
input_string.
Append item to inner_list.
If the first character of input_string is not SP or ")",
fail parsing.
The end of the Inner List was not found; fail parsing.
Parsing a DictionaryGiven an ASCII string as input_string, return an ordered map
whose values are (item_or_inner_list, parameters)
tuples. input_string is modified to remove the parsed value.
Let dictionary be an empty, ordered map.
While input_string is not empty:
Let this_key be the result of running Parsing a Key () with input_string.
If the first character of input_string is "=":
Consume the first character of input_string.
Let member be the result of running Parsing an Item or
Inner List () with input_string.
Otherwise:
Let value be Boolean true.
Let parameters be the result of running Parsing
Parameters ()
with input_string.
Let member be the tuple (value, parameters).
If dictionary already contains a key this_key (comparing character for character), overwrite its value with member.
Otherwise, append key this_key with value member to dictionary.
Discard any leading OWS characters from input_string.
If input_string is empty, return dictionary.
Consume the first character of input_string; if it is not
",", fail parsing.
Discard any leading OWS characters from input_string.
If input_string is empty, there is a trailing comma; fail parsing.
No structured data has been found; return dictionary (which is empty).
Note that when duplicate Dictionary keys are encountered, all but
the last instance are ignored.Parsing an ItemGiven an ASCII string as input_string, return a (bare_item,
parameters) tuple. input_string is modified to remove the parsed
value.
Let bare_item be the result of running Parsing a Bare Item
() with
input_string.
Let parameters be the result of running Parsing Parameters
() with
input_string.
Return the tuple (bare_item, parameters).
Parsing a Bare ItemGiven an ASCII string as input_string, return a bare
Item. input_string is modified to remove the parsed value.
If the first character of input_string is a "-" or a DIGIT,
return the result of running Parsing an Integer or Decimal
() with
input_string.
If the first character of input_string is a DQUOTE, return
the result of running Parsing a String () with
input_string.
If the first character of input_string is an ALPHA or "*",
return the result of running Parsing a Token () with input_string.
If the first character of input_string is ":", return the
result of running Parsing a Byte Sequence () with
input_string.
If the first character of input_string is "?", return the
result of running Parsing a Boolean () with
input_string.
Otherwise, the item type is unrecognized; fail parsing.
Parsing ParametersGiven an ASCII string as input_string, return an ordered map
whose values are bare Items. input_string is modified to remove
the parsed value.
Let parameters be an empty, ordered map.
While input_string is not empty:
If the first character of input_string is not ";", exit the loop.
Consume the ";" character from the beginning of input_string.
Discard any leading SP characters from input_string.
Let param_key be the result of running Parsing a Key
() with
input_string.
Let param_value be Boolean true.
If the first character of input_string is "=":
Consume the "=" character at the beginning of input_string.
Let param_value be the result of running Parsing a
Bare Item () with input_string.
If parameters already contains a key param_key (comparing character for character), overwrite its value with param_value.
Otherwise, append key param_key with value param_value to parameters.
Return parameters.
Note that when duplicate parameter keys are encountered,
all but the last instance are ignored.Parsing a KeyGiven an ASCII string as input_string, return a
key. input_string is modified to remove the parsed value.
If the first character of input_string is not lcalpha or
"*", fail parsing.
Let output_string be an empty string.
While input_string is not empty:
If the first character of input_string is not one of
lcalpha, DIGIT, "_", "-", ".", or "*", return
output_string.
Let char be the result of consuming the first character of input_string.
Append char to output_string.
Return output_string.
Parsing an Integer or DecimalGiven an ASCII string as input_string, return an Integer or
Decimal. input_string is modified to remove the parsed value.NOTE: This algorithm parses both Integers () and Decimals (), and returns the corresponding structure.
Let type be "integer".
Let sign be 1.
Let input_number be an empty string.
If the first character of input_string is "-", consume it and
set sign to -1.
If input_string is empty, there is an empty integer; fail
parsing.
If the first character of input_string is not a DIGIT, fail
parsing.
While input_string is not empty:
Let char be the result of consuming the first character of
input_string.
If char is a DIGIT, append it to input_number.
Else, if type is "integer" and char is ".":
If input_number contains more than 12 characters, fail parsing.
Otherwise, append char to input_number and set type to "decimal".
Otherwise, prepend char to input_string, and exit the loop.
If type is "integer" and input_number contains more than
15 characters, fail parsing.
If type is "decimal" and input_number contains more than
16 characters, fail parsing.
If type is "integer":
Parse input_number as an integer and let output_number be
the product of the result and sign.
Otherwise:
If the final character of input_number is ".", fail parsing.
If the number of characters after "." in input_number is
greater than three, fail parsing.
Parse input_number as a decimal number and let
output_number be the product of the result and sign.
Return output_number.
Parsing a StringGiven an ASCII string as input_string, return an unquoted
String. input_string is modified to remove the parsed value.
Let output_string be an empty string.
If the first character of input_string is not DQUOTE, fail parsing.
Discard the first character of input_string.
While input_string is not empty:
Let char be the result of consuming the first character of input_string.
If char is a backslash ("\"):
If input_string is now empty, fail parsing.
Let next_char be the result of consuming the first
character of input_string.
If next_char is not DQUOTE or "\", fail parsing.
Append next_char to output_string.
Else, if char is DQUOTE, return output_string.
Else, if char is in the range %x00-1f or %x7f-ff (i.e., it is
not in VCHAR or SP), fail parsing.
Else, append char to output_string.
Reached the end of input_string without finding a closing
DQUOTE; fail parsing.
Parsing a TokenGiven an ASCII string as input_string, return a
Token. input_string is modified to remove the parsed value.
If the first character of input_string is not ALPHA or "*",
fail parsing.
Let output_string be an empty string.
While input_string is not empty:
If the first character of input_string is not in tchar,
":", or "/", return output_string.
Let char be the result of consuming the first character of
input_string.
Append char to output_string.
Return output_string.
Parsing a Byte SequenceGiven an ASCII string as input_string, return a Byte
Sequence. input_string is modified to remove the parsed value.
If the first character of input_string is not ":", fail parsing.
Discard the first character of input_string.
If there is not a ":" character before the end of input_string, fail parsing.
Let b64_content be the result of consuming content of
input_string up to but not including the first instance of the
character ":".
Consume the ":" character at the beginning of input_string.
If b64_content contains a character not included in ALPHA,
DIGIT, "+", "/", and "=", fail parsing.
Let binary_content be the result of base64-decoding b64_content, synthesizing
padding if necessary (note the requirements about recipient
behavior below). If base64 decoding fails, parsing fails.
Return binary_content.
Because some implementations of base64 do not allow rejection of
encoded data that is not properly "=" padded (see ), parsers SHOULD NOT fail when "=" padding is not present, unless they cannot be
configured to do so.Because some implementations of base64 do not allow rejection of
encoded data that has non-zero pad bits (see ), parsers SHOULD NOT fail when
non-zero pad bits are present, unless they cannot be configured to
do so.This specification does not relax the requirements in , Sections and ; therefore,
parsers MUST fail on characters outside the base64 alphabet and on line
feeds in encoded data.Parsing a BooleanGiven an ASCII string as input_string, return a
Boolean. input_string is modified to remove the parsed value.
If the first character of input_string is not "?", fail parsing.
Discard the first character of input_string.
If the first character of input_string matches "1", discard
the first character, and return true.
If the first character of input_string matches "0", discard
the first character, and return false.
No value has matched; fail parsing.
IANA ConsiderationsThis document has no IANA actions.Security ConsiderationsThe size of most types defined by Structured Fields is not limited;
as a result, extremely large fields could be an attack vector (e.g., for
resource consumption). Most HTTP implementations limit the sizes of
individual fields as well as the overall header or trailer section size
to mitigate such attacks.It is possible for parties with the ability to inject new HTTP fields
to change the meaning of a Structured Field. In some circumstances, this
will cause parsing to fail, but it is not possible to reliably fail in
all such circumstances.ReferencesNormative ReferencesASCII format for network interchangeKey words for use in RFCs to Indicate Requirement LevelsIn many standards track documents several words are used to signify the requirements in the specification. These words are often capitalized. This document defines these words as they should be interpreted in IETF documents. This document specifies an Internet Best Current Practices for the Internet Community, and requests discussion and suggestions for improvements.The Base16, Base32, and Base64 Data EncodingsThis document describes the commonly used base 64, base 32, and base 16 encoding schemes. It also discusses the use of line-feeds in encoded data, use of padding in encoded data, use of non-alphabet characters in encoded data, use of different encoding alphabets, and canonical encodings. [STANDARDS-TRACK]Augmented BNF for Syntax Specifications: ABNFInternet technical specifications often need to define a formal syntax. Over the years, a modified version of Backus-Naur Form (BNF), called Augmented BNF (ABNF), has been popular among many Internet specifications. The current specification documents ABNF. It balances compactness and simplicity with reasonable representational power. The differences between standard BNF and ABNF involve naming rules, repetition, alternatives, order-independence, and value ranges. This specification also supplies additional rule definitions and encoding for a core lexical analyzer of the type common to several Internet specifications. [STANDARDS-TRACK]Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and RoutingThe Hypertext Transfer Protocol (HTTP) is a stateless application-level protocol for distributed, collaborative, hypertext information systems. This document provides an overview of HTTP architecture and its associated terminology, defines the "http" and "https" Uniform Resource Identifier (URI) schemes, defines the HTTP/1.1 message syntax and parsing requirements, and describes related security concerns for implementations.Ambiguity of Uppercase vs Lowercase in RFC 2119 Key WordsRFC 2119 specifies common key words that may be used in protocol specifications. This document aims to reduce the ambiguity by clarifying that only UPPERCASE usage of the key words have the defined special meanings.Informative ReferencesIEEE Standard for Floating-Point ArithmeticIEEEHypertext Transfer Protocol (HTTP/1.1): Semantics and ContentThe Hypertext Transfer Protocol (HTTP) is a stateless \%application- level protocol for distributed, collaborative, hypertext information systems. This document defines the semantics of HTTP/1.1 messages, as expressed by request methods, request header fields, response status codes, and response header fields, along with the payload of messages (metadata and body content) and mechanisms for content negotiation.The I-JSON Message FormatI-JSON (short for "Internet JSON") is a restricted profile of JSON designed to maximize interoperability and increase confidence that software can process it successfully with predictable results.Hypertext Transfer Protocol Version 2 (HTTP/2)This specification describes an optimized expression of the semantics of the Hypertext Transfer Protocol (HTTP), referred to as HTTP version 2 (HTTP/2). HTTP/2 enables a more efficient use of network resources and a reduced perception of latency by introducing header field compression and allowing multiple concurrent exchanges on the same connection. It also introduces unsolicited push of representations from servers to clients.This specification is an alternative to, but does not obsolete, the HTTP/1.1 message syntax. HTTP's existing semantics remain unchanged.HPACK: Header Compression for HTTP/2This specification defines HPACK, a compression format for efficiently representing HTTP header fields, to be used in HTTP/2.The JavaScript Object Notation (JSON) Data Interchange FormatJavaScript Object Notation (JSON) is a lightweight, text-based, language-independent data interchange format. It was derived from the ECMAScript Programming Language Standard. JSON defines a small set of formatting rules for the portable representation of structured data.This document removes inconsistencies with other specifications of JSON, repairs specification errors, and offers experience-based interoperability guidance.UTF-8, a transformation format of ISO 10646Frequently Asked QuestionsWhy Not JSON?Earlier proposals for Structured Fields were based upon JSON . However, constraining its use to
make it suitable for HTTP header fields required senders and
recipients to implement specific additional handling.For example, JSON has specification issues around large numbers and
objects with duplicate members. Although advice for avoiding these
issues is available (e.g., ),
it cannot be relied upon.Likewise, JSON strings are by default Unicode strings, which have a
number of potential interoperability issues (e.g., in
comparison). Although implementers can be advised to avoid non-ASCII
content where unnecessary, this is difficult to enforce.Another example is JSON's ability to nest content to arbitrary
depths. Since the resulting memory commitment might be unsuitable
(e.g., in embedded and other limited server deployments), it's
necessary to limit it in some fashion; however, existing JSON
implementations have no such limits, and even if a limit is specified,
it's likely that some field definition will find a need to violate
it.Because of JSON's broad adoption and implementation, it is
difficult to impose such additional constraints across all
implementations; some deployments would fail to enforce them, thereby
harming interoperability. In short, if it looks like JSON, people will
be tempted to use a JSON parser/serializer on field values.Since a major goal for Structured Fields is to improve
interoperability and simplify implementation, these concerns led to a
format that requires a dedicated parser and serializer.Additionally, there were widely shared feelings that JSON doesn't
"look right" in HTTP fields.Implementation NotesA generic implementation of this specification should expose the
top-level serialize ()
and parse () functions. They
need not be functions; for example, it could be implemented as an
object, with methods for each of the different top-level types.For interoperability, it's important that generic implementations be
complete and follow the algorithms closely; see . To aid this, a common test suite is being maintained
by the community at .Implementers should note that Dictionaries and Parameters are
order-preserving maps. Some fields may not convey meaning in the
ordering of these data types, but it should still be exposed so
that it will be available to applications that need to use it.Likewise, implementations should note that it's important to preserve
the distinction between Tokens and Strings. While most programming
languages have native types that map to the other types well, it may be
necessary to create a wrapper "token" object or use a parameter on
functions to assure that these types remain separate.The serialization algorithm is defined in a way that it is not
strictly limited to the data types defined in in every case. For example, Decimals are designed to
take broader input and round to allowed values.Implementations are allowed to limit the size of different
structures, subject to the minimums defined for each type. When a
structure exceeds an implementation limit, that structure fails parsing
or serialization.AcknowledgementsMany thanks to for his detailed feedback and careful
consideration during the development of this specification.Thanks also to , , ,
, ,
, , , and for their contributions.Authors' AddressesFastlyPrahranVICAustraliamnot@mnot.nethttps://www.mnot.net/The Varnish Cache Projectphk@varnish-cache.org