Skip to content

Commit

Permalink
Handle messages containing only end boundary, fixes Kludex#38
Browse files Browse the repository at this point in the history
  • Loading branch information
jhnstrk committed Oct 28, 2024
1 parent 8764067 commit fcd5d4d
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 @@ -1120,7 +1121,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 @@ -1397,6 +1401,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:
# Do nothing and just consume a byte in the end state.
if c not in (CR, LF):
Expand Down Expand Up @@ -1703,8 +1719,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 fcd5d4d

Please sign in to comment.