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