Debian Codegraph @

c-ext/decompressionreader.c

raw
1 /**
2 * Copyright (c) 2017-present, Gregory Szorc
3 * All rights reserved.
4 *
5 * This software may be modified and distributed under the terms
6 * of the BSD license. See the LICENSE file for details.
7 */
8
9 #include "python-zstandard.h"
10
11 extern PyObject *ZstdError;
12
13 static void decompressionreader_dealloc(ZstdDecompressionReader *self) {
14 Py_XDECREF(self->decompressor);
15 Py_XDECREF(self->reader);
16
17 if (self->buffer.buf) {
18 PyBuffer_Release(&self->buffer);
19 }
20
21 Py_CLEAR(self->readResult);
22
23 PyObject_Del(self);
24 }
25
26 static ZstdDecompressionReader *
27 decompressionreader_enter(ZstdDecompressionReader *self) {
28 if (self->entered) {
29 PyErr_SetString(PyExc_ValueError, "cannot __enter__ multiple times");
30 return NULL;
31 }
32
33 if (self->closed) {
34 PyErr_SetString(PyExc_ValueError, "stream is closed");
35 return NULL;
36 }
37
38 self->entered = 1;
39
40 Py_INCREF(self);
41 return self;
42 }
43
44 static PyObject *decompressionreader_exit(ZstdDecompressionReader *self,
45 PyObject *args) {
46 PyObject *exc_type;
47 PyObject *exc_value;
48 PyObject *exc_tb;
49
50 if (!PyArg_ParseTuple(args, "OOO:__exit__", &exc_type, &exc_value,
51 &exc_tb)) {
52 return NULL;
53 }
54
55 self->entered = 0;
56
57 if (NULL == PyObject_CallMethod((PyObject *)self, "close", NULL)) {
58 return NULL;
59 }
60
61 /* Release resources. */
62 Py_CLEAR(self->reader);
63 if (self->buffer.buf) {
64 PyBuffer_Release(&self->buffer);
65 memset(&self->buffer, 0, sizeof(self->buffer));
66 }
67
68 Py_CLEAR(self->decompressor);
69
70 Py_RETURN_FALSE;
71 }
72
73 static PyObject *decompressionreader_readable(PyObject *self) {
74 Py_RETURN_TRUE;
75 }
76
77 static PyObject *decompressionreader_writable(PyObject *self) {
78 Py_RETURN_FALSE;
79 }
80
81 static PyObject *decompressionreader_seekable(PyObject *self) {
82 Py_RETURN_FALSE;
83 }
84
85 static PyObject *decompressionreader_close(ZstdDecompressionReader *self) {
86 if (self->closed) {
87 Py_RETURN_NONE;
88 }
89
90 self->closed = 1;
91
92 if (self->closefd && self->reader != NULL &&
93 PyObject_HasAttrString(self->reader, "close")) {
94 return PyObject_CallMethod(self->reader, "close", NULL);
95 }
96
97 Py_RETURN_NONE;
98 }
99
100 static PyObject *decompressionreader_flush(PyObject *self) {
101 Py_RETURN_NONE;
102 }
103
104 static PyObject *decompressionreader_isatty(PyObject *self) {
105 Py_RETURN_FALSE;
106 }
107
108 /**
109 * Read available input.
110 *
111 * Returns 0 if no data was added to input.
112 * Returns 1 if new input data is available.
113 * Returns -1 on error and sets a Python exception as a side-effect.
114 */
115 int read_decompressor_input(ZstdDecompressionReader *self) {
116 if (self->finishedInput) {
117 return 0;
118 }
119
120 if (self->input.pos != self->input.size) {
121 return 0;
122 }
123
124 if (self->reader) {
125 Py_buffer buffer;
126
127 assert(self->readResult == NULL);
128 self->readResult =
129 PyObject_CallMethod(self->reader, "read", "k", self->readSize);
130 if (NULL == self->readResult) {
131 return -1;
132 }
133
134 memset(&buffer, 0, sizeof(buffer));
135
136 if (0 !=
137 PyObject_GetBuffer(self->readResult, &buffer, PyBUF_CONTIG_RO)) {
138 return -1;
139 }
140
141 /* EOF */
142 if (0 == buffer.len) {
143 self->finishedInput = 1;
144 Py_CLEAR(self->readResult);
145 }
146 else {
147 self->input.src = buffer.buf;
148 self->input.size = buffer.len;
149 self->input.pos = 0;
150 }
151
152 PyBuffer_Release(&buffer);
153 }
154 else {
155 assert(self->buffer.buf);
156 /*
157 * We should only get here once since expectation is we always
158 * exhaust input buffer before reading again.
159 */
160 assert(self->input.src == NULL);
161
162 self->input.src = self->buffer.buf;
163 self->input.size = self->buffer.len;
164 self->input.pos = 0;
165 }
166
167 return 1;
168 }
169
170 /**
171 * Decompresses available input into an output buffer.
172 *
173 * Returns 0 if we need more input.
174 * Returns 1 if output buffer should be emitted.
175 * Returns -1 on error and sets a Python exception.
176 */
177 int decompress_input(ZstdDecompressionReader *self, ZSTD_outBuffer *output) {
178 size_t zresult;
179
180 if (self->input.pos >= self->input.size) {
181 return 0;
182 }
183
184 Py_BEGIN_ALLOW_THREADS zresult =
185 ZSTD_decompressStream(self->decompressor->dctx, output, &self->input);
186 Py_END_ALLOW_THREADS
187
188 /* Input exhausted. Clear our state tracking. */
189 if (self->input.pos == self->input.size) {
190 memset(&self->input, 0, sizeof(self->input));
191 Py_CLEAR(self->readResult);
192
193 if (self->buffer.buf) {
194 self->finishedInput = 1;
195 }
196 }
197
198 if (ZSTD_isError(zresult)) {
199 PyErr_Format(ZstdError, "zstd decompress error: %s",
200 ZSTD_getErrorName(zresult));
201 return -1;
202 }
203
204 /* We fulfilled the full read request. Signal to emit. */
205 if (output->pos && output->pos == output->size) {
206 return 1;
207 }
208 /* We're at the end of a frame and we aren't allowed to return data
209 spanning frames. */
210 else if (output->pos && zresult == 0 && !self->readAcrossFrames) {
211 return 1;
212 }
213
214 /* There is more room in the output. Signal to collect more data. */
215 return 0;
216 }
217
218 static PyObject *decompressionreader_read(ZstdDecompressionReader *self,
219 PyObject *args, PyObject *kwargs) {
220 static char *kwlist[] = {"size", NULL};
221
222 Py_ssize_t size = -1;
223 PyObject *result = NULL;
224 char *resultBuffer;
225 Py_ssize_t resultSize;
226 ZSTD_outBuffer output;
227 int decompressResult, readResult;
228
229 if (self->closed) {
230 PyErr_SetString(PyExc_ValueError, "stream is closed");
231 return NULL;
232 }
233
234 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|n", kwlist, &size)) {
235 return NULL;
236 }
237
238 if (size < -1) {
239 PyErr_SetString(PyExc_ValueError,
240 "cannot read negative amounts less than -1");
241 return NULL;
242 }
243
244 if (size == -1) {
245 return PyObject_CallMethod((PyObject *)self, "readall", NULL);
246 }
247
248 if (self->finishedOutput || size == 0) {
249 return PyBytes_FromStringAndSize("", 0);
250 }
251
252 result = PyBytes_FromStringAndSize(NULL, size);
253 if (NULL == result) {
254 return NULL;
255 }
256
257 PyBytes_AsStringAndSize(result, &resultBuffer, &resultSize);
258
259 output.dst = resultBuffer;
260 output.size = resultSize;
261 output.pos = 0;
262
263 readinput:
264
265 decompressResult = decompress_input(self, &output);
266
267 if (-1 == decompressResult) {
268 Py_XDECREF(result);
269 return NULL;
270 }
271 else if (0 == decompressResult) {
272 }
273 else if (1 == decompressResult) {
274 self->bytesDecompressed += output.pos;
275
276 if (output.pos != output.size) {
277 if (safe_pybytes_resize(&result, output.pos)) {
278 Py_XDECREF(result);
279 return NULL;
280 }
281 }
282 return result;
283 }
284 else {
285 assert(0);
286 }
287
288 readResult = read_decompressor_input(self);
289
290 if (-1 == readResult) {
291 Py_XDECREF(result);
292 return NULL;
293 }
294 else if (0 == readResult) {
295 }
296 else if (1 == readResult) {
297 }
298 else {
299 assert(0);
300 }
301
302 if (self->input.size) {
303 goto readinput;
304 }
305
306 /* EOF */
307 self->bytesDecompressed += output.pos;
308
309 if (safe_pybytes_resize(&result, output.pos)) {
310 Py_XDECREF(result);
311 return NULL;
312 }
313
314 return result;
315 }
316
317 static PyObject *decompressionreader_read1(ZstdDecompressionReader *self,
318 PyObject *args, PyObject *kwargs) {
319 static char *kwlist[] = {"size", NULL};
320
321 Py_ssize_t size = -1;
322 PyObject *result = NULL;
323 char *resultBuffer;
324 Py_ssize_t resultSize;
325 ZSTD_outBuffer output;
326
327 if (self->closed) {
328 PyErr_SetString(PyExc_ValueError, "stream is closed");
329 return NULL;
330 }
331
332 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|n", kwlist, &size)) {
333 return NULL;
334 }
335
336 if (size < -1) {
337 PyErr_SetString(PyExc_ValueError,
338 "cannot read negative amounts less than -1");
339 return NULL;
340 }
341
342 if (self->finishedOutput || size == 0) {
343 return PyBytes_FromStringAndSize("", 0);
344 }
345
346 if (size == -1) {
347 size = ZSTD_DStreamOutSize();
348 }
349
350 result = PyBytes_FromStringAndSize(NULL, size);
351 if (NULL == result) {
352 return NULL;
353 }
354
355 PyBytes_AsStringAndSize(result, &resultBuffer, &resultSize);
356
357 output.dst = resultBuffer;
358 output.size = resultSize;
359 output.pos = 0;
360
361 /* read1() is supposed to use at most 1 read() from the underlying stream.
362 * However, we can't satisfy this requirement with decompression due to the
363 * nature of how decompression works. Our strategy is to read + decompress
364 * until we get any output, at which point we return. This satisfies the
365 * intent of the read1() API to limit read operations.
366 */
367 while (!self->finishedInput) {
368 int readResult, decompressResult;
369
370 readResult = read_decompressor_input(self);
371 if (-1 == readResult) {
372 Py_XDECREF(result);
373 return NULL;
374 }
375 else if (0 == readResult || 1 == readResult) {
376 }
377 else {
378 assert(0);
379 }
380
381 decompressResult = decompress_input(self, &output);
382
383 if (-1 == decompressResult) {
384 Py_XDECREF(result);
385 return NULL;
386 }
387 else if (0 == decompressResult || 1 == decompressResult) {
388 }
389 else {
390 assert(0);
391 }
392
393 if (output.pos) {
394 break;
395 }
396 }
397
398 self->bytesDecompressed += output.pos;
399 if (safe_pybytes_resize(&result, output.pos)) {
400 Py_XDECREF(result);
401 return NULL;
402 }
403
404 return result;
405 }
406
407 static PyObject *decompressionreader_readinto(ZstdDecompressionReader *self,
408 PyObject *args) {
409 Py_buffer dest;
410 ZSTD_outBuffer output;
411 int decompressResult, readResult;
412 PyObject *result = NULL;
413
414 if (self->closed) {
415 PyErr_SetString(PyExc_ValueError, "stream is closed");
416 return NULL;
417 }
418
419 if (self->finishedOutput) {
420 return PyLong_FromLong(0);
421 }
422
423 if (!PyArg_ParseTuple(args, "w*:readinto", &dest)) {
424 return NULL;
425 }
426
427 output.dst = dest.buf;
428 output.size = dest.len;
429 output.pos = 0;
430
431 readinput:
432
433 decompressResult = decompress_input(self, &output);
434
435 if (-1 == decompressResult) {
436 goto finally;
437 }
438 else if (0 == decompressResult) {
439 }
440 else if (1 == decompressResult) {
441 self->bytesDecompressed += output.pos;
442 result = PyLong_FromSize_t(output.pos);
443 goto finally;
444 }
445 else {
446 assert(0);
447 }
448
449 readResult = read_decompressor_input(self);
450
451 if (-1 == readResult) {
452 goto finally;
453 }
454 else if (0 == readResult) {
455 }
456 else if (1 == readResult) {
457 }
458 else {
459 assert(0);
460 }
461
462 if (self->input.size) {
463 goto readinput;
464 }
465
466 /* EOF */
467 self->bytesDecompressed += output.pos;
468 result = PyLong_FromSize_t(output.pos);
469
470 finally:
471 PyBuffer_Release(&dest);
472
473 return result;
474 }
475
476 static PyObject *decompressionreader_readinto1(ZstdDecompressionReader *self,
477 PyObject *args) {
478 Py_buffer dest;
479 ZSTD_outBuffer output;
480 PyObject *result = NULL;
481
482 if (self->closed) {
483 PyErr_SetString(PyExc_ValueError, "stream is closed");
484 return NULL;
485 }
486
487 if (self->finishedOutput) {
488 return PyLong_FromLong(0);
489 }
490
491 if (!PyArg_ParseTuple(args, "w*:readinto1", &dest)) {
492 return NULL;
493 }
494
495 output.dst = dest.buf;
496 output.size = dest.len;
497 output.pos = 0;
498
499 while (!self->finishedInput && !self->finishedOutput) {
500 int decompressResult, readResult;
501
502 readResult = read_decompressor_input(self);
503
504 if (-1 == readResult) {
505 goto finally;
506 }
507 else if (0 == readResult || 1 == readResult) {
508 }
509 else {
510 assert(0);
511 }
512
513 decompressResult = decompress_input(self, &output);
514
515 if (-1 == decompressResult) {
516 goto finally;
517 }
518 else if (0 == decompressResult || 1 == decompressResult) {
519 }
520 else {
521 assert(0);
522 }
523
524 if (output.pos) {
525 break;
526 }
527 }
528
529 self->bytesDecompressed += output.pos;
530 result = PyLong_FromSize_t(output.pos);
531
532 finally:
533 PyBuffer_Release(&dest);
534
535 return result;
536 }
537
538 static PyObject *decompressionreader_readall(PyObject *self) {
539 PyObject *chunks = NULL;
540 PyObject *empty = NULL;
541 PyObject *result = NULL;
542
543 /* Our strategy is to collect chunks into a list then join all the
544 * chunks at the end. We could potentially use e.g. an io.BytesIO. But
545 * this feels simple enough to implement and avoids potentially expensive
546 * reallocations of large buffers.
547 */
548 chunks = PyList_New(0);
549 if (NULL == chunks) {
550 return NULL;
551 }
552
553 while (1) {
554 PyObject *chunk = PyObject_CallMethod(self, "read", "i", 1048576);
555 if (NULL == chunk) {
556 Py_DECREF(chunks);
557 return NULL;
558 }
559
560 if (!PyBytes_Size(chunk)) {
561 Py_DECREF(chunk);
562 break;
563 }
564
565 if (PyList_Append(chunks, chunk)) {
566 Py_DECREF(chunk);
567 Py_DECREF(chunks);
568 return NULL;
569 }
570
571 Py_DECREF(chunk);
572 }
573
574 empty = PyBytes_FromStringAndSize("", 0);
575 if (NULL == empty) {
576 Py_DECREF(chunks);
577 return NULL;
578 }
579
580 result = PyObject_CallMethod(empty, "join", "O", chunks);
581
582 Py_DECREF(empty);
583 Py_DECREF(chunks);
584
585 return result;
586 }
587
588 static PyObject *decompressionreader_readline(PyObject *self, PyObject *args,
589 PyObject *kwargs) {
590 set_io_unsupported_operation();
591 return NULL;
592 }
593
594 static PyObject *decompressionreader_readlines(PyObject *self, PyObject *args,
595 PyObject *kwargs) {
596 set_io_unsupported_operation();
597 return NULL;
598 }
599
600 static PyObject *decompressionreader_seek(ZstdDecompressionReader *self,
601 PyObject *args) {
602 Py_ssize_t pos;
603 int whence = 0;
604 unsigned long long readAmount = 0;
605 size_t defaultOutSize = ZSTD_DStreamOutSize();
606
607 if (self->closed) {
608 PyErr_SetString(PyExc_ValueError, "stream is closed");
609 return NULL;
610 }
611
612 if (!PyArg_ParseTuple(args, "n|i:seek", &pos, &whence)) {
613 return NULL;
614 }
615
616 if (whence == SEEK_SET) {
617 if (pos < 0) {
618 PyErr_SetString(PyExc_OSError,
619 "cannot seek to negative position with SEEK_SET");
620 return NULL;
621 }
622
623 if ((unsigned long long)pos < self->bytesDecompressed) {
624 PyErr_SetString(PyExc_OSError,
625 "cannot seek zstd decompression stream backwards");
626 return NULL;
627 }
628
629 readAmount = pos - self->bytesDecompressed;
630 }
631 else if (whence == SEEK_CUR) {
632 if (pos < 0) {
633 PyErr_SetString(PyExc_OSError,
634 "cannot seek zstd decompression stream backwards");
635 return NULL;
636 }
637
638 readAmount = pos;
639 }
640 else if (whence == SEEK_END) {
641 /* We /could/ support this with pos==0. But let's not do that until
642 someone needs it. */
643 PyErr_SetString(
644 PyExc_OSError,
645 "zstd decompression streams cannot be seeked with SEEK_END");
646 return NULL;
647 }
648
649 /* It is a bit inefficient to do this via the Python API. But since there
650 is a bit of state tracking involved to read from this type, it is the
651 easiest to implement. */
652 while (readAmount) {
653 Py_ssize_t readSize;
654 PyObject *readResult = PyObject_CallMethod(
655 (PyObject *)self, "read", "K",
656 readAmount < defaultOutSize ? readAmount : defaultOutSize);
657
658 if (!readResult) {
659 return NULL;
660 }
661
662 readSize = PyBytes_GET_SIZE(readResult);
663
664 Py_CLEAR(readResult);
665
666 /* Empty read means EOF. */
667 if (!readSize) {
668 break;
669 }
670
671 readAmount -= readSize;
672 }
673
674 return PyLong_FromUnsignedLongLong(self->bytesDecompressed);
675 }
676
677 static PyObject *decompressionreader_tell(ZstdDecompressionReader *self) {
678 /* TODO should this raise OSError since stream isn't seekable? */
679 return PyLong_FromUnsignedLongLong(self->bytesDecompressed);
680 }
681
682 static PyObject *decompressionreader_write(PyObject *self, PyObject *args) {
683 set_io_unsupported_operation();
684 return NULL;
685 }
686
687 static PyObject *decompressionreader_writelines(PyObject *self,
688 PyObject *args) {
689 set_io_unsupported_operation();
690 return NULL;
691 }
692
693 static PyObject *decompressionreader_iter(PyObject *self) {
694 set_io_unsupported_operation();
695 return NULL;
696 }
697
698 static PyObject *decompressionreader_iternext(PyObject *self) {
699 set_io_unsupported_operation();
700 return NULL;
701 }
702
703 static PyMethodDef decompressionreader_methods[] = {
704 {"__enter__", (PyCFunction)decompressionreader_enter, METH_NOARGS,
705 PyDoc_STR("Enter a compression context")},
706 {"__exit__", (PyCFunction)decompressionreader_exit, METH_VARARGS,
707 PyDoc_STR("Exit a compression context")},
708 {"close", (PyCFunction)decompressionreader_close, METH_NOARGS,
709 PyDoc_STR("Close the stream so it cannot perform any more operations")},
710 {"flush", (PyCFunction)decompressionreader_flush, METH_NOARGS,
711 PyDoc_STR("no-ops")},
712 {"isatty", (PyCFunction)decompressionreader_isatty, METH_NOARGS,
713 PyDoc_STR("Returns False")},
714 {"readable", (PyCFunction)decompressionreader_readable, METH_NOARGS,
715 PyDoc_STR("Returns True")},
716 {"read", (PyCFunction)decompressionreader_read,
717 METH_VARARGS | METH_KEYWORDS, PyDoc_STR("read compressed data")},
718 {"read1", (PyCFunction)decompressionreader_read1,
719 METH_VARARGS | METH_KEYWORDS, PyDoc_STR("read compressed data")},
720 {"readinto", (PyCFunction)decompressionreader_readinto, METH_VARARGS, NULL},
721 {"readinto1", (PyCFunction)decompressionreader_readinto1, METH_VARARGS,
722 NULL},
723 {"readall", (PyCFunction)decompressionreader_readall, METH_NOARGS,
724 PyDoc_STR("Not implemented")},
725 {"readline", (PyCFunction)decompressionreader_readline,
726 METH_VARARGS | METH_KEYWORDS, PyDoc_STR("Not implemented")},
727 {"readlines", (PyCFunction)decompressionreader_readlines,
728 METH_VARARGS | METH_KEYWORDS, PyDoc_STR("Not implemented")},
729 {"seek", (PyCFunction)decompressionreader_seek, METH_VARARGS,
730 PyDoc_STR("Seek the stream")},
731 {"seekable", (PyCFunction)decompressionreader_seekable, METH_NOARGS,
732 PyDoc_STR("Returns False")},
733 {"tell", (PyCFunction)decompressionreader_tell, METH_NOARGS,
734 PyDoc_STR("Returns current number of bytes compressed")},
735 {"writable", (PyCFunction)decompressionreader_writable, METH_NOARGS,
736 PyDoc_STR("Returns False")},
737 {"write", (PyCFunction)decompressionreader_write, METH_VARARGS,
738 PyDoc_STR("unsupported operation")},
739 {"writelines", (PyCFunction)decompressionreader_writelines, METH_VARARGS,
740 PyDoc_STR("unsupported operation")},
741 {NULL, NULL}};
742
743 static PyMemberDef decompressionreader_members[] = {
744 {"closed", T_BOOL, offsetof(ZstdDecompressionReader, closed), READONLY,
745 "whether stream is closed"},
746 {NULL}};
747
748 PyType_Slot ZstdDecompressionReaderSlots[] = {
749 {Py_tp_dealloc, decompressionreader_dealloc},
750 {Py_tp_iter, decompressionreader_iter},
751 {Py_tp_iternext, decompressionreader_iternext},
752 {Py_tp_methods, decompressionreader_methods},
753 {Py_tp_members, decompressionreader_members},
754 {Py_tp_new, PyType_GenericNew},
755 {0, NULL},
756 };
757
758 PyType_Spec ZstdDecompressionReaderSpec = {
759 "zstandard.backend_c.ZstdDecompressionReader",
760 sizeof(ZstdDecompressionReader),
761 0,
762 Py_TPFLAGS_DEFAULT,
763 ZstdDecompressionReaderSlots,
764 };
765
766 PyTypeObject *ZstdDecompressionReaderType;
767
768 void decompressionreader_module_init(PyObject *mod) {
769 /* TODO make reader a sub-class of io.RawIOBase */
770
771 ZstdDecompressionReaderType =
772 (PyTypeObject *)PyType_FromSpec(&ZstdDecompressionReaderSpec);
773 if (PyType_Ready(ZstdDecompressionReaderType) < 0) {
774 return;
775 }
776
777 Py_INCREF((PyObject *)ZstdDecompressionReaderType);
778 PyModule_AddObject(mod, "ZstdDecompressionReader",
779 (PyObject *)ZstdDecompressionReaderType);
780 }