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