Skip to content

Commit a5b6974

Browse files
committed
guard the remaining writers against re-entry while packing
pack_ext_type, pack_array_header and pack_map_header also append to pk.buf, so calling any of them from default under an outer pack() let autoreset drain pk.length and silently truncate the outer output instead of raising. check _packing in those three as well.
1 parent 67f43ae commit a5b6974

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

‎msgpack/_packer.pyx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ cdef class Packer:
297297
@cython.critical_section
298298
def pack_ext_type(self, typecode, data):
299299
self._check_exports()
300+
self._check_packing()
300301
if len(data) > ITEM_LIMIT:
301302
raise ValueError("ext data too large")
302303
msgpack_pack_ext(&self.pk, typecode, len(data))
@@ -309,6 +310,7 @@ cdef class Packer:
309310
@cython.critical_section
310311
def pack_array_header(self, long long size):
311312
self._check_exports()
313+
self._check_packing()
312314
if size < 0:
313315
raise ValueError("array size must be non-negative")
314316
if size > ITEM_LIMIT:
@@ -322,6 +324,7 @@ cdef class Packer:
322324
@cython.critical_section
323325
def pack_map_header(self, long long size):
324326
self._check_exports()
327+
self._check_packing()
325328
if size < 0:
326329
raise ValueError("map size must be non-negative")
327330
if size > ITEM_LIMIT:

‎test/test_buffer.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,3 +73,31 @@ def pack():
7373
with raises(RuntimeError):
7474
packer.pack([b"A" * 512, pack])
7575
assert packer.pack([1, 2]) == b"\x92\x01\x02"
76+
77+
78+
@mark.skipif(
79+
Packer.__module__ == "msgpack.fallback",
80+
reason="reentrant guard is implemented in C extension only",
81+
)
82+
@mark.parametrize(
83+
"reenter",
84+
[
85+
lambda packer: packer.pack(1),
86+
lambda packer: packer.pack_map_pairs([(1, 2)]),
87+
lambda packer: packer.pack_ext_type(1, b"ext"),
88+
lambda packer: packer.pack_array_header(2),
89+
lambda packer: packer.pack_map_header(1),
90+
],
91+
)
92+
def test_packer_reentrant_writers(reenter):
93+
# every writer that appends to pk.buf must refuse to run under an outer
94+
# pack(), otherwise autoreset drains pk.length and the outer output is
95+
# silently truncated instead of raising
96+
def default(o):
97+
reenter(packer)
98+
return b"ok"
99+
100+
packer = Packer(default=default, buf_size=1024)
101+
with raises(RuntimeError):
102+
packer.pack([1, object(), 2])
103+
assert packer.pack([1, 2]) == b"\x92\x01\x02"

0 commit comments

Comments
 (0)