xref: /PHP-8.2/ext/zlib/zlib.c (revision d94be24f)
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 = safe_emalloc(zend_hash_num_elements(dictionary), sizeof(zend_string *), 0);
811 					zend_string **end, **ptr = strings - 1;
812 
813 					ZEND_HASH_FOREACH_VAL(dictionary, cur) {
814 						*++ptr = zval_get_string(cur);
815 						ZEND_ASSERT(*ptr);
816 						if (ZSTR_LEN(*ptr) == 0 || EG(exception)) {
817 							do {
818 								zend_string_release(*ptr);
819 							} while (--ptr >= strings);
820 							efree(strings);
821 							if (!EG(exception)) {
822 								zend_argument_value_error(2, "must not contain empty strings");
823 							}
824 							return 0;
825 						}
826 						if (zend_str_has_nul_byte(*ptr)) {
827 							do {
828 								zend_string_release(*ptr);
829 							} while (--ptr >= strings);
830 							efree(strings);
831 							zend_argument_value_error(2, "must not contain strings with null bytes");
832 							return 0;
833 						}
834 
835 						*dictlen += ZSTR_LEN(*ptr) + 1;
836 					} ZEND_HASH_FOREACH_END();
837 
838 					dictptr = *dict = emalloc(*dictlen);
839 					ptr = strings;
840 					end = strings + zend_hash_num_elements(dictionary);
841 					do {
842 						memcpy(dictptr, ZSTR_VAL(*ptr), ZSTR_LEN(*ptr));
843 						dictptr += ZSTR_LEN(*ptr);
844 						*dictptr++ = 0;
845 						zend_string_release_ex(*ptr, 0);
846 					} while (++ptr != end);
847 					efree(strings);
848 				}
849 			} break;
850 
851 			default:
852 				zend_argument_type_error(2, "must be of type zero-terminated string or array, %s given", zend_zval_type_name(option_buffer));
853 				return 0;
854 		}
855 	}
856 
857 	return 1;
858 }
859 
860 /* {{{ Initialize an incremental inflate context with the specified encoding */
PHP_FUNCTION(inflate_init)861 PHP_FUNCTION(inflate_init)
862 {
863 	php_zlib_context *ctx;
864 	zend_long encoding, window = 15;
865 	char *dict = NULL;
866 	size_t dictlen = 0;
867 	HashTable *options = NULL;
868 	zval *option_buffer;
869 
870 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "l|H", &encoding, &options)) {
871 		RETURN_THROWS();
872 	}
873 
874 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("window"))) != NULL) {
875 		window = zval_get_long(option_buffer);
876 	}
877 	if (window < 8 || window > 15) {
878 		zend_value_error("zlib window size (logarithm) (" ZEND_LONG_FMT ") must be within 8..15", window);
879 		RETURN_THROWS();
880 	}
881 
882 	if (!zlib_create_dictionary_string(options, &dict, &dictlen)) {
883 		RETURN_THROWS();
884 	}
885 
886 	switch (encoding) {
887 		case PHP_ZLIB_ENCODING_RAW:
888 		case PHP_ZLIB_ENCODING_GZIP:
889 		case PHP_ZLIB_ENCODING_DEFLATE:
890 			break;
891 		default:
892 			zend_value_error("Encoding mode must be ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP or ZLIB_ENCODING_DEFLATE");
893 			RETURN_THROWS();
894 	}
895 
896 	object_init_ex(return_value, inflate_context_ce);
897 	ctx = Z_INFLATE_CONTEXT_P(return_value);
898 
899 	ctx->Z.zalloc = php_zlib_alloc;
900 	ctx->Z.zfree = php_zlib_free;
901 	ctx->inflateDict = dict;
902 	ctx->inflateDictlen = dictlen;
903 	ctx->status = Z_OK;
904 
905 	if (encoding < 0) {
906 		encoding += 15 - window;
907 	} else {
908 		encoding -= 15 - window;
909 	}
910 
911 	if (inflateInit2(&ctx->Z, encoding) != Z_OK) {
912 		zval_ptr_dtor(return_value);
913 		php_error_docref(NULL, E_WARNING, "Failed allocating zlib.inflate context");
914 		RETURN_FALSE;
915 	}
916 
917 	if (encoding == PHP_ZLIB_ENCODING_RAW && dictlen > 0) {
918 		switch (inflateSetDictionary(&ctx->Z, (Bytef *) ctx->inflateDict, ctx->inflateDictlen)) {
919 			case Z_OK:
920 				efree(ctx->inflateDict);
921 				ctx->inflateDict = NULL;
922 				break;
923 			case Z_DATA_ERROR:
924 				php_error_docref(NULL, E_WARNING, "Dictionary does not match expected dictionary (incorrect adler32 hash)");
925 				efree(ctx->inflateDict);
926 				ctx->inflateDict = NULL;
927 				break;
928 			EMPTY_SWITCH_DEFAULT_CASE()
929 		}
930 	}
931 }
932 /* }}} */
933 
934 /* {{{ Incrementally inflate encoded data in the specified context */
PHP_FUNCTION(inflate_add)935 PHP_FUNCTION(inflate_add)
936 {
937 	zend_string *out;
938 	char *in_buf;
939 	size_t in_len, buffer_used = 0, CHUNK_SIZE = 8192;
940 	zval *res;
941 	php_zlib_context *ctx;
942 	zend_long flush_type = Z_SYNC_FLUSH;
943 	int status;
944 
945 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "Os|l", &res, inflate_context_ce, &in_buf, &in_len, &flush_type)) {
946 		RETURN_THROWS();
947 	}
948 
949 	ctx = Z_INFLATE_CONTEXT_P(res);
950 
951 	switch (flush_type) {
952 		case Z_NO_FLUSH:
953 		case Z_PARTIAL_FLUSH:
954 		case Z_SYNC_FLUSH:
955 		case Z_FULL_FLUSH:
956 		case Z_BLOCK:
957 		case Z_FINISH:
958 			break;
959 
960 		default:
961 			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");
962 			RETURN_THROWS();
963 	}
964 
965 	/* Lazy-resetting the zlib stream so ctx->total_in remains available until the next inflate_add() call. */
966 	if (ctx->status == Z_STREAM_END)
967 	{
968 		ctx->status = Z_OK;
969 		inflateReset(&ctx->Z);
970 	}
971 
972 	if (in_len <= 0 && flush_type != Z_FINISH) {
973 		RETURN_EMPTY_STRING();
974 	}
975 
976 	out = zend_string_alloc((in_len > CHUNK_SIZE) ? in_len : CHUNK_SIZE, 0);
977 	ctx->Z.next_in = (Bytef *) in_buf;
978 	ctx->Z.next_out = (Bytef *) ZSTR_VAL(out);
979 	ctx->Z.avail_in = in_len;
980 	ctx->Z.avail_out = ZSTR_LEN(out);
981 
982 	do {
983 		status = inflate(&ctx->Z, flush_type);
984 		buffer_used = ZSTR_LEN(out) - ctx->Z.avail_out;
985 
986 		ctx->status = status; /* Save status for exposing to userspace */
987 
988 		switch (status) {
989 			case Z_OK:
990 				if (ctx->Z.avail_out == 0) {
991 					/* more output buffer space needed; realloc and try again */
992 					out = zend_string_realloc(out, ZSTR_LEN(out) + CHUNK_SIZE, 0);
993 					ctx->Z.avail_out = CHUNK_SIZE;
994 					ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
995 					break;
996 				} else {
997 					goto complete;
998 				}
999 			case Z_STREAM_END:
1000 				goto complete;
1001 			case Z_BUF_ERROR:
1002 				if (flush_type == Z_FINISH && ctx->Z.avail_out == 0) {
1003 					/* more output buffer space needed; realloc and try again */
1004 					out = zend_string_realloc(out, ZSTR_LEN(out) + CHUNK_SIZE, 0);
1005 					ctx->Z.avail_out = CHUNK_SIZE;
1006 					ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1007 					break;
1008 				} else {
1009 					/* No more input data; we're finished */
1010 					goto complete;
1011 				}
1012 			case Z_NEED_DICT:
1013 				if (ctx->inflateDict) {
1014 					switch (inflateSetDictionary(&ctx->Z, (Bytef *) ctx->inflateDict, ctx->inflateDictlen)) {
1015 						case Z_OK:
1016 							efree(ctx->inflateDict);
1017 							ctx->inflateDict = NULL;
1018 							break;
1019 						case Z_DATA_ERROR:
1020 							efree(ctx->inflateDict);
1021 							ctx->inflateDict = NULL;
1022 							zend_string_release_ex(out, 0);
1023 							php_error_docref(NULL, E_WARNING, "Dictionary does not match expected dictionary (incorrect adler32 hash)");
1024 							RETURN_FALSE;
1025 						EMPTY_SWITCH_DEFAULT_CASE()
1026 					}
1027 					break;
1028 				} else {
1029 					php_error_docref(NULL, E_WARNING, "Inflating this data requires a preset dictionary, please specify it in the options array of inflate_init()");
1030 					RETURN_FALSE;
1031 				}
1032 			default:
1033 				zend_string_release_ex(out, 0);
1034 				php_error_docref(NULL, E_WARNING, "%s", zError(status));
1035 				RETURN_FALSE;
1036 		}
1037 	} while (1);
1038 
1039 complete:
1040 	out = zend_string_realloc(out, buffer_used, 0);
1041 	ZSTR_VAL(out)[buffer_used] = 0;
1042 	RETURN_STR(out);
1043 }
1044 /* }}} */
1045 
1046 /* {{{ Get decompression status, usually returns either ZLIB_OK or ZLIB_STREAM_END. */
PHP_FUNCTION(inflate_get_status)1047 PHP_FUNCTION(inflate_get_status)
1048 {
1049 	zval *res;
1050 	php_zlib_context *ctx;
1051 
1052 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &res, inflate_context_ce) != SUCCESS) {
1053 		RETURN_THROWS();
1054 	}
1055 
1056 	ctx = Z_INFLATE_CONTEXT_P(res);
1057 
1058 	RETURN_LONG(ctx->status);
1059 }
1060 /* }}} */
1061 
1062 /* {{{ Get number of bytes read so far. */
PHP_FUNCTION(inflate_get_read_len)1063 PHP_FUNCTION(inflate_get_read_len)
1064 {
1065 	zval *res;
1066 	php_zlib_context *ctx;
1067 
1068 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &res, inflate_context_ce) != SUCCESS) {
1069 		RETURN_THROWS();
1070 	}
1071 
1072 	ctx = Z_INFLATE_CONTEXT_P(res);
1073 
1074 	RETURN_LONG(ctx->Z.total_in);
1075 }
1076 /* }}} */
1077 
1078 /* {{{ Initialize an incremental deflate context using the specified encoding */
PHP_FUNCTION(deflate_init)1079 PHP_FUNCTION(deflate_init)
1080 {
1081 	php_zlib_context *ctx;
1082 	zend_long encoding, level = -1, memory = 8, window = 15, strategy = Z_DEFAULT_STRATEGY;
1083 	char *dict = NULL;
1084 	size_t dictlen = 0;
1085 	HashTable *options = NULL;
1086 	zval *option_buffer;
1087 
1088 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "l|H", &encoding, &options)) {
1089 		RETURN_THROWS();
1090 	}
1091 
1092 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("level"))) != NULL) {
1093 		level = zval_get_long(option_buffer);
1094 	}
1095 	if (level < -1 || level > 9) {
1096 		zend_value_error("deflate_init(): \"level\" option must be between -1 and 9");
1097 		RETURN_THROWS();
1098 	}
1099 
1100 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("memory"))) != NULL) {
1101 		memory = zval_get_long(option_buffer);
1102 	}
1103 	if (memory < 1 || memory > 9) {
1104 		zend_value_error("deflate_init(): \"memory\" option must be between 1 and 9");
1105 		RETURN_THROWS();
1106 	}
1107 
1108 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("window"))) != NULL) {
1109 		window = zval_get_long(option_buffer);
1110 	}
1111 	if (window < 8 || window > 15) {
1112 		zend_value_error("deflate_init(): \"window\" option must be between 8 and 15");
1113 		RETURN_THROWS();
1114 	}
1115 
1116 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("strategy"))) != NULL) {
1117 		strategy = zval_get_long(option_buffer);
1118 	}
1119 	switch (strategy) {
1120 		case Z_FILTERED:
1121 		case Z_HUFFMAN_ONLY:
1122 		case Z_RLE:
1123 		case Z_FIXED:
1124 		case Z_DEFAULT_STRATEGY:
1125 			break;
1126 		default:
1127 			zend_value_error("deflate_init(): \"strategy\" option must be one of ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED, or ZLIB_DEFAULT_STRATEGY");
1128 			RETURN_THROWS();
1129 	}
1130 
1131 	if (!zlib_create_dictionary_string(options, &dict, &dictlen)) {
1132 		RETURN_THROWS();
1133 	}
1134 
1135 	switch (encoding) {
1136 		case PHP_ZLIB_ENCODING_RAW:
1137 		case PHP_ZLIB_ENCODING_GZIP:
1138 		case PHP_ZLIB_ENCODING_DEFLATE:
1139 			break;
1140 		default:
1141 			zend_argument_value_error(1, "must be one of ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP, or ZLIB_ENCODING_DEFLATE");
1142 			RETURN_THROWS();
1143 	}
1144 
1145 	object_init_ex(return_value, deflate_context_ce);
1146 	ctx = Z_DEFLATE_CONTEXT_P(return_value);
1147 
1148 	ctx->Z.zalloc = php_zlib_alloc;
1149 	ctx->Z.zfree = php_zlib_free;
1150 
1151 	if (encoding < 0) {
1152 		encoding += 15 - window;
1153 	} else {
1154 		encoding -= 15 - window;
1155 	}
1156 
1157 	if (deflateInit2(&ctx->Z, level, Z_DEFLATED, encoding, memory, strategy) != Z_OK) {
1158 		zval_ptr_dtor(return_value);
1159 		php_error_docref(NULL, E_WARNING, "Failed allocating zlib.deflate context");
1160 		RETURN_FALSE;
1161 	}
1162 
1163 	if (dict) {
1164 		int success = deflateSetDictionary(&ctx->Z, (Bytef *) dict, dictlen);
1165 		ZEND_ASSERT(success == Z_OK);
1166 		efree(dict);
1167 	}
1168 }
1169 /* }}} */
1170 
1171 /* {{{ Incrementally deflate data in the specified context */
PHP_FUNCTION(deflate_add)1172 PHP_FUNCTION(deflate_add)
1173 {
1174 	zend_string *out;
1175 	char *in_buf;
1176 	size_t in_len, out_size, buffer_used;
1177 	zval *res;
1178 	php_zlib_context *ctx;
1179 	zend_long flush_type = Z_SYNC_FLUSH;
1180 	int status;
1181 
1182 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "Os|l", &res, deflate_context_ce, &in_buf, &in_len, &flush_type)) {
1183 		RETURN_THROWS();
1184 	}
1185 
1186 	ctx = Z_DEFLATE_CONTEXT_P(res);
1187 
1188 	switch (flush_type) {
1189 		case Z_BLOCK:
1190 #if ZLIB_VERNUM < 0x1240L
1191 			zend_throw_error(NULL, "zlib >= 1.2.4 required for BLOCK deflate; current version: %s", ZLIB_VERSION);
1192 			RETURN_THROWS();
1193 #endif
1194 		case Z_NO_FLUSH:
1195 		case Z_PARTIAL_FLUSH:
1196 		case Z_SYNC_FLUSH:
1197 		case Z_FULL_FLUSH:
1198 		case Z_FINISH:
1199 			break;
1200 
1201 		default:
1202 			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");
1203 			RETURN_THROWS();
1204 	}
1205 
1206 	if (in_len <= 0 && flush_type != Z_FINISH) {
1207 		RETURN_EMPTY_STRING();
1208 	}
1209 
1210 	out_size = PHP_ZLIB_BUFFER_SIZE_GUESS(in_len);
1211 	out_size = (out_size < 64) ? 64 : out_size;
1212 	out = zend_string_alloc(out_size, 0);
1213 
1214 	ctx->Z.next_in = (Bytef *) in_buf;
1215 	ctx->Z.next_out = (Bytef *) ZSTR_VAL(out);
1216 	ctx->Z.avail_in = in_len;
1217 	ctx->Z.avail_out = ZSTR_LEN(out);
1218 
1219 	buffer_used = 0;
1220 
1221 	do {
1222 		if (ctx->Z.avail_out == 0) {
1223 			/* more output buffer space needed; realloc and try again */
1224 			/* adding 64 more bytes solved every issue I have seen    */
1225 			out = zend_string_realloc(out, ZSTR_LEN(out) + 64, 0);
1226 			ctx->Z.avail_out = 64;
1227 			ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1228 		}
1229 		status = deflate(&ctx->Z, flush_type);
1230 		buffer_used = ZSTR_LEN(out) - ctx->Z.avail_out;
1231 	} while (status == Z_OK && ctx->Z.avail_out == 0);
1232 
1233 	switch (status) {
1234 		case Z_OK:
1235 			ZSTR_LEN(out) = (char *) ctx->Z.next_out - ZSTR_VAL(out);
1236 			ZSTR_VAL(out)[ZSTR_LEN(out)] = 0;
1237 			RETURN_STR(out);
1238 			break;
1239 		case Z_STREAM_END:
1240 			ZSTR_LEN(out) = (char *) ctx->Z.next_out - ZSTR_VAL(out);
1241 			ZSTR_VAL(out)[ZSTR_LEN(out)] = 0;
1242 			deflateReset(&ctx->Z);
1243 			RETURN_STR(out);
1244 			break;
1245 		default:
1246 			zend_string_release_ex(out, 0);
1247 			php_error_docref(NULL, E_WARNING, "zlib error (%s)", zError(status));
1248 			RETURN_FALSE;
1249 	}
1250 }
1251 /* }}} */
1252 
1253 #ifdef COMPILE_DL_ZLIB
1254 #ifdef ZTS
1255 ZEND_TSRMLS_CACHE_DEFINE()
1256 #endif
ZEND_GET_MODULE(php_zlib)1257 ZEND_GET_MODULE(php_zlib)
1258 #endif
1259 
1260 /* {{{ OnUpdate_zlib_output_compression */
1261 static PHP_INI_MH(OnUpdate_zlib_output_compression)
1262 {
1263 	int int_value;
1264 	char *ini_value;
1265 	if (new_value == NULL) {
1266 		return FAILURE;
1267 	}
1268 
1269 	if (zend_string_equals_literal_ci(new_value, "off")) {
1270 		int_value = 0;
1271 	} else if (zend_string_equals_literal_ci(new_value, "on")) {
1272 		int_value = 1;
1273 	} else {
1274 		int_value = (int) zend_ini_parse_quantity_warn(new_value, entry->name);
1275 	}
1276 	ini_value = zend_ini_string("output_handler", sizeof("output_handler") - 1, 0);
1277 
1278 	if (ini_value && *ini_value && int_value) {
1279 		php_error_docref("ref.outcontrol", E_CORE_ERROR, "Cannot use both zlib.output_compression and output_handler together!!");
1280 		return FAILURE;
1281 	}
1282 	if (stage == PHP_INI_STAGE_RUNTIME) {
1283 		int status = php_output_get_status();
1284 		if (status & PHP_OUTPUT_SENT) {
1285 			php_error_docref("ref.outcontrol", E_WARNING, "Cannot change zlib.output_compression - headers already sent");
1286 			return FAILURE;
1287 		}
1288 	}
1289 
1290 	zend_long *p = (zend_long *) ZEND_INI_GET_ADDR();
1291 	*p = int_value;
1292 
1293 	ZLIBG(output_compression) = ZLIBG(output_compression_default);
1294 	if (stage == PHP_INI_STAGE_RUNTIME && int_value) {
1295 		if (!php_output_handler_started(ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME))) {
1296 			php_zlib_output_compression_start();
1297 		}
1298 	}
1299 
1300 	return SUCCESS;
1301 }
1302 /* }}} */
1303 
1304 /* {{{ OnUpdate_zlib_output_handler */
PHP_INI_MH(OnUpdate_zlib_output_handler)1305 static PHP_INI_MH(OnUpdate_zlib_output_handler)
1306 {
1307 	if (stage == PHP_INI_STAGE_RUNTIME && (php_output_get_status() & PHP_OUTPUT_SENT)) {
1308 		php_error_docref("ref.outcontrol", E_WARNING, "Cannot change zlib.output_handler - headers already sent");
1309 		return FAILURE;
1310 	}
1311 
1312 	return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
1313 }
1314 /* }}} */
1315 
1316 /* {{{ INI */
1317 PHP_INI_BEGIN()
1318 	STD_PHP_INI_BOOLEAN("zlib.output_compression",      "0", PHP_INI_ALL, OnUpdate_zlib_output_compression,       output_compression_default,       zend_zlib_globals, zlib_globals)
1319 	STD_PHP_INI_ENTRY("zlib.output_compression_level", "-1", PHP_INI_ALL, OnUpdateLong,                           output_compression_level, zend_zlib_globals, zlib_globals)
1320 	STD_PHP_INI_ENTRY("zlib.output_handler",             "", PHP_INI_ALL, OnUpdate_zlib_output_handler,           output_handler,           zend_zlib_globals, zlib_globals)
PHP_INI_END()1321 PHP_INI_END()
1322 
1323 /* }}} */
1324 
1325 /* {{{ PHP_MINIT_FUNCTION */
1326 static PHP_MINIT_FUNCTION(zlib)
1327 {
1328 	php_register_url_stream_wrapper("compress.zlib", &php_stream_gzip_wrapper);
1329 	php_stream_filter_register_factory("zlib.*", &php_zlib_filter_factory);
1330 
1331 	php_output_handler_alias_register(ZEND_STRL("ob_gzhandler"), php_zlib_output_handler_init);
1332 	php_output_handler_conflict_register(ZEND_STRL("ob_gzhandler"), php_zlib_output_conflict_check);
1333 	php_output_handler_conflict_register(ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME), php_zlib_output_conflict_check);
1334 
1335 	inflate_context_ce = register_class_InflateContext();
1336 	inflate_context_ce->create_object = inflate_context_create_object;
1337 
1338 	memcpy(&inflate_context_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1339 	inflate_context_object_handlers.offset = XtOffsetOf(php_zlib_context, std);
1340 	inflate_context_object_handlers.free_obj = inflate_context_free_obj;
1341 	inflate_context_object_handlers.get_constructor = inflate_context_get_constructor;
1342 	inflate_context_object_handlers.clone_obj = NULL;
1343 	inflate_context_object_handlers.compare = zend_objects_not_comparable;
1344 
1345 	deflate_context_ce = register_class_DeflateContext();
1346 	deflate_context_ce->create_object = deflate_context_create_object;
1347 
1348 	memcpy(&deflate_context_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1349 	deflate_context_object_handlers.offset = XtOffsetOf(php_zlib_context, std);
1350 	deflate_context_object_handlers.free_obj = deflate_context_free_obj;
1351 	deflate_context_object_handlers.get_constructor = deflate_context_get_constructor;
1352 	deflate_context_object_handlers.clone_obj = NULL;
1353 	deflate_context_object_handlers.compare = zend_objects_not_comparable;
1354 
1355 	register_zlib_symbols(module_number);
1356 
1357 	REGISTER_INI_ENTRIES();
1358 	return SUCCESS;
1359 }
1360 /* }}} */
1361 
1362 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(zlib)1363 static PHP_MSHUTDOWN_FUNCTION(zlib)
1364 {
1365 	php_unregister_url_stream_wrapper("zlib");
1366 	php_stream_filter_unregister_factory("zlib.*");
1367 
1368 	UNREGISTER_INI_ENTRIES();
1369 
1370 	return SUCCESS;
1371 }
1372 /* }}} */
1373 
1374 /* {{{ PHP_RINIT_FUNCTION */
PHP_RINIT_FUNCTION(zlib)1375 static PHP_RINIT_FUNCTION(zlib)
1376 {
1377 	ZLIBG(compression_coding) = 0;
1378 	if (!ZLIBG(handler_registered)) {
1379 		ZLIBG(output_compression) = ZLIBG(output_compression_default);
1380 		php_zlib_output_compression_start();
1381 	}
1382 
1383 	return SUCCESS;
1384 }
1385 /* }}} */
1386 
1387 /* {{{ PHP_RSHUTDOWN_FUNCTION */
PHP_RSHUTDOWN_FUNCTION(zlib)1388 static PHP_RSHUTDOWN_FUNCTION(zlib)
1389 {
1390 	php_zlib_cleanup_ob_gzhandler_mess();
1391 	ZLIBG(handler_registered) = 0;
1392 
1393 	return SUCCESS;
1394 }
1395 /* }}} */
1396 
1397 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(zlib)1398 static PHP_MINFO_FUNCTION(zlib)
1399 {
1400 	php_info_print_table_start();
1401 	php_info_print_table_header(2, "ZLib Support", "enabled");
1402 	php_info_print_table_row(2, "Stream Wrapper", "compress.zlib://");
1403 	php_info_print_table_row(2, "Stream Filter", "zlib.inflate, zlib.deflate");
1404 	php_info_print_table_row(2, "Compiled Version", ZLIB_VERSION);
1405 	php_info_print_table_row(2, "Linked Version", (char *) zlibVersion());
1406 	php_info_print_table_end();
1407 
1408 	DISPLAY_INI_ENTRIES();
1409 }
1410 /* }}} */
1411 
1412 /* {{{ ZEND_MODULE_GLOBALS_CTOR */
PHP_GINIT_FUNCTION(zlib)1413 static PHP_GINIT_FUNCTION(zlib)
1414 {
1415 #if defined(COMPILE_DL_ZLIB) && defined(ZTS)
1416 	ZEND_TSRMLS_CACHE_UPDATE();
1417 #endif
1418 	zlib_globals->ob_gzhandler = NULL;
1419 	zlib_globals->handler_registered = 0;
1420 }
1421 /* }}} */
1422 
1423 /* {{{ php_zlib_module_entry */
1424 zend_module_entry php_zlib_module_entry = {
1425 	STANDARD_MODULE_HEADER,
1426 	"zlib",
1427 	ext_functions,
1428 	PHP_MINIT(zlib),
1429 	PHP_MSHUTDOWN(zlib),
1430 	PHP_RINIT(zlib),
1431 	PHP_RSHUTDOWN(zlib),
1432 	PHP_MINFO(zlib),
1433 	PHP_ZLIB_VERSION,
1434 	PHP_MODULE_GLOBALS(zlib),
1435 	PHP_GINIT(zlib),
1436 	NULL,
1437 	NULL,
1438 	STANDARD_MODULE_PROPERTIES_EX
1439 };
1440 /* }}} */
1441