Skip to content

Commit

Permalink
Handle messages containing only end boundary, fixes #38
Browse files Browse the repository at this point in the history
  • Loading branch information
jhnstrk committed Apr 23, 2024
1 parent 8b85d35 commit 2ace5c0
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 3 deletions.
23 changes: 20 additions & 3 deletions multipart/multipart.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,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 @@ -1105,7 +1106,10 @@ def data_callback(name: str, remaining: bool = False) -> None:
# 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 @@ -1390,6 +1394,18 @@ def data_callback(name: str, remaining: bool = False) -> None:
# 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:
# Do nothing and just consume a byte in the end state.
if c not in (CR, LF):
Expand Down Expand Up @@ -1689,7 +1705,8 @@ def on_headers_finished() -> None:

def _on_end() -> None:
nonlocal writer
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 2ace5c0

Please sign in to comment.