xref: /PHP-8.2/main/output.c (revision 89c3e034)
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: Zeev Suraski <zeev@php.net>                                 |
14    |          Thies C. Arntzen <thies@thieso.net>                         |
15    |          Marcus Boerger <helly@php.net>                              |
16    | New API: Michael Wallner <mike@php.net>                              |
17    +----------------------------------------------------------------------+
18 */
19 
20 #ifndef PHP_OUTPUT_DEBUG
21 # define PHP_OUTPUT_DEBUG 0
22 #endif
23 #ifndef PHP_OUTPUT_NOINLINE
24 # define PHP_OUTPUT_NOINLINE 0
25 #endif
26 
27 #include "php.h"
28 #include "ext/standard/head.h"
29 #include "ext/standard/url_scanner_ex.h"
30 #include "SAPI.h"
31 #include "zend_stack.h"
32 #include "php_output.h"
33 
34 PHPAPI ZEND_DECLARE_MODULE_GLOBALS(output)
35 
36 const char php_output_default_handler_name[sizeof("default output handler")] = "default output handler";
37 const char php_output_devnull_handler_name[sizeof("null output handler")] = "null output handler";
38 
39 #if PHP_OUTPUT_NOINLINE || PHP_OUTPUT_DEBUG
40 # undef inline
41 # define inline
42 #endif
43 
44 /* {{{ aliases, conflict and reverse conflict hash tables */
45 static HashTable php_output_handler_aliases;
46 static HashTable php_output_handler_conflicts;
47 static HashTable php_output_handler_reverse_conflicts;
48 /* }}} */
49 
50 /* {{{ forward declarations */
51 static inline int php_output_lock_error(int op);
52 static inline void php_output_op(int op, const char *str, size_t len);
53 
54 static inline php_output_handler *php_output_handler_init(zend_string *name, size_t chunk_size, int flags);
55 static inline php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context);
56 static inline int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf);
57 static inline zval *php_output_handler_status(php_output_handler *handler, zval *entry);
58 
59 static inline void php_output_context_init(php_output_context *context, int op);
60 static inline void php_output_context_reset(php_output_context *context);
61 static inline void php_output_context_swap(php_output_context *context);
62 static inline void php_output_context_dtor(php_output_context *context);
63 
64 static int php_output_stack_pop(int flags);
65 
66 static int php_output_stack_apply_op(void *h, void *c);
67 static int php_output_stack_apply_clean(void *h, void *c);
68 static int php_output_stack_apply_list(void *h, void *z);
69 static int php_output_stack_apply_status(void *h, void *z);
70 
71 static int php_output_handler_compat_func(void **handler_context, php_output_context *output_context);
72 static int php_output_handler_default_func(void **handler_context, php_output_context *output_context);
73 static int php_output_handler_devnull_func(void **handler_context, php_output_context *output_context);
74 /* }}} */
75 
76 /* {{{ static void php_output_init_globals(zend_output_globals *G)
77  * Initialize the module globals on MINIT */
php_output_init_globals(zend_output_globals * G)78 static inline void php_output_init_globals(zend_output_globals *G)
79 {
80 	memset(G, 0, sizeof(*G));
81 }
82 /* }}} */
83 
84 /* {{{ stderr/stdout writer if not PHP_OUTPUT_ACTIVATED */
php_output_stdout(const char * str,size_t str_len)85 static size_t php_output_stdout(const char *str, size_t str_len)
86 {
87 	fwrite(str, 1, str_len, stdout);
88 	return str_len;
89 }
php_output_stderr(const char * str,size_t str_len)90 static size_t php_output_stderr(const char *str, size_t str_len)
91 {
92 	fwrite(str, 1, str_len, stderr);
93 /* See http://support.microsoft.com/kb/190351 */
94 #ifdef PHP_WIN32
95 	fflush(stderr);
96 #endif
97 	return str_len;
98 }
99 static size_t (*php_output_direct)(const char *str, size_t str_len) = php_output_stderr;
100 /* }}} */
101 
102 /* {{{ void php_output_header(void) */
php_output_header(void)103 static void php_output_header(void)
104 {
105 	if (!SG(headers_sent)) {
106 		if (!OG(output_start_filename)) {
107 			if (zend_is_compiling()) {
108 				OG(output_start_filename) = zend_get_compiled_filename();
109 				OG(output_start_lineno) = zend_get_compiled_lineno();
110 			} else if (zend_is_executing()) {
111 				OG(output_start_filename) = zend_get_executed_filename_ex();
112 				OG(output_start_lineno) = zend_get_executed_lineno();
113 			}
114 			if (OG(output_start_filename)) {
115 				zend_string_addref(OG(output_start_filename));
116 			}
117 #if PHP_OUTPUT_DEBUG
118 			fprintf(stderr, "!!! output started at: %s (%d)\n",
119 				ZSTR_VAL(OG(output_start_filename)), OG(output_start_lineno));
120 #endif
121 		}
122 		if (!php_header()) {
123 			OG(flags) |= PHP_OUTPUT_DISABLED;
124 		}
125 	}
126 }
127 /* }}} */
128 
reverse_conflict_dtor(zval * zv)129 static void reverse_conflict_dtor(zval *zv)
130 {
131 	HashTable *ht = Z_PTR_P(zv);
132 	zend_hash_destroy(ht);
133 }
134 
135 /* {{{ void php_output_startup(void)
136  * Set up module globals and initialize the conflict and reverse conflict hash tables */
php_output_startup(void)137 PHPAPI void php_output_startup(void)
138 {
139 	ZEND_INIT_MODULE_GLOBALS(output, php_output_init_globals, NULL);
140 	zend_hash_init(&php_output_handler_aliases, 8, NULL, NULL, 1);
141 	zend_hash_init(&php_output_handler_conflicts, 8, NULL, NULL, 1);
142 	zend_hash_init(&php_output_handler_reverse_conflicts, 8, NULL, reverse_conflict_dtor, 1);
143 	php_output_direct = php_output_stdout;
144 }
145 /* }}} */
146 
147 /* {{{ void php_output_shutdown(void)
148  * Destroy module globals and the conflict and reverse conflict hash tables */
php_output_shutdown(void)149 PHPAPI void php_output_shutdown(void)
150 {
151 	php_output_direct = php_output_stderr;
152 	zend_hash_destroy(&php_output_handler_aliases);
153 	zend_hash_destroy(&php_output_handler_conflicts);
154 	zend_hash_destroy(&php_output_handler_reverse_conflicts);
155 }
156 /* }}} */
157 
158 /* {{{ SUCCESS|FAILURE php_output_activate(void)
159  * Reset output globals and setup the output handler stack */
php_output_activate(void)160 PHPAPI int php_output_activate(void)
161 {
162 #ifdef ZTS
163 	memset(TSRMG_BULK_STATIC(output_globals_id, zend_output_globals*), 0, sizeof(zend_output_globals));
164 #else
165 	memset(&output_globals, 0, sizeof(zend_output_globals));
166 #endif
167 
168 	zend_stack_init(&OG(handlers), sizeof(php_output_handler *));
169 	OG(flags) |= PHP_OUTPUT_ACTIVATED;
170 
171 	return SUCCESS;
172 }
173 /* }}} */
174 
175 /* {{{ void php_output_deactivate(void)
176  * Destroy the output handler stack */
php_output_deactivate(void)177 PHPAPI void php_output_deactivate(void)
178 {
179 	php_output_handler **handler = NULL;
180 
181 	if ((OG(flags) & PHP_OUTPUT_ACTIVATED)) {
182 		php_output_header();
183 
184 		OG(flags) ^= PHP_OUTPUT_ACTIVATED;
185 		OG(active) = NULL;
186 		OG(running) = NULL;
187 
188 		/* release all output handlers */
189 		if (OG(handlers).elements) {
190 			while ((handler = zend_stack_top(&OG(handlers)))) {
191 				php_output_handler_free(handler);
192 				zend_stack_del_top(&OG(handlers));
193 			}
194 		}
195 		zend_stack_destroy(&OG(handlers));
196 	}
197 
198 	if (OG(output_start_filename)) {
199 		zend_string_release(OG(output_start_filename));
200 		OG(output_start_filename) = NULL;
201 	}
202 }
203 /* }}} */
204 
205 /* {{{ void php_output_register_constants() */
php_output_register_constants(void)206 PHPAPI void php_output_register_constants(void)
207 {
208 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_START", PHP_OUTPUT_HANDLER_START, CONST_CS | CONST_PERSISTENT);
209 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_WRITE", PHP_OUTPUT_HANDLER_WRITE, CONST_CS | CONST_PERSISTENT);
210 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSH", PHP_OUTPUT_HANDLER_FLUSH, CONST_CS | CONST_PERSISTENT);
211 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEAN", PHP_OUTPUT_HANDLER_CLEAN, CONST_CS | CONST_PERSISTENT);
212 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FINAL", PHP_OUTPUT_HANDLER_FINAL, CONST_CS | CONST_PERSISTENT);
213 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CONT", PHP_OUTPUT_HANDLER_WRITE, CONST_CS | CONST_PERSISTENT);
214 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_END", PHP_OUTPUT_HANDLER_FINAL, CONST_CS | CONST_PERSISTENT);
215 
216 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_CLEANABLE", PHP_OUTPUT_HANDLER_CLEANABLE, CONST_CS | CONST_PERSISTENT);
217 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_FLUSHABLE", PHP_OUTPUT_HANDLER_FLUSHABLE, CONST_CS | CONST_PERSISTENT);
218 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_REMOVABLE", PHP_OUTPUT_HANDLER_REMOVABLE, CONST_CS | CONST_PERSISTENT);
219 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STDFLAGS", PHP_OUTPUT_HANDLER_STDFLAGS, CONST_CS | CONST_PERSISTENT);
220 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_STARTED", PHP_OUTPUT_HANDLER_STARTED, CONST_CS | CONST_PERSISTENT);
221 	REGISTER_MAIN_LONG_CONSTANT("PHP_OUTPUT_HANDLER_DISABLED", PHP_OUTPUT_HANDLER_DISABLED, CONST_CS | CONST_PERSISTENT);
222 }
223 /* }}} */
224 
225 /* {{{ void php_output_set_status(int status)
226  * Used by SAPIs to disable output */
php_output_set_status(int status)227 PHPAPI void php_output_set_status(int status)
228 {
229 	OG(flags) = (OG(flags) & ~0xf) | (status & 0xf);
230 }
231 /* }}} */
232 
233 /* {{{ int php_output_get_status()
234  * Get output control status */
php_output_get_status(void)235 PHPAPI int php_output_get_status(void)
236 {
237 	return (
238 		OG(flags)
239 		|	(OG(active) ? PHP_OUTPUT_ACTIVE : 0)
240 		|	(OG(running)? PHP_OUTPUT_LOCKED : 0)
241 	) & 0xff;
242 }
243 /* }}} */
244 
245 /* {{{ int php_output_write_unbuffered(const char *str, size_t len)
246  * Unbuffered write */
php_output_write_unbuffered(const char * str,size_t len)247 PHPAPI size_t php_output_write_unbuffered(const char *str, size_t len)
248 {
249 	if (OG(flags) & PHP_OUTPUT_ACTIVATED) {
250 		return sapi_module.ub_write(str, len);
251 	}
252 	return php_output_direct(str, len);
253 }
254 /* }}} */
255 
256 /* {{{ int php_output_write(const char *str, size_t len)
257  * Buffered write */
php_output_write(const char * str,size_t len)258 PHPAPI size_t php_output_write(const char *str, size_t len)
259 {
260 	if (OG(flags) & PHP_OUTPUT_ACTIVATED) {
261 		php_output_op(PHP_OUTPUT_HANDLER_WRITE, str, len);
262 		return len;
263 	}
264 	if (OG(flags) & PHP_OUTPUT_DISABLED) {
265 		return 0;
266 	}
267 	return php_output_direct(str, len);
268 }
269 /* }}} */
270 
271 /* {{{ SUCCESS|FAILURE php_output_flush(void)
272  * Flush the most recent output handlers buffer */
php_output_flush(void)273 PHPAPI int php_output_flush(void)
274 {
275 	php_output_context context;
276 
277 	if (OG(active) && (OG(active)->flags & PHP_OUTPUT_HANDLER_FLUSHABLE)) {
278 		php_output_context_init(&context, PHP_OUTPUT_HANDLER_FLUSH);
279 		php_output_handler_op(OG(active), &context);
280 		if (context.out.data && context.out.used) {
281 			zend_stack_del_top(&OG(handlers));
282 			php_output_write(context.out.data, context.out.used);
283 			zend_stack_push(&OG(handlers), &OG(active));
284 		}
285 		php_output_context_dtor(&context);
286 		return SUCCESS;
287 	}
288 	return FAILURE;
289 }
290 /* }}} */
291 
292 /* {{{ void php_output_flush_all()
293  * Flush all output buffers subsequently */
php_output_flush_all(void)294 PHPAPI void php_output_flush_all(void)
295 {
296 	if (OG(active)) {
297 		php_output_op(PHP_OUTPUT_HANDLER_FLUSH, NULL, 0);
298 	}
299 }
300 /* }}} */
301 
302 /* {{{ SUCCESS|FAILURE php_output_clean(void)
303  * Cleans the most recent output handlers buffer if the handler is cleanable */
php_output_clean(void)304 PHPAPI int php_output_clean(void)
305 {
306 	php_output_context context;
307 
308 	if (OG(active) && (OG(active)->flags & PHP_OUTPUT_HANDLER_CLEANABLE)) {
309 		php_output_context_init(&context, PHP_OUTPUT_HANDLER_CLEAN);
310 		php_output_handler_op(OG(active), &context);
311 		php_output_context_dtor(&context);
312 		return SUCCESS;
313 	}
314 	return FAILURE;
315 }
316 /* }}} */
317 
318 /* {{{ void php_output_clean_all(void)
319  * Cleans all output handler buffers, without regard whether the handler is cleanable */
php_output_clean_all(void)320 PHPAPI void php_output_clean_all(void)
321 {
322 	php_output_context context;
323 
324 	if (OG(active)) {
325 		php_output_context_init(&context, PHP_OUTPUT_HANDLER_CLEAN);
326 		zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_clean, &context);
327 	}
328 }
329 
330 /* {{{ SUCCESS|FAILURE php_output_end(void)
331  * Finalizes the most recent output handler at pops it off the stack if the handler is removable */
php_output_end(void)332 PHPAPI int php_output_end(void)
333 {
334 	if (php_output_stack_pop(PHP_OUTPUT_POP_TRY)) {
335 		return SUCCESS;
336 	}
337 	return FAILURE;
338 }
339 /* }}} */
340 
341 /* {{{ void php_output_end_all(void)
342  * Finalizes all output handlers and ends output buffering without regard whether a handler is removable */
php_output_end_all(void)343 PHPAPI void php_output_end_all(void)
344 {
345 	while (OG(active) && php_output_stack_pop(PHP_OUTPUT_POP_FORCE));
346 }
347 /* }}} */
348 
349 /* {{{ SUCCESS|FAILURE php_output_discard(void)
350  * Discards the most recent output handlers buffer and pops it off the stack if the handler is removable */
php_output_discard(void)351 PHPAPI int php_output_discard(void)
352 {
353 	if (php_output_stack_pop(PHP_OUTPUT_POP_DISCARD|PHP_OUTPUT_POP_TRY)) {
354 		return SUCCESS;
355 	}
356 	return FAILURE;
357 }
358 /* }}} */
359 
360 /* {{{ void php_output_discard_all(void)
361  * Discard all output handlers and buffers without regard whether a handler is removable */
php_output_discard_all(void)362 PHPAPI void php_output_discard_all(void)
363 {
364 	while (OG(active)) {
365 		php_output_stack_pop(PHP_OUTPUT_POP_DISCARD|PHP_OUTPUT_POP_FORCE);
366 	}
367 }
368 /* }}} */
369 
370 /* {{{ int php_output_get_level(void)
371  * Get output buffering level, ie. how many output handlers the stack contains */
php_output_get_level(void)372 PHPAPI int php_output_get_level(void)
373 {
374 	return OG(active) ? zend_stack_count(&OG(handlers)) : 0;
375 }
376 /* }}} */
377 
378 /* {{{ SUCCESS|FAILURE php_output_get_contents(zval *z)
379  * Get the contents of the active output handlers buffer */
php_output_get_contents(zval * p)380 PHPAPI int php_output_get_contents(zval *p)
381 {
382 	if (OG(active)) {
383 		if (OG(active)->buffer.used) {
384 			ZVAL_STRINGL(p, OG(active)->buffer.data, OG(active)->buffer.used);
385 		} else {
386 			ZVAL_EMPTY_STRING(p);
387 		}
388 		return SUCCESS;
389 	} else {
390 		ZVAL_NULL(p);
391 		return FAILURE;
392 	}
393 }
394 
395 /* {{{ SUCCESS|FAILURE php_output_get_length(zval *z)
396  * Get the length of the active output handlers buffer */
php_output_get_length(zval * p)397 PHPAPI int php_output_get_length(zval *p)
398 {
399 	if (OG(active)) {
400 		ZVAL_LONG(p, OG(active)->buffer.used);
401 		return SUCCESS;
402 	} else {
403 		ZVAL_NULL(p);
404 		return FAILURE;
405 	}
406 }
407 /* }}} */
408 
409 /* {{{ php_output_handler* php_output_get_active_handler(void)
410  * Get active output handler */
php_output_get_active_handler(void)411 PHPAPI php_output_handler* php_output_get_active_handler(void)
412 {
413 	return OG(active);
414 }
415 /* }}} */
416 
417 /* {{{ SUCCESS|FAILURE php_output_handler_start_default(void)
418  * Start a "default output handler" */
php_output_start_default(void)419 PHPAPI int php_output_start_default(void)
420 {
421 	php_output_handler *handler;
422 
423 	handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
424 	if (SUCCESS == php_output_handler_start(handler)) {
425 		return SUCCESS;
426 	}
427 	php_output_handler_free(&handler);
428 	return FAILURE;
429 }
430 /* }}} */
431 
432 /* {{{ SUCCESS|FAILURE php_output_handler_start_devnull(void)
433  * Start a "null output handler" */
php_output_start_devnull(void)434 PHPAPI int php_output_start_devnull(void)
435 {
436 	php_output_handler *handler;
437 
438 	handler = php_output_handler_create_internal(ZEND_STRL(php_output_devnull_handler_name), php_output_handler_devnull_func, PHP_OUTPUT_HANDLER_DEFAULT_SIZE, 0);
439 	if (SUCCESS == php_output_handler_start(handler)) {
440 		return SUCCESS;
441 	}
442 	php_output_handler_free(&handler);
443 	return FAILURE;
444 }
445 /* }}} */
446 
447 /* {{{ SUCCESS|FAILURE php_output_start_user(zval *handler, size_t chunk_size, int flags)
448  * Start a user level output handler */
php_output_start_user(zval * output_handler,size_t chunk_size,int flags)449 PHPAPI int php_output_start_user(zval *output_handler, size_t chunk_size, int flags)
450 {
451 	php_output_handler *handler;
452 
453 	if (output_handler) {
454 		handler = php_output_handler_create_user(output_handler, chunk_size, flags);
455 	} else {
456 		handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags);
457 	}
458 	if (SUCCESS == php_output_handler_start(handler)) {
459 		return SUCCESS;
460 	}
461 	php_output_handler_free(&handler);
462 	return FAILURE;
463 }
464 /* }}} */
465 
466 /* {{{ SUCCESS|FAILURE php_output_start_internal(zval *name, php_output_handler_func_t handler, size_t chunk_size, int flags)
467  * Start an internal output handler that does not have to maintain a non-global state */
php_output_start_internal(const char * name,size_t name_len,php_output_handler_func_t output_handler,size_t chunk_size,int flags)468 PHPAPI int php_output_start_internal(const char *name, size_t name_len, php_output_handler_func_t output_handler, size_t chunk_size, int flags)
469 {
470 	php_output_handler *handler;
471 
472 	handler = php_output_handler_create_internal(name, name_len, php_output_handler_compat_func, chunk_size, flags);
473 	php_output_handler_set_context(handler, output_handler, NULL);
474 	if (SUCCESS == php_output_handler_start(handler)) {
475 		return SUCCESS;
476 	}
477 	php_output_handler_free(&handler);
478 	return FAILURE;
479 }
480 /* }}} */
481 
482 /* {{{ php_output_handler *php_output_handler_create_user(zval *handler, size_t chunk_size, int flags)
483  * Create a user level output handler */
php_output_handler_create_user(zval * output_handler,size_t chunk_size,int flags)484 PHPAPI php_output_handler *php_output_handler_create_user(zval *output_handler, size_t chunk_size, int flags)
485 {
486 	zend_string *handler_name = NULL;
487 	char *error = NULL;
488 	php_output_handler *handler = NULL;
489 	php_output_handler_alias_ctor_t alias = NULL;
490 	php_output_handler_user_func_t *user = NULL;
491 
492 	switch (Z_TYPE_P(output_handler)) {
493 		case IS_NULL:
494 			handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags);
495 			break;
496 		case IS_STRING:
497 			if (Z_STRLEN_P(output_handler) && (alias = php_output_handler_alias(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler)))) {
498 				handler = alias(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler), chunk_size, flags);
499 				break;
500 			}
501 			ZEND_FALLTHROUGH;
502 		default:
503 			user = ecalloc(1, sizeof(php_output_handler_user_func_t));
504 			if (SUCCESS == zend_fcall_info_init(output_handler, 0, &user->fci, &user->fcc, &handler_name, &error)) {
505 				handler = php_output_handler_init(handler_name, chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_USER);
506 				ZVAL_COPY(&user->zoh, output_handler);
507 				handler->func.user = user;
508 			} else {
509 				efree(user);
510 			}
511 			if (error) {
512 				php_error_docref("ref.outcontrol", E_WARNING, "%s", error);
513 				efree(error);
514 			}
515 			if (handler_name) {
516 				zend_string_release_ex(handler_name, 0);
517 			}
518 	}
519 
520 	return handler;
521 }
522 /* }}} */
523 
524 /* {{{ php_output_handler *php_output_handler_create_internal(zval *name, php_output_handler_context_func_t handler, size_t chunk_size, int flags)
525  * Create an internal output handler that can maintain a non-global state */
php_output_handler_create_internal(const char * name,size_t name_len,php_output_handler_context_func_t output_handler,size_t chunk_size,int flags)526 PHPAPI php_output_handler *php_output_handler_create_internal(const char *name, size_t name_len, php_output_handler_context_func_t output_handler, size_t chunk_size, int flags)
527 {
528 	php_output_handler *handler;
529 	zend_string *str = zend_string_init(name, name_len, 0);
530 
531 	handler = php_output_handler_init(str, chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_INTERNAL);
532 	handler->func.internal = output_handler;
533 	zend_string_release_ex(str, 0);
534 
535 	return handler;
536 }
537 /* }}} */
538 
539 /* {{{ void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void*))
540  * Set the context/state of an output handler. Calls the dtor of the previous context if there is one */
php_output_handler_set_context(php_output_handler * handler,void * opaq,void (* dtor)(void *))541 PHPAPI void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void*))
542 {
543 	if (handler->dtor && handler->opaq) {
544 		handler->dtor(handler->opaq);
545 	}
546 	handler->dtor = dtor;
547 	handler->opaq = opaq;
548 }
549 /* }}} */
550 
551 /* {{{ SUCCESS|FAILURE php_output_handler_start(php_output_handler *handler)
552  * Starts the set up output handler and pushes it on top of the stack. Checks for any conflicts regarding the output handler to start */
php_output_handler_start(php_output_handler * handler)553 PHPAPI int php_output_handler_start(php_output_handler *handler)
554 {
555 	HashTable *rconflicts;
556 	php_output_handler_conflict_check_t conflict;
557 
558 	if (php_output_lock_error(PHP_OUTPUT_HANDLER_START) || !handler) {
559 		return FAILURE;
560 	}
561 	if (NULL != (conflict = zend_hash_find_ptr(&php_output_handler_conflicts, handler->name))) {
562 		if (SUCCESS != conflict(ZSTR_VAL(handler->name), ZSTR_LEN(handler->name))) {
563 			return FAILURE;
564 		}
565 	}
566 	if (NULL != (rconflicts = zend_hash_find_ptr(&php_output_handler_reverse_conflicts, handler->name))) {
567 		ZEND_HASH_PACKED_FOREACH_PTR(rconflicts, conflict) {
568 			if (SUCCESS != conflict(ZSTR_VAL(handler->name), ZSTR_LEN(handler->name))) {
569 				return FAILURE;
570 			}
571 		} ZEND_HASH_FOREACH_END();
572 	}
573 	/* zend_stack_push returns stack level */
574 	handler->level = zend_stack_push(&OG(handlers), &handler);
575 	OG(active) = handler;
576 	return SUCCESS;
577 }
578 /* }}} */
579 
580 /* {{{ int php_output_handler_started(zval *name)
581  * Check whether a certain output handler is in use */
php_output_handler_started(const char * name,size_t name_len)582 PHPAPI int php_output_handler_started(const char *name, size_t name_len)
583 {
584 	php_output_handler **handlers;
585 	int i, count = php_output_get_level();
586 
587 	if (count) {
588 		handlers = (php_output_handler **) zend_stack_base(&OG(handlers));
589 
590 		for (i = 0; i < count; ++i) {
591 			if (zend_string_equals_cstr(handlers[i]->name, name, name_len)) {
592 				return 1;
593 			}
594 		}
595 	}
596 
597 	return 0;
598 }
599 /* }}} */
600 
601 /* {{{ int php_output_handler_conflict(zval *handler_new, zval *handler_old)
602  * Check whether a certain handler is in use and issue a warning that the new handler would conflict with the already used one */
php_output_handler_conflict(const char * handler_new,size_t handler_new_len,const char * handler_set,size_t handler_set_len)603 PHPAPI int php_output_handler_conflict(const char *handler_new, size_t handler_new_len, const char *handler_set, size_t handler_set_len)
604 {
605 	if (php_output_handler_started(handler_set, handler_set_len)) {
606 		if (handler_new_len != handler_set_len || memcmp(handler_new, handler_set, handler_set_len)) {
607 			php_error_docref("ref.outcontrol", E_WARNING, "Output handler '%s' conflicts with '%s'", handler_new, handler_set);
608 		} else {
609 			php_error_docref("ref.outcontrol", E_WARNING, "Output handler '%s' cannot be used twice", handler_new);
610 		}
611 		return 1;
612 	}
613 	return 0;
614 }
615 /* }}} */
616 
617 /* {{{ SUCCESS|FAILURE php_output_handler_conflict_register(zval *name, php_output_handler_conflict_check_t check_func)
618  * Register a conflict checking function on MINIT */
php_output_handler_conflict_register(const char * name,size_t name_len,php_output_handler_conflict_check_t check_func)619 PHPAPI int php_output_handler_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func)
620 {
621 	zend_string *str;
622 
623 	if (!EG(current_module)) {
624 		zend_error(E_ERROR, "Cannot register an output handler conflict outside of MINIT");
625 		return FAILURE;
626 	}
627 	str = zend_string_init_interned(name, name_len, 1);
628 	zend_hash_update_ptr(&php_output_handler_conflicts, str, check_func);
629 	zend_string_release_ex(str, 1);
630 	return SUCCESS;
631 }
632 /* }}} */
633 
634 /* {{{ SUCCESS|FAILURE php_output_handler_reverse_conflict_register(zval *name, php_output_handler_conflict_check_t check_func)
635  * Register a reverse conflict checking function on MINIT */
php_output_handler_reverse_conflict_register(const char * name,size_t name_len,php_output_handler_conflict_check_t check_func)636 PHPAPI int php_output_handler_reverse_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func)
637 {
638 	HashTable rev, *rev_ptr = NULL;
639 
640 	if (!EG(current_module)) {
641 		zend_error(E_ERROR, "Cannot register a reverse output handler conflict outside of MINIT");
642 		return FAILURE;
643 	}
644 
645 	if (NULL != (rev_ptr = zend_hash_str_find_ptr(&php_output_handler_reverse_conflicts, name, name_len))) {
646 		return zend_hash_next_index_insert_ptr(rev_ptr, check_func) ? SUCCESS : FAILURE;
647 	} else {
648 		zend_string *str;
649 
650 		zend_hash_init(&rev, 8, NULL, NULL, 1);
651 		if (NULL == zend_hash_next_index_insert_ptr(&rev, check_func)) {
652 			zend_hash_destroy(&rev);
653 			return FAILURE;
654 		}
655 		str = zend_string_init_interned(name, name_len, 1);
656 		zend_hash_update_mem(&php_output_handler_reverse_conflicts, str, &rev, sizeof(HashTable));
657 		zend_string_release_ex(str, 1);
658 		return SUCCESS;
659 	}
660 }
661 /* }}} */
662 
663 /* {{{ php_output_handler_alias_ctor_t php_output_handler_alias(zval *name)
664  * Get an internal output handler for a user handler if it exists */
php_output_handler_alias(const char * name,size_t name_len)665 PHPAPI php_output_handler_alias_ctor_t php_output_handler_alias(const char *name, size_t name_len)
666 {
667 	return zend_hash_str_find_ptr(&php_output_handler_aliases, name, name_len);
668 }
669 /* }}} */
670 
671 /* {{{ SUCCESS|FAILURE php_output_handler_alias_register(zval *name, php_output_handler_alias_ctor_t func)
672  * Registers an internal output handler as alias for a user handler */
php_output_handler_alias_register(const char * name,size_t name_len,php_output_handler_alias_ctor_t func)673 PHPAPI int php_output_handler_alias_register(const char *name, size_t name_len, php_output_handler_alias_ctor_t func)
674 {
675 	zend_string *str;
676 
677 	if (!EG(current_module)) {
678 		zend_error(E_ERROR, "Cannot register an output handler alias outside of MINIT");
679 		return FAILURE;
680 	}
681 	str = zend_string_init_interned(name, name_len, 1);
682 	zend_hash_update_ptr(&php_output_handler_aliases, str, func);
683 	zend_string_release_ex(str, 1);
684 	return SUCCESS;
685 }
686 /* }}} */
687 
688 /* {{{ SUCCESS|FAILURE php_output_handler_hook(php_output_handler_hook_t type, void *arg)
689  * Output handler hook for output handler functions to check/modify the current handlers abilities */
php_output_handler_hook(php_output_handler_hook_t type,void * arg)690 PHPAPI int php_output_handler_hook(php_output_handler_hook_t type, void *arg)
691 {
692 	if (OG(running)) {
693 		switch (type) {
694 			case PHP_OUTPUT_HANDLER_HOOK_GET_OPAQ:
695 				*(void ***) arg = &OG(running)->opaq;
696 				return SUCCESS;
697 			case PHP_OUTPUT_HANDLER_HOOK_GET_FLAGS:
698 				*(int *) arg = OG(running)->flags;
699 				return SUCCESS;
700 			case PHP_OUTPUT_HANDLER_HOOK_GET_LEVEL:
701 				*(int *) arg = OG(running)->level;
702 				return SUCCESS;
703 			case PHP_OUTPUT_HANDLER_HOOK_IMMUTABLE:
704 				OG(running)->flags &= ~(PHP_OUTPUT_HANDLER_REMOVABLE|PHP_OUTPUT_HANDLER_CLEANABLE);
705 				return SUCCESS;
706 			case PHP_OUTPUT_HANDLER_HOOK_DISABLE:
707 				OG(running)->flags |= PHP_OUTPUT_HANDLER_DISABLED;
708 				return SUCCESS;
709 			default:
710 				break;
711 		}
712 	}
713 	return FAILURE;
714 }
715 /* }}} */
716 
717 /* {{{ void php_output_handler_dtor(php_output_handler *handler)
718  * Destroy an output handler */
php_output_handler_dtor(php_output_handler * handler)719 PHPAPI void php_output_handler_dtor(php_output_handler *handler)
720 {
721 	if (handler->name) {
722 		zend_string_release_ex(handler->name, 0);
723 	}
724 	if (handler->buffer.data) {
725 		efree(handler->buffer.data);
726 	}
727 	if (handler->flags & PHP_OUTPUT_HANDLER_USER) {
728 		zval_ptr_dtor(&handler->func.user->zoh);
729 		efree(handler->func.user);
730 	}
731 	if (handler->dtor && handler->opaq) {
732 		handler->dtor(handler->opaq);
733 	}
734 	memset(handler, 0, sizeof(*handler));
735 }
736 /* }}} */
737 
738 /* {{{ void php_output_handler_free(php_output_handler **handler)
739  * Destroy and free an output handler */
php_output_handler_free(php_output_handler ** h)740 PHPAPI void php_output_handler_free(php_output_handler **h)
741 {
742 	if (*h) {
743 		php_output_handler_dtor(*h);
744 		efree(*h);
745 		*h = NULL;
746 	}
747 }
748 /* }}} */
749 
750 /* void php_output_set_implicit_flush(int enabled)
751  * Enable or disable implicit flush */
php_output_set_implicit_flush(int flush)752 PHPAPI void php_output_set_implicit_flush(int flush)
753 {
754 	if (flush) {
755 		OG(flags) |= PHP_OUTPUT_IMPLICITFLUSH;
756 	} else {
757 		OG(flags) &= ~PHP_OUTPUT_IMPLICITFLUSH;
758 	}
759 }
760 /* }}} */
761 
762 /* {{{ char *php_output_get_start_filename(void)
763  * Get the file name where output has started */
php_output_get_start_filename(void)764 PHPAPI const char *php_output_get_start_filename(void)
765 {
766 	return OG(output_start_filename) ? ZSTR_VAL(OG(output_start_filename)) : NULL;
767 }
768 /* }}} */
769 
770 /* {{{ int php_output_get_start_lineno(void)
771  * Get the line number where output has started */
php_output_get_start_lineno(void)772 PHPAPI int php_output_get_start_lineno(void)
773 {
774 	return OG(output_start_lineno);
775 }
776 /* }}} */
777 
778 /* {{{ static int php_output_lock_error(int op)
779  * Checks whether an unallowed operation is attempted from within the output handler and issues a fatal error */
php_output_lock_error(int op)780 static inline int php_output_lock_error(int op)
781 {
782 	/* if there's no ob active, ob has been stopped */
783 	if (op && OG(active) && OG(running)) {
784 		/* fatal error */
785 		php_output_deactivate();
786 		php_error_docref("ref.outcontrol", E_ERROR, "Cannot use output buffering in output buffering display handlers");
787 		return 1;
788 	}
789 	return 0;
790 }
791 /* }}} */
792 
793 /* {{{ static php_output_context *php_output_context_init(php_output_context *context, int op)
794  * Initialize a new output context */
php_output_context_init(php_output_context * context,int op)795 static inline void php_output_context_init(php_output_context *context, int op)
796 {
797 	memset(context, 0, sizeof(php_output_context));
798 	context->op = op;
799 }
800 /* }}} */
801 
802 /* {{{ static void php_output_context_reset(php_output_context *context)
803  * Reset an output context */
php_output_context_reset(php_output_context * context)804 static inline void php_output_context_reset(php_output_context *context)
805 {
806 	int op = context->op;
807 	php_output_context_dtor(context);
808 	memset(context, 0, sizeof(php_output_context));
809 	context->op = op;
810 }
811 /* }}} */
812 
813 /* {{{ static void php_output_context_feed(php_output_context *context, char *, size_t, size_t)
814  * Feed output contexts input buffer */
php_output_context_feed(php_output_context * context,char * data,size_t size,size_t used,bool free)815 static inline void php_output_context_feed(php_output_context *context, char *data, size_t size, size_t used, bool free)
816 {
817 	if (context->in.free && context->in.data) {
818 		efree(context->in.data);
819 	}
820 	context->in.data = data;
821 	context->in.used = used;
822 	context->in.free = free;
823 	context->in.size = size;
824 }
825 /* }}} */
826 
827 /* {{{ static void php_output_context_swap(php_output_context *context)
828  * Swap output contexts buffers */
php_output_context_swap(php_output_context * context)829 static inline void php_output_context_swap(php_output_context *context)
830 {
831 	if (context->in.free && context->in.data) {
832 		efree(context->in.data);
833 	}
834 	context->in.data = context->out.data;
835 	context->in.used = context->out.used;
836 	context->in.free = context->out.free;
837 	context->in.size = context->out.size;
838 	context->out.data = NULL;
839 	context->out.used = 0;
840 	context->out.free = 0;
841 	context->out.size = 0;
842 }
843 /* }}} */
844 
845 /* {{{ static void php_output_context_pass(php_output_context *context)
846  * Pass input to output buffer */
php_output_context_pass(php_output_context * context)847 static inline void php_output_context_pass(php_output_context *context)
848 {
849 	context->out.data = context->in.data;
850 	context->out.used = context->in.used;
851 	context->out.size = context->in.size;
852 	context->out.free = context->in.free;
853 	context->in.data = NULL;
854 	context->in.used = 0;
855 	context->in.free = 0;
856 	context->in.size = 0;
857 }
858 /* }}} */
859 
860 /* {{{ static void php_output_context_dtor(php_output_context *context)
861  * Destroy the contents of an output context */
php_output_context_dtor(php_output_context * context)862 static inline void php_output_context_dtor(php_output_context *context)
863 {
864 	if (context->in.free && context->in.data) {
865 		efree(context->in.data);
866 		context->in.data = NULL;
867 	}
868 	if (context->out.free && context->out.data) {
869 		efree(context->out.data);
870 		context->out.data = NULL;
871 	}
872 }
873 /* }}} */
874 
875 /* {{{ static php_output_handler *php_output_handler_init(zval *name, size_t chunk_size, int flags)
876  * Allocates and initializes a php_output_handler structure */
php_output_handler_init(zend_string * name,size_t chunk_size,int flags)877 static inline php_output_handler *php_output_handler_init(zend_string *name, size_t chunk_size, int flags)
878 {
879 	php_output_handler *handler;
880 
881 	handler = ecalloc(1, sizeof(php_output_handler));
882 	handler->name = zend_string_copy(name);
883 	handler->size = chunk_size;
884 	handler->flags = flags;
885 	handler->buffer.size = PHP_OUTPUT_HANDLER_INITBUF_SIZE(chunk_size);
886 	handler->buffer.data = emalloc(handler->buffer.size);
887 
888 	return handler;
889 }
890 /* }}} */
891 
892 /* {{{ static int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf)
893  * Appends input to the output handlers buffer and indicates whether the buffer does not have to be processed by the output handler */
php_output_handler_append(php_output_handler * handler,const php_output_buffer * buf)894 static inline int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf)
895 {
896 	if (buf->used) {
897 		OG(flags) |= PHP_OUTPUT_WRITTEN;
898 		/* store it away */
899 		if ((handler->buffer.size - handler->buffer.used) <= buf->used) {
900 			size_t grow_int = PHP_OUTPUT_HANDLER_INITBUF_SIZE(handler->size);
901 			size_t grow_buf = PHP_OUTPUT_HANDLER_INITBUF_SIZE(buf->used - (handler->buffer.size - handler->buffer.used));
902 			size_t grow_max = MAX(grow_int, grow_buf);
903 
904 			handler->buffer.data = safe_erealloc(handler->buffer.data, 1, handler->buffer.size, grow_max);
905 			handler->buffer.size += grow_max;
906 		}
907 		memcpy(handler->buffer.data + handler->buffer.used, buf->data, buf->used);
908 		handler->buffer.used += buf->used;
909 
910 		/* chunked buffering */
911 		if (handler->size && (handler->buffer.used >= handler->size)) {
912 			/* store away errors and/or any intermediate output */
913 			return OG(running) ? 1 : 0;
914 		}
915 	}
916 	return 1;
917 }
918 /* }}} */
919 
920 /* {{{ static php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context)
921  * Output handler operation dispatcher, applying context op to the php_output_handler handler */
php_output_handler_op(php_output_handler * handler,php_output_context * context)922 static inline php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context)
923 {
924 	php_output_handler_status_t status;
925 	int original_op = context->op;
926 
927 #if PHP_OUTPUT_DEBUG
928 	fprintf(stderr, ">>> op(%d, "
929 					"handler=%p, "
930 					"name=%s, "
931 					"flags=%d, "
932 					"buffer.data=%s, "
933 					"buffer.used=%zu, "
934 					"buffer.size=%zu, "
935 					"in.data=%s, "
936 					"in.used=%zu)\n",
937 			context->op,
938 			handler,
939 			handler->name,
940 			handler->flags,
941 			handler->buffer.used?handler->buffer.data:"",
942 			handler->buffer.used,
943 			handler->buffer.size,
944 			context->in.used?context->in.data:"",
945 			context->in.used
946 	);
947 #endif
948 
949 	if (php_output_lock_error(context->op)) {
950 		/* fatal error */
951 		return PHP_OUTPUT_HANDLER_FAILURE;
952 	}
953 
954 	/* storable? */
955 	if (php_output_handler_append(handler, &context->in) && !context->op) {
956 		context->op = original_op;
957 		return PHP_OUTPUT_HANDLER_NO_DATA;
958 	} else {
959 		/* need to start? */
960 		if (!(handler->flags & PHP_OUTPUT_HANDLER_STARTED)) {
961 			context->op |= PHP_OUTPUT_HANDLER_START;
962 		}
963 
964 		OG(running) = handler;
965 		if (handler->flags & PHP_OUTPUT_HANDLER_USER) {
966 			zval retval, ob_data, ob_mode;
967 
968 			ZVAL_STRINGL(&ob_data, handler->buffer.data, handler->buffer.used);
969 			ZVAL_LONG(&ob_mode, (zend_long) context->op);
970 			zend_fcall_info_argn(&handler->func.user->fci, 2, &ob_data, &ob_mode);
971 			zval_ptr_dtor(&ob_data);
972 
973 #define PHP_OUTPUT_USER_SUCCESS(retval) ((Z_TYPE(retval) != IS_UNDEF) && !(Z_TYPE(retval) == IS_FALSE))
974 			if (SUCCESS == zend_fcall_info_call(&handler->func.user->fci, &handler->func.user->fcc, &retval, NULL) && PHP_OUTPUT_USER_SUCCESS(retval)) {
975 				/* user handler may have returned TRUE */
976 				status = PHP_OUTPUT_HANDLER_NO_DATA;
977 				if (Z_TYPE(retval) != IS_FALSE && Z_TYPE(retval) != IS_TRUE) {
978 					convert_to_string(&retval);
979 					if (Z_STRLEN(retval)) {
980 						context->out.data = estrndup(Z_STRVAL(retval), Z_STRLEN(retval));
981 						context->out.used = Z_STRLEN(retval);
982 						context->out.free = 1;
983 						status = PHP_OUTPUT_HANDLER_SUCCESS;
984 					}
985 				}
986 			} else {
987 				/* call failed, pass internal buffer along */
988 				status = PHP_OUTPUT_HANDLER_FAILURE;
989 			}
990 
991 			zend_fcall_info_argn(&handler->func.user->fci, 0);
992 			zval_ptr_dtor(&retval);
993 
994 		} else {
995 
996 			php_output_context_feed(context, handler->buffer.data, handler->buffer.size, handler->buffer.used, 0);
997 
998 			if (SUCCESS == handler->func.internal(&handler->opaq, context)) {
999 				if (context->out.used) {
1000 					status = PHP_OUTPUT_HANDLER_SUCCESS;
1001 				} else {
1002 					status = PHP_OUTPUT_HANDLER_NO_DATA;
1003 				}
1004 			} else {
1005 				status = PHP_OUTPUT_HANDLER_FAILURE;
1006 			}
1007 		}
1008 		handler->flags |= PHP_OUTPUT_HANDLER_STARTED;
1009 		OG(running) = NULL;
1010 	}
1011 
1012 	switch (status) {
1013 		case PHP_OUTPUT_HANDLER_FAILURE:
1014 			/* disable this handler */
1015 			handler->flags |= PHP_OUTPUT_HANDLER_DISABLED;
1016 			/* discard any output */
1017 			if (context->out.data && context->out.free) {
1018 				efree(context->out.data);
1019 			}
1020 			/* returns handlers buffer */
1021 			context->out.data = handler->buffer.data;
1022 			context->out.used = handler->buffer.used;
1023 			context->out.free = 1;
1024 			handler->buffer.data = NULL;
1025 			handler->buffer.used = 0;
1026 			handler->buffer.size = 0;
1027 			break;
1028 		case PHP_OUTPUT_HANDLER_NO_DATA:
1029 			/* handler ate all */
1030 			php_output_context_reset(context);
1031 			ZEND_FALLTHROUGH;
1032 		case PHP_OUTPUT_HANDLER_SUCCESS:
1033 			/* no more buffered data */
1034 			handler->buffer.used = 0;
1035 			handler->flags |= PHP_OUTPUT_HANDLER_PROCESSED;
1036 			break;
1037 	}
1038 
1039 	context->op = original_op;
1040 	return status;
1041 }
1042 /* }}} */
1043 
1044 
1045 /* {{{ static void php_output_op(int op, const char *str, size_t len)
1046  * Output op dispatcher, passes input and output handlers output through the output handler stack until it gets written to the SAPI */
php_output_op(int op,const char * str,size_t len)1047 static inline void php_output_op(int op, const char *str, size_t len)
1048 {
1049 	php_output_context context;
1050 	php_output_handler **active;
1051 	int obh_cnt;
1052 
1053 	if (php_output_lock_error(op)) {
1054 		return;
1055 	}
1056 
1057 	php_output_context_init(&context, op);
1058 
1059 	/*
1060 	 * broken up for better performance:
1061 	 *  - apply op to the one active handler; note that OG(active) might be popped off the stack on a flush
1062 	 *  - or apply op to the handler stack
1063 	 */
1064 	if (OG(active) && (obh_cnt = zend_stack_count(&OG(handlers)))) {
1065 		context.in.data = (char *) str;
1066 		context.in.used = len;
1067 
1068 		if (obh_cnt > 1) {
1069 			zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_op, &context);
1070 		} else if ((active = zend_stack_top(&OG(handlers))) && (!((*active)->flags & PHP_OUTPUT_HANDLER_DISABLED))) {
1071 			php_output_handler_op(*active, &context);
1072 		} else {
1073 			php_output_context_pass(&context);
1074 		}
1075 	} else {
1076 		context.out.data = (char *) str;
1077 		context.out.used = len;
1078 	}
1079 
1080 	if (context.out.data && context.out.used) {
1081 		php_output_header();
1082 
1083 		if (!(OG(flags) & PHP_OUTPUT_DISABLED)) {
1084 #if PHP_OUTPUT_DEBUG
1085 			fprintf(stderr, "::: sapi_write('%s', %zu)\n", context.out.data, context.out.used);
1086 #endif
1087 			sapi_module.ub_write(context.out.data, context.out.used);
1088 
1089 			if (OG(flags) & PHP_OUTPUT_IMPLICITFLUSH) {
1090 				sapi_flush();
1091 			}
1092 
1093 			OG(flags) |= PHP_OUTPUT_SENT;
1094 		}
1095 	}
1096 	php_output_context_dtor(&context);
1097 }
1098 /* }}} */
1099 
1100 /* {{{ static int php_output_stack_apply_op(void *h, void *c)
1101  * Operation callback for the stack apply function */
php_output_stack_apply_op(void * h,void * c)1102 static int php_output_stack_apply_op(void *h, void *c)
1103 {
1104 	int was_disabled;
1105 	php_output_handler_status_t status;
1106 	php_output_handler *handler = *(php_output_handler **) h;
1107 	php_output_context *context = (php_output_context *) c;
1108 
1109 	if ((was_disabled = (handler->flags & PHP_OUTPUT_HANDLER_DISABLED))) {
1110 		status = PHP_OUTPUT_HANDLER_FAILURE;
1111 	} else {
1112 		status = php_output_handler_op(handler, context);
1113 	}
1114 
1115 	/*
1116 	 * handler ate all => break
1117 	 * handler returned data or failed resp. is disabled => continue
1118 	 */
1119 	switch (status) {
1120 		case PHP_OUTPUT_HANDLER_NO_DATA:
1121 			return 1;
1122 
1123 		case PHP_OUTPUT_HANDLER_SUCCESS:
1124 			/* swap contexts buffers, unless this is the last handler in the stack */
1125 			if (handler->level) {
1126 				php_output_context_swap(context);
1127 			}
1128 			return 0;
1129 
1130 		case PHP_OUTPUT_HANDLER_FAILURE:
1131 		default:
1132 			if (was_disabled) {
1133 				/* pass input along, if it's the last handler in the stack */
1134 				if (!handler->level) {
1135 					php_output_context_pass(context);
1136 				}
1137 			} else {
1138 				/* swap buffers, unless this is the last handler */
1139 				if (handler->level) {
1140 					php_output_context_swap(context);
1141 				}
1142 			}
1143 			return 0;
1144 	}
1145 }
1146 /* }}} */
1147 
1148 /* {{{ static int php_output_stack_apply_clean(void *h, void *c)
1149  * Clean callback for the stack apply function */
php_output_stack_apply_clean(void * h,void * c)1150 static int php_output_stack_apply_clean(void *h, void *c)
1151 {
1152 	php_output_handler *handler = *(php_output_handler **) h;
1153 	php_output_context *context = (php_output_context *) c;
1154 
1155 	handler->buffer.used = 0;
1156 	php_output_handler_op(handler, context);
1157 	php_output_context_reset(context);
1158 	return 0;
1159 }
1160 /* }}} */
1161 
1162 /* {{{ static int php_output_stack_apply_list(void *h, void *z)
1163  * List callback for the stack apply function */
php_output_stack_apply_list(void * h,void * z)1164 static int php_output_stack_apply_list(void *h, void *z)
1165 {
1166 	php_output_handler *handler = *(php_output_handler **) h;
1167 	zval *array = (zval *) z;
1168 
1169 	add_next_index_str(array, zend_string_copy(handler->name));
1170 	return 0;
1171 }
1172 /* }}} */
1173 
1174 /* {{{ static int php_output_stack_apply_status(void *h, void *z)
1175  * Status callback for the stack apply function */
php_output_stack_apply_status(void * h,void * z)1176 static int php_output_stack_apply_status(void *h, void *z)
1177 {
1178 	php_output_handler *handler = *(php_output_handler **) h;
1179 	zval arr, *array = (zval *) z;
1180 
1181 	add_next_index_zval(array, php_output_handler_status(handler, &arr));
1182 
1183 	return 0;
1184 }
1185 
1186 /* {{{ static zval *php_output_handler_status(php_output_handler *handler, zval *entry)
1187  * Returns an array with the status of the output handler */
php_output_handler_status(php_output_handler * handler,zval * entry)1188 static inline zval *php_output_handler_status(php_output_handler *handler, zval *entry)
1189 {
1190 	ZEND_ASSERT(entry != NULL);
1191 
1192 	array_init(entry);
1193 	add_assoc_str(entry, "name", zend_string_copy(handler->name));
1194 	add_assoc_long(entry, "type", (zend_long) (handler->flags & 0xf));
1195 	add_assoc_long(entry, "flags", (zend_long) handler->flags);
1196 	add_assoc_long(entry, "level", (zend_long) handler->level);
1197 	add_assoc_long(entry, "chunk_size", (zend_long) handler->size);
1198 	add_assoc_long(entry, "buffer_size", (zend_long) handler->buffer.size);
1199 	add_assoc_long(entry, "buffer_used", (zend_long) handler->buffer.used);
1200 
1201 	return entry;
1202 }
1203 /* }}} */
1204 
1205 /* {{{ static int php_output_stack_pop(int flags)
1206  * Pops an output handler off the stack */
php_output_stack_pop(int flags)1207 static int php_output_stack_pop(int flags)
1208 {
1209 	php_output_context context;
1210 	php_output_handler **current, *orphan = OG(active);
1211 
1212 	if (!orphan) {
1213 		if (!(flags & PHP_OUTPUT_POP_SILENT)) {
1214 			php_error_docref("ref.outcontrol", E_NOTICE, "Failed to %s buffer. No buffer to %s", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send");
1215 		}
1216 		return 0;
1217 	} else if (!(flags & PHP_OUTPUT_POP_FORCE) && !(orphan->flags & PHP_OUTPUT_HANDLER_REMOVABLE)) {
1218 		if (!(flags & PHP_OUTPUT_POP_SILENT)) {
1219 			php_error_docref("ref.outcontrol", E_NOTICE, "Failed to %s buffer of %s (%d)", (flags&PHP_OUTPUT_POP_DISCARD)?"discard":"send", ZSTR_VAL(orphan->name), orphan->level);
1220 		}
1221 		return 0;
1222 	} else {
1223 		php_output_context_init(&context, PHP_OUTPUT_HANDLER_FINAL);
1224 
1225 		/* don't run the output handler if it's disabled */
1226 		if (!(orphan->flags & PHP_OUTPUT_HANDLER_DISABLED)) {
1227 			/* didn't it start yet? */
1228 			if (!(orphan->flags & PHP_OUTPUT_HANDLER_STARTED)) {
1229 				context.op |= PHP_OUTPUT_HANDLER_START;
1230 			}
1231 			/* signal that we're cleaning up */
1232 			if (flags & PHP_OUTPUT_POP_DISCARD) {
1233 				context.op |= PHP_OUTPUT_HANDLER_CLEAN;
1234 			}
1235 			php_output_handler_op(orphan, &context);
1236 		}
1237 
1238 		/* pop it off the stack */
1239 		zend_stack_del_top(&OG(handlers));
1240 		if ((current = zend_stack_top(&OG(handlers)))) {
1241 			OG(active) = *current;
1242 		} else {
1243 			OG(active) = NULL;
1244 		}
1245 
1246 		/* pass output along */
1247 		if (context.out.data && context.out.used && !(flags & PHP_OUTPUT_POP_DISCARD)) {
1248 			php_output_write(context.out.data, context.out.used);
1249 		}
1250 
1251 		/* destroy the handler (after write!) */
1252 		php_output_handler_free(&orphan);
1253 		php_output_context_dtor(&context);
1254 
1255 		return 1;
1256 	}
1257 }
1258 /* }}} */
1259 
1260 /* {{{ static SUCCESS|FAILURE php_output_handler_compat_func(void *ctx, php_output_context *)
1261  * php_output_handler_context_func_t for php_output_handler_func_t output handlers */
php_output_handler_compat_func(void ** handler_context,php_output_context * output_context)1262 static int php_output_handler_compat_func(void **handler_context, php_output_context *output_context)
1263 {
1264 	php_output_handler_func_t func = *(php_output_handler_func_t *) handler_context;
1265 
1266 	if (func) {
1267 		char *out_str = NULL;
1268 		size_t out_len = 0;
1269 
1270 		func(output_context->in.data, output_context->in.used, &out_str, &out_len, output_context->op);
1271 
1272 		if (out_str) {
1273 			output_context->out.data = out_str;
1274 			output_context->out.used = out_len;
1275 			output_context->out.free = 1;
1276 		} else {
1277 			php_output_context_pass(output_context);
1278 		}
1279 
1280 		return SUCCESS;
1281 	}
1282 	return FAILURE;
1283 }
1284 /* }}} */
1285 
1286 /* {{{ static SUCCESS|FAILURE php_output_handler_default_func(void *ctx, php_output_context *)
1287  * Default output handler */
php_output_handler_default_func(void ** handler_context,php_output_context * output_context)1288 static int php_output_handler_default_func(void **handler_context, php_output_context *output_context)
1289 {
1290 	php_output_context_pass(output_context);
1291 	return SUCCESS;
1292 }
1293 /* }}} */
1294 
1295 /* {{{ static SUCCESS|FAILURE php_output_handler_devnull_func(void *ctx, php_output_context *)
1296  * Null output handler */
php_output_handler_devnull_func(void ** handler_context,php_output_context * output_context)1297 static int php_output_handler_devnull_func(void **handler_context, php_output_context *output_context)
1298 {
1299 	return SUCCESS;
1300 }
1301 /* }}} */
1302 
1303 /*
1304  * USERLAND (nearly 1:1 of old output.c)
1305  */
1306 
1307 /* {{{ Turn on Output Buffering (specifying an optional output handler). */
PHP_FUNCTION(ob_start)1308 PHP_FUNCTION(ob_start)
1309 {
1310 	zval *output_handler = NULL;
1311 	zend_long chunk_size = 0;
1312 	zend_long flags = PHP_OUTPUT_HANDLER_STDFLAGS;
1313 
1314 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|zll", &output_handler, &chunk_size, &flags) == FAILURE) {
1315 		RETURN_THROWS();
1316 	}
1317 
1318 	if (chunk_size < 0) {
1319 		chunk_size = 0;
1320 	}
1321 
1322 	if (php_output_start_user(output_handler, chunk_size, flags) == FAILURE) {
1323 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to create buffer");
1324 		RETURN_FALSE;
1325 	}
1326 	RETURN_TRUE;
1327 }
1328 /* }}} */
1329 
1330 /* {{{ Flush (send) contents of the output buffer. The last buffer content is sent to next buffer */
PHP_FUNCTION(ob_flush)1331 PHP_FUNCTION(ob_flush)
1332 {
1333 	if (zend_parse_parameters_none() == FAILURE) {
1334 		RETURN_THROWS();
1335 	}
1336 
1337 	if (!OG(active)) {
1338 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to flush buffer. No buffer to flush");
1339 		RETURN_FALSE;
1340 	}
1341 
1342 	if (SUCCESS != php_output_flush()) {
1343 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to flush buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1344 		RETURN_FALSE;
1345 	}
1346 	RETURN_TRUE;
1347 }
1348 /* }}} */
1349 
1350 /* {{{ Clean (delete) the current output buffer */
PHP_FUNCTION(ob_clean)1351 PHP_FUNCTION(ob_clean)
1352 {
1353 	if (zend_parse_parameters_none() == FAILURE) {
1354 		RETURN_THROWS();
1355 	}
1356 
1357 	if (!OG(active)) {
1358 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer. No buffer to delete");
1359 		RETURN_FALSE;
1360 	}
1361 
1362 	if (SUCCESS != php_output_clean()) {
1363 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1364 		RETURN_FALSE;
1365 	}
1366 	RETURN_TRUE;
1367 }
1368 /* }}} */
1369 
1370 /* {{{ Flush (send) the output buffer, and delete current output buffer */
PHP_FUNCTION(ob_end_flush)1371 PHP_FUNCTION(ob_end_flush)
1372 {
1373 	if (zend_parse_parameters_none() == FAILURE) {
1374 		RETURN_THROWS();
1375 	}
1376 
1377 	if (!OG(active)) {
1378 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete and flush buffer. No buffer to delete or flush");
1379 		RETURN_FALSE;
1380 	}
1381 
1382 	RETURN_BOOL(SUCCESS == php_output_end());
1383 }
1384 /* }}} */
1385 
1386 /* {{{ Clean the output buffer, and delete current output buffer */
PHP_FUNCTION(ob_end_clean)1387 PHP_FUNCTION(ob_end_clean)
1388 {
1389 	if (zend_parse_parameters_none() == FAILURE) {
1390 		RETURN_THROWS();
1391 	}
1392 
1393 	if (!OG(active)) {
1394 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer. No buffer to delete");
1395 		RETURN_FALSE;
1396 	}
1397 
1398 	RETURN_BOOL(SUCCESS == php_output_discard());
1399 }
1400 /* }}} */
1401 
1402 /* {{{ Get current buffer contents, flush (send) the output buffer, and delete current output buffer */
PHP_FUNCTION(ob_get_flush)1403 PHP_FUNCTION(ob_get_flush)
1404 {
1405 	if (zend_parse_parameters_none() == FAILURE) {
1406 		RETURN_THROWS();
1407 	}
1408 
1409 	if (php_output_get_contents(return_value) == FAILURE) {
1410 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete and flush buffer. No buffer to delete or flush");
1411 		RETURN_FALSE;
1412 	}
1413 
1414 	if (SUCCESS != php_output_end()) {
1415 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1416 	}
1417 }
1418 /* }}} */
1419 
1420 /* {{{ Get current buffer contents and delete current output buffer */
PHP_FUNCTION(ob_get_clean)1421 PHP_FUNCTION(ob_get_clean)
1422 {
1423 	if (zend_parse_parameters_none() == FAILURE) {
1424 		RETURN_THROWS();
1425 	}
1426 
1427 	if(!OG(active)) {
1428 		RETURN_FALSE;
1429 	}
1430 
1431 	if (php_output_get_contents(return_value) == FAILURE) {
1432 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer. No buffer to delete");
1433 		RETURN_FALSE;
1434 	}
1435 
1436 	if (SUCCESS != php_output_discard()) {
1437 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1438 	}
1439 }
1440 /* }}} */
1441 
1442 /* {{{ Return the contents of the output buffer */
PHP_FUNCTION(ob_get_contents)1443 PHP_FUNCTION(ob_get_contents)
1444 {
1445 	if (zend_parse_parameters_none() == FAILURE) {
1446 		RETURN_THROWS();
1447 	}
1448 
1449 	if (php_output_get_contents(return_value) == FAILURE) {
1450 		RETURN_FALSE;
1451 	}
1452 }
1453 /* }}} */
1454 
1455 /* {{{ Return the nesting level of the output buffer */
PHP_FUNCTION(ob_get_level)1456 PHP_FUNCTION(ob_get_level)
1457 {
1458 	if (zend_parse_parameters_none() == FAILURE) {
1459 		RETURN_THROWS();
1460 	}
1461 
1462 	RETURN_LONG(php_output_get_level());
1463 }
1464 /* }}} */
1465 
1466 /* {{{ Return the length of the output buffer */
PHP_FUNCTION(ob_get_length)1467 PHP_FUNCTION(ob_get_length)
1468 {
1469 	if (zend_parse_parameters_none() == FAILURE) {
1470 		RETURN_THROWS();
1471 	}
1472 
1473 	if (php_output_get_length(return_value) == FAILURE) {
1474 		RETURN_FALSE;
1475 	}
1476 }
1477 /* }}} */
1478 
1479 /* {{{ List all output_buffers in an array */
PHP_FUNCTION(ob_list_handlers)1480 PHP_FUNCTION(ob_list_handlers)
1481 {
1482 	if (zend_parse_parameters_none() == FAILURE) {
1483 		RETURN_THROWS();
1484 	}
1485 
1486 	array_init(return_value);
1487 
1488 	if (!OG(active)) {
1489 		return;
1490 	}
1491 
1492 	zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_list, return_value);
1493 }
1494 /* }}} */
1495 
1496 /* {{{ Return the status of the active or all output buffers */
PHP_FUNCTION(ob_get_status)1497 PHP_FUNCTION(ob_get_status)
1498 {
1499 	bool full_status = 0;
1500 
1501 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &full_status) == FAILURE) {
1502 		RETURN_THROWS();
1503 	}
1504 
1505 	if (!OG(active)) {
1506 		array_init(return_value);
1507 		return;
1508 	}
1509 
1510 	if (full_status) {
1511 		array_init(return_value);
1512 		zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_status, return_value);
1513 	} else {
1514 		php_output_handler_status(OG(active), return_value);
1515 	}
1516 }
1517 /* }}} */
1518 
1519 /* {{{ Turn implicit flush on/off and is equivalent to calling flush() after every output call */
PHP_FUNCTION(ob_implicit_flush)1520 PHP_FUNCTION(ob_implicit_flush)
1521 {
1522 	zend_long flag = 1;
1523 
1524 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &flag) == FAILURE) {
1525 		RETURN_THROWS();
1526 	}
1527 
1528 	php_output_set_implicit_flush((int) flag);
1529 }
1530 /* }}} */
1531 
1532 /* {{{ Reset(clear) URL rewriter values */
PHP_FUNCTION(output_reset_rewrite_vars)1533 PHP_FUNCTION(output_reset_rewrite_vars)
1534 {
1535 	if (zend_parse_parameters_none() == FAILURE) {
1536 		RETURN_THROWS();
1537 	}
1538 
1539 	if (php_url_scanner_reset_vars() == SUCCESS) {
1540 		RETURN_TRUE;
1541 	} else {
1542 		RETURN_FALSE;
1543 	}
1544 }
1545 /* }}} */
1546 
1547 /* {{{ Add URL rewriter values */
PHP_FUNCTION(output_add_rewrite_var)1548 PHP_FUNCTION(output_add_rewrite_var)
1549 {
1550 	char *name, *value;
1551 	size_t name_len, value_len;
1552 
1553 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &name, &name_len, &value, &value_len) == FAILURE) {
1554 		RETURN_THROWS();
1555 	}
1556 
1557 	if (php_url_scanner_add_var(name, name_len, value, value_len, 1) == SUCCESS) {
1558 		RETURN_TRUE;
1559 	} else {
1560 		RETURN_FALSE;
1561 	}
1562 }
1563 /* }}} */
1564