xref: /PHP-8.1/ext/zlib/zlib.c (revision c510083c)
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    | https://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    | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
14    |          Stefan Röhrich <sr@linux.de>                                |
15    |          Zeev Suraski <zeev@php.net>                                 |
16    |          Jade Nicoletti <nicoletti@nns.ch>                           |
17    |          Michael Wallner <mike@php.net>                              |
18    +----------------------------------------------------------------------+
19  */
20 
21 #ifdef HAVE_CONFIG_H
22 #include "config.h"
23 #endif
24 
25 #include "php.h"
26 #include "SAPI.h"
27 #include "php_ini.h"
28 #include "ext/standard/info.h"
29 #include "ext/standard/php_string.h"
30 #include "php_zlib.h"
31 #include "zlib_arginfo.h"
32 
33 /*
34  * zlib include files can define the following preprocessor defines which rename
35  * the corresponding PHP functions to gzopen64, gzseek64 and gztell64 and thereby
36  * breaking some software, most notably PEAR's Archive_Tar, which halts execution
37  * without error message on gzip compressed archives.
38  *
39  * This only seems to happen on 32bit systems with large file support.
40  */
41 #undef gzopen
42 #undef gzseek
43 #undef gztell
44 
45 ZEND_DECLARE_MODULE_GLOBALS(zlib)
46 
47 /* InflateContext class */
48 
49 zend_class_entry *inflate_context_ce;
50 static zend_object_handlers inflate_context_object_handlers;
51 
inflate_context_from_obj(zend_object * obj)52 static inline php_zlib_context *inflate_context_from_obj(zend_object *obj) {
53 	return (php_zlib_context *)((char *)(obj) - XtOffsetOf(php_zlib_context, std));
54 }
55 
56 #define Z_INFLATE_CONTEXT_P(zv) inflate_context_from_obj(Z_OBJ_P(zv))
57 
inflate_context_create_object(zend_class_entry * class_type)58 static zend_object *inflate_context_create_object(zend_class_entry *class_type) {
59 	php_zlib_context *intern = zend_object_alloc(sizeof(php_zlib_context), class_type);
60 
61 	zend_object_std_init(&intern->std, class_type);
62 	object_properties_init(&intern->std, class_type);
63 	intern->std.handlers = &inflate_context_object_handlers;
64 
65 	return &intern->std;
66 }
67 
inflate_context_get_constructor(zend_object * object)68 static zend_function *inflate_context_get_constructor(zend_object *object) {
69 	zend_throw_error(NULL, "Cannot directly construct InflateContext, use inflate_init() instead");
70 	return NULL;
71 }
72 
inflate_context_free_obj(zend_object * object)73 static void inflate_context_free_obj(zend_object *object)
74 {
75 	php_zlib_context *intern = inflate_context_from_obj(object);
76 
77 	if (intern->inflateDict) {
78 		efree(intern->inflateDict);
79 	}
80 	inflateEnd(&intern->Z);
81 
82 	zend_object_std_dtor(&intern->std);
83 }
84 /* }}} */
85 
86 /* DeflateContext class */
87 
88 zend_class_entry *deflate_context_ce;
89 static zend_object_handlers deflate_context_object_handlers;
90 
deflate_context_from_obj(zend_object * obj)91 static inline php_zlib_context *deflate_context_from_obj(zend_object *obj) {
92 	return (php_zlib_context *)((char *)(obj) - XtOffsetOf(php_zlib_context, std));
93 }
94 
95 #define Z_DEFLATE_CONTEXT_P(zv) deflate_context_from_obj(Z_OBJ_P(zv))
96 
deflate_context_create_object(zend_class_entry * class_type)97 static zend_object *deflate_context_create_object(zend_class_entry *class_type) {
98 	php_zlib_context *intern = zend_object_alloc(sizeof(php_zlib_context), class_type);
99 
100 	zend_object_std_init(&intern->std, class_type);
101 	object_properties_init(&intern->std, class_type);
102 	intern->std.handlers = &deflate_context_object_handlers;
103 
104 	return &intern->std;
105 }
106 
deflate_context_get_constructor(zend_object * object)107 static zend_function *deflate_context_get_constructor(zend_object *object) {
108 	zend_throw_error(NULL, "Cannot directly construct DeflateContext, use deflate_init() instead");
109 	return NULL;
110 }
111 
deflate_context_free_obj(zend_object * object)112 static void deflate_context_free_obj(zend_object *object)
113 {
114 	php_zlib_context *intern = deflate_context_from_obj(object);
115 
116 	deflateEnd(&intern->Z);
117 
118 	zend_object_std_dtor(&intern->std);
119 }
120 /* }}} */
121 
122 /* {{{ Memory management wrappers */
123 
php_zlib_alloc(voidpf opaque,uInt items,uInt size)124 static voidpf php_zlib_alloc(voidpf opaque, uInt items, uInt size)
125 {
126 	return (voidpf)safe_emalloc(items, size, 0);
127 }
128 
php_zlib_free(voidpf opaque,voidpf address)129 static void php_zlib_free(voidpf opaque, voidpf address)
130 {
131 	efree((void*)address);
132 }
133 /* }}} */
134 
135 /* {{{ php_zlib_output_conflict_check() */
php_zlib_output_conflict_check(const char * handler_name,size_t handler_name_len)136 static int php_zlib_output_conflict_check(const char *handler_name, size_t handler_name_len)
137 {
138 	if (php_output_get_level() > 0) {
139 		if (php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME))
140 		||	php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL("ob_gzhandler"))
141 		||  php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL("mb_output_handler"))
142 		||	php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL("URL-Rewriter"))) {
143 			return FAILURE;
144 		}
145 	}
146 	return SUCCESS;
147 }
148 /* }}} */
149 
150 /* {{{ php_zlib_output_encoding() */
php_zlib_output_encoding(void)151 static int php_zlib_output_encoding(void)
152 {
153 	zval *enc;
154 
155 	if (!ZLIBG(compression_coding)) {
156 		if ((Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY || zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_SERVER))) &&
157 			(enc = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_ACCEPT_ENCODING", sizeof("HTTP_ACCEPT_ENCODING") - 1))) {
158 			convert_to_string(enc);
159 			if (strstr(Z_STRVAL_P(enc), "gzip")) {
160 				ZLIBG(compression_coding) = PHP_ZLIB_ENCODING_GZIP;
161 			} else if (strstr(Z_STRVAL_P(enc), "deflate")) {
162 				ZLIBG(compression_coding) = PHP_ZLIB_ENCODING_DEFLATE;
163 			}
164 		}
165 	}
166 	return ZLIBG(compression_coding);
167 }
168 /* }}} */
169 
170 /* {{{ php_zlib_output_handler_ex() */
php_zlib_output_handler_ex(php_zlib_context * ctx,php_output_context * output_context)171 static int php_zlib_output_handler_ex(php_zlib_context *ctx, php_output_context *output_context)
172 {
173 	int flags = Z_SYNC_FLUSH;
174 
175 	if (output_context->op & PHP_OUTPUT_HANDLER_START) {
176 		/* start up */
177 		if (Z_OK != deflateInit2(&ctx->Z, ZLIBG(output_compression_level), Z_DEFLATED, ZLIBG(compression_coding), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) {
178 			return FAILURE;
179 		}
180 	}
181 
182 	if (output_context->op & PHP_OUTPUT_HANDLER_CLEAN) {
183 		/* free buffers */
184 		deflateEnd(&ctx->Z);
185 
186 		if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) {
187 			/* discard */
188 			return SUCCESS;
189 		} else {
190 			/* restart */
191 			if (Z_OK != deflateInit2(&ctx->Z, ZLIBG(output_compression_level), Z_DEFLATED, ZLIBG(compression_coding), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) {
192 				return FAILURE;
193 			}
194 			ctx->buffer.used = 0;
195 		}
196 	} else {
197 		if (output_context->in.used) {
198 			/* append input */
199 			if (ctx->buffer.free < output_context->in.used) {
200 				if (!(ctx->buffer.aptr = erealloc_recoverable(ctx->buffer.data, ctx->buffer.used + ctx->buffer.free + output_context->in.used))) {
201 					deflateEnd(&ctx->Z);
202 					return FAILURE;
203 				}
204 				ctx->buffer.data = ctx->buffer.aptr;
205 				ctx->buffer.free += output_context->in.used;
206 			}
207 			memcpy(ctx->buffer.data + ctx->buffer.used, output_context->in.data, output_context->in.used);
208 			ctx->buffer.free -= output_context->in.used;
209 			ctx->buffer.used += output_context->in.used;
210 		}
211 		output_context->out.size = PHP_ZLIB_BUFFER_SIZE_GUESS(output_context->in.used);
212 		output_context->out.data = emalloc(output_context->out.size);
213 		output_context->out.free = 1;
214 		output_context->out.used = 0;
215 
216 		ctx->Z.avail_in = ctx->buffer.used;
217 		ctx->Z.next_in = (Bytef *) ctx->buffer.data;
218 		ctx->Z.avail_out = output_context->out.size;
219 		ctx->Z.next_out = (Bytef *) output_context->out.data;
220 
221 		if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) {
222 			flags = Z_FINISH;
223 		} else if (output_context->op & PHP_OUTPUT_HANDLER_FLUSH) {
224 			flags = Z_FULL_FLUSH;
225 		}
226 
227 		switch (deflate(&ctx->Z, flags)) {
228 			case Z_OK:
229 				if (flags == Z_FINISH) {
230 					deflateEnd(&ctx->Z);
231 					return FAILURE;
232 				}
233 				ZEND_FALLTHROUGH;
234 			case Z_STREAM_END:
235 				if (ctx->Z.avail_in) {
236 					memmove(ctx->buffer.data, ctx->buffer.data + ctx->buffer.used - ctx->Z.avail_in, ctx->Z.avail_in);
237 				}
238 				ctx->buffer.free += ctx->buffer.used - ctx->Z.avail_in;
239 				ctx->buffer.used = ctx->Z.avail_in;
240 				output_context->out.used = output_context->out.size - ctx->Z.avail_out;
241 				break;
242 			default:
243 				deflateEnd(&ctx->Z);
244 				return FAILURE;
245 		}
246 
247 		if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) {
248 			deflateEnd(&ctx->Z);
249 		}
250 	}
251 
252 	return SUCCESS;
253 }
254 /* }}} */
255 
256 /* {{{ php_zlib_output_handler() */
php_zlib_output_handler(void ** handler_context,php_output_context * output_context)257 static int php_zlib_output_handler(void **handler_context, php_output_context *output_context)
258 {
259 	php_zlib_context *ctx = *(php_zlib_context **) handler_context;
260 
261 	if (!php_zlib_output_encoding()) {
262 		/* "Vary: Accept-Encoding" header sent along uncompressed content breaks caching in MSIE,
263 			so let's just send it with successfully compressed content or unless the complete
264 			buffer gets discarded, see http://bugs.php.net/40325;
265 
266 			Test as follows:
267 			+Vary: $ HTTP_ACCEPT_ENCODING=gzip ./sapi/cgi/php <<<'<?php ob_start("ob_gzhandler"); echo "foo\n";'
268 			+Vary: $ HTTP_ACCEPT_ENCODING= ./sapi/cgi/php <<<'<?php ob_start("ob_gzhandler"); echo "foo\n";'
269 			-Vary: $ HTTP_ACCEPT_ENCODING=gzip ./sapi/cgi/php <<<'<?php ob_start("ob_gzhandler"); echo "foo\n"; ob_end_clean();'
270 			-Vary: $ HTTP_ACCEPT_ENCODING= ./sapi/cgi/php <<<'<?php ob_start("ob_gzhandler"); echo "foo\n"; ob_end_clean();'
271 		*/
272 		if ((output_context->op & PHP_OUTPUT_HANDLER_START)
273 		&&	(output_context->op != (PHP_OUTPUT_HANDLER_START|PHP_OUTPUT_HANDLER_CLEAN|PHP_OUTPUT_HANDLER_FINAL))
274 		) {
275 			sapi_add_header_ex(ZEND_STRL("Vary: Accept-Encoding"), 1, 0);
276 		}
277 		return FAILURE;
278 	}
279 
280 	if (SUCCESS != php_zlib_output_handler_ex(ctx, output_context)) {
281 		return FAILURE;
282 	}
283 
284 	if (!(output_context->op & PHP_OUTPUT_HANDLER_CLEAN) || ((output_context->op & PHP_OUTPUT_HANDLER_START) && !(output_context->op & PHP_OUTPUT_HANDLER_FINAL))) {
285 		int flags;
286 
287 		if (SUCCESS == php_output_handler_hook(PHP_OUTPUT_HANDLER_HOOK_GET_FLAGS, &flags)) {
288 			/* only run this once */
289 			if (!(flags & PHP_OUTPUT_HANDLER_STARTED)) {
290 				if (SG(headers_sent) || !ZLIBG(output_compression)) {
291 					deflateEnd(&ctx->Z);
292 					return FAILURE;
293 				}
294 				switch (ZLIBG(compression_coding)) {
295 					case PHP_ZLIB_ENCODING_GZIP:
296 						sapi_add_header_ex(ZEND_STRL("Content-Encoding: gzip"), 1, 1);
297 						break;
298 					case PHP_ZLIB_ENCODING_DEFLATE:
299 						sapi_add_header_ex(ZEND_STRL("Content-Encoding: deflate"), 1, 1);
300 						break;
301 					default:
302 						deflateEnd(&ctx->Z);
303 						return FAILURE;
304 				}
305 				sapi_add_header_ex(ZEND_STRL("Vary: Accept-Encoding"), 1, 0);
306 				php_output_handler_hook(PHP_OUTPUT_HANDLER_HOOK_IMMUTABLE, NULL);
307 			}
308 		}
309 	}
310 
311 	return SUCCESS;
312 }
313 /* }}} */
314 
315 /* {{{ php_zlib_output_handler_context_init() */
php_zlib_output_handler_context_init(void)316 static php_zlib_context *php_zlib_output_handler_context_init(void)
317 {
318 	php_zlib_context *ctx = (php_zlib_context *) ecalloc(1, sizeof(php_zlib_context));
319 	ctx->Z.zalloc = php_zlib_alloc;
320 	ctx->Z.zfree = php_zlib_free;
321 	return ctx;
322 }
323 /* }}} */
324 
325 /* {{{ php_zlib_output_handler_context_dtor() */
php_zlib_output_handler_context_dtor(void * opaq)326 static void php_zlib_output_handler_context_dtor(void *opaq)
327 {
328 	php_zlib_context *ctx = (php_zlib_context *) opaq;
329 
330 	if (ctx) {
331 		if (ctx->buffer.data) {
332 			efree(ctx->buffer.data);
333 		}
334 		efree(ctx);
335 	}
336 }
337 /* }}} */
338 
339 /* {{{ php_zlib_output_handler_init() */
php_zlib_output_handler_init(const char * handler_name,size_t handler_name_len,size_t chunk_size,int flags)340 static php_output_handler *php_zlib_output_handler_init(const char *handler_name, size_t handler_name_len, size_t chunk_size, int flags)
341 {
342 	php_output_handler *h = NULL;
343 
344 	if (!ZLIBG(output_compression)) {
345 		ZLIBG(output_compression) = chunk_size ? chunk_size : PHP_OUTPUT_HANDLER_DEFAULT_SIZE;
346 	}
347 
348 	ZLIBG(handler_registered) = 1;
349 
350 	if ((h = php_output_handler_create_internal(handler_name, handler_name_len, php_zlib_output_handler, chunk_size, flags))) {
351 		php_output_handler_set_context(h, php_zlib_output_handler_context_init(), php_zlib_output_handler_context_dtor);
352 	}
353 
354 	return h;
355 }
356 /* }}} */
357 
358 /* {{{ php_zlib_output_compression_start() */
php_zlib_output_compression_start(void)359 static void php_zlib_output_compression_start(void)
360 {
361 	zval zoh;
362 	php_output_handler *h;
363 
364 	switch (ZLIBG(output_compression)) {
365 		case 0:
366 			break;
367 		case 1:
368 			ZLIBG(output_compression) = PHP_OUTPUT_HANDLER_DEFAULT_SIZE;
369 			ZEND_FALLTHROUGH;
370 		default:
371 			if (	php_zlib_output_encoding() &&
372 					(h = php_zlib_output_handler_init(ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME), ZLIBG(output_compression), PHP_OUTPUT_HANDLER_STDFLAGS)) &&
373 					(SUCCESS == php_output_handler_start(h))) {
374 				if (ZLIBG(output_handler) && *ZLIBG(output_handler)) {
375 					ZVAL_STRING(&zoh, ZLIBG(output_handler));
376 					php_output_start_user(&zoh, ZLIBG(output_compression), PHP_OUTPUT_HANDLER_STDFLAGS);
377 					zval_ptr_dtor(&zoh);
378 				}
379 			}
380 			break;
381 	}
382 }
383 /* }}} */
384 
385 /* {{{ php_zlib_encode() */
php_zlib_encode(const char * in_buf,size_t in_len,int encoding,int level)386 static zend_string *php_zlib_encode(const char *in_buf, size_t in_len, int encoding, int level)
387 {
388 	int status;
389 	z_stream Z;
390 	zend_string *out;
391 
392 	memset(&Z, 0, sizeof(z_stream));
393 	Z.zalloc = php_zlib_alloc;
394 	Z.zfree = php_zlib_free;
395 
396 	if (Z_OK == (status = deflateInit2(&Z, level, Z_DEFLATED, encoding, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY))) {
397 		out = zend_string_alloc(PHP_ZLIB_BUFFER_SIZE_GUESS(in_len), 0);
398 
399 		Z.next_in = (Bytef *) in_buf;
400 		Z.next_out = (Bytef *) ZSTR_VAL(out);
401 		Z.avail_in = in_len;
402 		Z.avail_out = ZSTR_LEN(out);
403 
404 		status = deflate(&Z, Z_FINISH);
405 		deflateEnd(&Z);
406 
407 		if (Z_STREAM_END == status) {
408 			/* size buffer down to actual length */
409 			out = zend_string_truncate(out, Z.total_out, 0);
410 			ZSTR_VAL(out)[ZSTR_LEN(out)] = '\0';
411 			return out;
412 		} else {
413 			zend_string_efree(out);
414 		}
415 	}
416 
417 	php_error_docref(NULL, E_WARNING, "%s", zError(status));
418 	return NULL;
419 }
420 /* }}} */
421 
422 /* {{{ php_zlib_inflate_rounds() */
php_zlib_inflate_rounds(z_stream * Z,size_t max,char ** buf,size_t * len)423 static inline int php_zlib_inflate_rounds(z_stream *Z, size_t max, char **buf, size_t *len)
424 {
425 	int status, round = 0;
426 	php_zlib_buffer buffer = {NULL, NULL, 0, 0, 0};
427 
428 	*buf = NULL;
429 	*len = 0;
430 
431 	buffer.size = (max && (max < Z->avail_in)) ? max : Z->avail_in;
432 
433 	do {
434 		if ((max && (max <= buffer.used)) || !(buffer.aptr = erealloc_recoverable(buffer.data, buffer.size))) {
435 			status = Z_MEM_ERROR;
436 		} else {
437 			buffer.data = buffer.aptr;
438 			Z->avail_out = buffer.free = buffer.size - buffer.used;
439 			Z->next_out = (Bytef *) buffer.data + buffer.used;
440 #if 0
441 			fprintf(stderr, "\n%3d: %3d PRIOR: size=%7lu,\tfree=%7lu,\tused=%7lu,\tavail_in=%7lu,\tavail_out=%7lu\n", round, status, buffer.size, buffer.free, buffer.used, Z->avail_in, Z->avail_out);
442 #endif
443 			status = inflate(Z, Z_NO_FLUSH);
444 
445 			buffer.used += buffer.free - Z->avail_out;
446 			buffer.free = Z->avail_out;
447 #if 0
448 			fprintf(stderr, "%3d: %3d AFTER: size=%7lu,\tfree=%7lu,\tused=%7lu,\tavail_in=%7lu,\tavail_out=%7lu\n", round, status, buffer.size, buffer.free, buffer.used, Z->avail_in, Z->avail_out);
449 #endif
450 			buffer.size += (buffer.size >> 3) + 1;
451 		}
452 	} while ((Z_BUF_ERROR == status || (Z_OK == status && Z->avail_in)) && ++round < 100);
453 
454 	if (status == Z_STREAM_END) {
455 		buffer.data = erealloc(buffer.data, buffer.used + 1);
456 		buffer.data[buffer.used] = '\0';
457 		*buf = buffer.data;
458 		*len = buffer.used;
459 	} else {
460 		if (buffer.data) {
461 			efree(buffer.data);
462 		}
463 		/* HACK: See zlib/examples/zpipe.c inf() function for explanation. */
464 		/* This works as long as this function is not used for streaming. Required to catch very short invalid data. */
465 		status = (status == Z_OK) ? Z_DATA_ERROR : status;
466 	}
467 	return status;
468 }
469 /* }}} */
470 
471 /* {{{ php_zlib_decode() */
php_zlib_decode(const char * in_buf,size_t in_len,char ** out_buf,size_t * out_len,int encoding,size_t max_len)472 static int php_zlib_decode(const char *in_buf, size_t in_len, char **out_buf, size_t *out_len, int encoding, size_t max_len)
473 {
474 	int status = Z_DATA_ERROR;
475 	z_stream Z;
476 
477 	memset(&Z, 0, sizeof(z_stream));
478 	Z.zalloc = php_zlib_alloc;
479 	Z.zfree = php_zlib_free;
480 
481 	if (in_len) {
482 retry_raw_inflate:
483 		status = inflateInit2(&Z, encoding);
484 		if (Z_OK == status) {
485 			Z.next_in = (Bytef *) in_buf;
486 			Z.avail_in = in_len + 1; /* NOTE: data must be zero terminated */
487 
488 			switch (status = php_zlib_inflate_rounds(&Z, max_len, out_buf, out_len)) {
489 				case Z_STREAM_END:
490 					inflateEnd(&Z);
491 					return SUCCESS;
492 
493 				case Z_DATA_ERROR:
494 					/* raw deflated data? */
495 					if (PHP_ZLIB_ENCODING_ANY == encoding) {
496 						inflateEnd(&Z);
497 						encoding = PHP_ZLIB_ENCODING_RAW;
498 						goto retry_raw_inflate;
499 					}
500 			}
501 			inflateEnd(&Z);
502 		}
503 	}
504 
505 	*out_buf = NULL;
506 	*out_len = 0;
507 
508 	php_error_docref(NULL, E_WARNING, "%s", zError(status));
509 	return FAILURE;
510 }
511 /* }}} */
512 
513 /* {{{ php_zlib_cleanup_ob_gzhandler_mess() */
php_zlib_cleanup_ob_gzhandler_mess(void)514 static void php_zlib_cleanup_ob_gzhandler_mess(void)
515 {
516 	if (ZLIBG(ob_gzhandler)) {
517 		deflateEnd(&(ZLIBG(ob_gzhandler)->Z));
518 		php_zlib_output_handler_context_dtor(ZLIBG(ob_gzhandler));
519 		ZLIBG(ob_gzhandler) = NULL;
520 	}
521 }
522 /* }}} */
523 
524 /* {{{ Legacy hack */
PHP_FUNCTION(ob_gzhandler)525 PHP_FUNCTION(ob_gzhandler)
526 {
527 	char *in_str;
528 	size_t in_len;
529 	zend_long flags = 0;
530 	php_output_context ctx = {0};
531 	int encoding, rv;
532 
533 	/*
534 	 * NOTE that the real ob_gzhandler is an alias to "zlib output compression".
535 	 * This is a really bad hack, because
536 	 * - we have to initialize a php_zlib_context on demand
537 	 * - we have to clean it up in RSHUTDOWN
538 	 * - OG(running) is not set or set to any other output handler
539 	 * - we have to mess around with php_output_context */
540 
541 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "sl", &in_str, &in_len, &flags)) {
542 		RETURN_THROWS();
543 	}
544 
545 	if (!(encoding = php_zlib_output_encoding())) {
546 		RETURN_FALSE;
547 	}
548 
549 	if (flags & PHP_OUTPUT_HANDLER_START) {
550 		switch (encoding) {
551 			case PHP_ZLIB_ENCODING_GZIP:
552 				sapi_add_header_ex(ZEND_STRL("Content-Encoding: gzip"), 1, 1);
553 				break;
554 			case PHP_ZLIB_ENCODING_DEFLATE:
555 				sapi_add_header_ex(ZEND_STRL("Content-Encoding: deflate"), 1, 1);
556 				break;
557 		}
558 		sapi_add_header_ex(ZEND_STRL("Vary: Accept-Encoding"), 1, 0);
559 	}
560 
561 	if (!ZLIBG(ob_gzhandler)) {
562 		ZLIBG(ob_gzhandler) = php_zlib_output_handler_context_init();
563 	}
564 
565 	ctx.op = flags;
566 	ctx.in.data = in_str;
567 	ctx.in.used = in_len;
568 
569 	rv = php_zlib_output_handler_ex(ZLIBG(ob_gzhandler), &ctx);
570 
571 	if (SUCCESS != rv) {
572 		if (ctx.out.data && ctx.out.free) {
573 			efree(ctx.out.data);
574 		}
575 		php_zlib_cleanup_ob_gzhandler_mess();
576 		RETURN_FALSE;
577 	}
578 
579 	if (ctx.out.data) {
580 		RETVAL_STRINGL(ctx.out.data, ctx.out.used);
581 		if (ctx.out.free) {
582 			efree(ctx.out.data);
583 		}
584 	} else {
585 		RETVAL_EMPTY_STRING();
586 	}
587 }
588 /* }}} */
589 
590 /* {{{ Returns the coding type used for output compression */
PHP_FUNCTION(zlib_get_coding_type)591 PHP_FUNCTION(zlib_get_coding_type)
592 {
593 	if (zend_parse_parameters_none() == FAILURE) {
594 		RETURN_THROWS();
595 	}
596 	switch (ZLIBG(compression_coding)) {
597 		case PHP_ZLIB_ENCODING_GZIP:
598 			RETURN_STRINGL("gzip", sizeof("gzip") - 1);
599 		case PHP_ZLIB_ENCODING_DEFLATE:
600 			RETURN_STRINGL("deflate", sizeof("deflate") - 1);
601 		default:
602 			RETURN_FALSE;
603 	}
604 }
605 /* }}} */
606 
607 /* {{{ Read and uncompress entire .gz-file into an array */
PHP_FUNCTION(gzfile)608 PHP_FUNCTION(gzfile)
609 {
610 	char *filename;
611 	size_t filename_len;
612 	int flags = REPORT_ERRORS;
613 	char buf[8192] = {0};
614 	int i = 0;
615 	zend_long use_include_path = 0;
616 	php_stream *stream;
617 
618 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "p|l", &filename, &filename_len, &use_include_path)) {
619 		RETURN_THROWS();
620 	}
621 
622 	if (use_include_path) {
623 		flags |= USE_PATH;
624 	}
625 
626 	/* using a stream here is a bit more efficient (resource wise) than php_gzopen_wrapper */
627 	stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC);
628 
629 	if (!stream) {
630 		/* Error reporting is already done by stream code */
631 		RETURN_FALSE;
632 	}
633 
634 	/* Initialize return array */
635 	array_init(return_value);
636 
637 	/* Now loop through the file and do the magic quotes thing if needed */
638 	memset(buf, 0, sizeof(buf));
639 
640 	while (php_stream_gets(stream, buf, sizeof(buf) - 1) != NULL) {
641 		add_index_string(return_value, i++, buf);
642 	}
643 	php_stream_close(stream);
644 }
645 /* }}} */
646 
647 /* {{{ Open a .gz-file and return a .gz-file pointer */
PHP_FUNCTION(gzopen)648 PHP_FUNCTION(gzopen)
649 {
650 	char *filename;
651 	char *mode;
652 	size_t filename_len, mode_len;
653 	int flags = REPORT_ERRORS;
654 	php_stream *stream;
655 	zend_long use_include_path = 0;
656 
657 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ps|l", &filename, &filename_len, &mode, &mode_len, &use_include_path) == FAILURE) {
658 		RETURN_THROWS();
659 	}
660 
661 	if (use_include_path) {
662 		flags |= USE_PATH;
663 	}
664 
665 	stream = php_stream_gzopen(NULL, filename, mode, flags, NULL, NULL STREAMS_CC);
666 
667 	if (!stream) {
668 		RETURN_FALSE;
669 	}
670 	php_stream_to_zval(stream, return_value);
671 }
672 /* }}} */
673 
674 /* {{{ Output a .gz-file */
PHP_FUNCTION(readgzfile)675 PHP_FUNCTION(readgzfile)
676 {
677 	char *filename;
678 	size_t filename_len;
679 	int flags = REPORT_ERRORS;
680 	php_stream *stream;
681 	size_t size;
682 	zend_long use_include_path = 0;
683 
684 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|l", &filename, &filename_len, &use_include_path) == FAILURE) {
685 		RETURN_THROWS();
686 	}
687 
688 	if (use_include_path) {
689 		flags |= USE_PATH;
690 	}
691 
692 	stream = php_stream_gzopen(NULL, filename, "rb", flags, NULL, NULL STREAMS_CC);
693 
694 	if (!stream) {
695 		RETURN_FALSE;
696 	}
697 	size = php_stream_passthru(stream);
698 	php_stream_close(stream);
699 	RETURN_LONG(size);
700 }
701 /* }}} */
702 
703 #define PHP_ZLIB_ENCODE_FUNC(name, default_encoding) \
704 PHP_FUNCTION(name) \
705 { \
706 	zend_string *in, *out; \
707 	zend_long level = -1; \
708 	zend_long encoding = default_encoding; \
709 	if (default_encoding) { \
710 		if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "S|ll", &in, &level, &encoding)) { \
711 			RETURN_THROWS(); \
712 		} \
713 	} else { \
714 		if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "Sl|l", &in, &encoding, &level)) { \
715 			RETURN_THROWS(); \
716 		} \
717 	} \
718 	if (level < -1 || level > 9) { \
719 		zend_argument_value_error(default_encoding ? 2 : 3, "must be between -1 and 9"); \
720 		RETURN_THROWS(); \
721 	} \
722 	switch (encoding) { \
723 		case PHP_ZLIB_ENCODING_RAW: \
724 		case PHP_ZLIB_ENCODING_GZIP: \
725 		case PHP_ZLIB_ENCODING_DEFLATE: \
726 			break; \
727 		default: \
728 			zend_argument_value_error(default_encoding ? 3 : 2, "must be one of ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP, or ZLIB_ENCODING_DEFLATE"); \
729 			RETURN_THROWS(); \
730 	} \
731 	if ((out = php_zlib_encode(ZSTR_VAL(in), ZSTR_LEN(in), encoding, level)) == NULL) { \
732 		RETURN_FALSE; \
733 	} \
734 	RETURN_STR(out); \
735 }
736 
737 #define PHP_ZLIB_DECODE_FUNC(name, encoding) \
738 PHP_FUNCTION(name) \
739 { \
740 	char *in_buf, *out_buf; \
741 	size_t in_len; \
742 	size_t out_len; \
743 	zend_long max_len = 0; \
744 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "s|l", &in_buf, &in_len, &max_len)) { \
745 		RETURN_THROWS(); \
746 	} \
747 	if (max_len < 0) { \
748 		zend_argument_value_error(2, "must be greater than or equal to 0"); \
749 		RETURN_THROWS(); \
750 	} \
751 	if (SUCCESS != php_zlib_decode(in_buf, in_len, &out_buf, &out_len, encoding, max_len)) { \
752 		RETURN_FALSE; \
753 	} \
754 	RETVAL_STRINGL(out_buf, out_len); \
755 	efree(out_buf); \
756 }
757 
758 /* {{{ Compress data with the specified encoding */
759 PHP_ZLIB_ENCODE_FUNC(zlib_encode, 0);
760 /* }}} */
761 
762 /* {{{ Uncompress any raw/gzip/zlib encoded data */
763 PHP_ZLIB_DECODE_FUNC(zlib_decode, PHP_ZLIB_ENCODING_ANY);
764 /* }}} */
765 
766 /* NOTE: The naming of these userland functions was quite unlucky */
767 /* {{{ Encode data with the raw deflate encoding */
768 PHP_ZLIB_ENCODE_FUNC(gzdeflate, PHP_ZLIB_ENCODING_RAW);
769 /* }}} */
770 
771 /* {{{ Encode data with the gzip encoding */
772 PHP_ZLIB_ENCODE_FUNC(gzencode, PHP_ZLIB_ENCODING_GZIP);
773 /* }}} */
774 
775 /* {{{ Encode data with the zlib encoding */
776 PHP_ZLIB_ENCODE_FUNC(gzcompress, PHP_ZLIB_ENCODING_DEFLATE);
777 /* }}} */
778 
779 /* {{{ Decode raw deflate encoded data */
780 PHP_ZLIB_DECODE_FUNC(gzinflate, PHP_ZLIB_ENCODING_RAW);
781 /* }}} */
782 
783 /* {{{ Decode gzip encoded data */
784 PHP_ZLIB_DECODE_FUNC(gzdecode, PHP_ZLIB_ENCODING_GZIP);
785 /* }}} */
786 
787 /* {{{ Decode zlib encoded data */
788 PHP_ZLIB_DECODE_FUNC(gzuncompress, PHP_ZLIB_ENCODING_DEFLATE);
789 /* }}} */
790 
zlib_create_dictionary_string(HashTable * options,char ** dict,size_t * dictlen)791 static bool zlib_create_dictionary_string(HashTable *options, char **dict, size_t *dictlen) {
792 	zval *option_buffer;
793 
794 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("dictionary"))) != NULL) {
795 		ZVAL_DEREF(option_buffer);
796 		switch (Z_TYPE_P(option_buffer)) {
797 			case IS_STRING: {
798 				zend_string *str = Z_STR_P(option_buffer);
799 				*dict = emalloc(ZSTR_LEN(str));
800 				memcpy(*dict, ZSTR_VAL(str), ZSTR_LEN(str));
801 				*dictlen = ZSTR_LEN(str);
802 			} break;
803 
804 			case IS_ARRAY: {
805 				HashTable *dictionary = Z_ARR_P(option_buffer);
806 
807 				if (zend_hash_num_elements(dictionary) > 0) {
808 					char *dictptr;
809 					zval *cur;
810 					zend_string **strings = emalloc(sizeof(zend_string *) * zend_hash_num_elements(dictionary));
811 					zend_string **end, **ptr = strings - 1;
812 
813 					ZEND_HASH_FOREACH_VAL(dictionary, cur) {
814 						size_t i;
815 
816 						*++ptr = zval_get_string(cur);
817 						if (!*ptr || ZSTR_LEN(*ptr) == 0 || EG(exception)) {
818 							if (*ptr) {
819 								efree(*ptr);
820 							}
821 							while (--ptr >= strings) {
822 								efree(ptr);
823 							}
824 							efree(strings);
825 							if (!EG(exception)) {
826 								zend_argument_value_error(2, "must not contain empty strings");
827 							}
828 							return 0;
829 						}
830 						for (i = 0; i < ZSTR_LEN(*ptr); i++) {
831 							if (ZSTR_VAL(*ptr)[i] == 0) {
832 								do {
833 									efree(ptr);
834 								} while (--ptr >= strings);
835 								efree(strings);
836 								zend_argument_value_error(2, "must not contain strings with null bytes");
837 								return 0;
838 							}
839 						}
840 
841 						*dictlen += ZSTR_LEN(*ptr) + 1;
842 					} ZEND_HASH_FOREACH_END();
843 
844 					dictptr = *dict = emalloc(*dictlen);
845 					ptr = strings;
846 					end = strings + zend_hash_num_elements(dictionary);
847 					do {
848 						memcpy(dictptr, ZSTR_VAL(*ptr), ZSTR_LEN(*ptr));
849 						dictptr += ZSTR_LEN(*ptr);
850 						*dictptr++ = 0;
851 						zend_string_release_ex(*ptr, 0);
852 					} while (++ptr != end);
853 					efree(strings);
854 				}
855 			} break;
856 
857 			default:
858 				zend_argument_type_error(2, "must be of type zero-terminated string or array, %s given", zend_zval_type_name(option_buffer));
859 				return 0;
860 		}
861 	}
862 
863 	return 1;
864 }
865 
866 /* {{{ Initialize an incremental inflate context with the specified encoding */
PHP_FUNCTION(inflate_init)867 PHP_FUNCTION(inflate_init)
868 {
869 	php_zlib_context *ctx;
870 	zend_long encoding, window = 15;
871 	char *dict = NULL;
872 	size_t dictlen = 0;
873 	HashTable *options = NULL;
874 	zval *option_buffer;
875 
876 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "l|H", &encoding, &options)) {
877 		RETURN_THROWS();
878 	}
879 
880 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("window"))) != NULL) {
881 		window = zval_get_long(option_buffer);
882 	}
883 	if (window < 8 || window > 15) {
884 		zend_value_error("zlib window size (logarithm) (" ZEND_LONG_FMT ") must be within 8..15", window);
885 		RETURN_THROWS();
886 	}
887 
888 	if (!zlib_create_dictionary_string(options, &dict, &dictlen)) {
889 		RETURN_THROWS();
890 	}
891 
892 	switch (encoding) {
893 		case PHP_ZLIB_ENCODING_RAW:
894 		case PHP_ZLIB_ENCODING_GZIP:
895 		case PHP_ZLIB_ENCODING_DEFLATE:
896 			break;
897 		default:
898 			zend_value_error("Encoding mode must be ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP or ZLIB_ENCODING_DEFLATE");
899 			RETURN_THROWS();
900 	}
901 
902 	object_init_ex(return_value, inflate_context_ce);
903 	ctx = Z_INFLATE_CONTEXT_P(return_value);
904 
905 	ctx->Z.zalloc = php_zlib_alloc;
906 	ctx->Z.zfree = php_zlib_free;
907 	ctx->inflateDict = dict;
908 	ctx->inflateDictlen = dictlen;
909 	ctx->status = Z_OK;
910 
911 	if (encoding < 0) {
912 		encoding += 15 - window;
913 	} else {
914 		encoding -= 15 - window;
915 	}
916 
917 	if (inflateInit2(&ctx->Z, encoding) != Z_OK) {
918 		zval_ptr_dtor(return_value);
919 		php_error_docref(NULL, E_WARNING, "Failed allocating zlib.inflate context");
920 		RETURN_FALSE;
921 	}
922 
923 	if (encoding == PHP_ZLIB_ENCODING_RAW && dictlen > 0) {
924 		switch (inflateSetDictionary(&ctx->Z, (Bytef *) ctx->inflateDict, ctx->inflateDictlen)) {
925 			case Z_OK:
926 				efree(ctx->inflateDict);
927 				ctx->inflateDict = NULL;
928 				break;
929 			case Z_DATA_ERROR:
930 				php_error_docref(NULL, E_WARNING, "Dictionary does not match expected dictionary (incorrect adler32 hash)");
931 				efree(ctx->inflateDict);
932 				ctx->inflateDict = NULL;
933 				break;
934 			EMPTY_SWITCH_DEFAULT_CASE()
935 		}
936 	}
937 }
938 /* }}} */
939 
940 /* {{{ Incrementally inflate encoded data in the specified context */
PHP_FUNCTION(inflate_add)941 PHP_FUNCTION(inflate_add)
942 {
943 	zend_string *out;
944 	char *in_buf;
945 	size_t in_len, buffer_used = 0, CHUNK_SIZE = 8192;
946 	zval *res;
947 	php_zlib_context *ctx;
948 	zend_long flush_type = Z_SYNC_FLUSH;
949 	int status;
950 
951 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "Os|l", &res, inflate_context_ce, &in_buf, &in_len, &flush_type)) {
952 		RETURN_THROWS();
953 	}
954 
955 	ctx = Z_INFLATE_CONTEXT_P(res);
956 
957 	switch (flush_type) {
958 		case Z_NO_FLUSH:
959 		case Z_PARTIAL_FLUSH:
960 		case Z_SYNC_FLUSH:
961 		case Z_FULL_FLUSH:
962 		case Z_BLOCK:
963 		case Z_FINISH:
964 			break;
965 
966 		default:
967 			zend_argument_value_error(3, "must be one of ZLIB_NO_FLUSH, ZLIB_PARTIAL_FLUSH, ZLIB_SYNC_FLUSH, ZLIB_FULL_FLUSH, ZLIB_BLOCK, or ZLIB_FINISH");
968 			RETURN_THROWS();
969 	}
970 
971 	/* Lazy-resetting the zlib stream so ctx->total_in remains available until the next inflate_add() call. */
972 	if (ctx->status == Z_STREAM_END)
973 	{
974 		ctx->status = Z_OK;
975 		inflateReset(&ctx->Z);
976 	}
977 
978 	if (in_len <= 0 && flush_type != Z_FINISH) {
979 		RETURN_EMPTY_STRING();
980 	}
981 
982 	out = zend_string_alloc((in_len > CHUNK_SIZE) ? in_len : CHUNK_SIZE, 0);
983 	ctx->Z.next_in = (Bytef *) in_buf;
984 	ctx->Z.next_out = (Bytef *) ZSTR_VAL(out);
985 	ctx->Z.avail_in = in_len;
986 	ctx->Z.avail_out = ZSTR_LEN(out);
987 
988 	do {
989 		status = inflate(&ctx->Z, flush_type);
990 		buffer_used = ZSTR_LEN(out) - ctx->Z.avail_out;
991 
992 		ctx->status = status; /* Save status for exposing to userspace */
993 
994 		switch (status) {
995 			case Z_OK:
996 				if (ctx->Z.avail_out == 0) {
997 					/* more output buffer space needed; realloc and try again */
998 					out = zend_string_realloc(out, ZSTR_LEN(out) + CHUNK_SIZE, 0);
999 					ctx->Z.avail_out = CHUNK_SIZE;
1000 					ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1001 					break;
1002 				} else {
1003 					goto complete;
1004 				}
1005 			case Z_STREAM_END:
1006 				goto complete;
1007 			case Z_BUF_ERROR:
1008 				if (flush_type == Z_FINISH && ctx->Z.avail_out == 0) {
1009 					/* more output buffer space needed; realloc and try again */
1010 					out = zend_string_realloc(out, ZSTR_LEN(out) + CHUNK_SIZE, 0);
1011 					ctx->Z.avail_out = CHUNK_SIZE;
1012 					ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1013 					break;
1014 				} else {
1015 					/* No more input data; we're finished */
1016 					goto complete;
1017 				}
1018 			case Z_NEED_DICT:
1019 				if (ctx->inflateDict) {
1020 					switch (inflateSetDictionary(&ctx->Z, (Bytef *) ctx->inflateDict, ctx->inflateDictlen)) {
1021 						case Z_OK:
1022 							efree(ctx->inflateDict);
1023 							ctx->inflateDict = NULL;
1024 							break;
1025 						case Z_DATA_ERROR:
1026 							efree(ctx->inflateDict);
1027 							ctx->inflateDict = NULL;
1028 							zend_string_release_ex(out, 0);
1029 							php_error_docref(NULL, E_WARNING, "Dictionary does not match expected dictionary (incorrect adler32 hash)");
1030 							RETURN_FALSE;
1031 						EMPTY_SWITCH_DEFAULT_CASE()
1032 					}
1033 					break;
1034 				} else {
1035 					php_error_docref(NULL, E_WARNING, "Inflating this data requires a preset dictionary, please specify it in the options array of inflate_init()");
1036 					RETURN_FALSE;
1037 				}
1038 			default:
1039 				zend_string_release_ex(out, 0);
1040 				php_error_docref(NULL, E_WARNING, "%s", zError(status));
1041 				RETURN_FALSE;
1042 		}
1043 	} while (1);
1044 
1045 complete:
1046 	out = zend_string_realloc(out, buffer_used, 0);
1047 	ZSTR_VAL(out)[buffer_used] = 0;
1048 	RETURN_STR(out);
1049 }
1050 /* }}} */
1051 
1052 /* {{{ Get decompression status, usually returns either ZLIB_OK or ZLIB_STREAM_END. */
PHP_FUNCTION(inflate_get_status)1053 PHP_FUNCTION(inflate_get_status)
1054 {
1055 	zval *res;
1056 	php_zlib_context *ctx;
1057 
1058 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &res, inflate_context_ce) != SUCCESS) {
1059 		RETURN_THROWS();
1060 	}
1061 
1062 	ctx = Z_INFLATE_CONTEXT_P(res);
1063 
1064 	RETURN_LONG(ctx->status);
1065 }
1066 /* }}} */
1067 
1068 /* {{{ Get number of bytes read so far. */
PHP_FUNCTION(inflate_get_read_len)1069 PHP_FUNCTION(inflate_get_read_len)
1070 {
1071 	zval *res;
1072 	php_zlib_context *ctx;
1073 
1074 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &res, inflate_context_ce) != SUCCESS) {
1075 		RETURN_THROWS();
1076 	}
1077 
1078 	ctx = Z_INFLATE_CONTEXT_P(res);
1079 
1080 	RETURN_LONG(ctx->Z.total_in);
1081 }
1082 /* }}} */
1083 
1084 /* {{{ Initialize an incremental deflate context using the specified encoding */
PHP_FUNCTION(deflate_init)1085 PHP_FUNCTION(deflate_init)
1086 {
1087 	php_zlib_context *ctx;
1088 	zend_long encoding, level = -1, memory = 8, window = 15, strategy = Z_DEFAULT_STRATEGY;
1089 	char *dict = NULL;
1090 	size_t dictlen = 0;
1091 	HashTable *options = NULL;
1092 	zval *option_buffer;
1093 
1094 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "l|H", &encoding, &options)) {
1095 		RETURN_THROWS();
1096 	}
1097 
1098 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("level"))) != NULL) {
1099 		level = zval_get_long(option_buffer);
1100 	}
1101 	if (level < -1 || level > 9) {
1102 		zend_value_error("deflate_init(): \"level\" option must be between -1 and 9");
1103 		RETURN_THROWS();
1104 	}
1105 
1106 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("memory"))) != NULL) {
1107 		memory = zval_get_long(option_buffer);
1108 	}
1109 	if (memory < 1 || memory > 9) {
1110 		zend_value_error("deflate_init(): \"memory\" option must be between 1 and 9");
1111 		RETURN_THROWS();
1112 	}
1113 
1114 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("window"))) != NULL) {
1115 		window = zval_get_long(option_buffer);
1116 	}
1117 	if (window < 8 || window > 15) {
1118 		zend_value_error("deflate_init(): \"window\" option must be between 8 and 15");
1119 		RETURN_THROWS();
1120 	}
1121 
1122 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("strategy"))) != NULL) {
1123 		strategy = zval_get_long(option_buffer);
1124 	}
1125 	switch (strategy) {
1126 		case Z_FILTERED:
1127 		case Z_HUFFMAN_ONLY:
1128 		case Z_RLE:
1129 		case Z_FIXED:
1130 		case Z_DEFAULT_STRATEGY:
1131 			break;
1132 		default:
1133 			zend_value_error("deflate_init(): \"strategy\" option must be one of ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED, or ZLIB_DEFAULT_STRATEGY");
1134 			RETURN_THROWS();
1135 	}
1136 
1137 	if (!zlib_create_dictionary_string(options, &dict, &dictlen)) {
1138 		RETURN_THROWS();
1139 	}
1140 
1141 	switch (encoding) {
1142 		case PHP_ZLIB_ENCODING_RAW:
1143 		case PHP_ZLIB_ENCODING_GZIP:
1144 		case PHP_ZLIB_ENCODING_DEFLATE:
1145 			break;
1146 		default:
1147 			zend_argument_value_error(1, "must be one of ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP, or ZLIB_ENCODING_DEFLATE");
1148 			RETURN_THROWS();
1149 	}
1150 
1151 	object_init_ex(return_value, deflate_context_ce);
1152 	ctx = Z_DEFLATE_CONTEXT_P(return_value);
1153 
1154 	ctx->Z.zalloc = php_zlib_alloc;
1155 	ctx->Z.zfree = php_zlib_free;
1156 
1157 	if (encoding < 0) {
1158 		encoding += 15 - window;
1159 	} else {
1160 		encoding -= 15 - window;
1161 	}
1162 
1163 	if (deflateInit2(&ctx->Z, level, Z_DEFLATED, encoding, memory, strategy) != Z_OK) {
1164 		zval_ptr_dtor(return_value);
1165 		php_error_docref(NULL, E_WARNING, "Failed allocating zlib.deflate context");
1166 		RETURN_FALSE;
1167 	}
1168 
1169 	if (dict) {
1170 		int success = deflateSetDictionary(&ctx->Z, (Bytef *) dict, dictlen);
1171 		ZEND_ASSERT(success == Z_OK);
1172 		efree(dict);
1173 	}
1174 }
1175 /* }}} */
1176 
1177 /* {{{ Incrementally deflate data in the specified context */
PHP_FUNCTION(deflate_add)1178 PHP_FUNCTION(deflate_add)
1179 {
1180 	zend_string *out;
1181 	char *in_buf;
1182 	size_t in_len, out_size, buffer_used;
1183 	zval *res;
1184 	php_zlib_context *ctx;
1185 	zend_long flush_type = Z_SYNC_FLUSH;
1186 	int status;
1187 
1188 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "Os|l", &res, deflate_context_ce, &in_buf, &in_len, &flush_type)) {
1189 		RETURN_THROWS();
1190 	}
1191 
1192 	ctx = Z_DEFLATE_CONTEXT_P(res);
1193 
1194 	switch (flush_type) {
1195 		case Z_BLOCK:
1196 #if ZLIB_VERNUM < 0x1240L
1197 			zend_throw_error(NULL, "zlib >= 1.2.4 required for BLOCK deflate; current version: %s", ZLIB_VERSION);
1198 			RETURN_THROWS();
1199 #endif
1200 		case Z_NO_FLUSH:
1201 		case Z_PARTIAL_FLUSH:
1202 		case Z_SYNC_FLUSH:
1203 		case Z_FULL_FLUSH:
1204 		case Z_FINISH:
1205 			break;
1206 
1207 		default:
1208 			zend_argument_value_error(3, "must be one of ZLIB_NO_FLUSH, ZLIB_PARTIAL_FLUSH, ZLIB_SYNC_FLUSH, ZLIB_FULL_FLUSH, ZLIB_BLOCK, or ZLIB_FINISH");
1209 			RETURN_THROWS();
1210 	}
1211 
1212 	if (in_len <= 0 && flush_type != Z_FINISH) {
1213 		RETURN_EMPTY_STRING();
1214 	}
1215 
1216 	out_size = PHP_ZLIB_BUFFER_SIZE_GUESS(in_len);
1217 	out_size = (out_size < 64) ? 64 : out_size;
1218 	out = zend_string_alloc(out_size, 0);
1219 
1220 	ctx->Z.next_in = (Bytef *) in_buf;
1221 	ctx->Z.next_out = (Bytef *) ZSTR_VAL(out);
1222 	ctx->Z.avail_in = in_len;
1223 	ctx->Z.avail_out = ZSTR_LEN(out);
1224 
1225 	buffer_used = 0;
1226 
1227 	do {
1228 		if (ctx->Z.avail_out == 0) {
1229 			/* more output buffer space needed; realloc and try again */
1230 			/* adding 64 more bytes solved every issue I have seen    */
1231 			out = zend_string_realloc(out, ZSTR_LEN(out) + 64, 0);
1232 			ctx->Z.avail_out = 64;
1233 			ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1234 		}
1235 		status = deflate(&ctx->Z, flush_type);
1236 		buffer_used = ZSTR_LEN(out) - ctx->Z.avail_out;
1237 	} while (status == Z_OK && ctx->Z.avail_out == 0);
1238 
1239 	switch (status) {
1240 		case Z_OK:
1241 			ZSTR_LEN(out) = (char *) ctx->Z.next_out - ZSTR_VAL(out);
1242 			ZSTR_VAL(out)[ZSTR_LEN(out)] = 0;
1243 			RETURN_STR(out);
1244 			break;
1245 		case Z_STREAM_END:
1246 			ZSTR_LEN(out) = (char *) ctx->Z.next_out - ZSTR_VAL(out);
1247 			ZSTR_VAL(out)[ZSTR_LEN(out)] = 0;
1248 			deflateReset(&ctx->Z);
1249 			RETURN_STR(out);
1250 			break;
1251 		default:
1252 			zend_string_release_ex(out, 0);
1253 			php_error_docref(NULL, E_WARNING, "zlib error (%s)", zError(status));
1254 			RETURN_FALSE;
1255 	}
1256 }
1257 /* }}} */
1258 
1259 #ifdef COMPILE_DL_ZLIB
1260 #ifdef ZTS
1261 ZEND_TSRMLS_CACHE_DEFINE()
1262 #endif
ZEND_GET_MODULE(php_zlib)1263 ZEND_GET_MODULE(php_zlib)
1264 #endif
1265 
1266 /* {{{ OnUpdate_zlib_output_compression */
1267 static PHP_INI_MH(OnUpdate_zlib_output_compression)
1268 {
1269 	int int_value;
1270 	char *ini_value;
1271 	if (new_value == NULL) {
1272 		return FAILURE;
1273 	}
1274 
1275 	if (zend_string_equals_literal_ci(new_value, "off")) {
1276 		int_value = 0;
1277 	} else if (zend_string_equals_literal_ci(new_value, "on")) {
1278 		int_value = 1;
1279 	} else {
1280 		int_value = zend_atoi(ZSTR_VAL(new_value), ZSTR_LEN(new_value));
1281 	}
1282 	ini_value = zend_ini_string("output_handler", sizeof("output_handler") - 1, 0);
1283 
1284 	if (ini_value && *ini_value && int_value) {
1285 		php_error_docref("ref.outcontrol", E_CORE_ERROR, "Cannot use both zlib.output_compression and output_handler together!!");
1286 		return FAILURE;
1287 	}
1288 	if (stage == PHP_INI_STAGE_RUNTIME) {
1289 		int status = php_output_get_status();
1290 		if (status & PHP_OUTPUT_SENT) {
1291 			php_error_docref("ref.outcontrol", E_WARNING, "Cannot change zlib.output_compression - headers already sent");
1292 			return FAILURE;
1293 		}
1294 	}
1295 
1296 	zend_long *p = (zend_long *) ZEND_INI_GET_ADDR();
1297 	*p = int_value;
1298 
1299 	ZLIBG(output_compression) = ZLIBG(output_compression_default);
1300 	if (stage == PHP_INI_STAGE_RUNTIME && int_value) {
1301 		if (!php_output_handler_started(ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME))) {
1302 			php_zlib_output_compression_start();
1303 		}
1304 	}
1305 
1306 	return SUCCESS;
1307 }
1308 /* }}} */
1309 
1310 /* {{{ OnUpdate_zlib_output_handler */
PHP_INI_MH(OnUpdate_zlib_output_handler)1311 static PHP_INI_MH(OnUpdate_zlib_output_handler)
1312 {
1313 	if (stage == PHP_INI_STAGE_RUNTIME && (php_output_get_status() & PHP_OUTPUT_SENT)) {
1314 		php_error_docref("ref.outcontrol", E_WARNING, "Cannot change zlib.output_handler - headers already sent");
1315 		return FAILURE;
1316 	}
1317 
1318 	return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
1319 }
1320 /* }}} */
1321 
1322 /* {{{ INI */
1323 PHP_INI_BEGIN()
1324 	STD_PHP_INI_BOOLEAN("zlib.output_compression",      "0", PHP_INI_ALL, OnUpdate_zlib_output_compression,       output_compression_default,       zend_zlib_globals, zlib_globals)
1325 	STD_PHP_INI_ENTRY("zlib.output_compression_level", "-1", PHP_INI_ALL, OnUpdateLong,                           output_compression_level, zend_zlib_globals, zlib_globals)
1326 	STD_PHP_INI_ENTRY("zlib.output_handler",             "", PHP_INI_ALL, OnUpdate_zlib_output_handler,           output_handler,           zend_zlib_globals, zlib_globals)
PHP_INI_END()1327 PHP_INI_END()
1328 
1329 /* }}} */
1330 
1331 /* {{{ PHP_MINIT_FUNCTION */
1332 static PHP_MINIT_FUNCTION(zlib)
1333 {
1334 	php_register_url_stream_wrapper("compress.zlib", &php_stream_gzip_wrapper);
1335 	php_stream_filter_register_factory("zlib.*", &php_zlib_filter_factory);
1336 
1337 	php_output_handler_alias_register(ZEND_STRL("ob_gzhandler"), php_zlib_output_handler_init);
1338 	php_output_handler_conflict_register(ZEND_STRL("ob_gzhandler"), php_zlib_output_conflict_check);
1339 	php_output_handler_conflict_register(ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME), php_zlib_output_conflict_check);
1340 
1341 	inflate_context_ce = register_class_InflateContext();
1342 	inflate_context_ce->create_object = inflate_context_create_object;
1343 
1344 	memcpy(&inflate_context_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1345 	inflate_context_object_handlers.offset = XtOffsetOf(php_zlib_context, std);
1346 	inflate_context_object_handlers.free_obj = inflate_context_free_obj;
1347 	inflate_context_object_handlers.get_constructor = inflate_context_get_constructor;
1348 	inflate_context_object_handlers.clone_obj = NULL;
1349 	inflate_context_object_handlers.compare = zend_objects_not_comparable;
1350 
1351 	deflate_context_ce = register_class_DeflateContext();
1352 	deflate_context_ce->create_object = deflate_context_create_object;
1353 
1354 	memcpy(&deflate_context_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1355 	deflate_context_object_handlers.offset = XtOffsetOf(php_zlib_context, std);
1356 	deflate_context_object_handlers.free_obj = deflate_context_free_obj;
1357 	deflate_context_object_handlers.get_constructor = deflate_context_get_constructor;
1358 	deflate_context_object_handlers.clone_obj = NULL;
1359 	deflate_context_object_handlers.compare = zend_objects_not_comparable;
1360 
1361 	REGISTER_LONG_CONSTANT("FORCE_GZIP", PHP_ZLIB_ENCODING_GZIP, CONST_CS|CONST_PERSISTENT);
1362 	REGISTER_LONG_CONSTANT("FORCE_DEFLATE", PHP_ZLIB_ENCODING_DEFLATE, CONST_CS|CONST_PERSISTENT);
1363 
1364 	REGISTER_LONG_CONSTANT("ZLIB_ENCODING_RAW", PHP_ZLIB_ENCODING_RAW, CONST_CS|CONST_PERSISTENT);
1365 	REGISTER_LONG_CONSTANT("ZLIB_ENCODING_GZIP", PHP_ZLIB_ENCODING_GZIP, CONST_CS|CONST_PERSISTENT);
1366 	REGISTER_LONG_CONSTANT("ZLIB_ENCODING_DEFLATE", PHP_ZLIB_ENCODING_DEFLATE, CONST_CS|CONST_PERSISTENT);
1367 
1368 	REGISTER_LONG_CONSTANT("ZLIB_NO_FLUSH", Z_NO_FLUSH, CONST_CS|CONST_PERSISTENT);
1369 	REGISTER_LONG_CONSTANT("ZLIB_PARTIAL_FLUSH", Z_PARTIAL_FLUSH, CONST_CS|CONST_PERSISTENT);
1370 	REGISTER_LONG_CONSTANT("ZLIB_SYNC_FLUSH", Z_SYNC_FLUSH, CONST_CS|CONST_PERSISTENT);
1371 	REGISTER_LONG_CONSTANT("ZLIB_FULL_FLUSH", Z_FULL_FLUSH, CONST_CS|CONST_PERSISTENT);
1372 	REGISTER_LONG_CONSTANT("ZLIB_BLOCK", Z_BLOCK, CONST_CS|CONST_PERSISTENT);
1373 	REGISTER_LONG_CONSTANT("ZLIB_FINISH", Z_FINISH, CONST_CS|CONST_PERSISTENT);
1374 
1375 	REGISTER_LONG_CONSTANT("ZLIB_FILTERED", Z_FILTERED, CONST_CS|CONST_PERSISTENT);
1376 	REGISTER_LONG_CONSTANT("ZLIB_HUFFMAN_ONLY", Z_HUFFMAN_ONLY, CONST_CS|CONST_PERSISTENT);
1377 	REGISTER_LONG_CONSTANT("ZLIB_RLE", Z_RLE, CONST_CS|CONST_PERSISTENT);
1378 	REGISTER_LONG_CONSTANT("ZLIB_FIXED", Z_FIXED, CONST_CS|CONST_PERSISTENT);
1379 	REGISTER_LONG_CONSTANT("ZLIB_DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY, CONST_CS|CONST_PERSISTENT);
1380 
1381 	REGISTER_STRING_CONSTANT("ZLIB_VERSION", ZLIB_VERSION, CONST_CS|CONST_PERSISTENT);
1382 	REGISTER_LONG_CONSTANT("ZLIB_VERNUM", ZLIB_VERNUM, CONST_CS|CONST_PERSISTENT);
1383 
1384 	REGISTER_LONG_CONSTANT("ZLIB_OK", Z_OK, CONST_CS|CONST_PERSISTENT);
1385 	REGISTER_LONG_CONSTANT("ZLIB_STREAM_END", Z_STREAM_END, CONST_CS|CONST_PERSISTENT);
1386 	REGISTER_LONG_CONSTANT("ZLIB_NEED_DICT", Z_NEED_DICT, CONST_CS|CONST_PERSISTENT);
1387 	REGISTER_LONG_CONSTANT("ZLIB_ERRNO", Z_ERRNO, CONST_CS|CONST_PERSISTENT);
1388 	REGISTER_LONG_CONSTANT("ZLIB_STREAM_ERROR", Z_STREAM_ERROR, CONST_CS|CONST_PERSISTENT);
1389 	REGISTER_LONG_CONSTANT("ZLIB_DATA_ERROR", Z_DATA_ERROR, CONST_CS|CONST_PERSISTENT);
1390 	REGISTER_LONG_CONSTANT("ZLIB_MEM_ERROR", Z_MEM_ERROR, CONST_CS|CONST_PERSISTENT);
1391 	REGISTER_LONG_CONSTANT("ZLIB_BUF_ERROR", Z_BUF_ERROR, CONST_CS|CONST_PERSISTENT);
1392 	REGISTER_LONG_CONSTANT("ZLIB_VERSION_ERROR", Z_VERSION_ERROR, CONST_CS|CONST_PERSISTENT);
1393 
1394 	REGISTER_INI_ENTRIES();
1395 	return SUCCESS;
1396 }
1397 /* }}} */
1398 
1399 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(zlib)1400 static PHP_MSHUTDOWN_FUNCTION(zlib)
1401 {
1402 	php_unregister_url_stream_wrapper("zlib");
1403 	php_stream_filter_unregister_factory("zlib.*");
1404 
1405 	UNREGISTER_INI_ENTRIES();
1406 
1407 	return SUCCESS;
1408 }
1409 /* }}} */
1410 
1411 /* {{{ PHP_RINIT_FUNCTION */
PHP_RINIT_FUNCTION(zlib)1412 static PHP_RINIT_FUNCTION(zlib)
1413 {
1414 	ZLIBG(compression_coding) = 0;
1415 	if (!ZLIBG(handler_registered)) {
1416 		ZLIBG(output_compression) = ZLIBG(output_compression_default);
1417 		php_zlib_output_compression_start();
1418 	}
1419 
1420 	return SUCCESS;
1421 }
1422 /* }}} */
1423 
1424 /* {{{ PHP_RSHUTDOWN_FUNCTION */
PHP_RSHUTDOWN_FUNCTION(zlib)1425 static PHP_RSHUTDOWN_FUNCTION(zlib)
1426 {
1427 	php_zlib_cleanup_ob_gzhandler_mess();
1428 	ZLIBG(handler_registered) = 0;
1429 
1430 	return SUCCESS;
1431 }
1432 /* }}} */
1433 
1434 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(zlib)1435 static PHP_MINFO_FUNCTION(zlib)
1436 {
1437 	php_info_print_table_start();
1438 	php_info_print_table_header(2, "ZLib Support", "enabled");
1439 	php_info_print_table_row(2, "Stream Wrapper", "compress.zlib://");
1440 	php_info_print_table_row(2, "Stream Filter", "zlib.inflate, zlib.deflate");
1441 	php_info_print_table_row(2, "Compiled Version", ZLIB_VERSION);
1442 	php_info_print_table_row(2, "Linked Version", (char *) zlibVersion());
1443 	php_info_print_table_end();
1444 
1445 	DISPLAY_INI_ENTRIES();
1446 }
1447 /* }}} */
1448 
1449 /* {{{ ZEND_MODULE_GLOBALS_CTOR */
PHP_GINIT_FUNCTION(zlib)1450 static PHP_GINIT_FUNCTION(zlib)
1451 {
1452 #if defined(COMPILE_DL_ZLIB) && defined(ZTS)
1453 	ZEND_TSRMLS_CACHE_UPDATE();
1454 #endif
1455 	zlib_globals->ob_gzhandler = NULL;
1456 	zlib_globals->handler_registered = 0;
1457 }
1458 /* }}} */
1459 
1460 /* {{{ php_zlib_module_entry */
1461 zend_module_entry php_zlib_module_entry = {
1462 	STANDARD_MODULE_HEADER,
1463 	"zlib",
1464 	ext_functions,
1465 	PHP_MINIT(zlib),
1466 	PHP_MSHUTDOWN(zlib),
1467 	PHP_RINIT(zlib),
1468 	PHP_RSHUTDOWN(zlib),
1469 	PHP_MINFO(zlib),
1470 	PHP_ZLIB_VERSION,
1471 	PHP_MODULE_GLOBALS(zlib),
1472 	PHP_GINIT(zlib),
1473 	NULL,
1474 	NULL,
1475 	STANDARD_MODULE_PROPERTIES_EX
1476 };
1477 /* }}} */
1478