xref: /PHP-8.0/ext/zlib/zlib.c (revision 30f4c725)
1 /*
2    +----------------------------------------------------------------------+
3    | Copyright (c) The PHP Group                                          |
4    +----------------------------------------------------------------------+
5    | This source file is subject to version 3.01 of the PHP license,      |
6    | that is bundled with this package in the file LICENSE, and is        |
7    | available through the world-wide-web at the following url:           |
8    | http://www.php.net/license/3_01.txt                                  |
9    | If you did not receive a copy of the PHP license and are unable to   |
10    | obtain it through the world-wide-web, please send a note to          |
11    | license@php.net so we can mail you a copy immediately.               |
12    +----------------------------------------------------------------------+
13    | 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 #include "Zend/zend_interfaces.h"
33 
34 /*
35  * zlib include files can define the following preprocessor defines which rename
36  * the corresponding PHP functions to gzopen64, gzseek64 and gztell64 and thereby
37  * breaking some software, most notably PEAR's Archive_Tar, which halts execution
38  * without error message on gzip compressed archives.
39  *
40  * This only seems to happen on 32bit systems with large file support.
41  */
42 #undef gzopen
43 #undef gzseek
44 #undef gztell
45 
46 ZEND_DECLARE_MODULE_GLOBALS(zlib)
47 
48 /* InflateContext class */
49 
50 zend_class_entry *inflate_context_ce;
51 static zend_object_handlers inflate_context_object_handlers;
52 
inflate_context_from_obj(zend_object * obj)53 static inline php_zlib_context *inflate_context_from_obj(zend_object *obj) {
54 	return (php_zlib_context *)((char *)(obj) - XtOffsetOf(php_zlib_context, std));
55 }
56 
57 #define Z_INFLATE_CONTEXT_P(zv) inflate_context_from_obj(Z_OBJ_P(zv))
58 
inflate_context_create_object(zend_class_entry * class_type)59 static zend_object *inflate_context_create_object(zend_class_entry *class_type) {
60 	php_zlib_context *intern = zend_object_alloc(sizeof(php_zlib_context), class_type);
61 
62 	zend_object_std_init(&intern->std, class_type);
63 	object_properties_init(&intern->std, class_type);
64 	intern->std.handlers = &inflate_context_object_handlers;
65 
66 	return &intern->std;
67 }
68 
inflate_context_get_constructor(zend_object * object)69 static zend_function *inflate_context_get_constructor(zend_object *object) {
70 	zend_throw_error(NULL, "Cannot directly construct InflateContext, use inflate_init() instead");
71 	return NULL;
72 }
73 
inflate_context_free_obj(zend_object * object)74 static void inflate_context_free_obj(zend_object *object)
75 {
76 	php_zlib_context *intern = inflate_context_from_obj(object);
77 
78 	if (intern->inflateDict) {
79 		efree(intern->inflateDict);
80 	}
81 	inflateEnd(&intern->Z);
82 
83 	zend_object_std_dtor(&intern->std);
84 }
85 /* }}} */
86 
87 /* DeflateContext class */
88 
89 zend_class_entry *deflate_context_ce;
90 static zend_object_handlers deflate_context_object_handlers;
91 
deflate_context_from_obj(zend_object * obj)92 static inline php_zlib_context *deflate_context_from_obj(zend_object *obj) {
93 	return (php_zlib_context *)((char *)(obj) - XtOffsetOf(php_zlib_context, std));
94 }
95 
96 #define Z_DEFLATE_CONTEXT_P(zv) deflate_context_from_obj(Z_OBJ_P(zv))
97 
deflate_context_create_object(zend_class_entry * class_type)98 static zend_object *deflate_context_create_object(zend_class_entry *class_type) {
99 	php_zlib_context *intern = zend_object_alloc(sizeof(php_zlib_context), class_type);
100 
101 	zend_object_std_init(&intern->std, class_type);
102 	object_properties_init(&intern->std, class_type);
103 	intern->std.handlers = &deflate_context_object_handlers;
104 
105 	return &intern->std;
106 }
107 
deflate_context_get_constructor(zend_object * object)108 static zend_function *deflate_context_get_constructor(zend_object *object) {
109 	zend_throw_error(NULL, "Cannot directly construct DeflateContext, use deflate_init() instead");
110 	return NULL;
111 }
112 
deflate_context_free_obj(zend_object * object)113 static void deflate_context_free_obj(zend_object *object)
114 {
115 	php_zlib_context *intern = deflate_context_from_obj(object);
116 
117 	deflateEnd(&intern->Z);
118 
119 	zend_object_std_dtor(&intern->std);
120 }
121 /* }}} */
122 
123 /* {{{ Memory management wrappers */
124 
php_zlib_alloc(voidpf opaque,uInt items,uInt size)125 static voidpf php_zlib_alloc(voidpf opaque, uInt items, uInt size)
126 {
127 	return (voidpf)safe_emalloc(items, size, 0);
128 }
129 
php_zlib_free(voidpf opaque,voidpf address)130 static void php_zlib_free(voidpf opaque, voidpf address)
131 {
132 	efree((void*)address);
133 }
134 /* }}} */
135 
136 /* {{{ php_zlib_output_conflict_check() */
php_zlib_output_conflict_check(const char * handler_name,size_t handler_name_len)137 static int php_zlib_output_conflict_check(const char *handler_name, size_t handler_name_len)
138 {
139 	if (php_output_get_level() > 0) {
140 		if (php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME))
141 		||	php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL("ob_gzhandler"))
142 		||  php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL("mb_output_handler"))
143 		||	php_output_handler_conflict(handler_name, handler_name_len, ZEND_STRL("URL-Rewriter"))) {
144 			return FAILURE;
145 		}
146 	}
147 	return SUCCESS;
148 }
149 /* }}} */
150 
151 /* {{{ php_zlib_output_encoding() */
php_zlib_output_encoding(void)152 static int php_zlib_output_encoding(void)
153 {
154 	zval *enc;
155 
156 	if (!ZLIBG(compression_coding)) {
157 		if ((Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY || zend_is_auto_global_str(ZEND_STRL("_SERVER"))) &&
158 			(enc = zend_hash_str_find(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), "HTTP_ACCEPT_ENCODING", sizeof("HTTP_ACCEPT_ENCODING") - 1))) {
159 			convert_to_string(enc);
160 			if (strstr(Z_STRVAL_P(enc), "gzip")) {
161 				ZLIBG(compression_coding) = PHP_ZLIB_ENCODING_GZIP;
162 			} else if (strstr(Z_STRVAL_P(enc), "deflate")) {
163 				ZLIBG(compression_coding) = PHP_ZLIB_ENCODING_DEFLATE;
164 			}
165 		}
166 	}
167 	return ZLIBG(compression_coding);
168 }
169 /* }}} */
170 
171 /* {{{ php_zlib_output_handler_ex() */
php_zlib_output_handler_ex(php_zlib_context * ctx,php_output_context * output_context)172 static int php_zlib_output_handler_ex(php_zlib_context *ctx, php_output_context *output_context)
173 {
174 	int flags = Z_SYNC_FLUSH;
175 
176 	if (output_context->op & PHP_OUTPUT_HANDLER_START) {
177 		/* start up */
178 		if (Z_OK != deflateInit2(&ctx->Z, ZLIBG(output_compression_level), Z_DEFLATED, ZLIBG(compression_coding), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) {
179 			return FAILURE;
180 		}
181 	}
182 
183 	if (output_context->op & PHP_OUTPUT_HANDLER_CLEAN) {
184 		/* free buffers */
185 		deflateEnd(&ctx->Z);
186 
187 		if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) {
188 			/* discard */
189 			return SUCCESS;
190 		} else {
191 			/* restart */
192 			if (Z_OK != deflateInit2(&ctx->Z, ZLIBG(output_compression_level), Z_DEFLATED, ZLIBG(compression_coding), MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY)) {
193 				return FAILURE;
194 			}
195 			ctx->buffer.used = 0;
196 		}
197 	} else {
198 		if (output_context->in.used) {
199 			/* append input */
200 			if (ctx->buffer.free < output_context->in.used) {
201 				if (!(ctx->buffer.aptr = erealloc_recoverable(ctx->buffer.data, ctx->buffer.used + ctx->buffer.free + output_context->in.used))) {
202 					deflateEnd(&ctx->Z);
203 					return FAILURE;
204 				}
205 				ctx->buffer.data = ctx->buffer.aptr;
206 				ctx->buffer.free += output_context->in.used;
207 			}
208 			memcpy(ctx->buffer.data + ctx->buffer.used, output_context->in.data, output_context->in.used);
209 			ctx->buffer.free -= output_context->in.used;
210 			ctx->buffer.used += output_context->in.used;
211 		}
212 		output_context->out.size = PHP_ZLIB_BUFFER_SIZE_GUESS(output_context->in.used);
213 		output_context->out.data = emalloc(output_context->out.size);
214 		output_context->out.free = 1;
215 		output_context->out.used = 0;
216 
217 		ctx->Z.avail_in = ctx->buffer.used;
218 		ctx->Z.next_in = (Bytef *) ctx->buffer.data;
219 		ctx->Z.avail_out = output_context->out.size;
220 		ctx->Z.next_out = (Bytef *) output_context->out.data;
221 
222 		if (output_context->op & PHP_OUTPUT_HANDLER_FINAL) {
223 			flags = Z_FINISH;
224 		} else if (output_context->op & PHP_OUTPUT_HANDLER_FLUSH) {
225 			flags = Z_FULL_FLUSH;
226 		}
227 
228 		switch (deflate(&ctx->Z, flags)) {
229 			case Z_OK:
230 				if (flags == Z_FINISH) {
231 					deflateEnd(&ctx->Z);
232 					return FAILURE;
233 				}
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 			/* break omitted intentionally */
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 	register 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 zend_bool zlib_create_dictionary_string(HashTable *options, char **dict, size_t *dictlen) {
792 	zval *option_buffer;
793 
794 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("dictionary"))) != NULL) {
795 		ZVAL_DEREF(option_buffer);
796 		switch (Z_TYPE_P(option_buffer)) {
797 			case IS_STRING: {
798 				zend_string *str = Z_STR_P(option_buffer);
799 				*dict = emalloc(ZSTR_LEN(str));
800 				memcpy(*dict, ZSTR_VAL(str), ZSTR_LEN(str));
801 				*dictlen = ZSTR_LEN(str);
802 			} break;
803 
804 			case IS_ARRAY: {
805 				HashTable *dictionary = Z_ARR_P(option_buffer);
806 
807 				if (zend_hash_num_elements(dictionary) > 0) {
808 					char *dictptr;
809 					zval *cur;
810 					zend_string **strings = emalloc(sizeof(zend_string *) * zend_hash_num_elements(dictionary));
811 					zend_string **end, **ptr = strings - 1;
812 
813 					ZEND_HASH_FOREACH_VAL(dictionary, cur) {
814 						size_t i;
815 
816 						*++ptr = zval_get_string(cur);
817 						if (!*ptr || ZSTR_LEN(*ptr) == 0 || EG(exception)) {
818 							if (*ptr) {
819 								efree(*ptr);
820 							}
821 							while (--ptr >= strings) {
822 								efree(ptr);
823 							}
824 							efree(strings);
825 							if (!EG(exception)) {
826 								zend_argument_value_error(2, "must not contain empty strings");
827 							}
828 							return 0;
829 						}
830 						for (i = 0; i < ZSTR_LEN(*ptr); i++) {
831 							if (ZSTR_VAL(*ptr)[i] == 0) {
832 								do {
833 									efree(ptr);
834 								} while (--ptr >= strings);
835 								efree(strings);
836 								zend_argument_value_error(2, "must not contain strings with null bytes");
837 								return 0;
838 							}
839 						}
840 
841 						*dictlen += ZSTR_LEN(*ptr) + 1;
842 					} ZEND_HASH_FOREACH_END();
843 
844 					dictptr = *dict = emalloc(*dictlen);
845 					ptr = strings;
846 					end = strings + zend_hash_num_elements(dictionary);
847 					do {
848 						memcpy(dictptr, ZSTR_VAL(*ptr), ZSTR_LEN(*ptr));
849 						dictptr += ZSTR_LEN(*ptr);
850 						*dictptr++ = 0;
851 						zend_string_release_ex(*ptr, 0);
852 					} while (++ptr != end);
853 					efree(strings);
854 				}
855 			} break;
856 
857 			default:
858 				zend_argument_type_error(2, "must be of type zero-terminated string or array, %s given", zend_zval_type_name(option_buffer));
859 				return 0;
860 		}
861 	}
862 
863 	return 1;
864 }
865 
866 /* {{{ Initialize an incremental inflate context with the specified encoding */
PHP_FUNCTION(inflate_init)867 PHP_FUNCTION(inflate_init)
868 {
869 	php_zlib_context *ctx;
870 	zend_long encoding, window = 15;
871 	char *dict = NULL;
872 	size_t dictlen = 0;
873 	HashTable *options = NULL;
874 	zval *option_buffer;
875 
876 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "l|H", &encoding, &options)) {
877 		RETURN_THROWS();
878 	}
879 
880 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("window"))) != NULL) {
881 		window = zval_get_long(option_buffer);
882 	}
883 	if (window < 8 || window > 15) {
884 		zend_value_error("zlib window size (logarithm) (" ZEND_LONG_FMT ") must be within 8..15", window);
885 		RETURN_THROWS();
886 	}
887 
888 	if (!zlib_create_dictionary_string(options, &dict, &dictlen)) {
889 		RETURN_THROWS();
890 	}
891 
892 	switch (encoding) {
893 		case PHP_ZLIB_ENCODING_RAW:
894 		case PHP_ZLIB_ENCODING_GZIP:
895 		case PHP_ZLIB_ENCODING_DEFLATE:
896 			break;
897 		default:
898 			zend_value_error("Encoding mode must be ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP or ZLIB_ENCODING_DEFLATE");
899 			RETURN_THROWS();
900 	}
901 
902 	object_init_ex(return_value, inflate_context_ce);
903 	ctx = Z_INFLATE_CONTEXT_P(return_value);
904 
905 	ctx->Z.zalloc = php_zlib_alloc;
906 	ctx->Z.zfree = php_zlib_free;
907 	ctx->inflateDict = dict;
908 	ctx->inflateDictlen = dictlen;
909 	ctx->status = Z_OK;
910 
911 	if (encoding < 0) {
912 		encoding += 15 - window;
913 	} else {
914 		encoding -= 15 - window;
915 	}
916 
917 	if (inflateInit2(&ctx->Z, encoding) != Z_OK) {
918 		zval_ptr_dtor(return_value);
919 		php_error_docref(NULL, E_WARNING, "Failed allocating zlib.inflate context");
920 		RETURN_FALSE;
921 	}
922 
923 	if (encoding == PHP_ZLIB_ENCODING_RAW && dictlen > 0) {
924 		switch (inflateSetDictionary(&ctx->Z, (Bytef *) ctx->inflateDict, ctx->inflateDictlen)) {
925 			case Z_OK:
926 				efree(ctx->inflateDict);
927 				ctx->inflateDict = NULL;
928 				break;
929 			case Z_DATA_ERROR:
930 				php_error_docref(NULL, E_WARNING, "Dictionary does not match expected dictionary (incorrect adler32 hash)");
931 				efree(ctx->inflateDict);
932 				ctx->inflateDict = NULL;
933 			EMPTY_SWITCH_DEFAULT_CASE()
934 		}
935 	}
936 }
937 /* }}} */
938 
939 /* {{{ Incrementally inflate encoded data in the specified context */
PHP_FUNCTION(inflate_add)940 PHP_FUNCTION(inflate_add)
941 {
942 	zend_string *out;
943 	char *in_buf;
944 	size_t in_len, buffer_used = 0, CHUNK_SIZE = 8192;
945 	zval *res;
946 	php_zlib_context *ctx;
947 	zend_long flush_type = Z_SYNC_FLUSH;
948 	int status;
949 
950 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "Os|l", &res, inflate_context_ce, &in_buf, &in_len, &flush_type)) {
951 		RETURN_THROWS();
952 	}
953 
954 	ctx = Z_INFLATE_CONTEXT_P(res);
955 
956 	switch (flush_type) {
957 		case Z_NO_FLUSH:
958 		case Z_PARTIAL_FLUSH:
959 		case Z_SYNC_FLUSH:
960 		case Z_FULL_FLUSH:
961 		case Z_BLOCK:
962 		case Z_FINISH:
963 			break;
964 
965 		default:
966 			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");
967 			RETURN_THROWS();
968 	}
969 
970 	/* Lazy-resetting the zlib stream so ctx->total_in remains available until the next inflate_add() call. */
971 	if (ctx->status == Z_STREAM_END)
972 	{
973 		ctx->status = Z_OK;
974 		inflateReset(&ctx->Z);
975 	}
976 
977 	if (in_len <= 0 && flush_type != Z_FINISH) {
978 		RETURN_EMPTY_STRING();
979 	}
980 
981 	out = zend_string_alloc((in_len > CHUNK_SIZE) ? in_len : CHUNK_SIZE, 0);
982 	ctx->Z.next_in = (Bytef *) in_buf;
983 	ctx->Z.next_out = (Bytef *) ZSTR_VAL(out);
984 	ctx->Z.avail_in = in_len;
985 	ctx->Z.avail_out = ZSTR_LEN(out);
986 
987 	do {
988 		status = inflate(&ctx->Z, flush_type);
989 		buffer_used = ZSTR_LEN(out) - ctx->Z.avail_out;
990 
991 		ctx->status = status; /* Save status for exposing to userspace */
992 
993 		switch (status) {
994 			case Z_OK:
995 				if (ctx->Z.avail_out == 0) {
996 					/* more output buffer space needed; realloc and try again */
997 					out = zend_string_realloc(out, ZSTR_LEN(out) + CHUNK_SIZE, 0);
998 					ctx->Z.avail_out = CHUNK_SIZE;
999 					ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1000 					break;
1001 				} else {
1002 					goto complete;
1003 				}
1004 			case Z_STREAM_END:
1005 				goto complete;
1006 			case Z_BUF_ERROR:
1007 				if (flush_type == Z_FINISH && ctx->Z.avail_out == 0) {
1008 					/* more output buffer space needed; realloc and try again */
1009 					out = zend_string_realloc(out, ZSTR_LEN(out) + CHUNK_SIZE, 0);
1010 					ctx->Z.avail_out = CHUNK_SIZE;
1011 					ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1012 					break;
1013 				} else {
1014 					/* No more input data; we're finished */
1015 					goto complete;
1016 				}
1017 			case Z_NEED_DICT:
1018 				if (ctx->inflateDict) {
1019 					switch (inflateSetDictionary(&ctx->Z, (Bytef *) ctx->inflateDict, ctx->inflateDictlen)) {
1020 						case Z_OK:
1021 							efree(ctx->inflateDict);
1022 							ctx->inflateDict = NULL;
1023 							break;
1024 						case Z_DATA_ERROR:
1025 							efree(ctx->inflateDict);
1026 							ctx->inflateDict = NULL;
1027 							zend_string_release_ex(out, 0);
1028 							php_error_docref(NULL, E_WARNING, "Dictionary does not match expected dictionary (incorrect adler32 hash)");
1029 							RETURN_FALSE;
1030 						EMPTY_SWITCH_DEFAULT_CASE()
1031 					}
1032 					break;
1033 				} else {
1034 					php_error_docref(NULL, E_WARNING, "Inflating this data requires a preset dictionary, please specify it in the options array of inflate_init()");
1035 					RETURN_FALSE;
1036 				}
1037 			default:
1038 				zend_string_release_ex(out, 0);
1039 				php_error_docref(NULL, E_WARNING, "%s", zError(status));
1040 				RETURN_FALSE;
1041 		}
1042 	} while (1);
1043 
1044 complete:
1045 	out = zend_string_realloc(out, buffer_used, 0);
1046 	ZSTR_VAL(out)[buffer_used] = 0;
1047 	RETURN_STR(out);
1048 }
1049 /* }}} */
1050 
1051 /* {{{ Get decompression status, usually returns either ZLIB_OK or ZLIB_STREAM_END. */
PHP_FUNCTION(inflate_get_status)1052 PHP_FUNCTION(inflate_get_status)
1053 {
1054 	zval *res;
1055 	php_zlib_context *ctx;
1056 
1057 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &res, inflate_context_ce) != SUCCESS) {
1058 		RETURN_THROWS();
1059 	}
1060 
1061 	ctx = Z_INFLATE_CONTEXT_P(res);
1062 
1063 	RETURN_LONG(ctx->status);
1064 }
1065 /* }}} */
1066 
1067 /* {{{ Get number of bytes read so far. */
PHP_FUNCTION(inflate_get_read_len)1068 PHP_FUNCTION(inflate_get_read_len)
1069 {
1070 	zval *res;
1071 	php_zlib_context *ctx;
1072 
1073 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "O", &res, inflate_context_ce) != SUCCESS) {
1074 		RETURN_THROWS();
1075 	}
1076 
1077 	ctx = Z_INFLATE_CONTEXT_P(res);
1078 
1079 	RETURN_LONG(ctx->Z.total_in);
1080 }
1081 /* }}} */
1082 
1083 /* {{{ Initialize an incremental deflate context using the specified encoding */
PHP_FUNCTION(deflate_init)1084 PHP_FUNCTION(deflate_init)
1085 {
1086 	php_zlib_context *ctx;
1087 	zend_long encoding, level = -1, memory = 8, window = 15, strategy = Z_DEFAULT_STRATEGY;
1088 	char *dict = NULL;
1089 	size_t dictlen = 0;
1090 	HashTable *options = NULL;
1091 	zval *option_buffer;
1092 
1093 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "l|H", &encoding, &options)) {
1094 		RETURN_THROWS();
1095 	}
1096 
1097 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("level"))) != NULL) {
1098 		level = zval_get_long(option_buffer);
1099 	}
1100 	if (level < -1 || level > 9) {
1101 		zend_value_error("deflate_init(): \"level\" option must be between -1 and 9");
1102 		RETURN_THROWS();
1103 	}
1104 
1105 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("memory"))) != NULL) {
1106 		memory = zval_get_long(option_buffer);
1107 	}
1108 	if (memory < 1 || memory > 9) {
1109 		zend_value_error("deflate_init(): \"memory\" option must be between 1 and 9");
1110 		RETURN_THROWS();
1111 	}
1112 
1113 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("window"))) != NULL) {
1114 		window = zval_get_long(option_buffer);
1115 	}
1116 	if (window < 8 || window > 15) {
1117 		zend_value_error("deflate_init(): \"window\" option must be between 8 and 15");
1118 		RETURN_THROWS();
1119 	}
1120 
1121 	if (options && (option_buffer = zend_hash_str_find(options, ZEND_STRL("strategy"))) != NULL) {
1122 		strategy = zval_get_long(option_buffer);
1123 	}
1124 	switch (strategy) {
1125 		case Z_FILTERED:
1126 		case Z_HUFFMAN_ONLY:
1127 		case Z_RLE:
1128 		case Z_FIXED:
1129 		case Z_DEFAULT_STRATEGY:
1130 			break;
1131 		default:
1132 			zend_value_error("deflate_init(): \"strategy\" option must be one of ZLIB_FILTERED, ZLIB_HUFFMAN_ONLY, ZLIB_RLE, ZLIB_FIXED, or ZLIB_DEFAULT_STRATEGY");
1133 			RETURN_THROWS();
1134 	}
1135 
1136 	if (!zlib_create_dictionary_string(options, &dict, &dictlen)) {
1137 		RETURN_THROWS();
1138 	}
1139 
1140 	switch (encoding) {
1141 		case PHP_ZLIB_ENCODING_RAW:
1142 		case PHP_ZLIB_ENCODING_GZIP:
1143 		case PHP_ZLIB_ENCODING_DEFLATE:
1144 			break;
1145 		default:
1146 			zend_argument_value_error(1, "must be one of ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP, or ZLIB_ENCODING_DEFLATE");
1147 			RETURN_THROWS();
1148 	}
1149 
1150 	object_init_ex(return_value, deflate_context_ce);
1151 	ctx = Z_DEFLATE_CONTEXT_P(return_value);
1152 
1153 	ctx->Z.zalloc = php_zlib_alloc;
1154 	ctx->Z.zfree = php_zlib_free;
1155 
1156 	if (encoding < 0) {
1157 		encoding += 15 - window;
1158 	} else {
1159 		encoding -= 15 - window;
1160 	}
1161 
1162 	if (deflateInit2(&ctx->Z, level, Z_DEFLATED, encoding, memory, strategy) != Z_OK) {
1163 		zval_ptr_dtor(return_value);
1164 		php_error_docref(NULL, E_WARNING, "Failed allocating zlib.deflate context");
1165 		RETURN_FALSE;
1166 	}
1167 
1168 	if (dict) {
1169 		int success = deflateSetDictionary(&ctx->Z, (Bytef *) dict, dictlen);
1170 		ZEND_ASSERT(success == Z_OK);
1171 		efree(dict);
1172 	}
1173 }
1174 /* }}} */
1175 
1176 /* {{{ Incrementally deflate data in the specified context */
PHP_FUNCTION(deflate_add)1177 PHP_FUNCTION(deflate_add)
1178 {
1179 	zend_string *out;
1180 	char *in_buf;
1181 	size_t in_len, out_size, buffer_used;
1182 	zval *res;
1183 	php_zlib_context *ctx;
1184 	zend_long flush_type = Z_SYNC_FLUSH;
1185 	int status;
1186 
1187 	if (SUCCESS != zend_parse_parameters(ZEND_NUM_ARGS(), "Os|l", &res, deflate_context_ce, &in_buf, &in_len, &flush_type)) {
1188 		RETURN_THROWS();
1189 	}
1190 
1191 	ctx = Z_DEFLATE_CONTEXT_P(res);
1192 
1193 	switch (flush_type) {
1194 		case Z_BLOCK:
1195 #if ZLIB_VERNUM < 0x1240L
1196 			zend_throw_error(NULL, "zlib >= 1.2.4 required for BLOCK deflate; current version: %s", ZLIB_VERSION);
1197 			RETURN_THROWS();
1198 #endif
1199 		case Z_NO_FLUSH:
1200 		case Z_PARTIAL_FLUSH:
1201 		case Z_SYNC_FLUSH:
1202 		case Z_FULL_FLUSH:
1203 		case Z_FINISH:
1204 			break;
1205 
1206 		default:
1207 			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");
1208 			RETURN_THROWS();
1209 	}
1210 
1211 	if (in_len <= 0 && flush_type != Z_FINISH) {
1212 		RETURN_EMPTY_STRING();
1213 	}
1214 
1215 	out_size = PHP_ZLIB_BUFFER_SIZE_GUESS(in_len);
1216 	out_size = (out_size < 64) ? 64 : out_size;
1217 	out = zend_string_alloc(out_size, 0);
1218 
1219 	ctx->Z.next_in = (Bytef *) in_buf;
1220 	ctx->Z.next_out = (Bytef *) ZSTR_VAL(out);
1221 	ctx->Z.avail_in = in_len;
1222 	ctx->Z.avail_out = ZSTR_LEN(out);
1223 
1224 	buffer_used = 0;
1225 
1226 	do {
1227 		if (ctx->Z.avail_out == 0) {
1228 			/* more output buffer space needed; realloc and try again */
1229 			/* adding 64 more bytes solved every issue I have seen    */
1230 			out = zend_string_realloc(out, ZSTR_LEN(out) + 64, 0);
1231 			ctx->Z.avail_out = 64;
1232 			ctx->Z.next_out = (Bytef *) ZSTR_VAL(out) + buffer_used;
1233 		}
1234 		status = deflate(&ctx->Z, flush_type);
1235 		buffer_used = ZSTR_LEN(out) - ctx->Z.avail_out;
1236 	} while (status == Z_OK && ctx->Z.avail_out == 0);
1237 
1238 	switch (status) {
1239 		case Z_OK:
1240 			ZSTR_LEN(out) = (char *) ctx->Z.next_out - ZSTR_VAL(out);
1241 			ZSTR_VAL(out)[ZSTR_LEN(out)] = 0;
1242 			RETURN_STR(out);
1243 			break;
1244 		case Z_STREAM_END:
1245 			ZSTR_LEN(out) = (char *) ctx->Z.next_out - ZSTR_VAL(out);
1246 			ZSTR_VAL(out)[ZSTR_LEN(out)] = 0;
1247 			deflateReset(&ctx->Z);
1248 			RETURN_STR(out);
1249 			break;
1250 		default:
1251 			zend_string_release_ex(out, 0);
1252 			php_error_docref(NULL, E_WARNING, "zlib error (%s)", zError(status));
1253 			RETURN_FALSE;
1254 	}
1255 }
1256 /* }}} */
1257 
1258 #ifdef COMPILE_DL_ZLIB
1259 #ifdef ZTS
1260 ZEND_TSRMLS_CACHE_DEFINE()
1261 #endif
ZEND_GET_MODULE(php_zlib)1262 ZEND_GET_MODULE(php_zlib)
1263 #endif
1264 
1265 /* {{{ OnUpdate_zlib_output_compression */
1266 static PHP_INI_MH(OnUpdate_zlib_output_compression)
1267 {
1268 	int int_value;
1269 	char *ini_value;
1270 	if (new_value == NULL) {
1271 		return FAILURE;
1272 	}
1273 
1274 	if (!strncasecmp(ZSTR_VAL(new_value), "off", sizeof("off"))) {
1275 		int_value = 0;
1276 	} else if (!strncasecmp(ZSTR_VAL(new_value), "on", sizeof("on"))) {
1277 		int_value = 1;
1278 	} else {
1279 		int_value = zend_atoi(ZSTR_VAL(new_value), ZSTR_LEN(new_value));
1280 	}
1281 	ini_value = zend_ini_string("output_handler", sizeof("output_handler"), 0);
1282 
1283 	if (ini_value && *ini_value && int_value) {
1284 		php_error_docref("ref.outcontrol", E_CORE_ERROR, "Cannot use both zlib.output_compression and output_handler together!!");
1285 		return FAILURE;
1286 	}
1287 	if (stage == PHP_INI_STAGE_RUNTIME) {
1288 		int status = php_output_get_status();
1289 		if (status & PHP_OUTPUT_SENT) {
1290 			php_error_docref("ref.outcontrol", E_WARNING, "Cannot change zlib.output_compression - headers already sent");
1291 			return FAILURE;
1292 		}
1293 	}
1294 
1295 	zend_long *p = (zend_long *) ZEND_INI_GET_ADDR();
1296 	*p = int_value;
1297 
1298 	ZLIBG(output_compression) = ZLIBG(output_compression_default);
1299 	if (stage == PHP_INI_STAGE_RUNTIME && int_value) {
1300 		if (!php_output_handler_started(ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME))) {
1301 			php_zlib_output_compression_start();
1302 		}
1303 	}
1304 
1305 	return SUCCESS;
1306 }
1307 /* }}} */
1308 
1309 /* {{{ OnUpdate_zlib_output_handler */
PHP_INI_MH(OnUpdate_zlib_output_handler)1310 static PHP_INI_MH(OnUpdate_zlib_output_handler)
1311 {
1312 	if (stage == PHP_INI_STAGE_RUNTIME && (php_output_get_status() & PHP_OUTPUT_SENT)) {
1313 		php_error_docref("ref.outcontrol", E_WARNING, "Cannot change zlib.output_handler - headers already sent");
1314 		return FAILURE;
1315 	}
1316 
1317 	return OnUpdateString(entry, new_value, mh_arg1, mh_arg2, mh_arg3, stage);
1318 }
1319 /* }}} */
1320 
1321 /* {{{ INI */
1322 PHP_INI_BEGIN()
1323 	STD_PHP_INI_BOOLEAN("zlib.output_compression",      "0", PHP_INI_ALL, OnUpdate_zlib_output_compression,       output_compression_default,       zend_zlib_globals, zlib_globals)
1324 	STD_PHP_INI_ENTRY("zlib.output_compression_level", "-1", PHP_INI_ALL, OnUpdateLong,                           output_compression_level, zend_zlib_globals, zlib_globals)
1325 	STD_PHP_INI_ENTRY("zlib.output_handler",             "", PHP_INI_ALL, OnUpdate_zlib_output_handler,           output_handler,           zend_zlib_globals, zlib_globals)
PHP_INI_END()1326 PHP_INI_END()
1327 
1328 /* }}} */
1329 
1330 /* {{{ PHP_MINIT_FUNCTION */
1331 static PHP_MINIT_FUNCTION(zlib)
1332 {
1333 	php_register_url_stream_wrapper("compress.zlib", &php_stream_gzip_wrapper);
1334 	php_stream_filter_register_factory("zlib.*", &php_zlib_filter_factory);
1335 
1336 	php_output_handler_alias_register(ZEND_STRL("ob_gzhandler"), php_zlib_output_handler_init);
1337 	php_output_handler_conflict_register(ZEND_STRL("ob_gzhandler"), php_zlib_output_conflict_check);
1338 	php_output_handler_conflict_register(ZEND_STRL(PHP_ZLIB_OUTPUT_HANDLER_NAME), php_zlib_output_conflict_check);
1339 
1340 	zend_class_entry inflate_ce;
1341 	INIT_CLASS_ENTRY(inflate_ce, "InflateContext", class_InflateContext_methods);
1342 	inflate_context_ce = zend_register_internal_class(&inflate_ce);
1343 	inflate_context_ce->ce_flags |= ZEND_ACC_FINAL | ZEND_ACC_NO_DYNAMIC_PROPERTIES;
1344 	inflate_context_ce->create_object = inflate_context_create_object;
1345 	inflate_context_ce->serialize = zend_class_serialize_deny;
1346 	inflate_context_ce->unserialize = zend_class_unserialize_deny;
1347 
1348 	memcpy(&inflate_context_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1349 	inflate_context_object_handlers.offset = XtOffsetOf(php_zlib_context, std);
1350 	inflate_context_object_handlers.free_obj = inflate_context_free_obj;
1351 	inflate_context_object_handlers.get_constructor = inflate_context_get_constructor;
1352 	inflate_context_object_handlers.clone_obj = NULL;
1353 	inflate_context_object_handlers.compare = zend_objects_not_comparable;
1354 
1355 	zend_class_entry deflate_ce;
1356 	INIT_CLASS_ENTRY(deflate_ce, "DeflateContext", class_DeflateContext_methods);
1357 	deflate_context_ce = zend_register_internal_class(&deflate_ce);
1358 	deflate_context_ce->ce_flags |= ZEND_ACC_FINAL | ZEND_ACC_NO_DYNAMIC_PROPERTIES;
1359 	deflate_context_ce->create_object = deflate_context_create_object;
1360 	deflate_context_ce->serialize = zend_class_serialize_deny;
1361 	deflate_context_ce->unserialize = zend_class_unserialize_deny;
1362 
1363 	memcpy(&deflate_context_object_handlers, &std_object_handlers, sizeof(zend_object_handlers));
1364 	deflate_context_object_handlers.offset = XtOffsetOf(php_zlib_context, std);
1365 	deflate_context_object_handlers.free_obj = deflate_context_free_obj;
1366 	deflate_context_object_handlers.get_constructor = deflate_context_get_constructor;
1367 	deflate_context_object_handlers.clone_obj = NULL;
1368 	deflate_context_object_handlers.compare = zend_objects_not_comparable;
1369 
1370 	REGISTER_LONG_CONSTANT("FORCE_GZIP", PHP_ZLIB_ENCODING_GZIP, CONST_CS|CONST_PERSISTENT);
1371 	REGISTER_LONG_CONSTANT("FORCE_DEFLATE", PHP_ZLIB_ENCODING_DEFLATE, CONST_CS|CONST_PERSISTENT);
1372 
1373 	REGISTER_LONG_CONSTANT("ZLIB_ENCODING_RAW", PHP_ZLIB_ENCODING_RAW, CONST_CS|CONST_PERSISTENT);
1374 	REGISTER_LONG_CONSTANT("ZLIB_ENCODING_GZIP", PHP_ZLIB_ENCODING_GZIP, CONST_CS|CONST_PERSISTENT);
1375 	REGISTER_LONG_CONSTANT("ZLIB_ENCODING_DEFLATE", PHP_ZLIB_ENCODING_DEFLATE, CONST_CS|CONST_PERSISTENT);
1376 
1377 	REGISTER_LONG_CONSTANT("ZLIB_NO_FLUSH", Z_NO_FLUSH, CONST_CS|CONST_PERSISTENT);
1378 	REGISTER_LONG_CONSTANT("ZLIB_PARTIAL_FLUSH", Z_PARTIAL_FLUSH, CONST_CS|CONST_PERSISTENT);
1379 	REGISTER_LONG_CONSTANT("ZLIB_SYNC_FLUSH", Z_SYNC_FLUSH, CONST_CS|CONST_PERSISTENT);
1380 	REGISTER_LONG_CONSTANT("ZLIB_FULL_FLUSH", Z_FULL_FLUSH, CONST_CS|CONST_PERSISTENT);
1381 	REGISTER_LONG_CONSTANT("ZLIB_BLOCK", Z_BLOCK, CONST_CS|CONST_PERSISTENT);
1382 	REGISTER_LONG_CONSTANT("ZLIB_FINISH", Z_FINISH, CONST_CS|CONST_PERSISTENT);
1383 
1384 	REGISTER_LONG_CONSTANT("ZLIB_FILTERED", Z_FILTERED, CONST_CS|CONST_PERSISTENT);
1385 	REGISTER_LONG_CONSTANT("ZLIB_HUFFMAN_ONLY", Z_HUFFMAN_ONLY, CONST_CS|CONST_PERSISTENT);
1386 	REGISTER_LONG_CONSTANT("ZLIB_RLE", Z_RLE, CONST_CS|CONST_PERSISTENT);
1387 	REGISTER_LONG_CONSTANT("ZLIB_FIXED", Z_FIXED, CONST_CS|CONST_PERSISTENT);
1388 	REGISTER_LONG_CONSTANT("ZLIB_DEFAULT_STRATEGY", Z_DEFAULT_STRATEGY, CONST_CS|CONST_PERSISTENT);
1389 
1390 	REGISTER_STRING_CONSTANT("ZLIB_VERSION", ZLIB_VERSION, CONST_CS|CONST_PERSISTENT);
1391 	REGISTER_LONG_CONSTANT("ZLIB_VERNUM", ZLIB_VERNUM, CONST_CS|CONST_PERSISTENT);
1392 
1393 	REGISTER_LONG_CONSTANT("ZLIB_OK", Z_OK, CONST_CS|CONST_PERSISTENT);
1394 	REGISTER_LONG_CONSTANT("ZLIB_STREAM_END", Z_STREAM_END, CONST_CS|CONST_PERSISTENT);
1395 	REGISTER_LONG_CONSTANT("ZLIB_NEED_DICT", Z_NEED_DICT, CONST_CS|CONST_PERSISTENT);
1396 	REGISTER_LONG_CONSTANT("ZLIB_ERRNO", Z_ERRNO, CONST_CS|CONST_PERSISTENT);
1397 	REGISTER_LONG_CONSTANT("ZLIB_STREAM_ERROR", Z_STREAM_ERROR, CONST_CS|CONST_PERSISTENT);
1398 	REGISTER_LONG_CONSTANT("ZLIB_DATA_ERROR", Z_DATA_ERROR, CONST_CS|CONST_PERSISTENT);
1399 	REGISTER_LONG_CONSTANT("ZLIB_MEM_ERROR", Z_MEM_ERROR, CONST_CS|CONST_PERSISTENT);
1400 	REGISTER_LONG_CONSTANT("ZLIB_BUF_ERROR", Z_BUF_ERROR, CONST_CS|CONST_PERSISTENT);
1401 	REGISTER_LONG_CONSTANT("ZLIB_VERSION_ERROR", Z_VERSION_ERROR, CONST_CS|CONST_PERSISTENT);
1402 
1403 	REGISTER_INI_ENTRIES();
1404 	return SUCCESS;
1405 }
1406 /* }}} */
1407 
1408 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(zlib)1409 static PHP_MSHUTDOWN_FUNCTION(zlib)
1410 {
1411 	php_unregister_url_stream_wrapper("zlib");
1412 	php_stream_filter_unregister_factory("zlib.*");
1413 
1414 	UNREGISTER_INI_ENTRIES();
1415 
1416 	return SUCCESS;
1417 }
1418 /* }}} */
1419 
1420 /* {{{ PHP_RINIT_FUNCTION */
PHP_RINIT_FUNCTION(zlib)1421 static PHP_RINIT_FUNCTION(zlib)
1422 {
1423 	ZLIBG(compression_coding) = 0;
1424     if (!ZLIBG(handler_registered)) {
1425         ZLIBG(output_compression) = ZLIBG(output_compression_default);
1426         php_zlib_output_compression_start();
1427     }
1428 
1429 	return SUCCESS;
1430 }
1431 /* }}} */
1432 
1433 /* {{{ PHP_RSHUTDOWN_FUNCTION */
PHP_RSHUTDOWN_FUNCTION(zlib)1434 static PHP_RSHUTDOWN_FUNCTION(zlib)
1435 {
1436 	php_zlib_cleanup_ob_gzhandler_mess();
1437     ZLIBG(handler_registered) = 0;
1438 
1439     return SUCCESS;
1440 }
1441 /* }}} */
1442 
1443 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(zlib)1444 static PHP_MINFO_FUNCTION(zlib)
1445 {
1446 	php_info_print_table_start();
1447 	php_info_print_table_header(2, "ZLib Support", "enabled");
1448 	php_info_print_table_row(2, "Stream Wrapper", "compress.zlib://");
1449 	php_info_print_table_row(2, "Stream Filter", "zlib.inflate, zlib.deflate");
1450 	php_info_print_table_row(2, "Compiled Version", ZLIB_VERSION);
1451 	php_info_print_table_row(2, "Linked Version", (char *) zlibVersion());
1452 	php_info_print_table_end();
1453 
1454 	DISPLAY_INI_ENTRIES();
1455 }
1456 /* }}} */
1457 
1458 /* {{{ ZEND_MODULE_GLOBALS_CTOR */
PHP_GINIT_FUNCTION(zlib)1459 static PHP_GINIT_FUNCTION(zlib)
1460 {
1461 #if defined(COMPILE_DL_ZLIB) && defined(ZTS)
1462 	ZEND_TSRMLS_CACHE_UPDATE();
1463 #endif
1464 	zlib_globals->ob_gzhandler = NULL;
1465     zlib_globals->handler_registered = 0;
1466 }
1467 /* }}} */
1468 
1469 /* {{{ php_zlib_module_entry */
1470 zend_module_entry php_zlib_module_entry = {
1471 	STANDARD_MODULE_HEADER,
1472 	"zlib",
1473 	ext_functions,
1474 	PHP_MINIT(zlib),
1475 	PHP_MSHUTDOWN(zlib),
1476 	PHP_RINIT(zlib),
1477 	PHP_RSHUTDOWN(zlib),
1478 	PHP_MINFO(zlib),
1479 	PHP_ZLIB_VERSION,
1480 	PHP_MODULE_GLOBALS(zlib),
1481 	PHP_GINIT(zlib),
1482 	NULL,
1483 	NULL,
1484 	STANDARD_MODULE_PROPERTIES_EX
1485 };
1486 /* }}} */
1487