Debian Codegraph @

msgpack/_unpacker.pyx

raw
1 from cpython cimport *
2 cdef extern from "Python.h":
3 ctypedef struct PyObject
4 object PyMemoryView_GetContiguous(object obj, int buffertype, char order)
5
6 from libc.stdlib cimport *
7 from libc.string cimport *
8 from libc.limits cimport *
9 from libc.stdint cimport uint64_t
10
11 from .exceptions import (
12 BufferFull,
13 OutOfData,
14 ExtraData,
15 FormatError,
16 StackError,
17 )
18 from .ext import ExtType, Timestamp
19
20 cdef object giga = 1_000_000_000
21
22
23 cdef extern from "unpack.h":
24 ctypedef struct msgpack_user:
25 bint use_list
26 bint raw
27 bint has_pairs_hook # call object_hook with k-v pairs
28 bint strict_map_key
29 int timestamp
30 PyObject* object_hook
31 PyObject* list_hook
32 PyObject* ext_hook
33 PyObject* timestamp_t
34 PyObject *giga;
35 PyObject *utc;
36 const char *unicode_errors
37 Py_ssize_t max_str_len
38 Py_ssize_t max_bin_len
39 Py_ssize_t max_array_len
40 Py_ssize_t max_map_len
41 Py_ssize_t max_ext_len
42
43 ctypedef struct unpack_context:
44 msgpack_user user
45 PyObject* obj
46 Py_ssize_t count
47
48 ctypedef int (*execute_fn)(unpack_context* ctx, const char* data,
49 Py_ssize_t len, Py_ssize_t* off) except? -1
50 execute_fn unpack_construct
51 execute_fn unpack_skip
52 execute_fn read_array_header
53 execute_fn read_map_header
54
55 void unpack_init(unpack_context* ctx)
56 object unpack_data(unpack_context* ctx)
57 void unpack_clear(unpack_context* ctx)
58
59 cdef inline init_ctx(unpack_context *ctx,
60 object object_hook, object object_pairs_hook,
61 object list_hook, object ext_hook,
62 bint use_list, bint raw, int timestamp,
63 bint strict_map_key,
64 const char* unicode_errors,
65 Py_ssize_t max_str_len, Py_ssize_t max_bin_len,
66 Py_ssize_t max_array_len, Py_ssize_t max_map_len,
67 Py_ssize_t max_ext_len):
68 unpack_init(ctx)
69 ctx.user.use_list = use_list
70 ctx.user.raw = raw
71 ctx.user.strict_map_key = strict_map_key
72 ctx.user.object_hook = ctx.user.list_hook = <PyObject*>NULL
73 ctx.user.max_str_len = max_str_len
74 ctx.user.max_bin_len = max_bin_len
75 ctx.user.max_array_len = max_array_len
76 ctx.user.max_map_len = max_map_len
77 ctx.user.max_ext_len = max_ext_len
78
79 if object_hook is not None and object_pairs_hook is not None:
80 raise TypeError("object_pairs_hook and object_hook are mutually exclusive.")
81
82 if object_hook is not None:
83 if not PyCallable_Check(object_hook):
84 raise TypeError("object_hook must be a callable.")
85 ctx.user.object_hook = <PyObject*>object_hook
86
87 if object_pairs_hook is None:
88 ctx.user.has_pairs_hook = False
89 else:
90 if not PyCallable_Check(object_pairs_hook):
91 raise TypeError("object_pairs_hook must be a callable.")
92 ctx.user.object_hook = <PyObject*>object_pairs_hook
93 ctx.user.has_pairs_hook = True
94
95 if list_hook is not None:
96 if not PyCallable_Check(list_hook):
97 raise TypeError("list_hook must be a callable.")
98 ctx.user.list_hook = <PyObject*>list_hook
99
100 if ext_hook is not None:
101 if not PyCallable_Check(ext_hook):
102 raise TypeError("ext_hook must be a callable.")
103 ctx.user.ext_hook = <PyObject*>ext_hook
104
105 if timestamp < 0 or 3 < timestamp:
106 raise ValueError("timestamp must be 0..3")
107
108 # Add Timestamp type to the user object so it may be used in unpack.h
109 ctx.user.timestamp = timestamp
110 ctx.user.timestamp_t = <PyObject*>Timestamp
111 ctx.user.giga = <PyObject*>giga
112 ctx.user.utc = <PyObject*>utc
113 ctx.user.unicode_errors = unicode_errors
114
115 def default_read_extended_type(typecode, data):
116 raise NotImplementedError("Cannot decode extended type with typecode=%d" % typecode)
117
118 cdef inline int get_data_from_buffer(object obj,
119 Py_buffer *view,
120 char **buf,
121 Py_ssize_t *buffer_len) except 0:
122 cdef object contiguous
123 cdef Py_buffer tmp
124 if PyObject_GetBuffer(obj, view, PyBUF_FULL_RO) == -1:
125 raise
126 if view.itemsize != 1:
127 PyBuffer_Release(view)
128 raise BufferError("cannot unpack from multi-byte object")
129 if PyBuffer_IsContiguous(view, b'A') == 0:
130 PyBuffer_Release(view)
131 # create a contiguous copy and get buffer
132 contiguous = PyMemoryView_GetContiguous(obj, PyBUF_READ, b'C')
133 if PyObject_GetBuffer(contiguous, view, PyBUF_SIMPLE) == -1:
134 raise
135
136 buffer_len[0] = view.len
137 buf[0] = <char*> view.buf
138 return 1
139
140
141 def unpackb(object packed, *, object object_hook=None, object list_hook=None,
142 bint use_list=True, bint raw=False, int timestamp=0, bint strict_map_key=True,
143 unicode_errors=None,
144 object_pairs_hook=None, ext_hook=ExtType,
145 Py_ssize_t max_str_len=-1,
146 Py_ssize_t max_bin_len=-1,
147 Py_ssize_t max_array_len=-1,
148 Py_ssize_t max_map_len=-1,
149 Py_ssize_t max_ext_len=-1):
150 """
151 Unpack packed_bytes to object. Returns an unpacked object.
152
153 Raises ``ExtraData`` when *packed* contains extra bytes.
154 Raises ``ValueError`` when *packed* is incomplete.
155 Raises ``FormatError`` when *packed* is not valid msgpack.
156 Raises ``StackError`` when *packed* contains too nested.
157 Other exceptions can be raised during unpacking.
158
159 See :class:`Unpacker` for options.
160
161 *max_xxx_len* options are configured automatically from ``len(packed)``.
162 """
163 cdef unpack_context ctx
164 cdef Py_ssize_t off = 0
165 cdef int ret
166
167 cdef Py_buffer view
168 cdef char* buf = NULL
169 cdef Py_ssize_t buf_len
170 cdef const char* cerr = NULL
171
172 if unicode_errors is not None:
173 cerr = unicode_errors
174
175 get_data_from_buffer(packed, &view, &buf, &buf_len)
176
177 if max_str_len == -1:
178 max_str_len = buf_len
179 if max_bin_len == -1:
180 max_bin_len = buf_len
181 if max_array_len == -1:
182 max_array_len = buf_len
183 if max_map_len == -1:
184 max_map_len = buf_len//2
185 if max_ext_len == -1:
186 max_ext_len = buf_len
187
188 try:
189 init_ctx(&ctx, object_hook, object_pairs_hook, list_hook, ext_hook,
190 use_list, raw, timestamp, strict_map_key, cerr,
191 max_str_len, max_bin_len, max_array_len, max_map_len, max_ext_len)
192 ret = unpack_construct(&ctx, buf, buf_len, &off)
193 finally:
194 PyBuffer_Release(&view);
195
196 if ret == 1:
197 obj = unpack_data(&ctx)
198 if off < buf_len:
199 raise ExtraData(obj, PyBytes_FromStringAndSize(buf+off, buf_len-off))
200 return obj
201
202 unpack_clear(&ctx)
203 if ret == 0:
204 raise ValueError("Unpack failed: incomplete input")
205 elif ret == -2:
206 raise FormatError
207 elif ret == -3:
208 raise StackError
209 elif PyErr_Occurred():
210 raise
211 else:
212 raise ValueError("Unpack failed: error = %d" % (ret,))
213
214
215 cdef class Unpacker:
216 """Streaming unpacker.
217
218 Arguments:
219
220 :param file_like:
221 File-like object having `.read(n)` method.
222 If specified, unpacker reads serialized data from it and `.feed()` is not usable.
223
224 :param int read_size:
225 Used as `file_like.read(read_size)`. (default: `min(16*1024, max_buffer_size)`)
226
227 :param bool use_list:
228 If true, unpack msgpack array to Python list.
229 Otherwise, unpack to Python tuple. (default: True)
230
231 :param bool raw:
232 If true, unpack msgpack raw to Python bytes.
233 Otherwise, unpack to Python str by decoding with UTF-8 encoding (default).
234
235 :param int timestamp:
236 Control how timestamp type is unpacked:
237
238 0 - Timestamp
239 1 - float (Seconds from the EPOCH)
240 2 - int (Nanoseconds from the EPOCH)
241 3 - datetime.datetime (UTC).
242
243 :param bool strict_map_key:
244 If true (default), only str or bytes are accepted for map (dict) keys.
245
246 :param object_hook:
247 When specified, it should be callable.
248 Unpacker calls it with a dict argument after unpacking msgpack map.
249 (See also simplejson)
250
251 :param object_pairs_hook:
252 When specified, it should be callable.
253 Unpacker calls it with a list of key-value pairs after unpacking msgpack map.
254 (See also simplejson)
255
256 :param str unicode_errors:
257 The error handler for decoding unicode. (default: 'strict')
258 This option should be used only when you have msgpack data which
259 contains invalid UTF-8 string.
260
261 :param int max_buffer_size:
262 Limits size of data waiting unpacked. 0 means 2**32-1.
263 The default value is 100*1024*1024 (100MiB).
264 Raises `BufferFull` exception when it is insufficient.
265 You should set this parameter when unpacking data from untrusted source.
266
267 :param int max_str_len:
268 Deprecated, use *max_buffer_size* instead.
269 Limits max length of str. (default: max_buffer_size)
270
271 :param int max_bin_len:
272 Deprecated, use *max_buffer_size* instead.
273 Limits max length of bin. (default: max_buffer_size)
274
275 :param int max_array_len:
276 Limits max length of array.
277 (default: max_buffer_size)
278
279 :param int max_map_len:
280 Limits max length of map.
281 (default: max_buffer_size//2)
282
283 :param int max_ext_len:
284 Deprecated, use *max_buffer_size* instead.
285 Limits max size of ext type. (default: max_buffer_size)
286
287 Example of streaming deserialize from file-like object::
288
289 unpacker = Unpacker(file_like)
290 for o in unpacker:
291 process(o)
292
293 Example of streaming deserialize from socket::
294
295 unpacker = Unpacker()
296 while True:
297 buf = sock.recv(1024**2)
298 if not buf:
299 break
300 unpacker.feed(buf)
301 for o in unpacker:
302 process(o)
303
304 Raises ``ExtraData`` when *packed* contains extra bytes.
305 Raises ``OutOfData`` when *packed* is incomplete.
306 Raises ``FormatError`` when *packed* is not valid msgpack.
307 Raises ``StackError`` when *packed* contains too nested.
308 Other exceptions can be raised during unpacking.
309 """
310 cdef unpack_context ctx
311 cdef char* buf
312 cdef Py_ssize_t buf_size, buf_head, buf_tail
313 cdef object file_like
314 cdef object file_like_read
315 cdef Py_ssize_t read_size
316 # To maintain refcnt.
317 cdef object object_hook, object_pairs_hook, list_hook, ext_hook
318 cdef object unicode_errors
319 cdef Py_ssize_t max_buffer_size
320 cdef uint64_t stream_offset
321
322 def __dealloc__(self):
323 unpack_clear(&self.ctx)
324 PyMem_Free(self.buf)
325 self.buf = NULL
326
327 @cython.critical_section
328 def __init__(self, file_like=None, *, Py_ssize_t read_size=0,
329 bint use_list=True, bint raw=False, int timestamp=0, bint strict_map_key=True,
330 object object_hook=None, object object_pairs_hook=None, object list_hook=None,
331 unicode_errors=None, Py_ssize_t max_buffer_size=100*1024*1024,
332 object ext_hook=ExtType,
333 Py_ssize_t max_str_len=-1,
334 Py_ssize_t max_bin_len=-1,
335 Py_ssize_t max_array_len=-1,
336 Py_ssize_t max_map_len=-1,
337 Py_ssize_t max_ext_len=-1):
338 cdef const char *cerr=NULL
339
340 unpack_clear(&self.ctx)
341 unpack_init(&self.ctx)
342 if self.buf != NULL:
343 PyMem_Free(self.buf)
344 self.buf = NULL
345
346 self.object_hook = object_hook
347 self.object_pairs_hook = object_pairs_hook
348 self.list_hook = list_hook
349 self.ext_hook = ext_hook
350
351 self.file_like = file_like
352 if file_like:
353 self.file_like_read = file_like.read
354 if not PyCallable_Check(self.file_like_read):
355 raise TypeError("`file_like.read` must be a callable.")
356
357 if not max_buffer_size:
358 max_buffer_size = INT_MAX
359 if max_str_len == -1:
360 max_str_len = max_buffer_size
361 if max_bin_len == -1:
362 max_bin_len = max_buffer_size
363 if max_array_len == -1:
364 max_array_len = max_buffer_size
365 if max_map_len == -1:
366 max_map_len = max_buffer_size//2
367 if max_ext_len == -1:
368 max_ext_len = max_buffer_size
369
370 if read_size > max_buffer_size:
371 raise ValueError("read_size should be less or equal to max_buffer_size")
372 if not read_size:
373 read_size = min(max_buffer_size, 1024**2)
374
375 self.max_buffer_size = max_buffer_size
376 self.read_size = read_size
377 self.buf = <char*>PyMem_Malloc(read_size)
378 if self.buf == NULL:
379 raise MemoryError("Unable to allocate internal buffer.")
380 self.buf_size = read_size
381 self.buf_head = 0
382 self.buf_tail = 0
383 self.stream_offset = 0
384
385 if unicode_errors is not None:
386 self.unicode_errors = unicode_errors
387 cerr = unicode_errors
388
389 init_ctx(&self.ctx, object_hook, object_pairs_hook, list_hook,
390 ext_hook, use_list, raw, timestamp, strict_map_key, cerr,
391 max_str_len, max_bin_len, max_array_len,
392 max_map_len, max_ext_len)
393
394 @cython.critical_section
395 def feed(self, object next_bytes):
396 """Append `next_bytes` to internal buffer."""
397 cdef Py_buffer pybuff
398 cdef char* buf
399 cdef Py_ssize_t buf_len
400
401 if self.file_like is not None:
402 raise AssertionError(
403 "unpacker.feed() is not be able to use with `file_like`.")
404
405 get_data_from_buffer(next_bytes, &pybuff, &buf, &buf_len)
406 try:
407 self.append_buffer(buf, buf_len)
408 finally:
409 PyBuffer_Release(&pybuff)
410
411 cdef append_buffer(self, void* _buf, Py_ssize_t _buf_len):
412 cdef:
413 char* buf = self.buf
414 char* new_buf
415 Py_ssize_t head = self.buf_head
416 Py_ssize_t tail = self.buf_tail
417 Py_ssize_t buf_size = self.buf_size
418 Py_ssize_t new_size
419
420 if tail + _buf_len > buf_size:
421 if ((tail - head) + _buf_len) <= buf_size:
422 # move to front.
423 memmove(buf, buf + head, tail - head)
424 tail -= head
425 head = 0
426 else:
427 # expand buffer.
428 new_size = (tail-head) + _buf_len
429 if new_size > self.max_buffer_size:
430 raise BufferFull
431 new_size = min(new_size*2, self.max_buffer_size)
432 new_buf = <char*>PyMem_Malloc(new_size)
433 if new_buf == NULL:
434 # self.buf still holds old buffer and will be freed during
435 # obj destruction
436 raise MemoryError("Unable to enlarge internal buffer.")
437 memcpy(new_buf, buf + head, tail - head)
438 PyMem_Free(buf)
439
440 buf = new_buf
441 buf_size = new_size
442 tail -= head
443 head = 0
444
445 memcpy(buf + tail, <char*>(_buf), _buf_len)
446 self.buf = buf
447 self.buf_head = head
448 self.buf_size = buf_size
449 self.buf_tail = tail + _buf_len
450
451 cdef int read_from_file(self) except -1:
452 cdef Py_ssize_t remains = self.max_buffer_size - (self.buf_tail - self.buf_head)
453 if remains <= 0:
454 raise BufferFull
455
456 next_bytes = self.file_like_read(min(self.read_size, remains))
457 if next_bytes:
458 self.append_buffer(PyBytes_AsString(next_bytes), PyBytes_Size(next_bytes))
459 else:
460 self.file_like = None
461 return 0
462
463 cdef object _unpack(self, execute_fn execute, bint iter=0):
464 cdef int ret
465 cdef object obj
466 cdef Py_ssize_t prev_head
467
468 while 1:
469 prev_head = self.buf_head
470 if prev_head < self.buf_tail:
471 ret = execute(&self.ctx, self.buf, self.buf_tail, &self.buf_head)
472 self.stream_offset += self.buf_head - prev_head
473 else:
474 ret = 0
475
476 if ret == 1:
477 obj = unpack_data(&self.ctx)
478 unpack_init(&self.ctx)
479 return obj
480 if ret == 0:
481 if self.file_like is not None:
482 self.read_from_file()
483 continue
484 if iter:
485 raise StopIteration("No more data to unpack.")
486 else:
487 raise OutOfData("No more data to unpack.")
488
489 unpack_clear(&self.ctx)
490 if ret == -2:
491 raise FormatError
492 elif ret == -3:
493 raise StackError
494 elif PyErr_Occurred():
495 raise
496 else:
497 raise ValueError("Unpack failed: error = %d" % (ret,))
498
499 @cython.critical_section
500 def read_bytes(self, Py_ssize_t nbytes):
501 """Read a specified number of raw bytes from the stream"""
502 cdef Py_ssize_t nread
503 nread = min(self.buf_tail - self.buf_head, nbytes)
504 ret = PyBytes_FromStringAndSize(self.buf + self.buf_head, nread)
505 self.buf_head += nread
506 if nread < nbytes and self.file_like is not None:
507 ret += self.file_like.read(nbytes - nread)
508 nread = len(ret)
509 self.stream_offset += nread
510 return ret
511
512 @cython.critical_section
513 def unpack(self):
514 """Unpack one object
515
516 Raises `OutOfData` when there are no more bytes to unpack.
517 """
518 return self._unpack(unpack_construct)
519
520 @cython.critical_section
521 def skip(self):
522 """Read and ignore one object, returning None
523
524 Raises `OutOfData` when there are no more bytes to unpack.
525 """
526 return self._unpack(unpack_skip)
527
528 @cython.critical_section
529 def read_array_header(self):
530 """assuming the next object is an array, return its size n, such that
531 the next n unpack() calls will iterate over its contents.
532
533 Raises `OutOfData` when there are no more bytes to unpack.
534 """
535 return self._unpack(read_array_header)
536
537 @cython.critical_section
538 def read_map_header(self):
539 """assuming the next object is a map, return its size n, such that the
540 next n * 2 unpack() calls will iterate over its key-value pairs.
541
542 Raises `OutOfData` when there are no more bytes to unpack.
543 """
544 return self._unpack(read_map_header)
545
546 @cython.critical_section
547 def tell(self):
548 """Returns the current position of the Unpacker in bytes, i.e., the
549 number of bytes that were read from the input, also the starting
550 position of the next object.
551 """
552 return self.stream_offset
553
554 def __iter__(self):
555 return self
556
557 @cython.critical_section
558 def __next__(self):
559 return self._unpack(unpack_construct, 1)
560
561 # for debug.
562 #def _buf(self):
563 # return PyString_FromStringAndSize(self.buf, self.buf_tail)
564
565 #def _off(self):
566 # return self.buf_head