You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

626 lines
19 KiB

  1. /* _bz2 - Low-level Python interface to libbzip2. */
  2. #define PY_SSIZE_T_CLEAN
  3. #include "Python.h"
  4. #include "structmember.h"
  5. #ifdef WITH_THREAD
  6. #include "pythread.h"
  7. #endif
  8. #include <bzlib.h>
  9. #include <stdio.h>
  10. #ifndef BZ_CONFIG_ERROR
  11. #define BZ2_bzCompress bzCompress
  12. #define BZ2_bzCompressInit bzCompressInit
  13. #define BZ2_bzCompressEnd bzCompressEnd
  14. #define BZ2_bzDecompress bzDecompress
  15. #define BZ2_bzDecompressInit bzDecompressInit
  16. #define BZ2_bzDecompressEnd bzDecompressEnd
  17. #endif /* ! BZ_CONFIG_ERROR */
  18. #ifdef WITH_THREAD
  19. #define ACQUIRE_LOCK(obj) do { \
  20. if (!PyThread_acquire_lock((obj)->lock, 0)) { \
  21. Py_BEGIN_ALLOW_THREADS \
  22. PyThread_acquire_lock((obj)->lock, 1); \
  23. Py_END_ALLOW_THREADS \
  24. } } while (0)
  25. #define RELEASE_LOCK(obj) PyThread_release_lock((obj)->lock)
  26. #else
  27. #define ACQUIRE_LOCK(obj)
  28. #define RELEASE_LOCK(obj)
  29. #endif
  30. typedef struct {
  31. PyObject_HEAD
  32. bz_stream bzs;
  33. int flushed;
  34. #ifdef WITH_THREAD
  35. PyThread_type_lock lock;
  36. #endif
  37. } BZ2Compressor;
  38. typedef struct {
  39. PyObject_HEAD
  40. bz_stream bzs;
  41. char eof; /* T_BOOL expects a char */
  42. PyObject *unused_data;
  43. #ifdef WITH_THREAD
  44. PyThread_type_lock lock;
  45. #endif
  46. } BZ2Decompressor;
  47. /* Helper functions. */
  48. static int
  49. catch_bz2_error(int bzerror)
  50. {
  51. switch(bzerror) {
  52. case BZ_OK:
  53. case BZ_RUN_OK:
  54. case BZ_FLUSH_OK:
  55. case BZ_FINISH_OK:
  56. case BZ_STREAM_END:
  57. return 0;
  58. #ifdef BZ_CONFIG_ERROR
  59. case BZ_CONFIG_ERROR:
  60. PyErr_SetString(PyExc_SystemError,
  61. "libbzip2 was not compiled correctly");
  62. return 1;
  63. #endif
  64. case BZ_PARAM_ERROR:
  65. PyErr_SetString(PyExc_ValueError,
  66. "Internal error - "
  67. "invalid parameters passed to libbzip2");
  68. return 1;
  69. case BZ_MEM_ERROR:
  70. PyErr_NoMemory();
  71. return 1;
  72. case BZ_DATA_ERROR:
  73. case BZ_DATA_ERROR_MAGIC:
  74. PyErr_SetString(PyExc_IOError, "Invalid data stream");
  75. return 1;
  76. case BZ_IO_ERROR:
  77. PyErr_SetString(PyExc_IOError, "Unknown I/O error");
  78. return 1;
  79. case BZ_UNEXPECTED_EOF:
  80. PyErr_SetString(PyExc_EOFError,
  81. "Compressed file ended before the logical "
  82. "end-of-stream was detected");
  83. return 1;
  84. case BZ_SEQUENCE_ERROR:
  85. PyErr_SetString(PyExc_RuntimeError,
  86. "Internal error - "
  87. "Invalid sequence of commands sent to libbzip2");
  88. return 1;
  89. default:
  90. PyErr_Format(PyExc_IOError,
  91. "Unrecognized error from libbzip2: %d", bzerror);
  92. return 1;
  93. }
  94. }
  95. #if BUFSIZ < 8192
  96. #define SMALLCHUNK 8192
  97. #else
  98. #define SMALLCHUNK BUFSIZ
  99. #endif
  100. static int
  101. grow_buffer(PyObject **buf)
  102. {
  103. /* Expand the buffer by an amount proportional to the current size,
  104. giving us amortized linear-time behavior. Use a less-than-double
  105. growth factor to avoid excessive allocation. */
  106. size_t size = PyBytes_GET_SIZE(*buf);
  107. size_t new_size = size + (size >> 3) + 6;
  108. if (new_size > size) {
  109. return _PyBytes_Resize(buf, new_size);
  110. } else { /* overflow */
  111. PyErr_SetString(PyExc_OverflowError,
  112. "Unable to allocate buffer - output too large");
  113. return -1;
  114. }
  115. }
  116. /* BZ2Compressor class. */
  117. static PyObject *
  118. compress(BZ2Compressor *c, char *data, size_t len, int action)
  119. {
  120. size_t data_size = 0;
  121. PyObject *result;
  122. result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
  123. if (result == NULL)
  124. return NULL;
  125. c->bzs.next_in = data;
  126. c->bzs.avail_in = 0;
  127. c->bzs.next_out = PyBytes_AS_STRING(result);
  128. c->bzs.avail_out = SMALLCHUNK;
  129. for (;;) {
  130. char *this_out;
  131. int bzerror;
  132. /* On a 64-bit system, len might not fit in avail_in (an unsigned int).
  133. Do compression in chunks of no more than UINT_MAX bytes each. */
  134. if (c->bzs.avail_in == 0 && len > 0) {
  135. c->bzs.avail_in = (unsigned int)Py_MIN(len, UINT_MAX);
  136. len -= c->bzs.avail_in;
  137. }
  138. /* In regular compression mode, stop when input data is exhausted. */
  139. if (action == BZ_RUN && c->bzs.avail_in == 0)
  140. break;
  141. if (c->bzs.avail_out == 0) {
  142. size_t buffer_left = PyBytes_GET_SIZE(result) - data_size;
  143. if (buffer_left == 0) {
  144. if (grow_buffer(&result) < 0)
  145. goto error;
  146. c->bzs.next_out = PyBytes_AS_STRING(result) + data_size;
  147. buffer_left = PyBytes_GET_SIZE(result) - data_size;
  148. }
  149. c->bzs.avail_out = (unsigned int)Py_MIN(buffer_left, UINT_MAX);
  150. }
  151. Py_BEGIN_ALLOW_THREADS
  152. this_out = c->bzs.next_out;
  153. bzerror = BZ2_bzCompress(&c->bzs, action);
  154. data_size += c->bzs.next_out - this_out;
  155. Py_END_ALLOW_THREADS
  156. if (catch_bz2_error(bzerror))
  157. goto error;
  158. /* In flushing mode, stop when all buffered data has been flushed. */
  159. if (action == BZ_FINISH && bzerror == BZ_STREAM_END)
  160. break;
  161. }
  162. if (data_size != PyBytes_GET_SIZE(result))
  163. if (_PyBytes_Resize(&result, data_size) < 0)
  164. goto error;
  165. return result;
  166. error:
  167. Py_XDECREF(result);
  168. return NULL;
  169. }
  170. PyDoc_STRVAR(BZ2Compressor_compress__doc__,
  171. "compress(data) -> bytes\n"
  172. "\n"
  173. "Provide data to the compressor object. Returns a chunk of\n"
  174. "compressed data if possible, or b'' otherwise.\n"
  175. "\n"
  176. "When you have finished providing data to the compressor, call the\n"
  177. "flush() method to finish the compression process.\n");
  178. static PyObject *
  179. BZ2Compressor_compress(BZ2Compressor *self, PyObject *args)
  180. {
  181. Py_buffer buffer;
  182. PyObject *result = NULL;
  183. if (!PyArg_ParseTuple(args, "y*:compress", &buffer))
  184. return NULL;
  185. ACQUIRE_LOCK(self);
  186. if (self->flushed)
  187. PyErr_SetString(PyExc_ValueError, "Compressor has been flushed");
  188. else
  189. result = compress(self, buffer.buf, buffer.len, BZ_RUN);
  190. RELEASE_LOCK(self);
  191. PyBuffer_Release(&buffer);
  192. return result;
  193. }
  194. PyDoc_STRVAR(BZ2Compressor_flush__doc__,
  195. "flush() -> bytes\n"
  196. "\n"
  197. "Finish the compression process. Returns the compressed data left\n"
  198. "in internal buffers.\n"
  199. "\n"
  200. "The compressor object may not be used after this method is called.\n");
  201. static PyObject *
  202. BZ2Compressor_flush(BZ2Compressor *self, PyObject *noargs)
  203. {
  204. PyObject *result = NULL;
  205. ACQUIRE_LOCK(self);
  206. if (self->flushed)
  207. PyErr_SetString(PyExc_ValueError, "Repeated call to flush()");
  208. else {
  209. self->flushed = 1;
  210. result = compress(self, NULL, 0, BZ_FINISH);
  211. }
  212. RELEASE_LOCK(self);
  213. return result;
  214. }
  215. static void*
  216. BZ2_Malloc(void* ctx, int items, int size)
  217. {
  218. if (items < 0 || size < 0)
  219. return NULL;
  220. if ((size_t)items > (size_t)PY_SSIZE_T_MAX / (size_t)size)
  221. return NULL;
  222. /* PyMem_Malloc() cannot be used: compress() and decompress()
  223. release the GIL */
  224. return PyMem_RawMalloc(items * size);
  225. }
  226. static void
  227. BZ2_Free(void* ctx, void *ptr)
  228. {
  229. PyMem_RawFree(ptr);
  230. }
  231. static int
  232. BZ2Compressor_init(BZ2Compressor *self, PyObject *args, PyObject *kwargs)
  233. {
  234. int compresslevel = 9;
  235. int bzerror;
  236. if (!PyArg_ParseTuple(args, "|i:BZ2Compressor", &compresslevel))
  237. return -1;
  238. if (!(1 <= compresslevel && compresslevel <= 9)) {
  239. PyErr_SetString(PyExc_ValueError,
  240. "compresslevel must be between 1 and 9");
  241. return -1;
  242. }
  243. #ifdef WITH_THREAD
  244. self->lock = PyThread_allocate_lock();
  245. if (self->lock == NULL) {
  246. PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
  247. return -1;
  248. }
  249. #endif
  250. self->bzs.opaque = NULL;
  251. self->bzs.bzalloc = BZ2_Malloc;
  252. self->bzs.bzfree = BZ2_Free;
  253. bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0);
  254. if (catch_bz2_error(bzerror))
  255. goto error;
  256. return 0;
  257. error:
  258. #ifdef WITH_THREAD
  259. PyThread_free_lock(self->lock);
  260. self->lock = NULL;
  261. #endif
  262. return -1;
  263. }
  264. static void
  265. BZ2Compressor_dealloc(BZ2Compressor *self)
  266. {
  267. BZ2_bzCompressEnd(&self->bzs);
  268. #ifdef WITH_THREAD
  269. if (self->lock != NULL)
  270. PyThread_free_lock(self->lock);
  271. #endif
  272. Py_TYPE(self)->tp_free((PyObject *)self);
  273. }
  274. static PyMethodDef BZ2Compressor_methods[] = {
  275. {"compress", (PyCFunction)BZ2Compressor_compress, METH_VARARGS,
  276. BZ2Compressor_compress__doc__},
  277. {"flush", (PyCFunction)BZ2Compressor_flush, METH_NOARGS,
  278. BZ2Compressor_flush__doc__},
  279. {NULL}
  280. };
  281. PyDoc_STRVAR(BZ2Compressor__doc__,
  282. "BZ2Compressor(compresslevel=9)\n"
  283. "\n"
  284. "Create a compressor object for compressing data incrementally.\n"
  285. "\n"
  286. "compresslevel, if given, must be a number between 1 and 9.\n"
  287. "\n"
  288. "For one-shot compression, use the compress() function instead.\n");
  289. static PyTypeObject BZ2Compressor_Type = {
  290. PyVarObject_HEAD_INIT(NULL, 0)
  291. "_bz2.BZ2Compressor", /* tp_name */
  292. sizeof(BZ2Compressor), /* tp_basicsize */
  293. 0, /* tp_itemsize */
  294. (destructor)BZ2Compressor_dealloc, /* tp_dealloc */
  295. 0, /* tp_print */
  296. 0, /* tp_getattr */
  297. 0, /* tp_setattr */
  298. 0, /* tp_reserved */
  299. 0, /* tp_repr */
  300. 0, /* tp_as_number */
  301. 0, /* tp_as_sequence */
  302. 0, /* tp_as_mapping */
  303. 0, /* tp_hash */
  304. 0, /* tp_call */
  305. 0, /* tp_str */
  306. 0, /* tp_getattro */
  307. 0, /* tp_setattro */
  308. 0, /* tp_as_buffer */
  309. Py_TPFLAGS_DEFAULT, /* tp_flags */
  310. BZ2Compressor__doc__, /* tp_doc */
  311. 0, /* tp_traverse */
  312. 0, /* tp_clear */
  313. 0, /* tp_richcompare */
  314. 0, /* tp_weaklistoffset */
  315. 0, /* tp_iter */
  316. 0, /* tp_iternext */
  317. BZ2Compressor_methods, /* tp_methods */
  318. 0, /* tp_members */
  319. 0, /* tp_getset */
  320. 0, /* tp_base */
  321. 0, /* tp_dict */
  322. 0, /* tp_descr_get */
  323. 0, /* tp_descr_set */
  324. 0, /* tp_dictoffset */
  325. (initproc)BZ2Compressor_init, /* tp_init */
  326. 0, /* tp_alloc */
  327. PyType_GenericNew, /* tp_new */
  328. };
  329. /* BZ2Decompressor class. */
  330. static PyObject *
  331. decompress(BZ2Decompressor *d, char *data, size_t len)
  332. {
  333. size_t data_size = 0;
  334. PyObject *result;
  335. result = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
  336. if (result == NULL)
  337. return result;
  338. d->bzs.next_in = data;
  339. /* On a 64-bit system, len might not fit in avail_in (an unsigned int).
  340. Do decompression in chunks of no more than UINT_MAX bytes each. */
  341. d->bzs.avail_in = (unsigned int)Py_MIN(len, UINT_MAX);
  342. len -= d->bzs.avail_in;
  343. d->bzs.next_out = PyBytes_AS_STRING(result);
  344. d->bzs.avail_out = SMALLCHUNK;
  345. for (;;) {
  346. char *this_out;
  347. int bzerror;
  348. Py_BEGIN_ALLOW_THREADS
  349. this_out = d->bzs.next_out;
  350. bzerror = BZ2_bzDecompress(&d->bzs);
  351. data_size += d->bzs.next_out - this_out;
  352. Py_END_ALLOW_THREADS
  353. if (catch_bz2_error(bzerror))
  354. goto error;
  355. if (bzerror == BZ_STREAM_END) {
  356. d->eof = 1;
  357. len += d->bzs.avail_in;
  358. if (len > 0) { /* Save leftover input to unused_data */
  359. Py_CLEAR(d->unused_data);
  360. d->unused_data = PyBytes_FromStringAndSize(d->bzs.next_in, len);
  361. if (d->unused_data == NULL)
  362. goto error;
  363. }
  364. break;
  365. }
  366. if (d->bzs.avail_in == 0) {
  367. if (len == 0)
  368. break;
  369. d->bzs.avail_in = (unsigned int)Py_MIN(len, UINT_MAX);
  370. len -= d->bzs.avail_in;
  371. }
  372. if (d->bzs.avail_out == 0) {
  373. size_t buffer_left = PyBytes_GET_SIZE(result) - data_size;
  374. if (buffer_left == 0) {
  375. if (grow_buffer(&result) < 0)
  376. goto error;
  377. d->bzs.next_out = PyBytes_AS_STRING(result) + data_size;
  378. buffer_left = PyBytes_GET_SIZE(result) - data_size;
  379. }
  380. d->bzs.avail_out = (unsigned int)Py_MIN(buffer_left, UINT_MAX);
  381. }
  382. }
  383. if (data_size != PyBytes_GET_SIZE(result))
  384. if (_PyBytes_Resize(&result, data_size) < 0)
  385. goto error;
  386. return result;
  387. error:
  388. Py_XDECREF(result);
  389. return NULL;
  390. }
  391. PyDoc_STRVAR(BZ2Decompressor_decompress__doc__,
  392. "decompress(data) -> bytes\n"
  393. "\n"
  394. "Provide data to the decompressor object. Returns a chunk of\n"
  395. "decompressed data if possible, or b'' otherwise.\n"
  396. "\n"
  397. "Attempting to decompress data after the end of stream is reached\n"
  398. "raises an EOFError. Any data found after the end of the stream\n"
  399. "is ignored and saved in the unused_data attribute.\n");
  400. static PyObject *
  401. BZ2Decompressor_decompress(BZ2Decompressor *self, PyObject *args)
  402. {
  403. Py_buffer buffer;
  404. PyObject *result = NULL;
  405. if (!PyArg_ParseTuple(args, "y*:decompress", &buffer))
  406. return NULL;
  407. ACQUIRE_LOCK(self);
  408. if (self->eof)
  409. PyErr_SetString(PyExc_EOFError, "End of stream already reached");
  410. else
  411. result = decompress(self, buffer.buf, buffer.len);
  412. RELEASE_LOCK(self);
  413. PyBuffer_Release(&buffer);
  414. return result;
  415. }
  416. static int
  417. BZ2Decompressor_init(BZ2Decompressor *self, PyObject *args, PyObject *kwargs)
  418. {
  419. int bzerror;
  420. if (!PyArg_ParseTuple(args, ":BZ2Decompressor"))
  421. return -1;
  422. #ifdef WITH_THREAD
  423. self->lock = PyThread_allocate_lock();
  424. if (self->lock == NULL) {
  425. PyErr_SetString(PyExc_MemoryError, "Unable to allocate lock");
  426. return -1;
  427. }
  428. #endif
  429. self->unused_data = PyBytes_FromStringAndSize("", 0);
  430. if (self->unused_data == NULL)
  431. goto error;
  432. bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0);
  433. if (catch_bz2_error(bzerror))
  434. goto error;
  435. return 0;
  436. error:
  437. Py_CLEAR(self->unused_data);
  438. #ifdef WITH_THREAD
  439. PyThread_free_lock(self->lock);
  440. self->lock = NULL;
  441. #endif
  442. return -1;
  443. }
  444. static void
  445. BZ2Decompressor_dealloc(BZ2Decompressor *self)
  446. {
  447. BZ2_bzDecompressEnd(&self->bzs);
  448. Py_CLEAR(self->unused_data);
  449. #ifdef WITH_THREAD
  450. if (self->lock != NULL)
  451. PyThread_free_lock(self->lock);
  452. #endif
  453. Py_TYPE(self)->tp_free((PyObject *)self);
  454. }
  455. static PyMethodDef BZ2Decompressor_methods[] = {
  456. {"decompress", (PyCFunction)BZ2Decompressor_decompress, METH_VARARGS,
  457. BZ2Decompressor_decompress__doc__},
  458. {NULL}
  459. };
  460. PyDoc_STRVAR(BZ2Decompressor_eof__doc__,
  461. "True if the end-of-stream marker has been reached.");
  462. PyDoc_STRVAR(BZ2Decompressor_unused_data__doc__,
  463. "Data found after the end of the compressed stream.");
  464. static PyMemberDef BZ2Decompressor_members[] = {
  465. {"eof", T_BOOL, offsetof(BZ2Decompressor, eof),
  466. READONLY, BZ2Decompressor_eof__doc__},
  467. {"unused_data", T_OBJECT_EX, offsetof(BZ2Decompressor, unused_data),
  468. READONLY, BZ2Decompressor_unused_data__doc__},
  469. {NULL}
  470. };
  471. PyDoc_STRVAR(BZ2Decompressor__doc__,
  472. "BZ2Decompressor()\n"
  473. "\n"
  474. "Create a decompressor object for decompressing data incrementally.\n"
  475. "\n"
  476. "For one-shot decompression, use the decompress() function instead.\n");
  477. static PyTypeObject BZ2Decompressor_Type = {
  478. PyVarObject_HEAD_INIT(NULL, 0)
  479. "_bz2.BZ2Decompressor", /* tp_name */
  480. sizeof(BZ2Decompressor), /* tp_basicsize */
  481. 0, /* tp_itemsize */
  482. (destructor)BZ2Decompressor_dealloc,/* tp_dealloc */
  483. 0, /* tp_print */
  484. 0, /* tp_getattr */
  485. 0, /* tp_setattr */
  486. 0, /* tp_reserved */
  487. 0, /* tp_repr */
  488. 0, /* tp_as_number */
  489. 0, /* tp_as_sequence */
  490. 0, /* tp_as_mapping */
  491. 0, /* tp_hash */
  492. 0, /* tp_call */
  493. 0, /* tp_str */
  494. 0, /* tp_getattro */
  495. 0, /* tp_setattro */
  496. 0, /* tp_as_buffer */
  497. Py_TPFLAGS_DEFAULT, /* tp_flags */
  498. BZ2Decompressor__doc__, /* tp_doc */
  499. 0, /* tp_traverse */
  500. 0, /* tp_clear */
  501. 0, /* tp_richcompare */
  502. 0, /* tp_weaklistoffset */
  503. 0, /* tp_iter */
  504. 0, /* tp_iternext */
  505. BZ2Decompressor_methods, /* tp_methods */
  506. BZ2Decompressor_members, /* tp_members */
  507. 0, /* tp_getset */
  508. 0, /* tp_base */
  509. 0, /* tp_dict */
  510. 0, /* tp_descr_get */
  511. 0, /* tp_descr_set */
  512. 0, /* tp_dictoffset */
  513. (initproc)BZ2Decompressor_init, /* tp_init */
  514. 0, /* tp_alloc */
  515. PyType_GenericNew, /* tp_new */
  516. };
  517. /* Module initialization. */
  518. static struct PyModuleDef _bz2module = {
  519. PyModuleDef_HEAD_INIT,
  520. "_bz2",
  521. NULL,
  522. -1,
  523. NULL,
  524. NULL,
  525. NULL,
  526. NULL,
  527. NULL
  528. };
  529. PyMODINIT_FUNC
  530. PyInit__bz2(void)
  531. {
  532. PyObject *m;
  533. if (PyType_Ready(&BZ2Compressor_Type) < 0)
  534. return NULL;
  535. if (PyType_Ready(&BZ2Decompressor_Type) < 0)
  536. return NULL;
  537. m = PyModule_Create(&_bz2module);
  538. if (m == NULL)
  539. return NULL;
  540. Py_INCREF(&BZ2Compressor_Type);
  541. PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Compressor_Type);
  542. Py_INCREF(&BZ2Decompressor_Type);
  543. PyModule_AddObject(m, "BZ2Decompressor",
  544. (PyObject *)&BZ2Decompressor_Type);
  545. return m;
  546. }