1/*
2  +----------------------------------------------------------------------+
3  | PHP Version 7                                                        |
4  +----------------------------------------------------------------------+
5  | Copyright (c) 1997-2015 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    PHP_BZ2_VERSION,
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)
139{
140    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;
141    size_t ret = 0;
142
143    do {
144        int just_read;
145        size_t remain = count - ret;
146        int to_read = (int)(remain <= INT_MAX ? remain : INT_MAX);
147
148        just_read = BZ2_bzread(self->bz_file, buf, to_read);
149
150        if (just_read < 1) {
151            stream->eof = 0 == just_read;
152            break;
153        }
154
155        ret += just_read;
156    } while (ret < count);
157
158    return ret;
159}
160
161static size_t php_bz2iop_write(php_stream *stream, const char *buf, size_t count)
162{
163    size_t wrote = 0;
164    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;
165
166
167    do {
168        int just_wrote;
169        size_t remain = count - wrote;
170        int to_write = (int)(remain <= INT_MAX ? remain : INT_MAX);
171
172        just_wrote = BZ2_bzwrite(self->bz_file, (char*)buf, to_write);
173
174        if (just_wrote < 1) {
175            break;
176        }
177
178        wrote += just_wrote;
179
180    } while (wrote < count);
181
182    return wrote;
183}
184
185static int php_bz2iop_close(php_stream *stream, int close_handle)
186{
187    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;
188    int ret = EOF;
189
190    if (close_handle) {
191        BZ2_bzclose(self->bz_file);
192    }
193
194    if (self->stream) {
195        php_stream_free(self->stream, PHP_STREAM_FREE_CLOSE | (close_handle == 0 ? PHP_STREAM_FREE_PRESERVE_HANDLE : 0));
196    }
197
198    efree(self);
199
200    return ret;
201}
202
203static int php_bz2iop_flush(php_stream *stream)
204{
205    struct php_bz2_stream_data_t *self = (struct php_bz2_stream_data_t *)stream->abstract;
206    return BZ2_bzflush(self->bz_file);
207}
208/* }}} */
209
210php_stream_ops php_stream_bz2io_ops = {
211    php_bz2iop_write, php_bz2iop_read,
212    php_bz2iop_close, php_bz2iop_flush,
213    "BZip2",
214    NULL, /* seek */
215    NULL, /* cast */
216    NULL, /* stat */
217    NULL  /* set_option */
218};
219
220/* {{{ Bzip2 stream openers */
221PHP_BZ2_API php_stream *_php_stream_bz2open_from_BZFILE(BZFILE *bz,
222                                                        const char *mode, php_stream *innerstream STREAMS_DC)
223{
224    struct php_bz2_stream_data_t *self;
225
226    self = emalloc(sizeof(*self));
227
228    self->stream = innerstream;
229    self->bz_file = bz;
230
231    return php_stream_alloc_rel(&php_stream_bz2io_ops, self, 0, mode);
232}
233
234PHP_BZ2_API php_stream *_php_stream_bz2open(php_stream_wrapper *wrapper,
235                                            const char *path,
236                                            const char *mode,
237                                            int options,
238                                            zend_string **opened_path,
239                                            php_stream_context *context STREAMS_DC)
240{
241    php_stream *retstream = NULL, *stream = NULL;
242    char *path_copy = NULL;
243    BZFILE *bz_file = NULL;
244
245    if (strncasecmp("compress.bzip2://", path, 17) == 0) {
246        path += 17;
247    }
248    if (mode[0] == '\0' || (mode[0] != 'w' && mode[0] != 'r' && mode[1] != '\0')) {
249        return NULL;
250    }
251
252#ifdef VIRTUAL_DIR
253    virtual_filepath_ex(path, &path_copy, NULL);
254#else
255    path_copy = (char *)path;
256#endif
257
258    if (php_check_open_basedir(path_copy)) {
259#ifdef VIRTUAL_DIR
260        efree(path_copy);
261#endif
262        return NULL;
263    }
264
265    /* try and open it directly first */
266    bz_file = BZ2_bzopen(path_copy, mode);
267
268    if (opened_path && bz_file) {
269        *opened_path = zend_string_init(path_copy, strlen(path_copy), 0);
270    }
271
272#ifdef VIRTUAL_DIR
273    efree(path_copy);
274#endif
275
276    if (bz_file == NULL) {
277        /* that didn't work, so try and get something from the network/wrapper */
278        stream = php_stream_open_wrapper(path, mode, options | STREAM_WILL_CAST, opened_path);
279
280        if (stream) {
281            php_socket_t fd;
282            if (SUCCESS == php_stream_cast(stream, PHP_STREAM_AS_FD, (void **) &fd, REPORT_ERRORS)) {
283                bz_file = BZ2_bzdopen((int)fd, mode);
284            }
285        }
286
287        /* remove the file created by php_stream_open_wrapper(), it is not needed since BZ2 functions
288         * failed.
289         */
290        if (opened_path && !bz_file && mode[0] == 'w') {
291            VCWD_UNLINK((*opened_path)->val);
292        }
293    }
294
295    if (bz_file) {
296        retstream = _php_stream_bz2open_from_BZFILE(bz_file, mode, stream STREAMS_REL_CC);
297        if (retstream) {
298            return retstream;
299        }
300
301        BZ2_bzclose(bz_file);
302    }
303
304    if (stream) {
305        php_stream_close(stream);
306    }
307
308    return NULL;
309}
310
311/* }}} */
312
313static php_stream_wrapper_ops bzip2_stream_wops = {
314    _php_stream_bz2open,
315    NULL, /* close */
316    NULL, /* fstat */
317    NULL, /* stat */
318    NULL, /* opendir */
319    "BZip2",
320    NULL, /* unlink */
321    NULL, /* rename */
322    NULL, /* mkdir */
323    NULL  /* rmdir */
324};
325
326static php_stream_wrapper php_stream_bzip2_wrapper = {
327    &bzip2_stream_wops,
328    NULL,
329    0 /* is_url */
330};
331
332static void php_bz2_error(INTERNAL_FUNCTION_PARAMETERS, int);
333
334static PHP_MINIT_FUNCTION(bz2)
335{
336    php_register_url_stream_wrapper("compress.bzip2", &php_stream_bzip2_wrapper);
337    php_stream_filter_register_factory("bzip2.*", &php_bz2_filter_factory);
338    return SUCCESS;
339}
340
341static PHP_MSHUTDOWN_FUNCTION(bz2)
342{
343    php_unregister_url_stream_wrapper("compress.bzip2");
344    php_stream_filter_unregister_factory("bzip2.*");
345
346    return SUCCESS;
347}
348
349static PHP_MINFO_FUNCTION(bz2)
350{
351    php_info_print_table_start();
352    php_info_print_table_row(2, "BZip2 Support", "Enabled");
353    php_info_print_table_row(2, "Stream Wrapper support", "compress.bzip2://");
354    php_info_print_table_row(2, "Stream Filter support", "bzip2.decompress, bzip2.compress");
355    php_info_print_table_row(2, "BZip2 Version", (char *) BZ2_bzlibVersion());
356    php_info_print_table_end();
357}
358
359/* {{{ proto string bzread(resource bz[, int length])
360   Reads up to length bytes from a BZip2 stream, or 1024 bytes if length is not specified */
361static PHP_FUNCTION(bzread)
362{
363    zval *bz;
364    zend_long len = 1024;
365    php_stream *stream;
366    zend_string *data;
367
368    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "r|l", &bz, &len)) {
369        RETURN_FALSE;
370    }
371
372    php_stream_from_zval(stream, bz);
373
374    if ((len + 1) < 1) {
375        php_error_docref(NULL, E_WARNING, "length may not be negative");
376        RETURN_FALSE;
377    }
378    data = zend_string_alloc(len, 0);
379    data->len = php_stream_read(stream, data->val, data->len);
380    data->val[data->len] = '\0';
381
382    RETURN_NEW_STR(data);
383}
384/* }}} */
385
386/* {{{ proto resource bzopen(string|int file|fp, string mode)
387   Opens a new BZip2 stream */
388static PHP_FUNCTION(bzopen)
389{
390    zval     *file;   /* The file to open */
391    char     *mode;   /* The mode to open the stream with */
392    size_t      mode_len;
393
394    BZFILE   *bz;     /* The compressed file stream */
395    php_stream *stream = NULL;
396
397    if (zend_parse_parameters(ZEND_NUM_ARGS(), "zs", &file, &mode, &mode_len) == FAILURE) {
398        return;
399    }
400
401    if (mode_len != 1 || (mode[0] != 'r' && mode[0] != 'w')) {
402        php_error_docref(NULL, E_WARNING, "'%s' is not a valid mode for bzopen(). Only 'w' and 'r' are supported.", mode);
403        RETURN_FALSE;
404    }
405
406    /* If it's not a resource its a string containing the filename to open */
407    if (Z_TYPE_P(file) == IS_STRING) {
408        if (Z_STRLEN_P(file) == 0) {
409            php_error_docref(NULL, E_WARNING, "filename cannot be empty");
410            RETURN_FALSE;
411        }
412
413        if (CHECK_ZVAL_NULL_PATH(file)) {
414            RETURN_FALSE;
415        }
416
417        stream = php_stream_bz2open(NULL, Z_STRVAL_P(file), mode, REPORT_ERRORS, NULL);
418    } else if (Z_TYPE_P(file) == IS_RESOURCE) {
419        /* If it is a resource, than its a stream resource */
420        php_socket_t fd;
421        size_t stream_mode_len;
422
423        php_stream_from_zval(stream, file);
424        stream_mode_len = strlen(stream->mode);
425
426        if (stream_mode_len != 1 && !(stream_mode_len == 2 && memchr(stream->mode, 'b', 2))) {
427            php_error_docref(NULL, E_WARNING, "cannot use stream opened in mode '%s'", stream->mode);
428            RETURN_FALSE;
429        } else if (stream_mode_len == 1 && stream->mode[0] != 'r' && stream->mode[0] != 'w' && stream->mode[0] != 'a' && stream->mode[0] != 'x') {
430            php_error_docref(NULL, E_WARNING, "cannot use stream opened in mode '%s'", stream->mode);
431            RETURN_FALSE;
432        }
433
434        switch(mode[0]) {
435            case 'r':
436                /* only "r" and "rb" are supported */
437                if (stream->mode[0] != mode[0] && !(stream_mode_len == 2 && stream->mode[1] != mode[0])) {
438                    php_error_docref(NULL, E_WARNING, "cannot read from a stream opened in write only mode");
439                    RETURN_FALSE;
440                }
441                break;
442            case 'w':
443                /* support only "w"(b), "a"(b), "x"(b) */
444                if (stream->mode[0] != mode[0] && !(stream_mode_len == 2 && stream->mode[1] != mode[0])
445                    && stream->mode[0] != 'a' && !(stream_mode_len == 2 && stream->mode[1] != 'a')
446                    && stream->mode[0] != 'x' && !(stream_mode_len == 2 && stream->mode[1] != 'x')) {
447                    php_error_docref(NULL, E_WARNING, "cannot write to a stream opened in read only mode");
448                    RETURN_FALSE;
449                }
450                break;
451            default:
452                /* not reachable */
453                break;
454        }
455
456        if (FAILURE == php_stream_cast(stream, PHP_STREAM_AS_FD, (void *) &fd, REPORT_ERRORS)) {
457            RETURN_FALSE;
458        }
459
460        bz = BZ2_bzdopen((int)fd, mode);
461
462        stream = php_stream_bz2open_from_BZFILE(bz, mode, stream);
463    } else {
464        php_error_docref(NULL, E_WARNING, "first parameter has to be string or file-resource");
465        RETURN_FALSE;
466    }
467
468    if (stream) {
469        php_stream_to_zval(stream, return_value);
470    } else {
471        RETURN_FALSE;
472    }
473}
474/* }}} */
475
476/* {{{ proto int bzerrno(resource bz)
477   Returns the error number */
478static PHP_FUNCTION(bzerrno)
479{
480    php_bz2_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_BZ_ERRNO);
481}
482/* }}} */
483
484/* {{{ proto string bzerrstr(resource bz)
485   Returns the error string */
486static PHP_FUNCTION(bzerrstr)
487{
488    php_bz2_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_BZ_ERRSTR);
489}
490/* }}} */
491
492/* {{{ proto array bzerror(resource bz)
493   Returns the error number and error string in an associative array */
494static PHP_FUNCTION(bzerror)
495{
496    php_bz2_error(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_BZ_ERRBOTH);
497}
498/* }}} */
499
500/* {{{ proto string bzcompress(string source [, int blocksize100k [, int workfactor]])
501   Compresses a string into BZip2 encoded data */
502static PHP_FUNCTION(bzcompress)
503{
504    char             *source;          /* Source data to compress */
505    zend_long              zblock_size = 0; /* Optional block size to use */
506    zend_long              zwork_factor = 0;/* Optional work factor to use */
507    zend_string      *dest = NULL;     /* Destination to place the compressed data into */
508    int               error,           /* Error Container */
509                      block_size  = 4, /* Block size for compression algorithm */
510                      work_factor = 0, /* Work factor for compression algorithm */
511                      argc;            /* Argument count */
512    size_t               source_len;      /* Length of the source data */
513    unsigned int      dest_len;        /* Length of the destination buffer */
514
515    argc = ZEND_NUM_ARGS();
516
517    if (zend_parse_parameters(ZEND_NUM_ARGS(), "s|ll", &source, &source_len, &zblock_size, &zwork_factor) == FAILURE) {
518        return;
519    }
520
521    /* Assign them to easy to use variables, dest_len is initially the length of the data
522       + .01 x length of data + 600 which is the largest size the results of the compression
523       could possibly be, at least that's what the libbz2 docs say (thanks to jeremy@nirvani.net
524       for pointing this out).  */
525    dest_len = (unsigned int) (source_len + (0.01 * source_len) + 600);
526
527    /* Allocate the destination buffer */
528    dest = zend_string_alloc(dest_len, 0);
529
530    /* Handle the optional arguments */
531    if (argc > 1) {
532        block_size = zblock_size;
533    }
534
535    if (argc > 2) {
536        work_factor = zwork_factor;
537    }
538
539    error = BZ2_bzBuffToBuffCompress(dest->val, &dest_len, source, source_len, block_size, 0, work_factor);
540    if (error != BZ_OK) {
541        zend_string_free(dest);
542        RETURN_LONG(error);
543    } else {
544        /* Copy the buffer, we have perhaps allocate a lot more than we need,
545           so we erealloc() the buffer to the proper size */
546        dest->len = dest_len;
547        dest->val[dest->len] = '\0';
548        RETURN_NEW_STR(dest);
549    }
550}
551/* }}} */
552
553/* {{{ proto string bzdecompress(string source [, int small])
554   Decompresses BZip2 compressed data */
555static PHP_FUNCTION(bzdecompress)
556{
557    char *source, *dest;
558    size_t source_len;
559    int error;
560    zend_long small = 0;
561#if defined(PHP_WIN32)
562    unsigned __int64 size = 0;
563#else
564    unsigned long long size = 0;
565#endif
566    bz_stream bzs;
567
568    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &source, &source_len, &small)) {
569        RETURN_FALSE;
570    }
571
572    bzs.bzalloc = NULL;
573    bzs.bzfree = NULL;
574
575    if (BZ2_bzDecompressInit(&bzs, 0, (int)small) != BZ_OK) {
576        RETURN_FALSE;
577    }
578
579    bzs.next_in = source;
580    bzs.avail_in = source_len;
581
582    /* in most cases bz2 offers at least 2:1 compression, so we use that as our base */
583    bzs.avail_out = source_len * 2;
584    bzs.next_out = dest = emalloc(bzs.avail_out + 1);
585
586    while ((error = BZ2_bzDecompress(&bzs)) == BZ_OK && bzs.avail_in > 0) {
587        /* compression is better then 2:1, need to allocate more memory */
588        bzs.avail_out = source_len;
589        size = (bzs.total_out_hi32 * (unsigned int) -1) + bzs.total_out_lo32;
590        dest = safe_erealloc(dest, 1, bzs.avail_out+1, (size_t) size );
591        bzs.next_out = dest + size;
592    }
593
594    if (error == BZ_STREAM_END || error == BZ_OK) {
595        size = (bzs.total_out_hi32 * (unsigned int) -1) + bzs.total_out_lo32;
596        dest = safe_erealloc(dest, 1, (size_t) size, 1);
597        dest[size] = '\0';
598        RETVAL_STRINGL(dest, (int) size);
599        efree(dest);
600    } else { /* real error */
601        efree(dest);
602        RETVAL_LONG(error);
603    }
604
605    BZ2_bzDecompressEnd(&bzs);
606}
607/* }}} */
608
609/* {{{ php_bz2_error()
610   The central error handling interface, does the work for bzerrno, bzerrstr and bzerror */
611static void php_bz2_error(INTERNAL_FUNCTION_PARAMETERS, int opt)
612{
613    zval         *bzp;     /* BZip2 Resource Pointer */
614    php_stream   *stream;
615    const char   *errstr;  /* Error string */
616    int           errnum;  /* Error number */
617    struct php_bz2_stream_data_t *self;
618
619    if (zend_parse_parameters(ZEND_NUM_ARGS(), "r", &bzp) == FAILURE) {
620        return;
621    }
622
623    php_stream_from_zval(stream, bzp);
624
625    if (!php_stream_is(stream, PHP_STREAM_IS_BZIP2)) {
626        RETURN_FALSE;
627    }
628
629    self = (struct php_bz2_stream_data_t *) stream->abstract;
630
631    /* Fetch the error information */
632    errstr = BZ2_bzerror(self->bz_file, &errnum);
633
634    /* Determine what to return */
635    switch (opt) {
636        case PHP_BZ_ERRNO:
637            RETURN_LONG(errnum);
638            break;
639        case PHP_BZ_ERRSTR:
640            RETURN_STRING((char*)errstr);
641            break;
642        case PHP_BZ_ERRBOTH:
643            array_init(return_value);
644
645            add_assoc_long  (return_value, "errno",  errnum);
646            add_assoc_string(return_value, "errstr", (char*)errstr);
647            break;
648    }
649}
650/* }}} */
651
652#endif
653
654/*
655 * Local variables:
656 * tab-width: 4
657 * c-basic-offset: 4
658 * End:
659 * vim600: fdm=marker
660 * vim: noet sw=4 ts=4
661 */
662