1/*
2  +----------------------------------------------------------------------+
3  | PHP Version 5                                                        |
4  +----------------------------------------------------------------------+
5  | Copyright (c) 1997-2014 The PHP Group                                |
6  +----------------------------------------------------------------------+
7  | This source file is subject to version 3.01 of the PHP license,      |
8  | that is bundled with this package in the file LICENSE, and is        |
9  | available through the world-wide-web at the following url:           |
10  | http://www.php.net/license/3_01.txt                                  |
11  | If you did not receive a copy of the PHP license and are unable to   |
12  | obtain it through the world-wide-web, please send a note to          |
13  | license@php.net so we can mail you a copy immediately.               |
14  +----------------------------------------------------------------------+
15  | Author: Sterling Hughes <sterling@php.net>                           |
16  +----------------------------------------------------------------------+
17*/
18
19/* $Id$ */
20
21#ifdef HAVE_CONFIG_H
22#include "config.h"
23#endif
24
25#include "php.h"
26#include "php_bz2.h"
27
28#if HAVE_BZ2
29
30/* PHP Includes */
31#include "ext/standard/file.h"
32#include "ext/standard/info.h"
33#include "ext/standard/php_string.h"
34#include "main/php_network.h"
35
36/* for fileno() */
37#include <stdio.h>
38
39/* Internal error constants */
40#define PHP_BZ_ERRNO   0
41#define PHP_BZ_ERRSTR  1
42#define PHP_BZ_ERRBOTH 2
43
44static PHP_MINIT_FUNCTION(bz2);
45static PHP_MSHUTDOWN_FUNCTION(bz2);
46static PHP_MINFO_FUNCTION(bz2);
47static PHP_FUNCTION(bzopen);
48static PHP_FUNCTION(bzread);
49static PHP_FUNCTION(bzerrno);
50static PHP_FUNCTION(bzerrstr);
51static PHP_FUNCTION(bzerror);
52static PHP_FUNCTION(bzcompress);
53static PHP_FUNCTION(bzdecompress);
54
55/* {{{ arginfo */
56ZEND_BEGIN_ARG_INFO_EX(arginfo_bzread, 0, 0, 1)
57    ZEND_ARG_INFO(0, bz)
58    ZEND_ARG_INFO(0, length)
59ZEND_END_ARG_INFO()
60
61ZEND_BEGIN_ARG_INFO(arginfo_bzopen, 0)
62    ZEND_ARG_INFO(0, file)
63    ZEND_ARG_INFO(0, mode)
64ZEND_END_ARG_INFO()
65
66ZEND_BEGIN_ARG_INFO(arginfo_bzerrno, 0)
67    ZEND_ARG_INFO(0, bz)
68ZEND_END_ARG_INFO()
69
70ZEND_BEGIN_ARG_INFO(arginfo_bzerrstr, 0)
71    ZEND_ARG_INFO(0, bz)
72ZEND_END_ARG_INFO()
73
74ZEND_BEGIN_ARG_INFO(arginfo_bzerror, 0)
75    ZEND_ARG_INFO(0, bz)
76ZEND_END_ARG_INFO()
77
78ZEND_BEGIN_ARG_INFO_EX(arginfo_bzcompress, 0, 0, 2)
79    ZEND_ARG_INFO(0, source)
80    ZEND_ARG_INFO(0, blocksize)
81    ZEND_ARG_INFO(0, workfactor)
82ZEND_END_ARG_INFO()
83
84ZEND_BEGIN_ARG_INFO_EX(arginfo_bzdecompress, 0, 0, 1)
85    ZEND_ARG_INFO(0, source)
86    ZEND_ARG_INFO(0, small)
87ZEND_END_ARG_INFO()
88
89ZEND_BEGIN_ARG_INFO_EX(arginfo_bzwrite, 0, 0, 2)
90    ZEND_ARG_INFO(0, fp)
91    ZEND_ARG_INFO(0, str)
92    ZEND_ARG_INFO(0, length)
93ZEND_END_ARG_INFO()
94
95ZEND_BEGIN_ARG_INFO(arginfo_bzflush, 0)
96    ZEND_ARG_INFO(0, fp)
97ZEND_END_ARG_INFO()
98/* }}} */
99
100static const zend_function_entry bz2_functions[] = {
101    PHP_FE(bzopen,       arginfo_bzopen)
102    PHP_FE(bzread,       arginfo_bzread)
103    PHP_FALIAS(bzwrite,   fwrite,       arginfo_bzwrite)
104    PHP_FALIAS(bzflush,   fflush,       arginfo_bzflush)
105    PHP_FALIAS(bzclose,   fclose,       arginfo_bzflush)
106    PHP_FE(bzerrno,      arginfo_bzerrno)
107    PHP_FE(bzerrstr,     arginfo_bzerrstr)
108    PHP_FE(bzerror,      arginfo_bzerror)
109    PHP_FE(bzcompress,   arginfo_bzcompress)
110    PHP_FE(bzdecompress, arginfo_bzdecompress)
111    PHP_FE_END
112};
113
114zend_module_entry bz2_module_entry = {
115    STANDARD_MODULE_HEADER,
116    "bz2",
117    bz2_functions,
118    PHP_MINIT(bz2),
119    PHP_MSHUTDOWN(bz2),
120    NULL,
121    NULL,
122    PHP_MINFO(bz2),
123    NO_VERSION_YET,
124    STANDARD_MODULE_PROPERTIES
125};
126
127#ifdef COMPILE_DL_BZ2
128ZEND_GET_MODULE(bz2)
129#endif
130
131struct php_bz2_stream_data_t {
132    BZFILE *bz_file;
133    php_stream *stream;
134};
135
136/* {{{ BZip2 stream implementation */
137
138static size_t php_bz2iop_read(php_stream *stream, char *buf, size_t count TSRMLS_DC)
139{
140    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *) stream->abstract;
141    size_t ret;
142
143    ret = BZ2_bzread(self->bz_file, buf, count);
144
145    if (ret == 0) {
146        stream->eof = 1;
147    }
148
149    return ret;
150}
151
152static size_t php_bz2iop_write(php_stream *stream, const char *buf, size_t count TSRMLS_DC)
153{
154    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *) stream->abstract;
155
156    return BZ2_bzwrite(self->bz_file, (char*)buf, count);
157}
158
159static int php_bz2iop_close(php_stream *stream, int close_handle TSRMLS_DC)
160{
161    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;
162    int ret = EOF;
163
164    if (close_handle) {
165        BZ2_bzclose(self->bz_file);
166    }
167
168    if (self->stream) {
169        php_stream_free(self->stream, PHP_STREAM_FREE_CLOSE | (close_handle == 0 ? PHP_STREAM_FREE_PRESERVE_HANDLE : 0));
170    }
171
172    efree(self);
173
174    return ret;
175}
176
177static int php_bz2iop_flush(php_stream *stream TSRMLS_DC)
178{
179    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;
180    return BZ2_bzflush(self->bz_file);
181}
182/* }}} */
183
184php_stream_ops php_stream_bz2io_ops = {
185    php_bz2iop_write, php_bz2iop_read,
186    php_bz2iop_close, php_bz2iop_flush,
187    "BZip2",
188    NULL, /* seek */
189    NULL, /* cast */
190    NULL, /* stat */
191    NULL  /* set_option */
192};
193
194/* {{{ Bzip2 stream openers */
195PHP_BZ2_API php_stream *_php_stream_bz2open_from_BZFILE(BZFILE *bz,
196                                                        const char *mode, php_stream *innerstream STREAMS_DC TSRMLS_DC)
197{
198    struct php_bz2_stream_data_t *self;
199
200    self = emalloc(sizeof(*self));
201
202    self->stream = innerstream;
203    self->bz_file = bz;
204
205    return php_stream_alloc_rel(&php_stream_bz2io_ops, self, 0, mode);
206}
207
208PHP_BZ2_API php_stream *_php_stream_bz2open(php_stream_wrapper *wrapper,
209                                            const char *path,
210                                            const char *mode,
211                                            int options,
212                                            char **opened_path,
213                                            php_stream_context *context STREAMS_DC TSRMLS_DC)
214{
215    php_stream *retstream = NULL, *stream = NULL;
216    char *path_copy = NULL;
217    BZFILE *bz_file = NULL;
218
219    if (strncasecmp("compress.bzip2://", path, 17) == 0) {
220        path += 17;
221    }
222    if (mode[0] == '\0' || (mode[0] != 'w' && mode[0] != 'r' && mode[1] != '\0')) {
223        return NULL;
224    }
225
226#ifdef VIRTUAL_DIR
227    virtual_filepath_ex(path, &path_copy, NULL TSRMLS_CC);
228#else
229    path_copy = path;
230#endif
231
232    if (php_check_open_basedir(path_copy TSRMLS_CC)) {
233        return NULL;
234    }
235
236    /* try and open it directly first */
237    bz_file = BZ2_bzopen(path_copy, mode);
238
239    if (opened_path && bz_file) {
240        *opened_path = estrdup(path_copy);
241    }
242    path_copy = NULL;
243
244    if (bz_file == NULL) {
245        /* that didn't work, so try and get something from the network/wrapper */
246        stream = php_stream_open_wrapper(path, mode, options | STREAM_WILL_CAST, opened_path);
247
248        if (stream) {
249            php_socket_t fd;
250            if (SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **) &fd, REPORT_ERRORS)) {
251                bz_file = BZ2_bzdopen(fd, mode);
252            }
253        }
254
255        /* remove the file created by php_stream_open_wrapper(), it is not needed since BZ2 functions
256         * failed.
257         */
258        if (opened_path && !bz_file && mode[0] == 'w') {
259            VCWD_UNLINK(*opened_path);
260        }
261    }
262
263    if (bz_file) {
264        retstream = _php_stream_bz2open_from_BZFILE(bz_file, mode, stream STREAMS_REL_CC TSRMLS_CC);
265        if (retstream) {
266            return retstream;
267        }
268
269        BZ2_bzclose(bz_file);
270    }
271
272    if (stream) {
273        php_stream_close(stream);
274    }
275
276    return NULL;
277}
278
279/* }}} */
280
281static php_stream_wrapper_ops bzip2_stream_wops = {
282    _php_stream_bz2open,
283    NULL, /* close */
284    NULL, /* fstat */
285    NULL, /* stat */
286    NULL, /* opendir */
287    "BZip2",
288    NULL, /* unlink */
289    NULL, /* rename */
290    NULL, /* mkdir */
291    NULL  /* rmdir */
292};
293
294static php_stream_wrapper php_stream_bzip2_wrapper = {
295    &bzip2_stream_wops,
296    NULL,
297    0 /* is_url */
298};
299
300static void php_bz2_error(INTERNAL_FUNCTION_PARAMETERS, int);
301
302static PHP_MINIT_FUNCTION(bz2)
303{
304    php_register_url_stream_wrapper("compress.bzip2", &php_stream_bzip2_wrapper TSRMLS_CC);
305    php_stream_filter_register_factory("bzip2.*", &php_bz2_filter_factory TSRMLS_CC);
306    return SUCCESS;
307}
308
309static PHP_MSHUTDOWN_FUNCTION(bz2)
310{
311    php_unregister_url_stream_wrapper("compress.bzip2" TSRMLS_CC);
312    php_stream_filter_unregister_factory("bzip2.*" TSRMLS_CC);
313
314    return SUCCESS;
315}
316
317static PHP_MINFO_FUNCTION(bz2)
318{
319    php_info_print_table_start();
320    php_info_print_table_row(2, "BZip2 Support", "Enabled");
321    php_info_print_table_row(2, "Stream Wrapper support", "compress.bzip2://");
322    php_info_print_table_row(2, "Stream Filter support", "bzip2.decompress, bzip2.compress");
323    php_info_print_table_row(2, "BZip2 Version", (char *) BZ2_bzlibVersion());
324    php_info_print_table_end();
325}
326
327/* {{{ proto string bzread(resource bz[, int length])
328   Reads up to length bytes from a BZip2 stream, or 1024 bytes if length is not specified */
329static PHP_FUNCTION(bzread)
330{
331    zval *bz;
332    long len = 1024;
333    php_stream *stream;
334
335    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r|l", &bz, &len)) {
336        RETURN_FALSE;
337    }
338
339    php_stream_from_zval(stream, &bz);
340
341    if ((len + 1) < 1) {
342        php_error_docref(NULL TSRMLS_CC, E_WARNING, "length may not be negative");
343        RETURN_FALSE;
344    }
345
346    Z_STRVAL_P(return_value) = emalloc(len + 1);
347    Z_STRLEN_P(return_value) = php_stream_read(stream, Z_STRVAL_P(return_value), len);
348
349    if (Z_STRLEN_P(return_value) < 0) {
350        efree(Z_STRVAL_P(return_value));
351        php_error_docref(NULL TSRMLS_CC, E_WARNING, "could not read valid bz2 data from stream");
352        RETURN_FALSE;
353    }
354
355    Z_STRVAL_P(return_value)[Z_STRLEN_P(return_value)] = 0;
356    Z_TYPE_P(return_value) = IS_STRING;
357}
358/* }}} */
359
360/* {{{ proto resource bzopen(string|int file|fp, string mode)
361   Opens a new BZip2 stream */
362static PHP_FUNCTION(bzopen)
363{
364    zval    **file;   /* The file to open */
365    char     *mode;   /* The mode to open the stream with */
366    int      mode_len;
367
368    BZFILE   *bz;     /* The compressed file stream */
369    php_stream *stream = NULL;
370
371    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "Zs", &file, &mode, &mode_len) == FAILURE) {
372        return;
373    }
374
375    if (mode_len != 1 || (mode[0] != 'r' && mode[0] != 'w')) {
376        php_error_docref(NULL TSRMLS_CC, E_WARNING, "'%s' is not a valid mode for bzopen(). Only 'w' and 'r' are supported.", mode);
377        RETURN_FALSE;
378    }
379
380    /* If it's not a resource its a string containing the filename to open */
381    if (Z_TYPE_PP(file) == IS_STRING) {
382        if (Z_STRLEN_PP(file) == 0) {
383            php_error_docref(NULL TSRMLS_CC, E_WARNING, "filename cannot be empty");
384            RETURN_FALSE;
385        }
386
387        if (CHECK_ZVAL_NULL_PATH(*file)) {
388            RETURN_FALSE;
389        }
390
391        stream = php_stream_bz2open(NULL,
392                                    Z_STRVAL_PP(file),
393                                    mode,
394                                    REPORT_ERRORS,
395                                    NULL);
396    } else if (Z_TYPE_PP(file) == IS_RESOURCE) {
397        /* If it is a resource, than its a stream resource */
398        php_socket_t fd;
399        int stream_mode_len;
400
401        php_stream_from_zval(stream, file);
402        stream_mode_len = strlen(stream->mode);
403
404        if (stream_mode_len != 1 && !(stream_mode_len == 2 && memchr(stream->mode, 'b', 2))) {
405            php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot use stream opened in mode '%s'", stream->mode);
406            RETURN_FALSE;
407        } else if (stream_mode_len == 1 && stream->mode[0] != 'r' && stream->mode[0] != 'w' && stream->mode[0] != 'a' && stream->mode[0] != 'x') {
408            php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot use stream opened in mode '%s'", stream->mode);
409            RETURN_FALSE;
410        }
411
412        switch(mode[0]) {
413            case 'r':
414                /* only "r" and "rb" are supported */
415                if (stream->mode[0] != mode[0] && !(stream_mode_len == 2 && stream->mode[1] != mode[0])) {
416                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot read from a stream opened in write only mode");
417                    RETURN_FALSE;
418                }
419                break;
420            case 'w':
421                /* support only "w"(b), "a"(b), "x"(b) */
422                if (stream->mode[0] != mode[0] && !(stream_mode_len == 2 && stream->mode[1] != mode[0])
423                    && stream->mode[0] != 'a' && !(stream_mode_len == 2 && stream->mode[1] != 'a')
424                    && stream->mode[0] != 'x' && !(stream_mode_len == 2 && stream->mode[1] != 'x')) {
425                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "cannot write to a stream opened in read only mode");
426                    RETURN_FALSE;
427                }
428                break;
429            default:
430                /* not reachable */
431                break;
432        }
433
434        if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_FD, (void *) &fd, REPORT_ERRORS)) {
435            RETURN_FALSE;
436        }
437
438        bz = BZ2_bzdopen(fd, mode);
439
440        stream = php_stream_bz2open_from_BZFILE(bz, mode, stream);
441    } else {
442        php_error_docref(NULL TSRMLS_CC, E_WARNING, "first parameter has to be string or file-resource");
443        RETURN_FALSE;
444    }
445
446    if (stream) {
447        php_stream_to_zval(stream, return_value);
448    } else {
449        RETURN_FALSE;
450    }
451}
452/* }}} */
453
454/* {{{ proto int bzerrno(resource bz)
455   Returns the error number */
456static PHP_FUNCTION(bzerrno)
457{
458    php_bz2_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_BZ_ERRNO);
459}
460/* }}} */
461
462/* {{{ proto string bzerrstr(resource bz)
463   Returns the error string */
464static PHP_FUNCTION(bzerrstr)
465{
466    php_bz2_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_BZ_ERRSTR);
467}
468/* }}} */
469
470/* {{{ proto array bzerror(resource bz)
471   Returns the error number and error string in an associative array */
472static PHP_FUNCTION(bzerror)
473{
474    php_bz2_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_BZ_ERRBOTH);
475}
476/* }}} */
477
478/* {{{ proto string bzcompress(string source [, int blocksize100k [, int workfactor]])
479   Compresses a string into BZip2 encoded data */
480static PHP_FUNCTION(bzcompress)
481{
482    char             *source;          /* Source data to compress */
483    long              zblock_size = 0; /* Optional block size to use */
484    long              zwork_factor = 0;/* Optional work factor to use */
485    char             *dest = NULL;     /* Destination to place the compressed data into */
486    int               error,           /* Error Container */
487                      block_size  = 4, /* Block size for compression algorithm */
488                      work_factor = 0, /* Work factor for compression algorithm */
489                      argc;            /* Argument count */
490    int               source_len;      /* Length of the source data */
491    unsigned int      dest_len;        /* Length of the destination buffer */
492
493    argc = ZEND_NUM_ARGS();
494
495    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|ll", &source, &source_len, &zblock_size, &zwork_factor) == FAILURE) {
496        return;
497    }
498
499    /* Assign them to easy to use variables, dest_len is initially the length of the data
500       + .01 x length of data + 600 which is the largest size the results of the compression
501       could possibly be, at least that's what the libbz2 docs say (thanks to jeremy@nirvani.net
502       for pointing this out).  */
503    dest_len   = (unsigned int) (source_len + (0.01 * source_len) + 600);
504
505    /* Allocate the destination buffer */
506    dest = emalloc(dest_len + 1);
507
508    /* Handle the optional arguments */
509    if (argc > 1) {
510        block_size = zblock_size;
511    }
512
513    if (argc > 2) {
514        work_factor = zwork_factor;
515    }
516
517    error = BZ2_bzBuffToBuffCompress(dest, &dest_len, source, source_len, block_size, 0, work_factor);
518    if (error != BZ_OK) {
519        efree(dest);
520        RETURN_LONG(error);
521    } else {
522        /* Copy the buffer, we have perhaps allocate a lot more than we need,
523           so we erealloc() the buffer to the proper size */
524        dest = erealloc(dest, dest_len + 1);
525        dest[dest_len] = 0;
526        RETURN_STRINGL(dest, dest_len, 0);
527    }
528}
529/* }}} */
530
531/* {{{ proto string bzdecompress(string source [, int small])
532   Decompresses BZip2 compressed data */
533static PHP_FUNCTION(bzdecompress)
534{
535    char *source, *dest;
536    int source_len, error;
537    long small = 0;
538#if defined(PHP_WIN32)
539    unsigned __int64 size = 0;
540#else
541    unsigned long long size = 0;
542#endif
543    bz_stream bzs;
544
545    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|l", &source, &source_len, &small)) {
546        RETURN_FALSE;
547    }
548
549    bzs.bzalloc = NULL;
550    bzs.bzfree = NULL;
551
552    if (BZ2_bzDecompressInit(&bzs, 0, small) != BZ_OK) {
553        RETURN_FALSE;
554    }
555
556    bzs.next_in = source;
557    bzs.avail_in = source_len;
558
559    /* in most cases bz2 offers at least 2:1 compression, so we use that as our base */
560    bzs.avail_out = source_len * 2;
561    bzs.next_out = dest = emalloc(bzs.avail_out + 1);
562
563    while ((error = BZ2_bzDecompress(&bzs)) == BZ_OK && bzs.avail_in > 0) {
564        /* compression is better then 2:1, need to allocate more memory */
565        bzs.avail_out = source_len;
566        size = (bzs.total_out_hi32 * (unsigned int) -1) + bzs.total_out_lo32;
567        dest = safe_erealloc(dest, 1, bzs.avail_out+1, (size_t) size );
568        bzs.next_out = dest + size;
569    }
570
571    if (error == BZ_STREAM_END || error == BZ_OK) {
572        size = (bzs.total_out_hi32 * (unsigned int) -1) + bzs.total_out_lo32;
573        dest = safe_erealloc(dest, 1, (size_t) size, 1);
574        dest[size] = '\0';
575        RETVAL_STRINGL(dest, (int) size, 0);
576    } else { /* real error */
577        efree(dest);
578        RETVAL_LONG(error);
579    }
580
581    BZ2_bzDecompressEnd(&bzs);
582}
583/* }}} */
584
585/* {{{ php_bz2_error()
586   The central error handling interface, does the work for bzerrno, bzerrstr and bzerror */
587static void php_bz2_error(INTERNAL_FUNCTION_PARAMETERS, int opt)
588{
589    zval         *bzp;     /* BZip2 Resource Pointer */
590    php_stream   *stream;
591    const char   *errstr;  /* Error string */
592    int           errnum;  /* Error number */
593    struct php_bz2_stream_data_t *self;
594
595    if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "r", &bzp) == FAILURE) {
596        return;
597    }
598
599    php_stream_from_zval(stream, &bzp);
600
601    if (!php_stream_is(stream, PHP_STREAM_IS_BZIP2)) {
602        RETURN_FALSE;
603    }
604
605    self = (struct php_bz2_stream_data_t *) stream->abstract;
606
607    /* Fetch the error information */
608    errstr = BZ2_bzerror(self->bz_file, &errnum);
609
610    /* Determine what to return */
611    switch (opt) {
612        case PHP_BZ_ERRNO:
613            RETURN_LONG(errnum);
614            break;
615        case PHP_BZ_ERRSTR:
616            RETURN_STRING((char*)errstr, 1);
617            break;
618        case PHP_BZ_ERRBOTH:
619            array_init(return_value);
620
621            add_assoc_long  (return_value, "errno",  errnum);
622            add_assoc_string(return_value, "errstr", (char*)errstr, 1);
623            break;
624    }
625}
626/* }}} */
627
628#endif
629
630/*
631 * Local variables:
632 * tab-width: 4
633 * c-basic-offset: 4
634 * End:
635 * vim600: fdm=marker
636 * vim: noet sw=4 ts=4
637 */
638