RFC 9651
Structured Field Values for HTTP
๐ RFC 9651: Structured Field Values for HTTP ๐
Okay so bestie, this one is Internet Engineering Task Force (IETF) stuff, and it's by M. Nottingham (Cloudflare) and P-H. Kamp (The Varnish Cache Project) ๐. It's dated September 2024 and it's a Standards Track document, so it's the real deal, not a vibes-only draft ๐ . It obsoletes RFC 8941, meaning it replaces that older version, and it doesn't update anything else ๐ฆ. The ISSN is 2070-1721 โจ.
Abstract โจ
Okay so the big idea is making HTTP header and trailer fields way easier and safer to define and handle ๐ซถ. These fields are called "Structured Fields", "Structured Headers", or "Structured Trailers", and this doc gives you a set of data types plus the algorithms that go with them. It's built for people writing brand new HTTP fields ๐ธ.
This document obsoletes RFC 8941 ๐.
Status of This Memo โจ
This is an Internet Standards Track document ๐ .
It's a product of the Internet Engineering Task Force (IETF), it represents the consensus of the IETF community, it got public review, and the Internet Engineering Steering Group (IESG) approved it for publication ๐. If you want more on Internet Standards, check Section 2 of RFC 7841 ๐ง.
Info about the current status, errata, and how to send feedback lives at https://www.rfc-editor.org/info/rfc9651 ๐ฅ.
Copyright Notice โจ
Copyright (c) 2024 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 (https://trustee.ietf.org/license-info) as they stand on the publication date. Read them carefully, bestie, because they explain your rights and restrictions ๐. Code Components pulled out of this document must include Revised BSD License text as described in Section 4.e of the Trust Legal Provisions, and they come with no warranty as described in the Revised BSD License ๐
.
Table of Contents ๐ฆ
1. Introduction
1.1. Intentionally Strict Processing
1.2. Notational Conventions
2. Defining New Structured Fields
2.1. Example
2.2. Error Handling
2.3. Preserving Extensibility
2.4. Using New Structured Types in Extensions
3. Structured Data Types
3.1. Lists
3.1.1. Inner Lists
3.1.2. Parameters
3.2. Dictionaries
3.3. Items
3.3.1. Integers
3.3.2. Decimals
3.3.3. Strings
3.3.4. Tokens
3.3.5. Byte Sequences
3.3.6. Booleans
3.3.7. Dates
3.3.8. Display Strings
4. Working with Structured Fields in HTTP
4.1. Serializing Structured Fields
4.1.1. Serializing a List
4.1.2. Serializing a Dictionary
4.1.3. Serializing an Item
4.1.4. Serializing an Integer
4.1.5. Serializing a Decimal
4.1.6. Serializing a String
4.1.7. Serializing a Token
4.1.8. Serializing a Byte Sequence
4.1.9. Serializing a Boolean
4.1.10. Serializing a Date
4.1.11. Serializing a Display String
4.2. Parsing Structured Fields
4.2.1. Parsing a List
4.2.2. Parsing a Dictionary
4.2.3. Parsing an Item
4.2.4. Parsing an Integer or Decimal
4.2.5. Parsing a String
4.2.6. Parsing a Token
4.2.7. Parsing a Byte Sequence
4.2.8. Parsing a Boolean
4.2.9. Parsing a Date
4.2.10. Parsing a Display String
5. IANA Considerations
6. Security Considerations
7. References
7.1. Normative References
7.2. Informative References
Appendix A. Frequently Asked Questions
A.1. Why Not JSON?
Appendix B. Implementation Notes
Appendix C. ABNF
Appendix D. Changes from RFC 8941
Acknowledgements
Authors' Addresses
1. Introduction ๐
Okay so defining the syntax of a new HTTP header (or trailer) field is genuinely exhausting ๐ญ. Even with the guidance in Section 16.3.2 of [HTTP], a prospective field author still runs into a ton of decisions and pitfalls ๐.
And once a field exists, people keep writing bespoke parsers and serializers, because every field handles what looks like the same syntax a little differently ๐.
So this doc brings in a shared set of data structures for defining new HTTP field values ๐. It gives a generic, abstract model, plus a concrete serialization for expressing that model in HTTP [HTTP] header and trailer fields โจ.
A field defined as a "Structured Header" or "Structured Trailer" (or a "Structured Field" if it can be either) uses the types from this spec for its syntax and basic handling rules ๐ . That makes it easier to define and easier to implement ๐ซถ.
Future HTTP versions can also define other serializations of this same abstract model, so fields using it can be sent more efficiently without being redefined ๐ฆ.
It's not a goal of this document to redefine the syntax of existing HTTP fields ๐ โโ๏ธ. The mechanisms here are only meant for fields that explicitly opt in ๐.
Section 2 explains how to specify a Structured Field ๐. Section 3 defines the abstract data types you can use in Structured Fields ๐ง. Those types get serialized to and parsed from HTTP field values using the algorithms in Section 4 ๐ฅ.
1.1. Intentionally Strict Processing ๐
This spec is intentionally strict ๐ค. It defines parsing and serialization as step-by-step algorithms, and the only error handling it allows is failing the entire operation โ.
The point is faithful implementation and good interop ๐ซถ. If one implementation tried to be helpful by accepting sloppier input, it would push everyone else into making similar (but probably subtly different) workarounds, and that makes interop worse ๐.
So strictness is a feature, not a bug ๐. It lets the producer catch and fix non-conformant input early, and it avoids the interop and security problems that could otherwise happen ๐ฅ.
Also, if a field gets appended to by several parties (like intermediaries or different components of the sender), one party's bad value is likely to make the whole field fail parsing ๐ฌ.
1.2. 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 read as described in BCP 14 [RFC2119] [RFC8174] when, and only when, they appear in all capitals, as shown here ๐.
This doc uses the VCHAR, SP, DIGIT, ALPHA, and DQUOTE rules from [RFC5234] to describe characters and/or their ASCII bytes, depending on context ๐ง. It also uses the tchar and OWS rules from [HTTP] for the same job โจ.
The spec uses algorithms to describe parsing and serialization ๐ฅ. When parsing HTTP fields, implementations MUST behave indistinguishably from following the algorithms ๐ .
For serialization, the algorithms define the recommended way to produce fields ๐ธ. Implementations MAY differ from that behavior, as long as the output still gets handled correctly by the parsing algorithm in Section 4.2 ๐ฆ.
2. Defining New Structured Fields ๐
To specify an HTTP field as a Structured Field, its authors need to do the following ๐:
- Normatively reference this specification. Recipients and generators of the field need to know the requirements of this document are in effect ๐.
- Say whether the field is a Structured Header (header section only, the common case), a Structured Trailer (trailer section only), or a Structured Field (both) ๐ฆ.
- Specify the type of the field value: List (Section 3.1), Dictionary (Section 3.2), or Item (Section 3.3) ๐ .
- Define the semantics of the field value โจ.
- Specify any extra constraints on the field value, and what happens when those constraints get violated ๐ฅ.
Usually a field definition picks the top-level type (List, Dictionary, or Item) and then defines what types and constraints are allowed inside it ๐. For example, a List-typed header might have all Integer members, or a mix of types ๐ง. An Item-typed header might only allow Strings, and maybe only strings starting with the letter "Q" or strings in lowercase ๐. Inner Lists (Section 3.1.1) are only valid when a field definition explicitly allows them ๐ซถ.
Fields using the Display String type should carefully specify their allowed Unicode code points, for example by naming a profile from [PRECIS] ๐.
Field definitions can only use this spec for the entire field value, not a portion of it ๐ โโ๏ธ.
Specs can refer to a field name as a "Structured Header name", "Structured Trailer name", or "Structured Field name", whichever fits ๐. They can also call the field value a "Structured Header value", "Structured Trailer value", or "Structured Field value" as needed โจ.
This spec sets minimums for the length or number of various structures that implementations support ๐ . In most cases it doesn't set maximums, but authors should know that HTTP implementations do impose limits on the size of individual fields, the total number of fields, and/or the size of the whole header or trailer section ๐ญ.
2.1. Example ๐ง
A fictitious Foo-Example header field could be specified like this ๐:
| 42. Foo-Example Header Field
|
| The Foo-Example HTTP header field conveys information about how
| much Foo the message has.
|
| Foo-Example is an Item Structured Header Field [RFC9651]. Its
| value MUST be an Integer (Section 3.3.1 of [RFC9651]).
|
| 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 [RFC9651]), 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.
And an example of the field in use ๐ธ:
Foo-Example: 2; foourl="https://foo.example.com/"
Part 1 of 7 done, bestie! ๐ซถ Say "next" and I'll keep going with Section 2.2 ๐ .
2.2. Error Handling ๐
okay so, when parsing fails, the whole field gets ignored (see Section 4.2) ๐ and field definitions can't override that, bestie, because if they could, generic software would literally break ๐ญ they can only add extra constraints, like limiting the numeric range of Integers and Decimals, the format of Strings and Tokens, the types allowed in a Dictionary's values, or how many Items are in a List ๐
when a field-specific constraint gets violated, the whole field is ignored too ๐ unless the field definition says otherwise with its own handling rules. so like, if a header field is defined as an Item that's required to be an Integer, but you get a String instead, it should be ignored unless that field's definition explicitly says something different โจ
2.3. Preserving Extensibility ๐ฆ
Structured Fields are built to be extensible, and honestly that's so iconic ๐ because experience has shown that even stuff nobody planned for ends up needing the allowed syntax and semantics of a field to change in a controlled way ๐
both Items and Inner Lists take Parameters as an extensibility mechanism ๐ง so their values can later grow to hold more info if they need to ๐ to keep forward compatibility, field specs are discouraged from making an unrecognized parameter an error condition ๐ซถ
field specifications are required to be an Item, List, or Dictionary to preserve extensibility ๐ fields that get defined as some other type (like Integer) are assumed to be Items, meaning they allow Parameters ๐
to make sure this extensibility sticks around in the future, and to encourage consumers to use a complete parser implementation ๐ฅ, a field definition can say that "grease" parameters get added by senders ๐ธ a spec could stipulate that all parameters matching a defined pattern are reserved for this, and then encourage senders to include them on some portion of requests โจ this helps discourage recipients from writing a parser that ignores Parameters altogether ๐
specs that use Dictionaries can also stay forward compatible by requiring that the presence of unknown keys, along with their value and type, be ignored ๐ later specs can then add more keys and put constraints on them as needed ๐ฆ
an extension to a Structured Field can require that an entire field value be ignored by a recipient that understands the extension if the constraints it defines on that value aren't met ๐ญ๐
2.4. Using New Structured Types in Extensions ๐
because a field definition needs to reference a specific RFC for Structured Fields, the types usable in its value are limited to the ones defined in that RFC ๐ for example, a field whose definition references this document can have a value using the Date type (Section 3.3.7) โจ but a field whose definition references RFC 8941 can't, because it'll be treated as invalid (and therefore discarded) by implementations of that specification ๐
this limit also applies to future extensions of a field ๐ like, a field defined with a reference to RFC 8941 can't use the Date type, because some recipients might still be running a parser based on RFC 8941 to process it ๐
BUT, this document is designed to be backward compatible with RFC 8941 ๐ซถ a parser that implements the requirements here can also parse valid Structured Fields whose definitions reference RFC 8941 ๐
upgrading a Structured Fields implementation to support a newer revision of the spec (like this document) means some field values that were invalid under the earlier RFC might become valid when processed ๐ง
for example, a field instance might contain a syntactically valid Date (Section 3.3.7), even though that field's definition doesn't accommodate Dates ๐ญ an implementation based on RFC 8941 would fail parsing that field instance because Dates aren't defined in that spec ๐ if that implementation got upgraded to this specification, parsing would now succeed โจ in some cases the resulting Date value gets rejected by field-specific logic, but values in fields that are otherwise ignored (like extension parameters) might not get detected, and the field might end up being accepted and processed ๐ฅ
3. Structured Data Types ๐
this section gives an overview of the abstract types Structured Fields use, plus a quick description and examples of how each one gets serialized into textual HTTP fields ๐ Section 4 is where the details of parsing from and serializing into textual HTTP fields live ๐ธ
in summary ๐:
- there are three top-level types an HTTP field can be defined as: Lists, Dictionaries, and Items โจ
- Lists and Dictionaries are containers, and 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 ๐ฆ
3.1. Lists ๐ง
Lists are arrays of zero or more members, each of which can be an Item (Section 3.3) or an Inner List (Section 3.1.1), and both of those can be Parameterized (Section 3.1.2) ๐
an empty List is denoted by not serializing the field at all ๐ which means fields defined as Lists have a default empty value ๐ซถ
when serialized as a textual HTTP field, 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
lowkey important: Lists can have their members split across multiple lines of the same header or trailer section, as per Section 5.3 of [HTTP] ๐ฅ for example, these are equivalent:
Example-List: sugar, tea, rum
and
Example-List: sugar, tea
Example-List: rum
BUT individual members of a List cannot be safely split between lines ๐ see Section 4.2 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 ๐
3.1.1. Inner Lists ๐
an Inner List is an array of zero or more Items (Section 3.3) ๐ both the individual Items and the Inner List itself can be Parameterized (Section 3.1.2) ๐ฆ
when serialized in a textual HTTP field, Inner Lists are denoted by surrounding parentheses, 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"), ()
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 ๐ธ
3.1.2. Parameters โจ
Parameters are an ordered map of key-value pairs associated with an Item (Section 3.3) or Inner List (Section 3.1.1) ๐ the keys are unique within the scope of the Parameters they occur in, and the values are bare items (meaning they themselves can't be parameterized; see Section 3.3) ๐
Implementations MUST provide access to Parameters both by index and by key ๐ฅ Specifications MAY use either means of accessing them ๐ซถ
note that parameters are ordered, and parameter keys cannot contain uppercase letters ๐
when serialized in a textual HTTP field, 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 Section 3.3.6) 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 only applies to serialization ๐ฆ parsers are still required to correctly handle the true value when it shows up 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 ๐
3.2. Dictionaries ๐
Dictionaries are ordered maps of key-value pairs, where the keys are short textual strings and the values are Items (Section 3.3) or arrays of Items, and both of those can be Parameterized (Section 3.1.2) โจ there can be zero or more members, and their keys are unique within the scope of the Dictionary they occur in ๐
Implementations MUST provide access to Dictionaries both by index and by key ๐ฅ Specifications MAY use either means of accessing the members ๐ซถ
same as Lists, an empty Dictionary is represented by omitting the entire field ๐ which implies that fields defined as Dictionaries have a default empty value ๐
typically, a field specification defines the semantics of a Dictionary by specifying the allowed types for individual members by their keys, plus whether their presence is required or optional ๐ธ Recipients MUST ignore members whose keys are undefined or unknown, unless the field's specification specifically disallows them ๐
when serialized as a textual HTTP field, 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 there because of the Byte Sequence; see Section 3.3.5 ๐
Members whose value is Boolean (see Section 3.3.6) 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 only applies to serialization ๐ง parsers are still required to correctly handle the true Boolean value when it shows up 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
note that Dictionaries can have their members split across multiple lines of the same header or trailer section ๐ for example, these are equivalent:
Example-Dict: foo=1, bar=2
and
Example-Dict: foo=1
Example-Dict: bar=2
BUT individual members of a Dictionary cannot be safely split between lines ๐ see Section 4.2 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 ๐
3.3. Items ๐ฆ
an Item can be an Integer (Section 3.3.1), a Decimal (Section 3.3.2), a String (Section 3.3.3), a Token (Section 3.3.4), a Byte Sequence (Section 3.3.5), a Boolean (Section 3.3.6), or a Date (Section 3.3.7) ๐ง it can have associated parameters (Section 3.1.2) ๐
for example, a header field defined to be an Item that is an Integer might look like:
Example-Integer: 5
or with parameters:
Example-Integer: 5; foo=bar
3.3.1. Integers ๐ขโจ
Okay so Integers range from -999,999,999,999,999 to 999,999,999,999,999 inclusive, which is up to fifteen digits, signed ๐. That range is there for IEEE 754 compatibility [IEEE754], so they play nice with floats ๐ฆ
Here's an example:
Example-Integer: 42
Integers bigger than 15 digits can still be supported in a few ways: by using a String (Section 3.3.3), a Byte Sequence (Section 3.3.5), or a parameter on an Integer that acts as a scaling factor ๐ง
You can serialize Integers with leading zeros (like "0002" or "-01") and signed zero ("-0"), but these distinctions may not be preserved by implementations ๐
Also, the commas in Integers are only there in this section's prose for readability ๐ They're not valid in the wire format, so don't put them in your actual headers!
3.3.2. Decimals ๐
Decimals are numbers with an integer part and a fractional part ๐ธ The integer part has at most 12 digits, and the fractional part has at most three digits.
For example, a header whose value is defined as a Decimal could look like this:
Example-Decimal: 4.5
Leading zeros ("0002.5", "-01.334"), trailing zeros ("5.230", "-0.40"), and signed zero ("-0.0") are all serializable, but these distinctions may not be preserved by implementations ๐
Heads up: the serialization algorithm (Section 4.1.5) rounds input that has more than three digits of precision in the fractional part. If you want a different rounding strategy, the field definition should specify it to happen before serialization ๐ง
3.3.3. Strings ๐
Strings are zero or more printable ASCII [RFC0020] characters, meaning the range %x20 to %x7E. Tabs, newlines, carriage returns, and friends are all excluded ๐ซ
Non-ASCII characters aren't directly supported in Strings, because they cause a bunch of interoperability headaches ๐ญ With a few exceptions, field values don't need them anyway. If a field does need to show non-ASCII content, use a Display String (Section 3.3.8) instead โจ
In a textual HTTP field, Strings get wrapped in double quotes, and a backslash ("\") is used to escape double quotes and backslashes. Like so:
Example-String: "hello world"
Only DQUOTE works as a delimiter here, so single quotes don't count ๐
โโ๏ธ Also, only DQUOTE and "\" can be escaped, and any other character after "\" MUST cause parsing to fail ๐
Parsers MUST support Strings (after any decoding) with at least 1024 characters ๐ช
3.3.4. Tokens ๐
Tokens are short textual words that start with an alphabetic character or "*", followed by zero or more token characters. The token characters are the same ones allowed by the token ABNF rule defined in [HTTP], plus ":" and "/" ๐งฉ
Here's one:
Example-Token: foo123/456
Parsers MUST support Tokens with at least 512 characters ๐
Tokens are mostly defined so they play nicely with the data model of existing HTTP fields. They might need some extra steps to use in certain implementations, so for new fields, you're encouraged to use Strings instead ๐ซถ
3.3.5. Byte Sequences ๐ฆ
Byte Sequences can be conveyed in Structured Fields ๐ฆ
In a textual HTTP field, a Byte Sequence is wrapped in colons and encoded using base64 ([RFC4648], Section 4) ๐ Here's what it looks like:
Example-ByteSequence: :cHJldGVuZCB0aGlzIGlzIGJpbmFyeSBjb250ZW50Lg==:
Parsers MUST support Byte Sequences with at least 16384 octets after decoding ๐ง
3.3.6. Booleans โ
Boolean values can be conveyed in Structured Fields too ๐
In a textual HTTP field, a Boolean starts with a "?", followed by a "1" for true or a "0" for false:
Example-Boolean: ?1
Plot twist: in Dictionary (Section 3.2) and Parameter (Section 3.1.2) values, Boolean true is shown just by leaving the value out entirely ๐คฏ
3.3.7. Dates ๐
Dates can be conveyed in Structured Fields ๐๏ธ
Their data model is kind of like Integers. They represent a delta in seconds from 1970-01-01T00:00:00Z, which can be negative, and leap seconds are excluded. Because of that, the serialization looks a lot like Integers, except it's marked with a leading "@" so you can tell them apart ๐ฐ๏ธ
Example-Date: @1659578233
Parsers MUST support Dates whose values include all days in years 1 to 9999. In delta seconds from 1970-01-01T00:00:00Z, that's -62,135,596,800 to 253,402,214,400 ๐
3.3.8. Display Strings ๐ฌ
Display Strings are a lot like Strings, in that they hold zero or more characters. The difference is that they allow Unicode scalar values (basically every Unicode code point except surrogates), while Strings don't ๐
Display Strings are meant for values that get shown to end users, so they might need to carry non-ASCII content. It is NOT RECOMMENDED to use them when a String (Section 3.3.3) or Token (Section 3.3.4) would do the job, because Unicode brings processing considerations (like normalization) and security considerations (like homograph attacks) that make it way harder to handle correctly ๐ตโ๐ซ
Note that Display Strings don't tell you what language the value is in. If you need that, you can handle it separately, like with a parameter ๐
In textual HTTP fields, Display Strings look similar to Strings, except non-ASCII characters are percent-encoded. There's a leading "%" so people (and parsers) know it's not a regular String ๐
Example-DisplayString: %"This is intended for display to %c3%bcsers."
Also check out Section 6 for more security considerations when handling Display Strings ๐
4. Working with Structured Fields in HTTP ๐ ๏ธ
This section explains how to serialize and parse the abstract types from Section 3 into textual HTTP field values, plus other encodings that are compatible with them (for example, in HTTP/2 [HTTP/2] before compression with HPACK [HPACK]) ๐ง
4.1. Serializing Structured Fields ๐ง
Given a structure defined in this specification, return an ASCII string that's suitable for use in an HTTP field value โจ
- If the structure is a Dictionary or List and its value is empty (meaning it has no members), do not serialize the field at all. That means you omit both the field-name and the field-value ๐
- If the structure is a List, let
output_stringbe the result of running Serializing a List (Section 4.1.1) with the structure. - Else, if the structure is a Dictionary, let
output_stringbe the result of running Serializing a Dictionary (Section 4.1.2) with the structure. - Else, if the structure is an Item, let
output_stringbe the result of running Serializing an Item (Section 4.1.3) with the structure. - Else, fail serialization ๐
- Return
output_stringconverted into an array of bytes, using ASCII encoding [RFC0020] ๐ซง
4.1.1. Serializing a List ๐
Given an array of (member_value, parameters) tuples as input_list, return an ASCII string suitable for use in an HTTP field value ๐ท
- Let
outputbe an empty string. - For each
(member_value, parameters)ofinput_list:- If
member_valueis an array, append the result of running Serializing an Inner List (Section 4.1.1.1) with(member_value, parameters)tooutput. - Otherwise, append the result of running Serializing an Item (Section 4.1.3) with
(member_value, parameters)tooutput. - If more
member_values remain ininput_list:- Append
","tooutput. - Append a single
SPtooutput.
- Append
- If
- Return
output๐
4.1.1.1. Serializing an Inner List ๐ช
Given 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
outputbe the string"(". - For each
(member_value, parameters)ofinner_list:- Append the result of running Serializing an Item (Section 4.1.3) with
(member_value, parameters)tooutput. - If more values remain in
inner_list, append a singleSPtooutput.
- Append the result of running Serializing an Item (Section 4.1.3) with
- Append
")"tooutput. - Append the result of running Serializing Parameters (Section 4.1.1.2) with
list_parameterstooutput. - Return
output๐
4.1.1.2. Serializing Parameters ๐ท๏ธ
Given an ordered Dictionary as input_parameters (where each member has a param_key and a param_value), return an ASCII string suitable for use in an HTTP field value ๐ฆ
- Let
outputbe an empty string. - For each
param_keywith a value ofparam_valueininput_parameters:- Append
";"tooutput. - Append the result of running Serializing a Key (Section 4.1.1.3) with
param_keytooutput. - If
param_valueis not Boolean true:- Append
"="tooutput. - Append the result of running Serializing a bare Item (Section 4.1.3.1) with
param_valuetooutput.
- Append
- Append
- Return
outputโจ
4.1.1.3. Serializing a Key ๐
Given a key as input_key, return an ASCII string suitable for use in an HTTP field value ๐๏ธ
- Convert
input_keyinto a sequence of ASCII characters. If conversion fails, fail serialization. - If
input_keycontains characters that aren't inlcalpha,DIGIT,"_","-",".", or"*", fail serialization ๐ โโ๏ธ - If the first character of
input_keyis notlcalphaor"*", fail serialization. - Let
outputbe an empty string. - Append
input_keytooutput. - Return
output๐
4.1.2. Serializing a Dictionary ๐
Given an ordered Dictionary as input_dictionary (where each member has a member_key and a tuple value of (member_value, parameters)), return an ASCII string suitable for use in an HTTP field value ๐
- Let
outputbe an empty string. - For each
member_keywith a value of(member_value, parameters)ininput_dictionary:- Append the result of running Serializing a Key (Section 4.1.1.3) with the member's
member_keytooutput. - If
member_valueis Boolean true:- Append the result of running Serializing Parameters (Section 4.1.1.2) with
parameterstooutput.
- Append the result of running Serializing Parameters (Section 4.1.1.2) with
- Otherwise:
- Append
"="tooutput. - If
member_valueis an array, append the result of running Serializing an Inner List (Section 4.1.1.1) with(member_value, parameters)tooutput. - Otherwise, append the result of running Serializing an Item (Section 4.1.3) with
(member_value, parameters)tooutput.
- Append
- If more members remain in
input_dictionary:- Append
","tooutput. - Append a single
SPtooutput.
- Append
- Append the result of running Serializing a Key (Section 4.1.1.3) with the member's
- Return
output๐
4.1.3. Serializing an Item ๐งธ
Given an Item as bare_item and Parameters as item_parameters, return an ASCII string suitable for use in an HTTP field value ๐ซถ
- Let
outputbe an empty string. - Append the result of running Serializing a Bare Item (Section 4.1.3.1) with
bare_itemtooutput. - Append the result of running Serializing Parameters (Section 4.1.1.2) with
item_parameterstooutput. - Return
output๐
4.1.3.1. Serializing a Bare Item โจ
okay bestie, this is where we take a bare Item (input_item) and turn it into an ASCII string that's safe to drop into an HTTP field value ๐ we check what type it is and hand it off to the right serializer. it's like a sorting hat ๐ง
- If
input_itemis an Integer, return the result of running Serializing an Integer (Section 4.1.4) withinput_item. - If
input_itemis a Decimal, return the result of running Serializing a Decimal (Section 4.1.5) withinput_item. - If
input_itemis a String, return the result of running Serializing a String (Section 4.1.6) withinput_item. - If
input_itemis a Token, return the result of running Serializing a Token (Section 4.1.7) withinput_item. - If
input_itemis a Byte Sequence, return the result of running Serializing a Byte Sequence (Section 4.1.8) withinput_item. - If
input_itemis a Boolean, return the result of running Serializing a Boolean (Section 4.1.9) withinput_item. - If
input_itemis a Date, return the result of running Serializing a Date (Section 4.1.10) withinput_item. - If
input_itemis a Display String, return the result of running Serializing a Display String (Section 4.1.11) withinput_item. - Otherwise, fail serialization. ๐
4.1.4. Serializing an Integer ๐ข
this one's giving simple. we take an Integer (input_integer) and make it an ASCII string ๐
- If
input_integeris not an integer in the range of -999,999,999,999,999 to 999,999,999,999,999 inclusive, fail serialization. - Let
outputbe an empty string. - If
input_integeris less than (but not equal to) 0, append"-"tooutput. - Append
input_integer's numeric value represented in base 10 using only decimal digits tooutput. - Return
output.
4.1.5. Serializing a Decimal ๐ฆ
decimals are a little more work, bestie, because we have to round and count digits so nothing goes sideways ๐ธ take a decimal number (input_decimal) and make it an ASCII string.
- If
input_decimalis not a decimal number, fail serialization. - If
input_decimalhas 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_decimalhas more than 12 significant digits to the left of the decimal point after rounding, fail serialization. - Let
outputbe an empty string. - If
input_decimalis less than (but not equal to) 0, append"-"tooutput. - Append
input_decimal's integer component represented in base 10 (using only decimal digits) tooutput; if it is zero, append"0". - Append
"."tooutput. - If
input_decimal's fractional component is zero, append"0"tooutput. - Otherwise, append the significant digits of
input_decimal's fractional component represented in base 10 (using only decimal digits) tooutput. - Return
output.
4.1.6. Serializing a String ๐
strings get the most babysitting, periodt ๐
we only allow ASCII, we only allow certain characters, and then we wrap the whole thing in quotes and escape the sneaky ones. take a String (input_string) and make it an ASCII string.
- Convert
input_stringinto a sequence of ASCII characters; if conversion fails, fail serialization. - If
input_stringcontains characters in the range%x00-1for%x7f-ff(i.e., not in VCHAR or SP), fail serialization. - Let
outputbe the string DQUOTE. - For each character
charininput_string:- If
charis"\"or DQUOTE:- Append
"\"tooutput. - Append
chartooutput.
- Append
- If
- Append DQUOTE to
output. - Return
output.
4.1.7. Serializing a Token ๐
tokens are the cool, no-quotes-needed kind ๐ we just check the first character and the rest, then tack it on.
- Convert
input_tokeninto a sequence of ASCII characters; if conversion fails, fail serialization. - If the first character of
input_tokenis not ALPHA or"*", or the remaining portion contains a character not in tchar,":", or"/", fail serialization. - Let
outputbe an empty string. - Append
input_tokentooutput. - Return
output.
4.1.8. Serializing a Byte Sequence ๐ง
byte sequences get base64-encoded and wrapped in colons, but there are a couple of padding rules we have to follow, so pay attention ๐
- If
input_bytesis not a sequence of bytes, fail serialization. - Let
outputbe an empty string. - Append
":"tooutput. - Append the result of base64-encoding
input_bytesas per [RFC4648], Section 4, taking account of the requirements below. - Append
":"tooutput. - Return
output.
The encoded data is required to be padded with "=", as per [RFC4648], Section 3.2.
Likewise, encoded data SHOULD have pad bits set to zero, as per [RFC4648], Section 3.5, unless it is not possible to do so due to implementation constraints.
4.1.9. Serializing a Boolean ๐ธ
booleans are the simplest little guys ever. a question mark, then a 1 or a 0. that's it, that's the tea ๐
- If
input_booleanis not a boolean, fail serialization. - Let
outputbe an empty string. - Append
"?"tooutput. - If
input_booleanis true, append"1"tooutput. - If
input_booleanis false, append"0"tooutput. - Return
output.
4.1.10. Serializing a Date ๐
dates are just integers with an @ in front, which is honestly iconic ๐
- Let
outputbe"@". - Append to
outputthe result of running Serializing an Integer withinput_date(Section 4.1.4). - Return
output.
4.1.11. Serializing a Display String ๐ซถ
display strings are Unicode, so we first turn them into UTF-8 bytes, then percent-encode the risky bytes and leave the rest alone. no cap, this is the most detailed one in the whole section ๐ฅน
- If
input_sequenceis not a sequence of Unicode code points, fail serialization. - Let
byte_arraybe the result of applying UTF-8 encoding (Section 3 of [UTF8]) toinput_sequence. If encoding fails, fail serialization. - Let
encoded_stringbe a string containing"%"followed by DQUOTE. - For each
byteinbyte_array:- If
byteis%x25("%"),%x22(DQUOTE), or in the ranges%x00-1for%x7f-ff:- Append
"%"toencoded_string. - Let
encoded_bytebe the result of applying base16 encoding (Section 8 of [RFC4648]) tobyte, with any alphabetic characters converted to lowercase. - Append
encoded_bytetoencoded_string.
- Append
- Otherwise, decode
byteas an ASCII character and append the result toencoded_string.
- If
- Append DQUOTE to
encoded_string. - Return
encoded_string.
Note that [UTF8] prohibits the encoding of code points between U+D800 and U+DFFF (surrogates); if they occur in input_sequence, serialization will fail. ๐
4.2. Parsing Structured Fields ๐
okay bestie, parsing is where the edge cases hide, and they can cause interoperability or even security problems. so this section lays out exactly how to do it safely ๐ก๏ธ
when 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 field value.
- Convert
input_bytesinto an ASCII stringinput_string; if conversion fails, fail parsing. - Discard any leading SP characters from
input_string. - If
field_typeis"list", letoutputbe the result of running Parsing a List (Section 4.2.1) withinput_string. - If
field_typeis"dictionary", letoutputbe the result of running Parsing a Dictionary (Section 4.2.2) withinput_string. - If
field_typeis"item", letoutputbe the result of running Parsing an Item (Section 4.2.3) withinput_string. - Discard any leading SP characters from
input_string. - If
input_stringis 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 Section 5.2 of [HTTP]; 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 field 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, either the entire field value MUST be ignored (i.e., treated as if the field were not present in the section), or alternatively the complete HTTP message MUST be treated as malformed. This is intentionally strict to improve interoperability and safety, and field specifications that use Structured Fields 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. ๐ฆ
4.2.1. Parsing a List ๐
Given 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
membersbe an empty array. - While
input_stringis not empty:- Append the result of running Parsing an Item or Inner List (Section 4.2.1.1) with
input_stringtomembers. - Discard any leading OWS characters from
input_string. - If
input_stringis empty, returnmembers. - Consume the first character of
input_string; if it is not",", fail parsing. - Discard any leading OWS characters from
input_string. - If
input_stringis empty, there is a trailing comma; fail parsing.
- Append the result of running Parsing an Item or Inner List (Section 4.2.1.1) with
- No structured data has been found; return
members(which is empty). ๐ซฅ
4.2.1.1. Parsing an Item or Inner List ๐ง
Given 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_stringis"(", return the result of running Parsing an Inner List (Section 4.2.1.2) withinput_string. - Return the result of running Parsing an Item (Section 4.2.3) with
input_string.
4.2.1.2. Parsing an Inner List ๐ง
okay so this is the inner list parser ๐
Given an ASCII string as input_string, it hands back the tuple (inner_list, parameters), where inner_list is an array of (bare_item, parameters) tuples. It also chews through input_string and removes whatever it parsed ๐ซถ
- Consume the first character of
input_string; if it is not"(", fail parsing. - Let
inner_listbe an empty array. - While
input_stringis not empty:- Discard any leading SP characters from
input_string. - If the first character of
input_stringis")":- Consume the first character of
input_string. - Let
parametersbe the result of running Parsing Parameters (Section 4.2.3.2) withinput_string. - Return the tuple (
inner_list,parameters).
- Consume the first character of
- Let
itembe the result of running Parsing an Item (Section 4.2.3) withinput_string. - Append
itemtoinner_list. - If the first character of
input_stringis not SP or")", fail parsing.
- Discard any leading SP characters from
- The end of the Inner List was not found; fail parsing.
4.2.2. Parsing a Dictionary ๐
this one is giving key-value vibes ๐ Given an ASCII string as input_string, it returns an ordered map whose values are (item_or_inner_list, parameters) tuples. Same deal: input_string gets modified to remove the parsed value.
- Let
dictionarybe an empty, ordered map. - While
input_stringis not empty:- Let
this_keybe the result of running Parsing a Key (Section 4.2.3.3) withinput_string. - If the first character of
input_stringis"=":- Consume the first character of
input_string. - Let
memberbe the result of running Parsing an Item or Inner List (Section 4.2.1.1) withinput_string.
- Consume the first character of
- Otherwise:
- Let
valuebe Boolean true. - Let
parametersbe the result of running Parsing Parameters (Section 4.2.3.2) withinput_string. - Let
memberbe the tuple (value,parameters).
- Let
- If
dictionaryalready contains a keythis_key(comparing character for character), overwrite its value withmember. - Otherwise, append key
this_keywith valuemembertodictionary. - Discard any leading OWS characters from
input_string. - If
input_stringis empty, returndictionary. - Consume the first character of
input_string; if it is not",", fail parsing. - Discard any leading OWS characters from
input_string. - If
input_stringis empty, there is a trailing comma; fail parsing.
- Let
- 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. so the last one wins, sorry earlier copies ๐
4.2.3. Parsing an Item ๐
Given an ASCII string as input_string, this returns a (bare_item, parameters) tuple, and input_string gets modified to remove the parsed value.
- Let
bare_itembe the result of running Parsing a Bare Item (Section 4.2.3.1) withinput_string. - Let
parametersbe the result of running Parsing Parameters (Section 4.2.3.2) withinput_string. - Return the tuple (
bare_item,parameters).
4.2.3.1. Parsing a Bare Item ๐
Given an ASCII string as input_string, this returns a bare Item. Again, input_string is modified to remove the parsed value. The first character decides which parser takes over, so it's basically a bouncer at the door ๐ช
- If the first character of
input_stringis a"-"or a DIGIT, return the result of running Parsing an Integer or Decimal (Section 4.2.4) withinput_string. - If the first character of
input_stringis a DQUOTE, return the result of running Parsing a String (Section 4.2.5) withinput_string. - If the first character of
input_stringis an ALPHA or"*", return the result of running Parsing a Token (Section 4.2.6) withinput_string. - If the first character of
input_stringis":", return the result of running Parsing a Byte Sequence (Section 4.2.7) withinput_string. - If the first character of
input_stringis"?", return the result of running Parsing a Boolean (Section 4.2.8) withinput_string. - If the first character of
input_stringis"@", return the result of running Parsing a Date (Section 4.2.9) withinput_string. - If the first character of
input_stringis"%", return the result of running Parsing a Display String (Section 4.2.10) withinput_string. - Otherwise, the item type is unrecognized; fail parsing.
4.2.3.2. Parsing Parameters โจ
Given an ASCII string as input_string, this returns an ordered map whose values are bare Items. input_string gets modified to remove the parsed value.
- Let
parametersbe an empty, ordered map. - While
input_stringis not empty:- If the first character of
input_stringis not";", exit the loop. - Consume the
";"character from the beginning ofinput_string. - Discard any leading SP characters from
input_string. - Let
param_keybe the result of running Parsing a Key (Section 4.2.3.3) withinput_string. - Let
param_valuebe Boolean true. - If the first character of
input_stringis"=":- Consume the
"="character at the beginning ofinput_string. - Let
param_valuebe the result of running Parsing a Bare Item (Section 4.2.3.1) withinput_string.
- Consume the
- If
parametersalready contains a keyparam_key(comparing character for character), overwrite its value withparam_value. - Otherwise, append key
param_keywith valueparam_valuetoparameters.
- If the first character of
- Return
parameters.
Note that when duplicate parameter keys are encountered, all but the last instance are ignored.
4.2.3.3. Parsing a Key ๐ฆ
Given an ASCII string as input_string, this returns a key, and input_string gets modified to remove the parsed value.
- If the first character of
input_stringis not lcalpha or"*", fail parsing. - Let
output_stringbe an empty string. - While
input_stringis not empty:- If the first character of
input_stringis not one of lcalpha, DIGIT,"_","-",".", or"*", returnoutput_string. - Let
charbe the result of consuming the first character ofinput_string. - Append
chartooutput_string.
- If the first character of
- Return
output_string.
4.2.4. Parsing an Integer or Decimal ๐ฅ
Given an ASCII string as input_string, this returns an Integer or Decimal, and input_string is modified to remove the parsed value.
NOTE: This algorithm parses both Integers (Section 3.3.1) and Decimals (Section 3.3.2), and returns the corresponding structure. one parser, two number types, very efficient ๐ง
- Let
typebe"integer". - Let
signbe 1. - Let
input_numberbe an empty string. - If the first character of
input_stringis"-", consume it and setsignto -1. - If
input_stringis empty, there is an empty integer; fail parsing. - If the first character of
input_stringis not a DIGIT, fail parsing. - While
input_stringis not empty:- Let
charbe the result of consuming the first character ofinput_string. - If
charis a DIGIT, append it toinput_number. - Else, if
typeis"integer"andcharis".":- If
input_numbercontains more than 12 characters, fail parsing. - Otherwise, append
chartoinput_numberand settypeto"decimal".
- If
- Otherwise, prepend
chartoinput_string, and exit the loop. - If
typeis"integer"andinput_numbercontains more than 15 characters, fail parsing. - If
typeis"decimal"andinput_numbercontains more than 16 characters, fail parsing.
- Let
- If
typeis"integer":- Let
output_numberbe an Integer that is the result of parsinginput_numberas an integer.
- Let
- Otherwise:
- If the final character of
input_numberis".", fail parsing. - If the number of characters after
"."ininput_numberis greater than three, fail parsing. - Let
output_numberbe a Decimal that is the result of parsinginput_numberas a decimal number.
- If the final character of
- Let
output_numberbe the product ofoutput_numberandsign. - Return
output_number.
4.2.5. Parsing a String ๐
Given an ASCII string as input_string, this returns an unquoted String, and input_string is modified to remove the parsed value.
- Let
output_stringbe an empty string. - If the first character of
input_stringis not DQUOTE, fail parsing. - Discard the first character of
input_string. - While
input_stringis not empty:- Let
charbe the result of consuming the first character ofinput_string. - If
charis a backslash ("\"):- If
input_stringis now empty, fail parsing. - Let
next_charbe the result of consuming the first character ofinput_string. - If
next_charis not DQUOTE or"\", fail parsing. - Append
next_chartooutput_string.
- If
- Else, if
charis DQUOTE, returnoutput_string. - Else, if
charis in the range %x00-1f or %x7f-ff (i.e., it is not in VCHAR or SP), fail parsing. - Else, append
chartooutput_string.
- Let
- Reached the end of
input_stringwithout finding a closing DQUOTE; fail parsing.
4.2.6. Parsing a Token ๐ธ
Given an ASCII string as input_string, this returns a Token, and input_string is modified to remove the parsed value.
- If the first character of
input_stringis not ALPHA or"*", fail parsing. - Let
output_stringbe an empty string. - While
input_stringis not empty:- If the first character of
input_stringis not in tchar,":", or"/", returnoutput_string. - Let
charbe the result of consuming the first character ofinput_string. - Append
chartooutput_string.
- If the first character of
- Return
output_string.
4.2.7. Parsing a Byte Sequence ๐ซง
Given an ASCII string as input_string, this returns a Byte Sequence, and input_string is modified to remove the parsed value.
- If the first character of
input_stringis not":", fail parsing. - Discard the first character of
input_string. - If there is not a
":"character before the end ofinput_string, fail parsing. - Let
b64_contentbe the result of consuming content ofinput_stringup to but not including the first instance of the character":". - Consume the
":"character at the beginning ofinput_string. - If
b64_contentcontains a character not included in ALPHA, DIGIT,"+","/", and"=", fail parsing. - Let
binary_contentbe the result of base64-decoding [RFC4648]b64_content, synthesizing padding if necessary (note the requirements about recipient behavior below). If base64 decoding fails, parsing fails. - Return
binary_content.
okay so base64 libraries aren't always strict ๐ญ Some of them can't reject data that's missing its "=" padding (see [RFC4648], Section 3.2), so parsers SHOULD NOT fail when that padding isn't there, unless they can't be configured to behave that way ๐
same energy for the pad bits: some base64 implementations can't reject data whose pad bits aren't zero (see [RFC4648], Section 3.5), so parsers SHOULD NOT fail when non-zero pad bits show up, unless they can't be configured to do so ๐
BUT here's the plot twist ๐ This specification does not relax the requirements in Sections 3.1 and 3.3 of [RFC4648]; therefore, parsers MUST fail on characters outside the base64 alphabet and on line feeds in encoded data. ๐ซ
4.2.8. Parsing a Boolean ๐ฆ
okay so this one is a Boolean parser and it's giving simple ๐
Given an ASCII string as input_string, you return a Boolean, and input_string gets modified to remove the parsed value.
- If the first character of
input_stringis not?, fail parsing. - Discard the first character of
input_string. - If the first character of
input_stringmatches1, discard the first character, and return true. - If the first character of
input_stringmatches0, discard the first character, and return false. - No value has matched; fail parsing.
4.2.9. Parsing a Date ๐
bestie, dates are parsed with a leading @ โจ Given an ASCII string as input_string, you return a Date, and input_string gets modified to remove the parsed value.
- If the first character of
input_stringis not@, fail parsing. - Discard the first character of
input_string. - Let
output_datebe the result of running Parsing an Integer or Decimal (Section 4.2.4) withinput_string. - If
output_dateis a Decimal, fail parsing. - Return
output_date.
4.2.10. Parsing a Display String ๐
this one is the main character of the parsers ๐ Given an ASCII string as input_string, you return a sequence of Unicode code points, and input_string gets modified to remove the parsed value. It's a little bit of a journey, so hold on tight ๐ญ
- If the first two characters of
input_stringare not%followed by", fail parsing. - Discard the first two characters of
input_string. - Let
byte_arraybe an empty byte array. - While
input_stringis not empty:- Let
charbe the result of consuming the first character ofinput_string. - If
charis in the range%x00-1for%x7f-ff(i.e., it is not in VCHAR or SP), fail parsing. - If
charis%:- Let
octet_hexbe the result of consuming two characters frominput_string. If there are not two characters, fail parsing. - If
octet_hexcontains characters outside the range%x30-39or%x61-66(i.e., it is not in 0-9 or lowercase a-f), fail parsing. - Let
octetbe the result of hex decodingoctet_hex(Section 8 of [RFC4648]). - Append
octettobyte_array.
- Let
- If
charis DQUOTE:- Let
unicode_sequencebe the result of decodingbyte_arrayas a UTF-8 string (Section 3 of [UTF8]). Fail parsing if decoding fails. - Return
unicode_sequence.
- Let
- Otherwise, if
charis not%or DQUOTE:- Let
bytebe the result of applying ASCII encoding tochar. - Append
bytetobyte_array.
- Let
- Let
- Reached the end of
input_stringwithout finding a closing DQUOTE; fail parsing.
5. IANA Considerations ๐ธ
so IANA added a little note to the "Hypertext Transfer Protocol (HTTP) Field Name Registry" ๐ Here's exactly what it says:
The "Structured Type" column indicates the type of the field (per
RFC 9651), if any, and may be "Dictionary", "List", or "Item".
Note that field names beginning with characters other than ALPHA
or "*" will not be able to be represented as a Structured Fields
Token and therefore may be incompatible with being mapped into
field values that refer to it.
A new column, "Structured Type", has been added to the registry, and every existing registry entry listed in Table 1 got its indicated Structured Type too โจ
+==========================================+=================+
| Field Name | Structured Type |
+==========================================+=================+
| Accept-CH | List |
+------------------------------------------+-----------------+
| Cache-Status | List |
+------------------------------------------+-----------------+
| CDN-Cache-Control | Dictionary |
+------------------------------------------+-----------------+
| Cross-Origin-Embedder-Policy | Item |
+------------------------------------------+-----------------+
| Cross-Origin-Embedder-Policy-Report-Only | Item |
+------------------------------------------+-----------------+
| Cross-Origin-Opener-Policy | Item |
+------------------------------------------+-----------------+
| Cross-Origin-Opener-Policy-Report-Only | Item |
+------------------------------------------+-----------------+
| Origin-Agent-Cluster | Item |
+------------------------------------------+-----------------+
| Priority | Dictionary |
+------------------------------------------+-----------------+
| Proxy-Status | List |
+------------------------------------------+-----------------+
Table 1: Existing Fields
6. Security Considerations ๐ฅ
okay bestie, read this part slowly, it's serious ๐
The size of most types defined by Structured Fields is not limited, which means extremely large fields could be an attack vector (for example, for resource consumption) ๐ To mitigate that, most HTTP implementations limit the sizes of individual fields as well as the overall header or trailer section size.
Parties with the ability to inject new HTTP fields can change the meaning of a Structured Field ๐ฑ In some circumstances that will make parsing fail, but it is not possible to reliably fail in all such circumstances.
The Display String type can convey any possible Unicode code point without sanitization. That means it might contain unassigned code points, control points (including NUL), or noncharacters ๐ซฃ So applications consuming Display Strings need to consider strategies like filtering or escaping untrusted content before displaying it. See [PRECIS] and [UNICODE-SECURITY].
7. References ๐
7.1. Normative References
[HTTP]Fielding, R., Ed., Nottingham, M., Ed., and J. Reschke, Ed., "HTTP Semantics", STD 97, RFC 9110, DOI 10.17487/RFC9110, June 2022,https://www.rfc-editor.org/info/rfc9110.[RFC0020]Cerf, V., "ASCII format for network interchange", STD 80, RFC 20, DOI 10.17487/RFC0020, October 1969,https://www.rfc-editor.org/info/rfc20.[RFC2119]Bradner, S., "Key words for use in RFCs to Indicate Requirement Levels", BCP 14, RFC 2119, DOI 10.17487/RFC2119, March 1997,https://www.rfc-editor.org/info/rfc2119.[RFC4648]Josefsson, S., "The Base16, Base32, and Base64 Data Encodings", RFC 4648, DOI 10.17487/RFC4648, October 2006,https://www.rfc-editor.org/info/rfc4648.[RFC8174]Leiba, B., "Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words", BCP 14, RFC 8174, DOI 10.17487/RFC8174, May 2017,https://www.rfc-editor.org/info/rfc8174.[UTF8]Yergeau, F., "UTF-8, a transformation format of ISO 10646", STD 63, RFC 3629, DOI 10.17487/RFC3629, November 2003,https://www.rfc-editor.org/info/rfc3629.
7.2. Informative References
[HPACK]Peon, R. and H. Ruellan, "HPACK: Header Compression for HTTP/2", RFC 7541, DOI 10.17487/RFC7541, May 2015,https://www.rfc-editor.org/info/rfc7541.[HTTP/2]Thomson, M., Ed. and C. Benfield, Ed., "HTTP/2", RFC 9113, DOI 10.17487/RFC9113, June 2022,https://www.rfc-editor.org/info/rfc9113.[IEEE754]IEEE, "IEEE Standard for Floating-Point Arithmetic", IEEE Std 754-2019, DOI 10.1109/IEEESTD.2019.8766229, ISBN 978-1-5044-5924-2, July 2019,https://ieeexplore.ieee.org/document/8766229.[PRECIS]Saint-Andre, P. and M. Blanchet, "PRECIS Framework: Preparation, Enforcement, and Comparison of Internationalized Strings in Application Protocols", RFC 8264, DOI 10.17487/RFC8264, October 2017,https://www.rfc-editor.org/info/rfc8264.[RFC5234]Crocker, D., Ed. and P. Overell, "Augmented BNF for Syntax Specifications: ABNF", STD 68, RFC 5234, DOI 10.17487/RFC5234, January 2008,https://www.rfc-editor.org/info/rfc5234.[RFC7493]Bray, T., Ed., "The I-JSON Message Format", RFC 7493, DOI 10.17487/RFC7493, March 2015,https://www.rfc-editor.org/info/rfc7493.[RFC8259]Bray, T., Ed., "The JavaScript Object Notation (JSON) Data Interchange Format", STD 90, RFC 8259, DOI 10.17487/RFC8259, December 2017,https://www.rfc-editor.org/info/rfc8259.[UNICODE-SECURITY]Davis, M. and M. Suignard, "Unicode Security Considerations", Unicode Technical Report #36, 19 September 2014,https://www.unicode.org/reports/tr36/tr36-15.html. Latest version available athttps://www.unicode.org/reports/tr36/.
Appendix A. Frequently Asked Questions ๐
A.1. Why Not JSON? ๐
okay so the earliest Structured Fields proposals were based on JSON [RFC8259] ๐ฌ The catch is that making JSON fit for HTTP fields meant senders and recipients had to implement extra special handling, which is a lot.
JSON has issues with large numbers and with objects that have duplicate members. There is advice for avoiding these (e.g., [RFC7493]), but it can't be relied upon ๐
JSON strings are Unicode strings by default, and that causes a bunch of potential interoperability problems (e.g., in comparison) ๐ You can advise implementers to avoid non-ASCII content where it isn't needed, but that's hard to enforce.
Then there's JSON's ability to nest content to arbitrary depths. The memory that takes might be unsuitable for embedded and other limited server deployments, so it needs to be limited somehow. The thing is, existing JSON implementations have no such limits, and even if a limit gets specified, some field definition will probably find a reason to break it ๐
JSON is so widely adopted and implemented that it's really hard to impose extra constraints across every implementation, and some deployments would fail to enforce them, which hurts interoperability. Basically, if it looks like JSON, people will be tempted to run a JSON parser/serializer on field values ๐ญ
A major goal for Structured Fields is improving interoperability and simplifying implementation, so these concerns led to a format that needs a dedicated parser and serializer ๐ง There were also widely shared feelings that JSON just doesn't "look right" in HTTP fields ๐
Appendix B. Implementation Notes โจ
okay bestie, so a generic implementation of this spec should expose the top-level serialize (Section 4.1) and parse (Section 4.2) functions ๐ They don't have to literally be functions, though. You could build it as an object with methods for each of the top-level types, and that's totally valid ๐ง
For interoperability, generic implementations need to be complete and follow the algorithms closely, see Section 1.1 ๐ซถ The community also keeps a shared test suite at <https://github.com/httpwg/structured-field-tests>, so you can check your work. It's giving accountability ๐ญ
Implementers, listen up ๐ Dictionaries and Parameters are order-preserving maps. Some fields might not mean anything based on ordering, but the order should still be exposed so applications that need it can use it.
Also, keep Tokens and Strings separate! Most languages have built-in types that map pretty well to the other types, but you might need a wrapper "token" object or a parameter on your functions so the two types don't blur together ๐ฆ
The serialization algorithm isn't strictly limited to the data types in Section 3 in every case. For example, Decimals are designed to take broader input and round it to allowed values. Main character energy ๐
Implementations can limit the size of different structures, as long as they respect the minimums defined for each type. When a structure goes over an implementation limit, it fails parsing or serialization. No cap, that's a hard stop ๐
Appendix C. ABNF ๐ธ
This section uses the Augmented Backus-Naur Form (ABNF) notation [RFC5234] to illustrate the expected syntax of Structured Fields. Real talk though, it can't be used to validate them, because it doesn't capture every requirement ๐
This section is non-normative. If the ABNF and the parsing algorithms ever disagree, the specified algorithms take precedence. The algorithms win, periodt ๐
sf-list = list-member *( OWS "," OWS list-member )
list-member = sf-item / inner-list
inner-list = "(" *SP [ sf-item *( 1*SP sf-item ) *SP ] ")"
parameters
parameters = *( ";" *SP parameter )
parameter = param-key [ "=" param-value ]
param-key = key
key = ( lcalpha / "*" )
*( lcalpha / DIGIT / "_" / "-" / "." / "*" )
lcalpha = %x61-7A ; a-z
param-value = bare-item
sf-dictionary = dict-member *( OWS "," OWS dict-member )
dict-member = member-key ( parameters / ( "=" member-value ))
member-key = key
member-value = sf-item / inner-list
sf-item = bare-item parameters
bare-item = sf-integer / sf-decimal / sf-string / sf-token
/ sf-binary / sf-boolean / sf-date / sf-displaystring
sf-integer = ["-"] 1*15DIGIT
sf-decimal = ["-"] 1*12DIGIT "." 1*3DIGIT
sf-string = DQUOTE *( unescaped / "%" / bs-escaped ) DQUOTE
sf-token = ( ALPHA / "*" ) *( tchar / ":" / "/" )
sf-binary = ":" base64 ":"
sf-boolean = "?" ( "0" / "1" )
sf-date = "@" sf-integer
sf-displaystring = "%" DQUOTE *( unescaped / "\" / pct-encoded )
DQUOTE
base64 = *( ALPHA / DIGIT / "+" / "/" ) *"="
unescaped = %x20-21 / %x23-24 / %x26-5B / %x5D-7E
bs-escaped = "\" ( DQUOTE / "\" )
pct-encoded = "%" lc-hexdig lc-hexdig
lc-hexdig = DIGIT / %x61-66 ; 0-9, a-f
Appendix D. Changes from RFC 8941 ๐ฆ
This revision of the "Structured Field Values for HTTP" specification has made the following changes, bestie:
- Added the Date Structured Type. (Section 3.3.7) ๐
- Stopped encouraging use of ABNF in definitions of new Structured Fields. (Section 2) ๐ โโ๏ธ
- Moved ABNF to an informative appendix. (Appendix C) ๐
- Added a "Structured Type" column to the "Hypertext Transfer Protocol (HTTP) Field Name Registry". (Section 5) ๐๏ธ
- Refined parse failure handling. (Section 4.2) ๐ ๏ธ
- Added the Display String Structured Type. (Section 3.3.8) ๐
Acknowledgements ๐ซถ
Many thanks to Matthew Kerwin for his detailed feedback and careful consideration during the development of this specification. Absolute legend ๐
Thanks also to Ian Clelland, Roy Fielding, Anne van Kesteren, Kazuho Oku, Evert Pot, Julian Reschke, Martin Thomson, Mike West, and Jeffrey Yasskin for their contributions. Everyone who helped make this happen is iconic โจ
Authors' Addresses ๐ฎ
Mark Nottingham
Cloudflare
Prahran VIC
Australia
Email: mnot@mnot.net
URI: https://www.mnot.net/
Poul-Henning Kamp
The Varnish Cache Project
Email: phk@varnish-cache.org
๐ฆ where this page comes from
- ietf: rfc9651 2024-09
- ๐ girlified by claude-haiku-5-5 on : a language model's rewrite of the original, under its terms