Skip to content

Do not fail silently when unpacking large messages #504

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions msgpack/_unpacker.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -441,12 +441,17 @@ cdef class Unpacker(object):
self.buf_tail = tail + _buf_len

cdef read_from_file(self):
current_size = self.buf_tail - self.buf_head
next_bytes = self.file_like_read(
min(self.read_size,
self.max_buffer_size - (self.buf_tail - self.buf_head)
))
min(self.read_size, self.max_buffer_size - current_size + 1)
)
if next_bytes:
self.append_buffer(PyBytes_AsString(next_bytes), PyBytes_Size(next_bytes))
next_bytes_size = PyBytes_Size(next_bytes)
if next_bytes_size + current_size > self.max_buffer_size:
raise ValueError(
"object exceeds max_buffer_size(%s)" % self.max_buffer_size
)
self.append_buffer(PyBytes_AsString(next_bytes), next_bytes_size)
else:
self.file_like = None

Expand Down
19 changes: 18 additions & 1 deletion test/test_unpack.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from io import BytesIO
import sys
from msgpack import Unpacker, packb, OutOfData, ExtType
from msgpack import Unpacker, pack, packb, OutOfData, ExtType
from pytest import raises, mark

try:
Expand Down Expand Up @@ -90,3 +90,20 @@ def test_unpacker_tell_read_bytes():
assert obj == unp
assert pos == unpacker.tell()
assert unpacker.read_bytes(n) == raw


def test_unpacker_raise_max_buffer_size():
max_buffer_size = 1024
small_value = b"a" * max_buffer_size

f = BytesIO()
pack(small_value, f)
f.seek(0)
assert list(Unpacker(f, max_buffer_size=max_buffer_size)) == [small_value]

large_value = b"a" * (max_buffer_size + 1)
f = BytesIO()
pack(large_value, f)
f.seek(0)
with raises(ValueError):
list(Unpacker(f, max_buffer_size=max_buffer_size))