Debian Codegraph @

source/cbor.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include "cbor.h"
6
7 #include <aws/common/cbor.h>
8
9 /* Maximum nesting depth for recursive CBOR decoding to prevent stack exhaustion */
10 static const size_t s_cbor_max_decode_depth = 128;
11
12 /*******************************************************************************
13 * ENCODE
14 ******************************************************************************/
15
16 static const char *s_capsule_name_cbor_encoder = "aws_cbor_encoder";
17
18 static struct aws_cbor_encoder *s_cbor_encoder_from_capsule(PyObject *py_capsule) {
19 return PyCapsule_GetPointer(py_capsule, s_capsule_name_cbor_encoder);
20 }
21
22 /* Runs when GC destroys the capsule */
23 static void s_cbor_encoder_capsule_destructor(PyObject *py_capsule) {
24 struct aws_cbor_encoder *encoder = s_cbor_encoder_from_capsule(py_capsule);
25 if (encoder) {
26 aws_cbor_encoder_destroy(encoder);
27 }
28 }
29
30 PyObject *aws_py_cbor_encoder_new(PyObject *self, PyObject *args) {
31 (void)self;
32 (void)args;
33 struct aws_cbor_encoder *encoder = aws_cbor_encoder_new(aws_py_get_allocator());
34 AWS_ASSERT(encoder != NULL);
35 PyObject *py_capsule = PyCapsule_New(encoder, s_capsule_name_cbor_encoder, s_cbor_encoder_capsule_destructor);
36 if (!py_capsule) {
37 aws_cbor_encoder_destroy(encoder);
38 return NULL;
39 }
40 return py_capsule;
41 }
42
43 PyObject *aws_py_cbor_encoder_get_encoded_data(PyObject *self, PyObject *args) {
44 (void)self;
45 PyObject *py_capsule = NULL;
46 if (!PyArg_ParseTuple(args, "O", &py_capsule)) {
47 return NULL;
48 }
49 struct aws_cbor_encoder *encoder = s_cbor_encoder_from_capsule(py_capsule);
50 if (!encoder) {
51 return NULL;
52 }
53 struct aws_byte_cursor encoded_data = aws_cbor_encoder_get_encoded_data(encoder);
54 return PyBytes_FromStringAndSize((const char *)encoded_data.ptr, encoded_data.len);
55 }
56
57 #define S_ENCODER_WRITE_PYOBJECT(ctype, py_conversion, field) \
58 static PyObject *s_cbor_encoder_write_pyobject_as_##field(struct aws_cbor_encoder *encoder, PyObject *py_object) { \
59 ctype data = py_conversion(py_object); \
60 if (PyErr_Occurred()) { \
61 /* Add context to make debugging easier */ \
62 PyErr_Format(PyExc_TypeError, "Failed to convert Python object to " #ctype " for CBOR " #field); \
63 return NULL; \
64 } \
65 aws_cbor_encoder_write_##field(encoder, data); \
66 Py_RETURN_NONE; \
67 }
68
69 S_ENCODER_WRITE_PYOBJECT(uint64_t, PyLong_AsUnsignedLongLong, uint)
70 S_ENCODER_WRITE_PYOBJECT(uint64_t, PyLong_AsUnsignedLongLong, negint)
71 S_ENCODER_WRITE_PYOBJECT(double, PyFloat_AsDouble, float)
72 S_ENCODER_WRITE_PYOBJECT(struct aws_byte_cursor, aws_byte_cursor_from_pybytes, bytes)
73 S_ENCODER_WRITE_PYOBJECT(struct aws_byte_cursor, aws_byte_cursor_from_pyunicode, text)
74 S_ENCODER_WRITE_PYOBJECT(bool, PyObject_IsTrue, bool)
75
76 S_ENCODER_WRITE_PYOBJECT(uint64_t, PyLong_AsUnsignedLongLong, array_start)
77 S_ENCODER_WRITE_PYOBJECT(uint64_t, PyLong_AsUnsignedLongLong, map_start)
78 S_ENCODER_WRITE_PYOBJECT(uint64_t, PyLong_AsUnsignedLongLong, tag)
79
80 static PyObject *s_cbor_encoder_write_pyobject(struct aws_cbor_encoder *encoder, PyObject *py_object);
81
82 static PyObject *s_cbor_encoder_write_pylong(struct aws_cbor_encoder *encoder, PyObject *py_object) {
83 long val = 0;
84 int overflow = 0;
85
86 val = PyLong_AsLongAndOverflow(py_object, &overflow);
87 if (overflow == 0) {
88 if (val >= 0) {
89 aws_cbor_encoder_write_uint(encoder, (uint64_t)val);
90 } else {
91 uint64_t val_unsigned = (uint64_t)(-val) - 1;
92 aws_cbor_encoder_write_negint(encoder, val_unsigned);
93 }
94 } else if (overflow < 0) {
95 /**
96 * The py object is negative and too small.
97 * Convert the value to -1 - value in python to encode.
98 */
99 PyObject *abs_val = PyNumber_Negative(py_object);
100 if (!abs_val) {
101 return NULL;
102 }
103 PyObject *minus_one = PyLong_FromLong(1);
104 if (!minus_one) {
105 Py_DECREF(abs_val);
106 return NULL;
107 }
108 /* -value - 1 */
109 PyObject *result = PyNumber_Subtract(abs_val, minus_one);
110 Py_DECREF(abs_val);
111 Py_DECREF(minus_one);
112
113 if (!result) {
114 return NULL;
115 }
116 /* Convert to uint64_t and check for overflow */
117 uint64_t val_to_encode = PyLong_AsUnsignedLongLong(result);
118 Py_DECREF(result);
119 if (PyErr_Occurred()) {
120 /* Value is too large even for uint64_t */
121 PyErr_SetString(PyExc_OverflowError, "The integer is too large, BigNumber is not supported yet.");
122 return NULL;
123 }
124
125 aws_cbor_encoder_write_negint(encoder, val_to_encode);
126 } else {
127 uint64_t val_to_encode = PyLong_AsUnsignedLongLong(py_object);
128
129 if (PyErr_Occurred()) {
130 /* Value is too large for uint64_t */
131 PyErr_SetString(PyExc_OverflowError, "The integer is too large, BigNumber is not supported yet.");
132 return NULL;
133 }
134
135 aws_cbor_encoder_write_uint(encoder, val_to_encode);
136 }
137 Py_RETURN_NONE;
138 }
139
140 static PyObject *s_cbor_encoder_write_pylist(struct aws_cbor_encoder *encoder, PyObject *py_list) {
141 Py_ssize_t size = PyList_Size(py_list);
142 aws_cbor_encoder_write_array_start(encoder, (size_t)size);
143 for (Py_ssize_t i = 0; i < size; i++) {
144 PyObject *item = PyList_GetItem(py_list, i);
145 if (!item) {
146 PyErr_SetString(PyExc_RuntimeError, "Failed to get item from list");
147 return NULL;
148 }
149 PyObject *result = s_cbor_encoder_write_pyobject(encoder, item);
150 if (!result) {
151 // Error already set by s_cbor_encoder_write_pyobject
152 return NULL;
153 }
154 Py_DECREF(result);
155 }
156 Py_RETURN_NONE;
157 }
158
159 static PyObject *s_cbor_encoder_write_pydict(struct aws_cbor_encoder *encoder, PyObject *py_dict) {
160 Py_ssize_t size = PyDict_Size(py_dict);
161 aws_cbor_encoder_write_map_start(encoder, (size_t)size);
162 PyObject *key = NULL;
163 PyObject *value = NULL;
164 Py_ssize_t pos = 0;
165
166 /* Accessing the pydict without lock, since the cbor_decoder and encoder are not thread-safe. It's user's
167 * responsibility to not modifying the map from another thread. */
168 while (PyDict_Next(py_dict, &pos, &key, &value)) {
169 PyObject *key_result = s_cbor_encoder_write_pyobject(encoder, key);
170 if (!key_result) {
171 // Error already set by s_cbor_encoder_write_pyobject
172 return NULL;
173 }
174 Py_DECREF(key_result);
175
176 PyObject *value_result = s_cbor_encoder_write_pyobject(encoder, value);
177 if (!value_result) {
178 // Error already set by s_cbor_encoder_write_pyobject
179 return NULL;
180 }
181 Py_DECREF(value_result);
182 }
183 Py_RETURN_NONE;
184 }
185
186 static PyObject *s_cbor_encoder_write_pyobject(struct aws_cbor_encoder *encoder, PyObject *py_object) {
187
188 /**
189 * TODO: timestamp <-> datetime?? Decimal fraction <-> decimal??
190 */
191
192 /* Handle None first as it's a singleton, not a type */
193 if (py_object == Py_None) {
194 aws_cbor_encoder_write_null(encoder);
195 Py_RETURN_NONE;
196 }
197
198 /* Get type once for efficiency - PyObject_Type returns a new reference */
199 /* https://docs.python.org/3/c-api/structures.html#c.Py_TYPE is not a stable API until 3.14, so that we cannot use
200 * it. */
201 PyObject *type = PyObject_Type(py_object);
202 if (!type) {
203 return NULL;
204 }
205
206 PyObject *result = NULL;
207
208 /* Exact type matches first (no subclasses) */
209 if (type == (PyObject *)&PyLong_Type) {
210 result = s_cbor_encoder_write_pylong(encoder, py_object);
211 } else if (type == (PyObject *)&PyFloat_Type) {
212 result = s_cbor_encoder_write_pyobject_as_float(encoder, py_object);
213 } else if (type == (PyObject *)&PyBool_Type) {
214 result = s_cbor_encoder_write_pyobject_as_bool(encoder, py_object);
215 } else if (type == (PyObject *)&PyBytes_Type) {
216 result = s_cbor_encoder_write_pyobject_as_bytes(encoder, py_object);
217 } else if (PyType_IsSubtype((PyTypeObject *)type, &PyUnicode_Type)) {
218 /* Allow subclasses of `str` */
219 result = s_cbor_encoder_write_pyobject_as_text(encoder, py_object);
220 } else if (PyType_IsSubtype((PyTypeObject *)type, &PyList_Type)) {
221 /* Write py_list, allow subclasses of `list` */
222 result = s_cbor_encoder_write_pylist(encoder, py_object);
223 } else if (PyType_IsSubtype((PyTypeObject *)type, &PyDict_Type)) {
224 /* Write py_dict, allow subclasses of `dict` */
225 result = s_cbor_encoder_write_pydict(encoder, py_object);
226 } else {
227 /* Unsupported type */
228 PyErr_Format(PyExc_ValueError, "Not supported type %R", type);
229 }
230
231 /* Release the type reference */
232 Py_DECREF(type);
233 return result;
234 }
235
236 /*********************************** BINDINGS ***********************************************/
237
238 #define ENCODER_WRITE(field, encoder_fn) \
239 PyObject *aws_py_cbor_encoder_write_##field(PyObject *self, PyObject *args) { \
240 (void)self; \
241 PyObject *py_object; \
242 PyObject *py_capsule; \
243 if (!PyArg_ParseTuple(args, "OO", &py_capsule, &py_object)) { \
244 return NULL; \
245 } \
246 struct aws_cbor_encoder *encoder = s_cbor_encoder_from_capsule(py_capsule); \
247 if (!encoder) { \
248 return NULL; \
249 } \
250 return encoder_fn(encoder, py_object); \
251 }
252
253 ENCODER_WRITE(uint, s_cbor_encoder_write_pyobject_as_uint)
254 ENCODER_WRITE(negint, s_cbor_encoder_write_pyobject_as_negint)
255 ENCODER_WRITE(float, s_cbor_encoder_write_pyobject_as_float)
256 ENCODER_WRITE(bytes, s_cbor_encoder_write_pyobject_as_bytes)
257 ENCODER_WRITE(text, s_cbor_encoder_write_pyobject_as_text)
258 ENCODER_WRITE(bool, s_cbor_encoder_write_pyobject_as_bool)
259 ENCODER_WRITE(array_start, s_cbor_encoder_write_pyobject_as_array_start)
260 ENCODER_WRITE(map_start, s_cbor_encoder_write_pyobject_as_map_start)
261 ENCODER_WRITE(tag, s_cbor_encoder_write_pyobject_as_tag)
262 ENCODER_WRITE(py_list, s_cbor_encoder_write_pylist)
263 ENCODER_WRITE(py_dict, s_cbor_encoder_write_pydict)
264 ENCODER_WRITE(data_item, s_cbor_encoder_write_pyobject)
265
266 PyObject *aws_py_cbor_encoder_write_simple_types(PyObject *self, PyObject *args) {
267 (void)self;
268 PyObject *py_capsule = NULL;
269 Py_ssize_t type_enum = AWS_CBOR_TYPE_UNKNOWN;
270 if (!PyArg_ParseTuple(args, "On", &py_capsule, &type_enum)) {
271 return NULL;
272 }
273 struct aws_cbor_encoder *encoder = s_cbor_encoder_from_capsule(py_capsule);
274 if (!encoder) {
275 return NULL;
276 }
277 switch (type_enum) {
278 case AWS_CBOR_TYPE_NULL:
279 aws_cbor_encoder_write_null(encoder);
280 break;
281 case AWS_CBOR_TYPE_UNDEFINED:
282 aws_cbor_encoder_write_undefined(encoder);
283 break;
284 case AWS_CBOR_TYPE_INDEF_ARRAY_START:
285 aws_cbor_encoder_write_indef_array_start(encoder);
286 break;
287 case AWS_CBOR_TYPE_INDEF_MAP_START:
288 aws_cbor_encoder_write_indef_map_start(encoder);
289 break;
290 case AWS_CBOR_TYPE_INDEF_BYTES_START:
291 aws_cbor_encoder_write_indef_bytes_start(encoder);
292 break;
293 case AWS_CBOR_TYPE_INDEF_TEXT_START:
294 aws_cbor_encoder_write_indef_text_start(encoder);
295 break;
296 case AWS_CBOR_TYPE_BREAK:
297 aws_cbor_encoder_write_break(encoder);
298 break;
299 default:
300 PyErr_Format(PyExc_ValueError, "Not supported simple type");
301 return NULL;
302 }
303 Py_RETURN_NONE;
304 }
305
306 /*******************************************************************************
307 * DECODE
308 ******************************************************************************/
309
310 struct decoder_binding {
311 struct aws_cbor_decoder *native;
312
313 /* Encoder has simple lifetime, no async/multi-thread allowed. */
314 PyObject *self_py;
315
316 /* Current recursion depth for pop_next_data_item */
317 size_t current_depth;
318 };
319
320 static const char *s_capsule_name_cbor_decoder = "aws_cbor_decoder";
321
322 static struct aws_cbor_decoder *s_cbor_decoder_from_capsule(PyObject *py_capsule) {
323 struct decoder_binding *binding = PyCapsule_GetPointer(py_capsule, s_capsule_name_cbor_decoder);
324 if (!binding) {
325 return NULL;
326 }
327 return binding->native;
328 }
329 /* Runs when GC destroys the capsule */
330 static void s_cbor_decoder_capsule_destructor(PyObject *py_capsule) {
331 struct decoder_binding *binding = PyCapsule_GetPointer(py_capsule, s_capsule_name_cbor_decoder);
332 if (binding) {
333 aws_cbor_decoder_destroy(binding->native);
334 aws_mem_release(aws_py_get_allocator(), binding);
335 }
336 }
337
338 PyObject *aws_py_cbor_decoder_new(PyObject *self, PyObject *args) {
339 (void)self;
340 /* The python object will keep the src alive from python. */
341 PyObject *py_self = NULL;
342 struct aws_byte_cursor src = {0}; /* s# */
343
344 if (!PyArg_ParseTuple(args, "Os#", &py_self, &src.ptr, &src.len)) {
345 return NULL;
346 }
347 struct decoder_binding *binding = aws_mem_calloc(aws_py_get_allocator(), 1, sizeof(struct decoder_binding));
348 binding->native = aws_cbor_decoder_new(aws_py_get_allocator(), src);
349 AWS_ASSERT(binding->native != NULL);
350 PyObject *py_capsule = PyCapsule_New(binding, s_capsule_name_cbor_decoder, s_cbor_decoder_capsule_destructor);
351 if (!py_capsule) {
352 aws_cbor_decoder_destroy(binding->native);
353 aws_mem_release(aws_py_get_allocator(), binding);
354 return NULL;
355 }
356 /* The binding and the py_object have the same life time */
357 binding->self_py = py_self;
358 return py_capsule;
359 }
360
361 static struct aws_cbor_decoder *s_get_decoder_from_py_arg(PyObject *self, PyObject *args) {
362 (void)self;
363 PyObject *py_capsule = NULL;
364 if (!PyArg_ParseTuple(args, "O", &py_capsule)) {
365 return NULL;
366 }
367 return s_cbor_decoder_from_capsule(py_capsule);
368 }
369
370 #define S_POP_NEXT_TO_PYOBJECT(ctype, field, py_conversion) \
371 static PyObject *s_cbor_decoder_pop_next_##field##_to_pyobject(struct aws_cbor_decoder *decoder) { \
372 ctype out_val; \
373 if (aws_cbor_decoder_pop_next_##field(decoder, &out_val)) { \
374 return PyErr_AwsLastError(); \
375 } \
376 return py_conversion(out_val); \
377 }
378
379 #define S_POP_NEXT_TO_PYOBJECT_CURSOR(field, py_conversion) \
380 static PyObject *s_cbor_decoder_pop_next_##field##_to_pyobject(struct aws_cbor_decoder *decoder) { \
381 struct aws_byte_cursor out_val; \
382 if (aws_cbor_decoder_pop_next_##field(decoder, &out_val)) { \
383 return PyErr_AwsLastError(); \
384 } \
385 return py_conversion(&out_val); \
386 }
387
388 S_POP_NEXT_TO_PYOBJECT(uint64_t, unsigned_int_val, PyLong_FromUnsignedLongLong)
389 S_POP_NEXT_TO_PYOBJECT(uint64_t, negative_int_val, PyLong_FromUnsignedLongLong)
390 S_POP_NEXT_TO_PYOBJECT(double, float_val, PyFloat_FromDouble)
391 S_POP_NEXT_TO_PYOBJECT(bool, boolean_val, PyBool_FromLong)
392 S_POP_NEXT_TO_PYOBJECT_CURSOR(bytes_val, PyBytes_FromAwsByteCursor)
393 S_POP_NEXT_TO_PYOBJECT_CURSOR(text_val, PyUnicode_FromAwsByteCursor)
394 S_POP_NEXT_TO_PYOBJECT(uint64_t, array_start, PyLong_FromUnsignedLongLong)
395 S_POP_NEXT_TO_PYOBJECT(uint64_t, map_start, PyLong_FromUnsignedLongLong)
396 S_POP_NEXT_TO_PYOBJECT(uint64_t, tag_val, PyLong_FromUnsignedLongLong)
397
398 static PyObject *s_cbor_decoder_pop_next_data_item_to_pyobject(struct decoder_binding *binding);
399
400 /**
401 * helper to convert next data item to py_list
402 */
403 static PyObject *s_cbor_decoder_pop_next_data_item_to_py_list(struct decoder_binding *binding) {
404 struct aws_cbor_decoder *decoder = binding->native;
405 enum aws_cbor_type out_type = AWS_CBOR_TYPE_UNKNOWN;
406 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
407 return PyErr_AwsLastError();
408 }
409 PyObject *array = NULL;
410 PyObject *item = NULL;
411 switch (out_type) {
412 case AWS_CBOR_TYPE_ARRAY_START: {
413 uint64_t num_array_item = 0;
414 aws_cbor_decoder_pop_next_array_start(decoder, &num_array_item);
415 if (num_array_item > PY_SSIZE_T_MAX) {
416 PyErr_SetString(PyExc_OverflowError, "number of array is too large to fit.");
417 return NULL;
418 }
419 array = PyList_New((Py_ssize_t)num_array_item);
420 if (!array) {
421 return NULL;
422 }
423 for (size_t i = 0; i < num_array_item; ++i) {
424 item = s_cbor_decoder_pop_next_data_item_to_pyobject(binding);
425 if (!item) {
426 goto error;
427 }
428 PyList_SetItem(array, i, item); /* Steals reference to item */
429 }
430 return array;
431 }
432 case AWS_CBOR_TYPE_INDEF_ARRAY_START: {
433 array = PyList_New(0);
434 if (!array) {
435 return NULL;
436 }
437 /* Consume the inf array start */
438 aws_cbor_decoder_consume_next_single_element(decoder);
439 aws_cbor_decoder_peek_type(decoder, &out_type);
440 while (out_type != AWS_CBOR_TYPE_BREAK) {
441 item = s_cbor_decoder_pop_next_data_item_to_pyobject(binding);
442 if (!item) {
443 goto error;
444 }
445 if (PyList_Append(array, item) == -1) {
446 goto error;
447 }
448 /* Append will not steal the reference, deref here. */
449 Py_DECREF(item);
450 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
451 PyErr_AwsLastError();
452 goto error;
453 }
454 }
455 /* Consume the break element */
456 aws_cbor_decoder_consume_next_single_element(decoder);
457 return array;
458 }
459 default:
460 aws_raise_error(AWS_ERROR_CBOR_UNEXPECTED_TYPE);
461 return PyErr_AwsLastError();
462 }
463 error:
464 if (array) {
465 Py_DECREF(array);
466 }
467 return NULL;
468 }
469
470 /**
471 * helper to convert next data item to py_dict
472 */
473 static PyObject *s_cbor_decoder_pop_next_data_item_to_py_dict(struct decoder_binding *binding) {
474 struct aws_cbor_decoder *decoder = binding->native;
475 enum aws_cbor_type out_type = AWS_CBOR_TYPE_UNKNOWN;
476 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
477 return PyErr_AwsLastError();
478 }
479 PyObject *dict = NULL;
480 PyObject *key = NULL;
481 PyObject *value = NULL;
482 switch (out_type) {
483 case AWS_CBOR_TYPE_MAP_START: {
484 uint64_t num_item = 0;
485 aws_cbor_decoder_pop_next_map_start(decoder, &num_item);
486 if (num_item > PY_SSIZE_T_MAX) {
487 PyErr_SetString(PyExc_OverflowError, "number of dict is too large to fit.");
488 return NULL;
489 }
490 dict = PyDict_New();
491 if (!dict) {
492 return NULL;
493 }
494 for (size_t i = 0; i < num_item; ++i) {
495 key = s_cbor_decoder_pop_next_data_item_to_pyobject(binding);
496 value = s_cbor_decoder_pop_next_data_item_to_pyobject(binding);
497 if (!key || !value) {
498 goto error;
499 }
500 if (PyDict_SetItem(dict, key, value) == -1) {
501 goto error;
502 }
503 Py_DECREF(key);
504 Py_DECREF(value);
505 }
506 return dict;
507 }
508 case AWS_CBOR_TYPE_INDEF_MAP_START: {
509 dict = PyDict_New();
510 if (!dict) {
511 return NULL;
512 }
513 /* Consume the inf array start */
514 aws_cbor_decoder_consume_next_single_element(decoder);
515 aws_cbor_decoder_peek_type(decoder, &out_type);
516 while (out_type != AWS_CBOR_TYPE_BREAK) {
517 key = s_cbor_decoder_pop_next_data_item_to_pyobject(binding);
518 value = s_cbor_decoder_pop_next_data_item_to_pyobject(binding);
519 if (!key || !value) {
520 goto error;
521 }
522 if (PyDict_SetItem(dict, key, value) == -1) {
523 goto error;
524 }
525 Py_DECREF(key);
526 Py_DECREF(value);
527 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
528 PyErr_AwsLastError();
529 goto error;
530 }
531 }
532 /* Consume the break element */
533 aws_cbor_decoder_consume_next_single_element(decoder);
534 return dict;
535 }
536 default:
537 aws_raise_error(AWS_ERROR_CBOR_UNEXPECTED_TYPE);
538 return PyErr_AwsLastError();
539 }
540 error:
541 if (dict) {
542 Py_DECREF(dict);
543 }
544 if (key) {
545 Py_DECREF(key);
546 }
547 if (value) {
548 Py_DECREF(value);
549 }
550 return NULL;
551 }
552
553 /**
554 * helper to get the next inf byte
555 */
556 static PyObject *s_cbor_decoder_pop_next_inf_bytes_to_py_bytes(struct aws_cbor_decoder *decoder) {
557 enum aws_cbor_type out_type = AWS_CBOR_TYPE_UNKNOWN;
558 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
559 return PyErr_AwsLastError();
560 }
561 if (out_type != AWS_CBOR_TYPE_INDEF_BYTES_START) {
562 aws_raise_error(AWS_ERROR_CBOR_UNEXPECTED_TYPE);
563 return PyErr_AwsLastError();
564 }
565 /* consume the bytes start element */
566 aws_cbor_decoder_consume_next_single_element(decoder);
567 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
568 return PyErr_AwsLastError();
569 }
570 /* Empty bytes */
571 PyObject *result = PyBytes_FromStringAndSize(NULL, 0);
572 while (out_type != AWS_CBOR_TYPE_BREAK) {
573 PyObject *next_part = s_cbor_decoder_pop_next_bytes_val_to_pyobject(decoder);
574 if (!next_part) {
575 Py_DECREF(result);
576 return NULL;
577 }
578 /* The reference to the old value of bytes will be stolen and next_part will be del. */
579 PyBytes_ConcatAndDel(&result, next_part);
580 if (!result) {
581 return NULL;
582 }
583 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
584 return PyErr_AwsLastError();
585 }
586 }
587 /* Consume the break element */
588 aws_cbor_decoder_consume_next_single_element(decoder);
589 return result;
590 }
591
592 /**
593 * helper to get the next inf string
594 */
595 static PyObject *s_cbor_decoder_pop_next_inf_string_to_py_str(struct aws_cbor_decoder *decoder) {
596 enum aws_cbor_type out_type = AWS_CBOR_TYPE_UNKNOWN;
597 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
598 return PyErr_AwsLastError();
599 }
600 if (out_type != AWS_CBOR_TYPE_INDEF_TEXT_START) {
601 aws_raise_error(AWS_ERROR_CBOR_UNEXPECTED_TYPE);
602 return PyErr_AwsLastError();
603 }
604 /* consume the bytes start element */
605 aws_cbor_decoder_consume_next_single_element(decoder);
606 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
607 return PyErr_AwsLastError();
608 }
609 /* Empty string */
610 PyObject *result = PyUnicode_FromStringAndSize(NULL, 0);
611 while (out_type != AWS_CBOR_TYPE_BREAK) {
612 PyObject *next_part = s_cbor_decoder_pop_next_text_val_to_pyobject(decoder);
613 if (!next_part) {
614 Py_DECREF(result);
615 return NULL;
616 }
617 /* Returns a new reference and keep the arguments unchanged. */
618 PyObject *concat_val = PyUnicode_Concat(result, next_part);
619 Py_DECREF(result);
620 Py_DECREF(next_part);
621 if (!concat_val) {
622 return NULL;
623 }
624 result = concat_val;
625 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
626 return PyErr_AwsLastError();
627 }
628 }
629 /* Consume the break element */
630 aws_cbor_decoder_consume_next_single_element(decoder);
631 return result;
632 }
633
634 /**
635 * Generic helper to convert a cbor encoded data to PyObject
636 */
637 static PyObject *s_cbor_decoder_pop_next_tag_to_pyobject(struct decoder_binding *binding) {
638 struct aws_cbor_decoder *decoder = binding->native;
639 uint64_t out_tag_val = 0;
640 if (aws_cbor_decoder_pop_next_tag_val(decoder, &out_tag_val)) {
641 return PyErr_AwsLastError();
642 }
643 /* TODO: implement those tags */
644 switch (out_tag_val) {
645 case AWS_CBOR_TAG_EPOCH_TIME: {
646 enum aws_cbor_type out_type = AWS_CBOR_TYPE_UNKNOWN;
647 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
648 return PyErr_AwsLastError();
649 }
650 if (out_type == AWS_CBOR_TYPE_FLOAT || out_type == AWS_CBOR_TYPE_UINT || out_type == AWS_CBOR_TYPE_NEGINT) {
651 PyObject *val = s_cbor_decoder_pop_next_data_item_to_pyobject(binding);
652 PyObject *result = PyObject_CallMethod(binding->self_py, "_on_epoch_time_callback", "(O)", val);
653 Py_DECREF(val);
654 return result;
655 } else {
656 aws_raise_error(AWS_ERROR_CBOR_UNEXPECTED_TYPE);
657 return PyErr_AwsLastError();
658 }
659 }
660 case AWS_CBOR_TAG_UNSIGNED_BIGNUM:
661 case AWS_CBOR_TAG_NEGATIVE_BIGNUM:
662 case AWS_CBOR_TAG_DECIMAL_FRACTION:
663 default:
664 PyErr_Format(PyExc_ValueError, "Unsupported tag value: %" PRIu64 ".", out_tag_val);
665 return NULL;
666 }
667 Py_RETURN_NONE;
668 }
669
670 /**
671 * Generic helper to convert a cbor encoded data to PyObject
672 */
673 static PyObject *s_cbor_decoder_pop_next_data_item_to_pyobject(struct decoder_binding *binding) {
674 if (binding->current_depth >= s_cbor_max_decode_depth) {
675 PyErr_SetString(PyExc_RecursionError, "CBOR nesting depth exceeds maximum allowed (128)");
676 return NULL;
677 }
678 ++binding->current_depth;
679
680 PyObject *result = NULL;
681 struct aws_cbor_decoder *decoder = binding->native;
682 enum aws_cbor_type out_type = AWS_CBOR_TYPE_UNKNOWN;
683 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
684 result = PyErr_AwsLastError();
685 goto done;
686 }
687 switch (out_type) {
688 case AWS_CBOR_TYPE_UINT:
689 result = s_cbor_decoder_pop_next_unsigned_int_val_to_pyobject(decoder);
690 break;
691 case AWS_CBOR_TYPE_NEGINT: {
692 /* The value from native code is -1 - val. */
693 PyObject *minus_one = PyLong_FromLong(-1);
694 if (!minus_one) {
695 break;
696 }
697 PyObject *val = s_cbor_decoder_pop_next_negative_int_val_to_pyobject(decoder);
698 if (!val) {
699 Py_DECREF(minus_one);
700 break;
701 }
702 result = PyNumber_Subtract(minus_one, val);
703 Py_DECREF(minus_one);
704 Py_DECREF(val);
705 break;
706 }
707 case AWS_CBOR_TYPE_FLOAT:
708 result = s_cbor_decoder_pop_next_float_val_to_pyobject(decoder);
709 break;
710 case AWS_CBOR_TYPE_BYTES:
711 result = s_cbor_decoder_pop_next_bytes_val_to_pyobject(decoder);
712 break;
713 case AWS_CBOR_TYPE_TEXT:
714 result = s_cbor_decoder_pop_next_text_val_to_pyobject(decoder);
715 break;
716 case AWS_CBOR_TYPE_BOOL:
717 result = s_cbor_decoder_pop_next_boolean_val_to_pyobject(decoder);
718 break;
719 case AWS_CBOR_TYPE_NULL:
720 /* fall through */
721 case AWS_CBOR_TYPE_UNDEFINED:
722 aws_cbor_decoder_consume_next_single_element(decoder);
723 Py_INCREF(Py_None);
724 result = Py_None;
725 break;
726 case AWS_CBOR_TYPE_MAP_START:
727 /* fall through */
728 case AWS_CBOR_TYPE_INDEF_MAP_START:
729 result = s_cbor_decoder_pop_next_data_item_to_py_dict(binding);
730 break;
731 case AWS_CBOR_TYPE_ARRAY_START:
732 /* fall through */
733 case AWS_CBOR_TYPE_INDEF_ARRAY_START:
734 result = s_cbor_decoder_pop_next_data_item_to_py_list(binding);
735 break;
736 case AWS_CBOR_TYPE_INDEF_BYTES_START:
737 result = s_cbor_decoder_pop_next_inf_bytes_to_py_bytes(decoder);
738 break;
739 case AWS_CBOR_TYPE_INDEF_TEXT_START:
740 result = s_cbor_decoder_pop_next_inf_string_to_py_str(decoder);
741 break;
742 case AWS_CBOR_TYPE_TAG:
743 result = s_cbor_decoder_pop_next_tag_to_pyobject(binding);
744 break;
745 default:
746 aws_raise_error(AWS_ERROR_CBOR_UNEXPECTED_TYPE);
747 result = PyErr_AwsLastError();
748 break;
749 }
750 done:
751 --binding->current_depth;
752 return result;
753 }
754
755 /*********************************** BINDINGS ***********************************************/
756
757 PyObject *aws_py_cbor_decoder_peek_type(PyObject *self, PyObject *args) {
758 struct aws_cbor_decoder *decoder = s_get_decoder_from_py_arg(self, args);
759 if (!decoder) {
760 return NULL;
761 }
762 enum aws_cbor_type out_type = AWS_CBOR_TYPE_UNKNOWN;
763 if (aws_cbor_decoder_peek_type(decoder, &out_type)) {
764 return PyErr_AwsLastError();
765 }
766 return PyLong_FromSize_t(out_type);
767 }
768
769 PyObject *aws_py_cbor_decoder_get_remaining_bytes_len(PyObject *self, PyObject *args) {
770 struct aws_cbor_decoder *decoder = s_get_decoder_from_py_arg(self, args);
771 if (!decoder) {
772 return NULL;
773 }
774 size_t remaining_len = aws_cbor_decoder_get_remaining_length(decoder);
775 return PyLong_FromSize_t(remaining_len);
776 }
777
778 PyObject *aws_py_cbor_decoder_consume_next_element(PyObject *self, PyObject *args) {
779 struct aws_cbor_decoder *decoder = s_get_decoder_from_py_arg(self, args);
780 if (!decoder) {
781 return NULL;
782 }
783 if (aws_cbor_decoder_consume_next_single_element(decoder)) {
784 return PyErr_AwsLastError();
785 }
786 Py_RETURN_NONE;
787 }
788
789 PyObject *aws_py_cbor_decoder_consume_next_data_item(PyObject *self, PyObject *args) {
790 struct aws_cbor_decoder *decoder = s_get_decoder_from_py_arg(self, args);
791 if (!decoder) {
792 return NULL;
793 }
794 if (aws_cbor_decoder_consume_next_whole_data_item(decoder)) {
795 return PyErr_AwsLastError();
796 }
797 Py_RETURN_NONE;
798 }
799
800 #define DECODER_POP(field, decoder_fn) \
801 PyObject *aws_py_cbor_decoder_pop_next_##field(PyObject *self, PyObject *args) { \
802 struct aws_cbor_decoder *decoder = s_get_decoder_from_py_arg(self, args); \
803 if (!decoder) { \
804 return NULL; \
805 } \
806 return decoder_fn(decoder); \
807 }
808
809 #define DECODER_POP_WITH_BINDING(field, decoder_binding_fn) \
810 PyObject *aws_py_cbor_decoder_pop_next_##field(PyObject *self, PyObject *args) { \
811 (void)self; \
812 PyObject *py_capsule = NULL; \
813 if (!PyArg_ParseTuple(args, "O", &py_capsule)) { \
814 return NULL; \
815 } \
816 struct decoder_binding *binding = PyCapsule_GetPointer(py_capsule, s_capsule_name_cbor_decoder); \
817 if (!binding) { \
818 return NULL; \
819 } \
820 return decoder_binding_fn(binding); \
821 }
822
823 DECODER_POP(unsigned_int, s_cbor_decoder_pop_next_unsigned_int_val_to_pyobject)
824 DECODER_POP(negative_int, s_cbor_decoder_pop_next_negative_int_val_to_pyobject)
825 DECODER_POP(float, s_cbor_decoder_pop_next_float_val_to_pyobject)
826 DECODER_POP(boolean, s_cbor_decoder_pop_next_boolean_val_to_pyobject)
827 DECODER_POP(bytes, s_cbor_decoder_pop_next_bytes_val_to_pyobject)
828 DECODER_POP(text, s_cbor_decoder_pop_next_text_val_to_pyobject)
829 DECODER_POP(tag, s_cbor_decoder_pop_next_tag_val_to_pyobject)
830 DECODER_POP(array_start, s_cbor_decoder_pop_next_array_start_to_pyobject)
831 DECODER_POP(map_start, s_cbor_decoder_pop_next_map_start_to_pyobject)
832
833 DECODER_POP_WITH_BINDING(py_list, s_cbor_decoder_pop_next_data_item_to_py_list)
834 DECODER_POP_WITH_BINDING(py_dict, s_cbor_decoder_pop_next_data_item_to_py_dict)
835 DECODER_POP_WITH_BINDING(data_item, s_cbor_decoder_pop_next_data_item_to_pyobject)