Parsing States
Relevant source files
The following files were used as context for generating this wiki page:
The python-multipart library utilizes a state-machine architecture to perform streaming parsing of various HTTP body formats, including multipart/form-data, application/x-www-form-urlencoded, and raw octet streams. By maintaining an internal state, the parsers can process data in small chunks (as it arrives over the network) without requiring the entire payload to be loaded into memory.
Parsing states are primarily defined using IntEnum classes, which track the progress of the parser through boundaries, headers, and body data. This mechanism ensures that the parser knows exactly how to interpret the next byte in the stream based on the bytes that preceded it.
Sources: python_multipart/multipart.py:82-89, python_multipart/multipart.py:92-99
Multipart State Machine
The MultipartParser uses a complex state machine to navigate the nested structure of a multipart message. It transitions through states to identify the preamble, part boundaries, header sections, and the actual content of each part.
State Definitions
The MultipartState enumeration defines the lifecycle of a multipart parse operation:
| State | Value | Description |
|---|---|---|
START | 0 | Initial state; skips leading newlines before the first boundary. |
START_BOUNDARY | 1 | Matching the characters of the part boundary. |
HEADER_FIELD_START | 2 | Preparing to read a new header field name. |
HEADER_FIELD | 3 | Currently reading a header field (e.g., "Content-Type"). |
HEADER_VALUE_START | 4 | Transitioning from the colon to the header value. |
HEADER_VALUE | 5 | Reading the value associated with a header field. |
HEADER_VALUE_ALMOST_DONE | 6 | Found CR at the end of a header value, expecting LF. |
HEADERS_ALMOST_DONE | 7 | Found CR after all headers, expecting LF before data. |
PART_DATA_START | 8 | Initializing the capture of part body data. |
PART_DATA | 9 | Reading the body content and searching for the next boundary. |
PART_DATA_END | 10 | Reached the end of a part's data. |
END_BOUNDARY | 11 | Matching the final closing boundary. |
END | 12 | Final state; terminal state of the parser. |
Sources: python_multipart/multipart.py:92-108, python_multipart/multipart.py:840-1090
State Transition Logic
The parser iterates through each byte in the input buffer, updating the self.state attribute. It uses an index variable to track progress within fixed strings like boundaries and a marks dictionary to record offsets for data callbacks.
The diagram above shows the high-level flow of the MultipartState machine as it processes parts.
Sources: python_multipart/multipart.py:839-1090
Querystring State Machine
The QuerystringParser handles application/x-www-form-urlencoded data using a simpler three-state machine. It alternates between identifying field names and their corresponding values.
State Definitions
The QuerystringState enumeration tracks the parser's position relative to separators (& or ;) and value assignments (=):
| State | Value | Description |
|---|---|---|
BEFORE_FIELD | 0 | Initial state or state between field pairs. |
FIELD_NAME | 1 | Currently reading the key portion of the pair. |
FIELD_DATA | 2 | Currently reading the value portion of the pair. |
Sources: python_multipart/multipart.py:82-89
Logic and Error Handling
The parser transitions from FIELD_NAME to FIELD_DATA upon encountering an equals sign (=). If strict_parsing is enabled, the parser will raise a QuerystringParseError if a field name is encountered without a following value assignment.
The flow shows how the parser switches between keys and values in a standard URL-encoded string.
Sources: python_multipart/multipart.py:688-780, tests/test_multipart.py:441-470
Internal Tracking and Data Buffering
The state machine relies on several internal variables to manage state transitions across multiple write() calls:
self.index: Tracks the current position within the boundary string duringMultipartState.PART_DATAorSTART_BOUNDARY.self.marks: A dictionary storing the starting index of the current segment (e.g.,header_value,part_data) within the current data chunk.self.flags: Bitwise flags used to distinguish between a standard part boundary (FLAG_PART_BOUNDARY) and the final terminal boundary (FLAG_LAST_BOUNDARY).self._current_header_size: Tracks the size of the current header line to enforcemax_header_sizelimits.
Sources: python_multipart/multipart.py:110-111, python_multipart/multipart.py:817-837, python_multipart/multipart.py:853-863
Header Limit States
Recent updates introduced states and counters to prevent resource exhaustion attacks via oversized headers. The parser tracks _current_header_count and _current_header_size during header parsing states.
Sources: CHANGELOG.md:12-14, python_multipart/multipart.py:830-834
Octet Stream Handling
While the OctetStreamParser does not use an IntEnum for its states, it maintains a binary _started flag. This acts as a simple two-state machine:
- Unstarted: The
on_startcallback has not been triggered. - Started: The
on_startcallback has fired, and all subsequent data is passed toon_datauntilfinalize()is called.
Sources: python_multipart/multipart.py:594-610
Conclusion
The use of discrete parsing states allows python-multipart to maintain high performance and a low memory footprint. By treating the incoming data as a stream of bytes and transitioning through the MultipartState or QuerystringState machines, the library provides a robust mechanism for handling complex HTTP payloads in a non-blocking manner.
Sources: python_multipart/multipart.py:1141-1180, README.md:10-14