Skip to content

Commit

Permalink
Handle messages containing only end boundary, fixes #38 (#142)
Browse files Browse the repository at this point in the history
  • Loading branch information
jhnstrk authored Dec 11, 2024
1 parent f1c5a28 commit 04d3cf5
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 4 deletions.
24 changes: 20 additions & 4 deletions python_multipart/multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ class MultipartState(IntEnum):
PART_DATA_START = 8
PART_DATA = 9
PART_DATA_END = 10
END = 11
END_BOUNDARY = 11
END = 12


# Flags for the multipart parser.
Expand Down Expand Up @@ -1119,7 +1120,10 @@ def data_callback(name: CallbackName, end_i: int, remaining: bool = False) -> No
# Check to ensure that the last 2 characters in our boundary
# are CRLF.
if index == len(boundary) - 2:
if c != CR:
if c == HYPHEN:
# Potential empty message.
state = MultipartState.END_BOUNDARY
elif c != CR:
# Error!
msg = "Did not find CR at end of boundary (%d)" % (i,)
self.logger.warning(msg)
Expand Down Expand Up @@ -1396,6 +1400,18 @@ def data_callback(name: CallbackName, end_i: int, remaining: bool = False) -> No
# the start of the boundary itself.
i -= 1

elif state == MultipartState.END_BOUNDARY:
if index == len(boundary) - 2 + 1:
if c != HYPHEN:
msg = "Did not find - at end of boundary (%d)" % (i,)
self.logger.warning(msg)
e = MultipartParseError(msg)
e.offset = i
raise e
index += 1
self.callback("end")
state = MultipartState.END

elif state == MultipartState.END:
# Don't do anything if chunk ends with CRLF.
if c == CR and i + 1 < length and data[i + 1] == LF:
Expand Down Expand Up @@ -1707,8 +1723,8 @@ def on_headers_finished() -> None:

def _on_end() -> None:
nonlocal writer
assert writer is not None
writer.finalize()
if writer is not None:
writer.finalize()
if self.on_end is not None:
self.on_end()

Expand Down
1 change: 1 addition & 0 deletions tests/test_data/http/empty_message.http
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
----boundary--
2 changes: 2 additions & 0 deletions tests/test_data/http/empty_message.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
boundary: --boundary
expected: []
1 change: 1 addition & 0 deletions tests/test_data/http/empty_message_with_bad_end.http
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
----boundary-X
3 changes: 3 additions & 0 deletions tests/test_data/http/empty_message_with_bad_end.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
boundary: --boundary
expected:
error: 13

0 comments on commit 04d3cf5

Please sign in to comment.