Debian Codegraph @

python/_brotli.c

raw symbols SCIP
1 #include <assert.h>
2 #include <stddef.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #define PY_SSIZE_T_CLEAN 1
7 #include <Python.h>
8 #include <bytesobject.h>
9 #include <structmember.h>
10
11 #include <brotli/types.h>
12 #include <brotli/decode.h>
13 #include <brotli/encode.h>
14
15 #if PY_MAJOR_VERSION >= 3
16 #define PY_GET_TYPE(Obj) (Py_TYPE(Obj))
17 #else
18 #define PY_GET_TYPE(Obj) ((Obj)->ob_type)
19 #endif
20
21 static const char kErrorAttr[] = "error";
22 #if PY_MAJOR_VERSION >= 3
23 static const char kModuleAttr[] = "_module";
24 #else
25 static PyObject* BrotliError;
26 #endif
27
28 static const char kInvalidBufferError[] =
29 "brotli: data must be a C-contiguous buffer";
30 static const char kOomError[] = "brotli: unable to allocate memory";
31 static const char kCompressCreateError[] =
32 "brotli: failed to create native encoder instance";
33 static const char kCompressUnhealthyError[] = "brotli: encoder is unhealthy";
34 static const char kCompressConcurrentError[] =
35 "brotli: encoder concurrent access";
36 static const char kCompressError[] = "brotli: encoder failed";
37 static const char kInvalidModeError[] = "brotli: invalid mode";
38 static const char kInvalidQualityError[] =
39 "brotli: invalid quality; range is 0 to 11";
40 static const char kInvalidLgwinError[] =
41 "brotli: invalid lgwin; range is 10 to 24";
42 static const char kInvalidLgblockError[] =
43 "brotli: invalid lgblock; range is 16 to 24, or 0";
44 static const char kDecompressCreateError[] =
45 "brotli: failed to create native decoder instance";
46 static const char kDecompressUnhealthyError[] = "brotli: decoder is unhealthy";
47 static const char kDecompressConcurrentError[] =
48 "brotli: decoder concurrent access";
49 static const char kDecompressSinkError[] =
50 "brotli: decoder process called with data when 'can_accept_more_data()' is "
51 "False";
52 static const char kDecompressError[] = "brotli: decoder failed";
53
54 /* clang-format off */
55 PyDoc_STRVAR(brotli_error_doc,
56 "An error occurred in the Brotli implementation.");
57 PyDoc_STRVAR(brotli_Compressor_doc,
58 "An object to compress a byte string.\n"
59 "\n"
60 "Signature:\n"
61 " Compressor(mode=MODE_GENERIC, quality=11, lgwin=22, lgblock=0)\n"
62 "\n"
63 "Args:\n"
64 " mode (int): The compression mode can be MODE_GENERIC (default),\n"
65 " MODE_TEXT (for UTF-8 format text input) or MODE_FONT (for WOFF 2.0).\n"
66 " quality (int): Controls the compression-speed vs compression-\n"
67 " density tradeoff. The higher the quality, the slower the compression.\n"
68 " Must be in [0 .. 11]. Defaults to 11.\n"
69 " lgwin (int): Base 2 logarithm of the sliding window size.\n"
70 " Must be in [10 .. 24]. Defaults to 22.\n"
71 " lgblock (int): Base 2 logarithm of the maximum input block size.\n"
72 " Must be 0 or in [16 .. 24]. If set to 0, the value will be set based\n"
73 " on the quality. Defaults to 0.\n"
74 "\n"
75 "Raises:\n"
76 " brotli.error: If arguments are invalid.\n");
77 PyDoc_STRVAR(brotli_Compressor_process_doc,
78 "Process 'data' for compression, returning a bytes-object that contains\n"
79 "compressed output data. This data should be concatenated to the output\n"
80 "produced by any preceding calls to the 'process()' or 'flush()' methods.\n"
81 "Some or all of the input may be kept in internal buffers for later\n"
82 "processing, and the compressed output data may be empty until enough input\n"
83 "has been accumulated.\n"
84 "\n"
85 "Signature:\n"
86 " process(data) -> bytes\n"
87 "\n"
88 "Args:\n"
89 " data (bytes): The input data;\n"
90 " MUST provide C-contiguous one-dimensional bytes view.\n"
91 "\n"
92 "Returns:\n"
93 " The compressed output data (bytes)\n"
94 "\n"
95 "Raises:\n"
96 " brotli.error: If compression fails\n");
97 PyDoc_STRVAR(brotli_Compressor_flush_doc,
98 "Process all pending input, returning a bytes-object containing the remaining\n"
99 "compressed data. This data should be concatenated to the output produced by\n"
100 "any preceding calls to the 'process()' or 'flush()' methods.\n"
101 "\n"
102 "Signature:\n"
103 " flush() -> bytes\n"
104 "\n"
105 "Returns:\n"
106 " The compressed output data (bytes)\n"
107 "\n"
108 "Raises:\n"
109 " brotli.error: If compression fails\n");
110 PyDoc_STRVAR(brotli_Compressor_finish_doc,
111 "Process all pending input and complete all compression, returning\n"
112 "a 'bytes'-object containing the remaining compressed data. This data\n"
113 "should be concatenated to the output produced by any preceding calls\n"
114 "to the 'process()' or 'flush()' methods.\n"
115 "After calling 'finish()', the 'process()' and 'flush()' methods\n"
116 "cannot be called again, and a new \"Compressor\" object should be created.\n"
117 "\n"
118 "Signature:\n"
119 " finish() -> bytes\n"
120 "\n"
121 "Returns:\n"
122 " The compressed output data (bytes)\n"
123 "\n"
124 "Raises:\n"
125 " brotli.error: If compression fails\n");
126 PyDoc_STRVAR(brotli_Decompressor_doc,
127 "An object to decompress a byte string.\n"
128 "\n"
129 "Signature:\n"
130 " Decompressor()\n"
131 "\n"
132 "Raises:\n"
133 " brotli.error: If arguments are invalid.\n");
134 PyDoc_STRVAR(brotli_Decompressor_process_doc,
135 "Process 'data' for decompression, returning a bytes-object that contains \n"
136 "decompressed output data. This data should be concatenated to the output\n"
137 "produced by any preceding calls to the 'process()' method.\n"
138 "Some or all of the input may be kept in internal buffers for later\n"
139 "processing, and the decompressed output data may be empty until enough input\n"
140 "has been accumulated.\n"
141 "\n"
142 "Signature:\n"
143 " process(data, output_buffer_limit=int) -> bytes\n"
144 "\n"
145 "Args:\n"
146 " data (bytes): The input data;\n"
147 " MUST provide C-contiguous one-dimensional bytes view.\n"
148 " output_buffer_limit (int): The maximum size of the output buffer.\n"
149 " If set, the output buffer will not grow once its size\n"
150 " equal or exceeding that value. If the limit is reached,\n"
151 " further calls to process (potentially with empty input) will\n"
152 " continue to yield more data. Following 'process()' must only\n"
153 " be called with empty input until 'can_accept_more_data()'\n"
154 " once returns True.\n"
155 "\n"
156 "Returns:\n"
157 " The decompressed output data (bytes)\n"
158 "\n"
159 "Raises:\n"
160 " brotli.error: If decompression fails\n");
161 PyDoc_STRVAR(brotli_Decompressor_is_finished_doc,
162 "Checks if decoder instance reached the final state.\n"
163 "\n"
164 "Signature:\n"
165 " is_finished() -> bool\n"
166 "\n"
167 "Returns:\n"
168 " True if the decoder is in a state where it reached the end of the input\n"
169 " and produced all of the output\n"
170 " False otherwise\n");
171 PyDoc_STRVAR(brotli_Decompressor_can_accept_more_data_doc,
172 "Checks if the decoder instance can accept more compressed data.\n"
173 "If the 'decompress()' method on this instance of decompressor was never\n"
174 "called with 'max_length', this method will always return True.\n"
175 "\n"
176 "Signature:"
177 " can_accept_more_data() -> bool\n"
178 "\n"
179 "Returns:\n"
180 " True if the decoder is ready to accept more compressed data via\n"
181 " 'decompress()'\n"
182 " False if the decoder needs to output some data via 'decompress(b'')'\n"
183 " before being provided any more compressed data\n");
184 PyDoc_STRVAR(brotli_decompress__doc__,
185 "Decompress a compressed byte string.\n"
186 "\n"
187 "Signature:\n"
188 " decompress(data) -> bytes\n"
189 "\n"
190 "Args:\n"
191 " data (bytes): The input data;\n"
192 " MUST provide C-contiguous one-dimensional bytes view.\n"
193 "\n"
194 "Returns:\n"
195 " The decompressed byte string.\n"
196 "\n"
197 "Raises:\n"
198 " brotli.error: If decompressor fails.\n");
199 PyDoc_STRVAR(brotli_doc,
200 "Implementation module for the Brotli library.");
201 /* clang-format on */
202
203 static void set_brotli_exception(PyObject* t, const char* msg) {
204 #if PY_MAJOR_VERSION >= 3
205 PyObject* error = NULL;
206 PyObject* module = NULL;
207 assert(t != NULL);
208 assert(PyType_Check(t));
209 module = PyObject_GetAttrString(t, kModuleAttr);
210 if (!module) return; /* AttributeError raised. */
211 error = PyObject_GetAttrString(module, kErrorAttr);
212 Py_DECREF(module);
213 if (error == NULL) return; /* AttributeError raised. */
214 PyErr_SetString(error, msg);
215 Py_DECREF(error);
216 #else
217 PyErr_SetString(BrotliError, msg);
218 #endif
219 }
220
221 static void set_brotli_exception_from_module(PyObject* m, const char* msg) {
222 #if PY_MAJOR_VERSION >= 3
223 PyObject* error = NULL;
224 assert(m != NULL);
225 assert(PyModule_Check(m));
226 error = PyObject_GetAttrString(m, kErrorAttr);
227 if (error == NULL) return; /* AttributeError raised. */
228 PyErr_SetString(error, msg);
229 Py_DECREF(error);
230 #else
231 PyErr_SetString(BrotliError, msg);
232 #endif
233 }
234
235 /*
236 Checks if the `object` provides a C-bytes buffer view.
237 Returns non-zero on success.
238 Returns zero and sets an exception on failure.
239 */
240 static int get_data_view(PyObject* object, Py_buffer* view) {
241 /* PyBUF_SIMPLE means: no shape, no strides, no sub-offsets. */
242 if (PyObject_GetBuffer(object, view, PyBUF_SIMPLE) != 0) goto error;
243 if (view->len == 0) return 1;
244 /* https://docs.python.org/3/c-api/buffer.html:
245 If shape is NULL as a result of a PyBUF_SIMPLE or a PyBUF_WRITABLE request,
246 the consumer must disregard itemsize and assume itemsize == 1.*/
247 if (((view->ndim == 0) || (view->ndim == 1)) && (view->shape == NULL) &&
248 (view->strides == NULL)) {
249 return 1;
250 } else {
251 PyBuffer_Release(view);
252 }
253 error:
254 PyErr_SetString(PyExc_TypeError, kInvalidBufferError);
255 return 0;
256 }
257
258 /* --- Buffer --- */
259
260 typedef struct {
261 size_t size;
262 void* next; /* Block* */
263 uint8_t payload[16];
264 } Block;
265
266 typedef struct {
267 Block* head;
268 Block* tail;
269 size_t avail_out;
270 uint8_t* next_out;
271 size_t num_blocks;
272 uint64_t total_allocated;
273 } Buffer;
274
275 static void Buffer_Init(Buffer* buffer) {
276 buffer->head = NULL;
277 buffer->tail = NULL;
278 buffer->avail_out = 0;
279 buffer->next_out = NULL;
280 buffer->num_blocks = 0;
281 buffer->total_allocated = 0;
282 }
283
284 /*
285 Grow the buffer.
286
287 Return 0 on success.
288 Return -1 on failure, but do NOT raise an exception.
289 */
290 static int Buffer_Grow(Buffer* buffer) {
291 size_t log_size = buffer->num_blocks + 15;
292 size_t size = 1 << (log_size > 24 ? 24 : log_size);
293 size_t payload_size = size - offsetof(Block, payload);
294 Block* block = NULL;
295
296 assert(buffer->avail_out == 0);
297
298 if (buffer->total_allocated >= PY_SSIZE_T_MAX - payload_size) return -1;
299
300 assert(size > sizeof(Block));
301 block = (Block*)malloc(size);
302 if (block == NULL) return -1;
303 block->size = payload_size;
304 block->next = NULL;
305 if (buffer->head == NULL) {
306 buffer->head = block;
307 } else {
308 buffer->tail->next = block;
309 }
310 buffer->tail = block;
311 buffer->next_out = block->payload;
312 buffer->avail_out = payload_size;
313 buffer->total_allocated += payload_size;
314 buffer->num_blocks++;
315 return 0;
316 }
317
318 static void Buffer_Cleanup(Buffer* buffer) {
319 Block* block = NULL;
320 if (buffer->head == NULL) return;
321 block = buffer->head;
322 buffer->head = NULL;
323 while (block != NULL) {
324 Block* next = block->next;
325 block->next = NULL;
326 free(block);
327 block = next;
328 }
329 }
330
331 /*
332 Finish the buffer.
333
334 Return a bytes object on success.
335 Return NULL on OOM, but do NOT raise an exception.
336 */
337 static PyObject* Buffer_Finish(Buffer* buffer) {
338 uint64_t out_size = buffer->total_allocated - buffer->avail_out;
339 Py_ssize_t len = (Py_ssize_t)out_size;
340 PyObject* result = NULL;
341 uint8_t* out = NULL;
342 Py_ssize_t pos = 0;
343 Block* block = NULL;
344 size_t tail_len = 0;
345
346 if ((uint64_t)len != out_size) {
347 return NULL;
348 }
349
350 result = PyBytes_FromStringAndSize(NULL, len);
351 if (result == NULL) {
352 PyErr_Clear(); /* OOM exception will be raised by callers. */
353 return NULL;
354 }
355 if (len == 0) return result;
356
357 out = PyBytes_AS_STRING(result);
358 block = buffer->head;
359 while (block != buffer->tail) {
360 memcpy(out + pos, block->payload, block->size);
361 pos += block->size;
362 block = block->next;
363 }
364 tail_len = block->size - buffer->avail_out;
365 if (tail_len > 0) {
366 memcpy(out + pos, block->payload, tail_len);
367 }
368 return result;
369 }
370
371 /* --- Compressor --- */
372
373 typedef struct {
374 PyObject_HEAD BrotliEncoderState* enc;
375 int healthy;
376 int processing;
377 } PyBrotli_Compressor;
378
379 static PyObject* brotli_Compressor_new(PyTypeObject* type, PyObject* args,
380 PyObject* keywds) {
381 /* `tp_itemsize` is 0, so `nitems` could be 0. */
382 PyBrotli_Compressor* self = (PyBrotli_Compressor*)type->tp_alloc(type, 0);
383 PyObject* self_type = (PyObject*)type;
384
385 if (self == NULL) return NULL;
386
387 self->healthy = 0;
388 self->processing = 0;
389 self->enc = BrotliEncoderCreateInstance(0, 0, 0);
390 if (self->enc == NULL) {
391 set_brotli_exception(self_type, kCompressCreateError);
392 PY_GET_TYPE(self)->tp_free((PyObject*)self);
393 return NULL;
394 }
395 self->healthy = 1;
396
397 return (PyObject*)self;
398 }
399
400 static int brotli_Compressor_init(PyBrotli_Compressor* self, PyObject* args,
401 PyObject* keywds) {
402 static const char* kwlist[] = {"mode", "quality", "lgwin", "lgblock", NULL};
403
404 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
405 unsigned char mode = BROTLI_DEFAULT_MODE;
406 unsigned char quality = BROTLI_DEFAULT_QUALITY;
407 unsigned char lgwin = BROTLI_DEFAULT_WINDOW;
408 unsigned char lgblock = 0;
409
410 int ok = PyArg_ParseTupleAndKeywords(args, keywds, "|bbbb:Compressor",
411 (char**)kwlist, &mode, &quality, &lgwin,
412 &lgblock);
413
414 assert(self->healthy);
415
416 if (!ok) {
417 self->healthy = 0;
418 return -1;
419 }
420
421 if ((mode == 0) || (mode == 1) || (mode == 2)) {
422 BrotliEncoderSetParameter(self->enc, BROTLI_PARAM_MODE, (uint32_t)mode);
423 } else {
424 set_brotli_exception(self_type, kInvalidModeError);
425 self->healthy = 0;
426 return -1;
427 }
428 if (quality <= 11) {
429 BrotliEncoderSetParameter(self->enc, BROTLI_PARAM_QUALITY,
430 (uint32_t)quality);
431 } else {
432 set_brotli_exception(self_type, kInvalidQualityError);
433 self->healthy = 0;
434 return -1;
435 }
436 if ((10 <= lgwin) && (lgwin <= 24)) {
437 BrotliEncoderSetParameter(self->enc, BROTLI_PARAM_LGWIN, (uint32_t)lgwin);
438 } else {
439 set_brotli_exception(self_type, kInvalidLgwinError);
440 self->healthy = 0;
441 return -1;
442 }
443 if ((lgblock == 0) || ((16 <= lgblock) && (lgblock <= 24))) {
444 BrotliEncoderSetParameter(self->enc, BROTLI_PARAM_LGBLOCK,
445 (uint32_t)lgblock);
446 } else {
447 set_brotli_exception(self_type, kInvalidLgblockError);
448 self->healthy = 0;
449 return -1;
450 }
451
452 return 0;
453 }
454
455 static void brotli_Compressor_dealloc(PyBrotli_Compressor* self) {
456 if (self->enc) BrotliEncoderDestroyInstance(self->enc);
457 PY_GET_TYPE(self)->tp_free((PyObject*)self);
458 }
459
460 /*
461 Compress "utility knife" used for process / flush / finish.
462
463 Continues processing until all input is consumed.
464 Might return NULL on OOM or internal encoder error.
465 */
466 static PyObject* compress_stream(PyBrotli_Compressor* self,
467 BrotliEncoderOperation op, uint8_t* input,
468 size_t input_length) {
469 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
470 size_t available_in = input_length;
471 const uint8_t* next_in = input;
472 Buffer buffer;
473 PyObject* ret = NULL;
474 int oom = 0;
475 BROTLI_BOOL ok = BROTLI_FALSE;
476 BrotliEncoderState* enc = self->enc;
477 /* Callers must ensure mutually exclusive access to the encoder. */
478 assert(self->processing == 1);
479
480 Buffer_Init(&buffer);
481 if (Buffer_Grow(&buffer) < 0) {
482 oom = 1;
483 goto error;
484 }
485
486 Py_BEGIN_ALLOW_THREADS;
487 while (1) {
488 ok = BrotliEncoderCompressStream(enc, op, &available_in, &next_in,
489 &buffer.avail_out, &buffer.next_out, NULL);
490 if (!ok) break;
491
492 if ((available_in > 0) || BrotliEncoderHasMoreOutput(enc)) {
493 if (buffer.avail_out == 0) {
494 if (Buffer_Grow(&buffer) < 0) {
495 oom = 1;
496 break;
497 }
498 }
499 continue;
500 }
501 break;
502 }
503 Py_END_ALLOW_THREADS;
504
505 if (oom) goto error;
506 if (ok) {
507 ret = Buffer_Finish(&buffer);
508 if (ret == NULL) oom = 1;
509 } else { /* Not ok */
510 set_brotli_exception(self_type, kCompressError);
511 }
512
513 error:
514 if (oom) {
515 PyErr_SetString(PyExc_MemoryError, kOomError);
516 assert(ret == NULL);
517 }
518 Buffer_Cleanup(&buffer);
519 if (PyErr_Occurred() != NULL) {
520 assert(ret == NULL);
521 self->healthy = 0;
522 return NULL;
523 }
524 return ret;
525 }
526
527 static PyObject* brotli_Compressor_process(PyBrotli_Compressor* self,
528 PyObject* args) {
529 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
530 PyObject* ret = NULL;
531 PyObject* input_object = NULL;
532 Py_buffer input;
533
534 if (self->healthy == 0) {
535 set_brotli_exception(self_type, kCompressUnhealthyError);
536 return NULL;
537 }
538 if (self->processing != 0) {
539 set_brotli_exception(self_type, kCompressConcurrentError);
540 return NULL;
541 }
542
543 if (!PyArg_ParseTuple(args, "O:process", &input_object)) {
544 return NULL;
545 }
546 if (!get_data_view(input_object, &input)) {
547 return NULL;
548 }
549
550 self->processing = 1;
551 ret = compress_stream(self, BROTLI_OPERATION_PROCESS, (uint8_t*)input.buf,
552 input.len);
553 PyBuffer_Release(&input);
554 self->processing = 0;
555 return ret;
556 }
557
558 static PyObject* brotli_Compressor_flush(PyBrotli_Compressor* self) {
559 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
560 PyObject* ret = NULL;
561
562 if (self->healthy == 0) {
563 set_brotli_exception(self_type, kCompressUnhealthyError);
564 return NULL;
565 }
566 if (self->processing != 0) {
567 set_brotli_exception(self_type, kCompressConcurrentError);
568 return NULL;
569 }
570
571 self->processing = 1;
572 ret = compress_stream(self, BROTLI_OPERATION_FLUSH, NULL, 0);
573 self->processing = 0;
574 return ret;
575 }
576
577 static PyObject* brotli_Compressor_finish(PyBrotli_Compressor* self) {
578 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
579 PyObject* ret = NULL;
580
581 if (self->healthy == 0) {
582 set_brotli_exception(self_type, kCompressUnhealthyError);
583 return NULL;
584 }
585 if (self->processing != 0) {
586 set_brotli_exception(self_type, kCompressConcurrentError);
587 return NULL;
588 }
589
590 self->processing = 1;
591 ret = compress_stream(self, BROTLI_OPERATION_FINISH, NULL, 0);
592 self->processing = 0;
593 if (ret != NULL) {
594 assert(BrotliEncoderIsFinished(self->enc));
595 }
596 return ret;
597 }
598
599 /* --- Decompressor --- */
600
601 typedef struct {
602 PyObject_HEAD BrotliDecoderState* dec;
603 uint8_t* unconsumed_data;
604 size_t unconsumed_data_length;
605 int healthy;
606 int processing;
607 } PyBrotli_Decompressor;
608
609 static PyObject* brotli_Decompressor_new(PyTypeObject* type, PyObject* args,
610 PyObject* keywds) {
611 /* `tp_itemsize` is 0, so `nitems` could be 0. */
612 PyBrotli_Decompressor* self = (PyBrotli_Decompressor*)type->tp_alloc(type, 0);
613 PyObject* self_type = (PyObject*)type;
614
615 if (self == NULL) return NULL;
616 self->healthy = 0;
617 self->processing = 0;
618
619 self->dec = BrotliDecoderCreateInstance(0, 0, 0);
620 if (self->dec == NULL) {
621 set_brotli_exception(self_type, kDecompressCreateError);
622 PY_GET_TYPE(self)->tp_free((PyObject*)self);
623 return NULL;
624 }
625
626 self->unconsumed_data = NULL;
627 self->unconsumed_data_length = 0;
628 self->healthy = 1;
629
630 return (PyObject*)self;
631 }
632
633 static int brotli_Decompressor_init(PyBrotli_Decompressor* self, PyObject* args,
634 PyObject* keywds) {
635 static const char* kwlist[] = {NULL};
636
637 int ok = PyArg_ParseTupleAndKeywords(args, keywds, "|:Decompressor",
638 (char**)kwlist);
639
640 assert(self->healthy);
641
642 if (!ok) {
643 self->healthy = 0;
644 return -1;
645 }
646
647 return 0;
648 }
649
650 static void brotli_Decompressor_dealloc(PyBrotli_Decompressor* self) {
651 if (self->dec) BrotliDecoderDestroyInstance(self->dec);
652 if (self->unconsumed_data) {
653 free(self->unconsumed_data);
654 self->unconsumed_data = NULL;
655 }
656 PY_GET_TYPE(self)->tp_free((PyObject*)self);
657 }
658
659 static PyObject* brotli_Decompressor_process(PyBrotli_Decompressor* self,
660 PyObject* args, PyObject* keywds) {
661 static const char* kwlist[] = {"", "output_buffer_limit", NULL};
662
663 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
664 PyObject* ret = NULL;
665 PyObject* input_object = NULL;
666 Py_buffer input;
667 Py_ssize_t output_buffer_limit = PY_SSIZE_T_MAX;
668 const uint8_t* next_in = NULL;
669 size_t avail_in = 0;
670 BrotliDecoderResult result = BROTLI_DECODER_RESULT_ERROR;
671 Buffer buffer;
672 uint8_t* new_tail = NULL;
673 size_t new_tail_length = 0;
674 int oom = 0;
675
676 if (self->healthy == 0) {
677 set_brotli_exception(self_type, kDecompressUnhealthyError);
678 return NULL;
679 }
680 if (self->processing != 0) {
681 set_brotli_exception(self_type, kDecompressConcurrentError);
682 return NULL;
683 }
684
685 if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|n:process", (char**)kwlist,
686 &input_object, &output_buffer_limit)) {
687 return NULL;
688 }
689 if (!get_data_view(input_object, &input)) {
690 return NULL;
691 }
692
693 Buffer_Init(&buffer);
694 self->processing = 1;
695
696 if (self->unconsumed_data_length > 0) {
697 if (input.len > 0) {
698 set_brotli_exception(self_type, kDecompressSinkError);
699 goto finally;
700 }
701 next_in = self->unconsumed_data;
702 avail_in = self->unconsumed_data_length;
703 } else {
704 next_in = (uint8_t*)input.buf;
705 avail_in = input.len;
706 }
707
708 /* While not guaranteed, we expect that some output will be produced. */
709 if (Buffer_Grow(&buffer) < 0) {
710 oom = 1;
711 goto finally;
712 }
713
714 Py_BEGIN_ALLOW_THREADS;
715 while (1) {
716 result = BrotliDecoderDecompressStream(self->dec, &avail_in, &next_in,
717 &buffer.avail_out, &buffer.next_out,
718 NULL);
719
720 if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
721 assert(buffer.avail_out == 0);
722 /* All allocated is used -> reached the output length limit. */
723 if (buffer.total_allocated >= output_buffer_limit) break;
724 if (Buffer_Grow(&buffer) < 0) {
725 oom = 1;
726 break;
727 }
728 continue;
729 }
730 break;
731 }
732 Py_END_ALLOW_THREADS;
733
734 if (oom) {
735 goto finally;
736 } else if (result == BROTLI_DECODER_RESULT_ERROR) {
737 set_brotli_exception(self_type, kDecompressError);
738 goto finally;
739 }
740
741 /* Here result is either SUCCESS / NEEDS_MORE_INPUT / NEEDS_MORE_OUTPUT (if
742 `output_buffer_limit` was reached). */
743
744 if (avail_in > 0) {
745 new_tail = malloc(avail_in);
746 if (new_tail == NULL) {
747 oom = 1;
748 goto finally;
749 }
750 memcpy(new_tail, next_in, avail_in);
751 new_tail_length = avail_in;
752 }
753
754 if ((result == BROTLI_DECODER_RESULT_SUCCESS) && (avail_in > 0)) {
755 /* TODO(eustas): Add API to ignore / fetch unused "tail"? */
756 set_brotli_exception(self_type, kDecompressError);
757 goto finally;
758 }
759
760 ret = Buffer_Finish(&buffer);
761 if (ret == NULL) oom = 1;
762
763 finally:
764 if (oom) {
765 PyErr_SetString(PyExc_MemoryError, kOomError);
766 assert(ret == NULL);
767 }
768 PyBuffer_Release(&input);
769 Buffer_Cleanup(&buffer);
770 if (self->unconsumed_data) {
771 free(self->unconsumed_data);
772 self->unconsumed_data = NULL;
773 }
774 self->unconsumed_data = new_tail;
775 self->unconsumed_data_length = new_tail_length;
776 if (PyErr_Occurred() != NULL) {
777 assert(ret == NULL);
778 self->healthy = 0;
779 }
780 self->processing = 0;
781 return ret;
782 }
783
784 static PyObject* brotli_Decompressor_is_finished(PyBrotli_Decompressor* self) {
785 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
786 if (self->healthy == 0) {
787 set_brotli_exception(self_type, kDecompressUnhealthyError);
788 return NULL;
789 }
790 if (self->processing != 0) {
791 set_brotli_exception(self_type, kDecompressConcurrentError);
792 return NULL;
793 }
794 if (BrotliDecoderIsFinished(self->dec)) {
795 Py_RETURN_TRUE;
796 } else {
797 Py_RETURN_FALSE;
798 }
799 }
800
801 static PyObject* brotli_Decompressor_can_accept_more_data(
802 PyBrotli_Decompressor* self) {
803 PyObject* self_type = (PyObject*)PY_GET_TYPE((PyObject*)self);
804 if (self->healthy == 0) {
805 set_brotli_exception(self_type, kDecompressUnhealthyError);
806 return NULL;
807 }
808 if (self->processing != 0) {
809 set_brotli_exception(self_type, kDecompressConcurrentError);
810 return NULL;
811 }
812 if (self->unconsumed_data_length > 0) {
813 Py_RETURN_FALSE;
814 } else {
815 Py_RETURN_TRUE;
816 }
817 }
818
819 /* --- Module functions --- */
820
821 static PyObject* brotli_decompress(PyObject* m, PyObject* args,
822 PyObject* keywds) {
823 static const char* kwlist[] = {"string", NULL};
824
825 BrotliDecoderState* state = NULL;
826 BrotliDecoderResult result = BROTLI_DECODER_RESULT_ERROR;
827 const uint8_t* next_in = NULL;
828 size_t available_in = 0;
829 Buffer buffer;
830 PyObject* ret = NULL;
831 PyObject* input_object = NULL;
832 Py_buffer input;
833 int oom = 0;
834
835 if (!PyArg_ParseTupleAndKeywords(args, keywds, "O|:decompress",
836 (char**)kwlist, &input_object)) {
837 return NULL;
838 }
839 if (!get_data_view(input_object, &input)) {
840 return NULL;
841 }
842
843 Buffer_Init(&buffer);
844
845 next_in = (uint8_t*)input.buf;
846 available_in = input.len;
847
848 state = BrotliDecoderCreateInstance(0, 0, 0);
849 if (state == NULL) {
850 oom = 1;
851 goto finally;
852 }
853
854 if (Buffer_Grow(&buffer) < 0) {
855 oom = 1;
856 goto finally;
857 }
858
859 Py_BEGIN_ALLOW_THREADS;
860 while (1) {
861 result = BrotliDecoderDecompressStream(
862 state, &available_in, &next_in, &buffer.avail_out, &buffer.next_out, 0);
863 if (result == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
864 assert(buffer.avail_out == 0);
865 if (Buffer_Grow(&buffer) < 0) {
866 oom = 1;
867 break;
868 }
869 continue;
870 }
871 break;
872 }
873 Py_END_ALLOW_THREADS;
874
875 if (oom) {
876 goto finally;
877 } else if (result != BROTLI_DECODER_RESULT_SUCCESS || available_in > 0) {
878 set_brotli_exception_from_module(m, kDecompressError);
879 goto finally;
880 }
881
882 ret = Buffer_Finish(&buffer);
883 if (ret == NULL) oom = 1;
884
885 finally:
886 if (oom) PyErr_SetString(PyExc_MemoryError, kOomError);
887 PyBuffer_Release(&input);
888 Buffer_Cleanup(&buffer);
889 if (state) BrotliDecoderDestroyInstance(state);
890 return ret;
891 }
892
893 /* Module definition */
894
895 static int init_brotli_mod(PyObject* m);
896
897 static PyMethodDef brotli_methods[] = {
898 {"decompress", (PyCFunction)brotli_decompress, METH_VARARGS | METH_KEYWORDS,
899 brotli_decompress__doc__},
900 {NULL, NULL, 0, NULL}};
901
902 static PyMethodDef brotli_Compressor_methods[] = {
903 {"process", (PyCFunction)brotli_Compressor_process, METH_VARARGS,
904 brotli_Compressor_process_doc},
905 {"flush", (PyCFunction)brotli_Compressor_flush, METH_NOARGS,
906 brotli_Compressor_flush_doc},
907 {"finish", (PyCFunction)brotli_Compressor_finish, METH_NOARGS,
908 brotli_Compressor_finish_doc},
909 {NULL} /* Sentinel */
910 };
911
912 static PyMethodDef brotli_Decompressor_methods[] = {
913 {"process", (PyCFunction)brotli_Decompressor_process,
914 METH_VARARGS | METH_KEYWORDS, brotli_Decompressor_process_doc},
915 {"is_finished", (PyCFunction)brotli_Decompressor_is_finished, METH_NOARGS,
916 brotli_Decompressor_is_finished_doc},
917 {"can_accept_more_data",
918 (PyCFunction)brotli_Decompressor_can_accept_more_data, METH_NOARGS,
919 brotli_Decompressor_can_accept_more_data_doc},
920 {NULL} /* Sentinel */
921 };
922
923 #if PY_MAJOR_VERSION >= 3
924
925 #if PY_MINOR_VERSION >= 5
926 static PyModuleDef_Slot brotli_mod_slots[] = {
927 {Py_mod_exec, init_brotli_mod},
928 #if PY_MINOR_VERSION >= 12
929 {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
930 #endif
931 {0, NULL}};
932 #endif
933
934 static struct PyModuleDef brotli_module = {
935 PyModuleDef_HEAD_INIT,
936 "_brotli", /* m_name */
937 brotli_doc, /* m_doc */
938 0, /* m_size */
939 brotli_methods, /* m_methods */
940 #if PY_MINOR_VERSION >= 5
941 brotli_mod_slots, /* m_slots */
942 #else
943 NULL, /* m_reload */
944 #endif
945 NULL, /* m_traverse */
946 NULL, /* m_clear */
947 NULL /* m_free */
948 };
949
950 static PyType_Slot brotli_Compressor_slots[] = {
951 {Py_tp_dealloc, (destructor)brotli_Compressor_dealloc},
952 {Py_tp_doc, (void*)brotli_Compressor_doc},
953 {Py_tp_methods, brotli_Compressor_methods},
954 {Py_tp_init, (initproc)brotli_Compressor_init},
955 {Py_tp_new, brotli_Compressor_new},
956 {0, 0},
957 };
958
959 static PyType_Spec brotli_Compressor_spec = {
960 "brotli.Compressor", sizeof(PyBrotli_Compressor), 0,
961 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, brotli_Compressor_slots};
962
963 static PyType_Slot brotli_Decompressor_slots[] = {
964 {Py_tp_dealloc, (destructor)brotli_Decompressor_dealloc},
965 {Py_tp_doc, (void*)brotli_Decompressor_doc},
966 {Py_tp_methods, brotli_Decompressor_methods},
967 {Py_tp_init, (initproc)brotli_Decompressor_init},
968 {Py_tp_new, brotli_Decompressor_new},
969 {0, 0},
970 };
971
972 static PyType_Spec brotli_Decompressor_spec = {
973 "brotli.Decompressor", sizeof(PyBrotli_Decompressor), 0,
974 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, brotli_Decompressor_slots};
975
976 PyMODINIT_FUNC PyInit__brotli(void) {
977 #if PY_MINOR_VERSION < 5
978 PyObject* m = PyModule_Create(&brotli_module);
979 if (m == NULL) return NULL;
980 if (init_brotli_mod(m) < 0) {
981 Py_DECREF(m);
982 m = NULL;
983 }
984 return m;
985 #else
986 return PyModuleDef_Init(&brotli_module);
987 #endif
988 }
989
990 #else
991
992 static PyTypeObject brotli_CompressorType = {
993 PyObject_HEAD_INIT(NULL) 0, /* ob_size */
994 "brotli.Compressor", /* tp_name */
995 sizeof(PyBrotli_Compressor), /* tp_basicsize */
996 0, /* tp_itemsize */
997 (destructor)brotli_Compressor_dealloc, /* tp_dealloc */
998 0, /* tp_print */
999 0, /* tp_getattr */
1000 0, /* tp_setattr */
1001 0, /* tp_compare */
1002 0, /* tp_repr */
1003 0, /* tp_as_number */
1004 0, /* tp_as_sequence */
1005 0, /* tp_as_mapping */
1006 0, /* tp_hash */
1007 0, /* tp_call */
1008 0, /* tp_str */
1009 0, /* tp_getattro */
1010 0, /* tp_setattro */
1011 0, /* tp_as_buffer */
1012 Py_TPFLAGS_DEFAULT, /* tp_flags */
1013 brotli_Compressor_doc, /* tp_doc */
1014 0, /* tp_traverse */
1015 0, /* tp_clear */
1016 0, /* tp_richcompare */
1017 0, /* tp_weaklistoffset */
1018 0, /* tp_iter */
1019 0, /* tp_iternext */
1020 brotli_Compressor_methods, /* tp_methods */
1021 0, /* tp_members */
1022 0, /* tp_getset */
1023 0, /* tp_base */
1024 0, /* tp_dict */
1025 0, /* tp_descr_get */
1026 0, /* tp_descr_set */
1027 0, /* tp_dictoffset */
1028 (initproc)brotli_Compressor_init, /* tp_init */
1029 0, /* tp_alloc */
1030 brotli_Compressor_new, /* tp_new */
1031 };
1032
1033 static PyTypeObject brotli_DecompressorType = {
1034 PyObject_HEAD_INIT(NULL) 0, /* ob_size */
1035 "brotli.Decompressor", /* tp_name */
1036 sizeof(PyBrotli_Decompressor), /* tp_basicsize */
1037 0, /* tp_itemsize */
1038 (destructor)brotli_Decompressor_dealloc, /* tp_dealloc */
1039 0, /* tp_print */
1040 0, /* tp_getattr */
1041 0, /* tp_setattr */
1042 0, /* tp_compare */
1043 0, /* tp_repr */
1044 0, /* tp_as_number */
1045 0, /* tp_as_sequence */
1046 0, /* tp_as_mapping */
1047 0, /* tp_hash */
1048 0, /* tp_call */
1049 0, /* tp_str */
1050 0, /* tp_getattro */
1051 0, /* tp_setattro */
1052 0, /* tp_as_buffer */
1053 Py_TPFLAGS_DEFAULT, /* tp_flags */
1054 brotli_Decompressor_doc, /* tp_doc */
1055 0, /* tp_traverse */
1056 0, /* tp_clear */
1057 0, /* tp_richcompare */
1058 0, /* tp_weaklistoffset */
1059 0, /* tp_iter */
1060 0, /* tp_iternext */
1061 brotli_Decompressor_methods, /* tp_methods */
1062 0, /* tp_members */
1063 0, /* tp_getset */
1064 0, /* tp_base */
1065 0, /* tp_dict */
1066 0, /* tp_descr_get */
1067 0, /* tp_descr_set */
1068 0, /* tp_dictoffset */
1069 (initproc)brotli_Decompressor_init, /* tp_init */
1070 0, /* tp_alloc */
1071 brotli_Decompressor_new, /* tp_new */
1072 };
1073
1074 PyMODINIT_FUNC init_brotli(void) {
1075 PyObject* m = Py_InitModule3("_brotli", brotli_methods, brotli_doc);
1076 if (m == NULL) return;
1077 init_brotli_mod(m);
1078 }
1079
1080 #endif
1081
1082 /* Emulates PyModule_AddObject */
1083 static int RegisterObject(PyObject* mod, const char* name, PyObject* value) {
1084 assert(value != NULL);
1085 #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >= 10
1086 int ret = PyModule_AddObjectRef(mod, name, value);
1087 /* Emulates PyModule_AddObject, i.e. decrements the reference count on
1088 success. */
1089 if (ret == 0) Py_DECREF(value);
1090 return ret;
1091 #else
1092 return PyModule_AddObject(mod, name, value);
1093 #endif
1094 }
1095
1096 static int init_brotli_mod(PyObject* m) {
1097 PyObject* error_type = NULL;
1098 PyObject* compressor_type = NULL;
1099 PyObject* decompressor_type = NULL;
1100 assert(m != NULL);
1101
1102 error_type = PyErr_NewExceptionWithDoc((char*)"brotli.error",
1103 brotli_error_doc, NULL, NULL);
1104 if (error_type == NULL) goto error;
1105
1106 if (RegisterObject(m, kErrorAttr, error_type) < 0) goto error;
1107 #if PY_MAJOR_VERSION < 3
1108 /* Assumption: pointer is used only while module is alive and well. */
1109 BrotliError = error_type;
1110 #endif
1111 error_type = NULL;
1112
1113 #if PY_MAJOR_VERSION >= 3
1114 compressor_type = PyType_FromSpec(&brotli_Compressor_spec);
1115 decompressor_type = PyType_FromSpec(&brotli_Decompressor_spec);
1116 #else
1117 compressor_type = (PyObject*)&brotli_CompressorType;
1118 Py_INCREF(compressor_type);
1119 decompressor_type = (PyObject*)&brotli_DecompressorType;
1120 Py_INCREF(decompressor_type);
1121 #endif
1122 if (compressor_type == NULL) goto error;
1123 if (PyType_Ready((PyTypeObject*)compressor_type) < 0) goto error;
1124 #if PY_MAJOR_VERSION >= 3
1125 if (PyObject_SetAttrString(compressor_type, kModuleAttr, m) < 0) goto error;
1126 #endif
1127 if (RegisterObject(m, "Compressor", compressor_type) < 0) goto error;
1128 compressor_type = NULL;
1129
1130 if (decompressor_type == NULL) goto error;
1131 if (PyType_Ready((PyTypeObject*)decompressor_type) < 0) goto error;
1132 #if PY_MAJOR_VERSION >= 3
1133 if (PyObject_SetAttrString(decompressor_type, kModuleAttr, m) < 0) goto error;
1134 #endif
1135 if (RegisterObject(m, "Decompressor", decompressor_type) < 0) goto error;
1136 decompressor_type = NULL;
1137
1138 PyModule_AddIntConstant(m, "MODE_GENERIC", (int)BROTLI_MODE_GENERIC);
1139 PyModule_AddIntConstant(m, "MODE_TEXT", (int)BROTLI_MODE_TEXT);
1140 PyModule_AddIntConstant(m, "MODE_FONT", (int)BROTLI_MODE_FONT);
1141
1142 char version[16]; /* 3 + 1 + 4 + 1 + 4 + 1 == 14 */
1143 uint32_t decoderVersion = BrotliDecoderVersion();
1144 snprintf(version, sizeof(version), "%d.%d.%d", decoderVersion >> 24,
1145 (decoderVersion >> 12) & 0xFFF, decoderVersion & 0xFFF);
1146 PyModule_AddStringConstant(m, "__version__", version);
1147
1148 return 0;
1149
1150 error:
1151 if (error_type != NULL) {
1152 Py_DECREF(error_type);
1153 error_type = NULL;
1154 }
1155 if (compressor_type != NULL) {
1156 Py_DECREF(compressor_type);
1157 compressor_type = NULL;
1158 }
1159 if (decompressor_type != NULL) {
1160 Py_DECREF(decompressor_type);
1161 decompressor_type = NULL;
1162 }
1163 return -1;
1164 }