xref: /php-src/main/output.c (revision b9e895bc)
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 		ZVAL_STRINGL(p, OG(active)->buffer.data, OG(active)->buffer.used);
384 		return SUCCESS;
385 	} else {
386 		ZVAL_NULL(p);
387 		return FAILURE;
388 	}
389 }
390 
391 /* {{{ SUCCESS|FAILURE php_output_get_length(zval *z)
392  * Get the length of the active output handlers buffer */
php_output_get_length(zval * p)393 PHPAPI int php_output_get_length(zval *p)
394 {
395 	if (OG(active)) {
396 		ZVAL_LONG(p, OG(active)->buffer.used);
397 		return SUCCESS;
398 	} else {
399 		ZVAL_NULL(p);
400 		return FAILURE;
401 	}
402 }
403 /* }}} */
404 
405 /* {{{ php_output_handler* php_output_get_active_handler(void)
406  * Get active output handler */
php_output_get_active_handler(void)407 PHPAPI php_output_handler* php_output_get_active_handler(void)
408 {
409 	return OG(active);
410 }
411 /* }}} */
412 
413 /* {{{ SUCCESS|FAILURE php_output_handler_start_default(void)
414  * Start a "default output handler" */
php_output_start_default(void)415 PHPAPI int php_output_start_default(void)
416 {
417 	php_output_handler *handler;
418 
419 	handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, 0, PHP_OUTPUT_HANDLER_STDFLAGS);
420 	if (SUCCESS == php_output_handler_start(handler)) {
421 		return SUCCESS;
422 	}
423 	php_output_handler_free(&handler);
424 	return FAILURE;
425 }
426 /* }}} */
427 
428 /* {{{ SUCCESS|FAILURE php_output_handler_start_devnull(void)
429  * Start a "null output handler" */
php_output_start_devnull(void)430 PHPAPI int php_output_start_devnull(void)
431 {
432 	php_output_handler *handler;
433 
434 	handler = php_output_handler_create_internal(ZEND_STRL(php_output_devnull_handler_name), php_output_handler_devnull_func, PHP_OUTPUT_HANDLER_DEFAULT_SIZE, 0);
435 	if (SUCCESS == php_output_handler_start(handler)) {
436 		return SUCCESS;
437 	}
438 	php_output_handler_free(&handler);
439 	return FAILURE;
440 }
441 /* }}} */
442 
443 /* {{{ SUCCESS|FAILURE php_output_start_user(zval *handler, size_t chunk_size, int flags)
444  * Start a user level output handler */
php_output_start_user(zval * output_handler,size_t chunk_size,int flags)445 PHPAPI int php_output_start_user(zval *output_handler, size_t chunk_size, int flags)
446 {
447 	php_output_handler *handler;
448 
449 	if (output_handler) {
450 		handler = php_output_handler_create_user(output_handler, chunk_size, flags);
451 	} else {
452 		handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags);
453 	}
454 	if (SUCCESS == php_output_handler_start(handler)) {
455 		return SUCCESS;
456 	}
457 	php_output_handler_free(&handler);
458 	return FAILURE;
459 }
460 /* }}} */
461 
462 /* {{{ SUCCESS|FAILURE php_output_start_internal(zval *name, php_output_handler_func_t handler, size_t chunk_size, int flags)
463  * 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)464 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)
465 {
466 	php_output_handler *handler;
467 
468 	handler = php_output_handler_create_internal(name, name_len, php_output_handler_compat_func, chunk_size, flags);
469 	php_output_handler_set_context(handler, output_handler, NULL);
470 	if (SUCCESS == php_output_handler_start(handler)) {
471 		return SUCCESS;
472 	}
473 	php_output_handler_free(&handler);
474 	return FAILURE;
475 }
476 /* }}} */
477 
478 /* {{{ php_output_handler *php_output_handler_create_user(zval *handler, size_t chunk_size, int flags)
479  * Create a user level output handler */
php_output_handler_create_user(zval * output_handler,size_t chunk_size,int flags)480 PHPAPI php_output_handler *php_output_handler_create_user(zval *output_handler, size_t chunk_size, int flags)
481 {
482 	zend_string *handler_name = NULL;
483 	char *error = NULL;
484 	php_output_handler *handler = NULL;
485 	php_output_handler_alias_ctor_t alias = NULL;
486 	php_output_handler_user_func_t *user = NULL;
487 
488 	switch (Z_TYPE_P(output_handler)) {
489 		case IS_NULL:
490 			handler = php_output_handler_create_internal(ZEND_STRL(php_output_default_handler_name), php_output_handler_default_func, chunk_size, flags);
491 			break;
492 		case IS_STRING:
493 			if (Z_STRLEN_P(output_handler) && (alias = php_output_handler_alias(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler)))) {
494 				handler = alias(Z_STRVAL_P(output_handler), Z_STRLEN_P(output_handler), chunk_size, flags);
495 				break;
496 			}
497 			ZEND_FALLTHROUGH;
498 		default:
499 			user = ecalloc(1, sizeof(php_output_handler_user_func_t));
500 			if (SUCCESS == zend_fcall_info_init(output_handler, 0, &user->fci, &user->fcc, &handler_name, &error)) {
501 				handler = php_output_handler_init(handler_name, chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_USER);
502 				ZVAL_COPY(&user->zoh, output_handler);
503 				handler->func.user = user;
504 			} else {
505 				efree(user);
506 			}
507 			if (error) {
508 				php_error_docref("ref.outcontrol", E_WARNING, "%s", error);
509 				efree(error);
510 			}
511 			if (handler_name) {
512 				zend_string_release_ex(handler_name, 0);
513 			}
514 	}
515 
516 	return handler;
517 }
518 /* }}} */
519 
520 /* {{{ php_output_handler *php_output_handler_create_internal(zval *name, php_output_handler_context_func_t handler, size_t chunk_size, int flags)
521  * 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)522 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)
523 {
524 	php_output_handler *handler;
525 	zend_string *str = zend_string_init(name, name_len, 0);
526 
527 	handler = php_output_handler_init(str, chunk_size, (flags & ~0xf) | PHP_OUTPUT_HANDLER_INTERNAL);
528 	handler->func.internal = output_handler;
529 	zend_string_release_ex(str, 0);
530 
531 	return handler;
532 }
533 /* }}} */
534 
535 /* {{{ void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void*))
536  * 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 *))537 PHPAPI void php_output_handler_set_context(php_output_handler *handler, void *opaq, void (*dtor)(void*))
538 {
539 	if (handler->dtor && handler->opaq) {
540 		handler->dtor(handler->opaq);
541 	}
542 	handler->dtor = dtor;
543 	handler->opaq = opaq;
544 }
545 /* }}} */
546 
547 /* {{{ SUCCESS|FAILURE php_output_handler_start(php_output_handler *handler)
548  * 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)549 PHPAPI int php_output_handler_start(php_output_handler *handler)
550 {
551 	HashTable *rconflicts;
552 	php_output_handler_conflict_check_t conflict;
553 
554 	if (php_output_lock_error(PHP_OUTPUT_HANDLER_START) || !handler) {
555 		return FAILURE;
556 	}
557 	if (NULL != (conflict = zend_hash_find_ptr(&php_output_handler_conflicts, handler->name))) {
558 		if (SUCCESS != conflict(ZSTR_VAL(handler->name), ZSTR_LEN(handler->name))) {
559 			return FAILURE;
560 		}
561 	}
562 	if (NULL != (rconflicts = zend_hash_find_ptr(&php_output_handler_reverse_conflicts, handler->name))) {
563 		ZEND_HASH_PACKED_FOREACH_PTR(rconflicts, conflict) {
564 			if (SUCCESS != conflict(ZSTR_VAL(handler->name), ZSTR_LEN(handler->name))) {
565 				return FAILURE;
566 			}
567 		} ZEND_HASH_FOREACH_END();
568 	}
569 	/* zend_stack_push returns stack level */
570 	handler->level = zend_stack_push(&OG(handlers), &handler);
571 	OG(active) = handler;
572 	return SUCCESS;
573 }
574 /* }}} */
575 
576 /* {{{ int php_output_handler_started(zval *name)
577  * Check whether a certain output handler is in use */
php_output_handler_started(const char * name,size_t name_len)578 PHPAPI int php_output_handler_started(const char *name, size_t name_len)
579 {
580 	php_output_handler **handlers;
581 	int i, count = php_output_get_level();
582 
583 	if (count) {
584 		handlers = (php_output_handler **) zend_stack_base(&OG(handlers));
585 
586 		for (i = 0; i < count; ++i) {
587 			if (zend_string_equals_cstr(handlers[i]->name, name, name_len)) {
588 				return 1;
589 			}
590 		}
591 	}
592 
593 	return 0;
594 }
595 /* }}} */
596 
597 /* {{{ int php_output_handler_conflict(zval *handler_new, zval *handler_old)
598  * 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)599 PHPAPI int php_output_handler_conflict(const char *handler_new, size_t handler_new_len, const char *handler_set, size_t handler_set_len)
600 {
601 	if (php_output_handler_started(handler_set, handler_set_len)) {
602 		if (handler_new_len != handler_set_len || memcmp(handler_new, handler_set, handler_set_len)) {
603 			php_error_docref("ref.outcontrol", E_WARNING, "Output handler '%s' conflicts with '%s'", handler_new, handler_set);
604 		} else {
605 			php_error_docref("ref.outcontrol", E_WARNING, "Output handler '%s' cannot be used twice", handler_new);
606 		}
607 		return 1;
608 	}
609 	return 0;
610 }
611 /* }}} */
612 
613 /* {{{ SUCCESS|FAILURE php_output_handler_conflict_register(zval *name, php_output_handler_conflict_check_t check_func)
614  * 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)615 PHPAPI int php_output_handler_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func)
616 {
617 	zend_string *str;
618 
619 	if (!EG(current_module)) {
620 		zend_error(E_ERROR, "Cannot register an output handler conflict outside of MINIT");
621 		return FAILURE;
622 	}
623 	str = zend_string_init_interned(name, name_len, 1);
624 	zend_hash_update_ptr(&php_output_handler_conflicts, str, check_func);
625 	zend_string_release_ex(str, 1);
626 	return SUCCESS;
627 }
628 /* }}} */
629 
630 /* {{{ SUCCESS|FAILURE php_output_handler_reverse_conflict_register(zval *name, php_output_handler_conflict_check_t check_func)
631  * 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)632 PHPAPI int php_output_handler_reverse_conflict_register(const char *name, size_t name_len, php_output_handler_conflict_check_t check_func)
633 {
634 	HashTable rev, *rev_ptr = NULL;
635 
636 	if (!EG(current_module)) {
637 		zend_error(E_ERROR, "Cannot register a reverse output handler conflict outside of MINIT");
638 		return FAILURE;
639 	}
640 
641 	if (NULL != (rev_ptr = zend_hash_str_find_ptr(&php_output_handler_reverse_conflicts, name, name_len))) {
642 		return zend_hash_next_index_insert_ptr(rev_ptr, check_func) ? SUCCESS : FAILURE;
643 	} else {
644 		zend_string *str;
645 
646 		zend_hash_init(&rev, 8, NULL, NULL, 1);
647 		if (NULL == zend_hash_next_index_insert_ptr(&rev, check_func)) {
648 			zend_hash_destroy(&rev);
649 			return FAILURE;
650 		}
651 		str = zend_string_init_interned(name, name_len, 1);
652 		zend_hash_update_mem(&php_output_handler_reverse_conflicts, str, &rev, sizeof(HashTable));
653 		zend_string_release_ex(str, 1);
654 		return SUCCESS;
655 	}
656 }
657 /* }}} */
658 
659 /* {{{ php_output_handler_alias_ctor_t php_output_handler_alias(zval *name)
660  * Get an internal output handler for a user handler if it exists */
php_output_handler_alias(const char * name,size_t name_len)661 PHPAPI php_output_handler_alias_ctor_t php_output_handler_alias(const char *name, size_t name_len)
662 {
663 	return zend_hash_str_find_ptr(&php_output_handler_aliases, name, name_len);
664 }
665 /* }}} */
666 
667 /* {{{ SUCCESS|FAILURE php_output_handler_alias_register(zval *name, php_output_handler_alias_ctor_t func)
668  * 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)669 PHPAPI int php_output_handler_alias_register(const char *name, size_t name_len, php_output_handler_alias_ctor_t func)
670 {
671 	zend_string *str;
672 
673 	if (!EG(current_module)) {
674 		zend_error(E_ERROR, "Cannot register an output handler alias outside of MINIT");
675 		return FAILURE;
676 	}
677 	str = zend_string_init_interned(name, name_len, 1);
678 	zend_hash_update_ptr(&php_output_handler_aliases, str, func);
679 	zend_string_release_ex(str, 1);
680 	return SUCCESS;
681 }
682 /* }}} */
683 
684 /* {{{ SUCCESS|FAILURE php_output_handler_hook(php_output_handler_hook_t type, void *arg)
685  * 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)686 PHPAPI int php_output_handler_hook(php_output_handler_hook_t type, void *arg)
687 {
688 	if (OG(running)) {
689 		switch (type) {
690 			case PHP_OUTPUT_HANDLER_HOOK_GET_OPAQ:
691 				*(void ***) arg = &OG(running)->opaq;
692 				return SUCCESS;
693 			case PHP_OUTPUT_HANDLER_HOOK_GET_FLAGS:
694 				*(int *) arg = OG(running)->flags;
695 				return SUCCESS;
696 			case PHP_OUTPUT_HANDLER_HOOK_GET_LEVEL:
697 				*(int *) arg = OG(running)->level;
698 				return SUCCESS;
699 			case PHP_OUTPUT_HANDLER_HOOK_IMMUTABLE:
700 				OG(running)->flags &= ~(PHP_OUTPUT_HANDLER_REMOVABLE|PHP_OUTPUT_HANDLER_CLEANABLE);
701 				return SUCCESS;
702 			case PHP_OUTPUT_HANDLER_HOOK_DISABLE:
703 				OG(running)->flags |= PHP_OUTPUT_HANDLER_DISABLED;
704 				return SUCCESS;
705 			default:
706 				break;
707 		}
708 	}
709 	return FAILURE;
710 }
711 /* }}} */
712 
713 /* {{{ void php_output_handler_dtor(php_output_handler *handler)
714  * Destroy an output handler */
php_output_handler_dtor(php_output_handler * handler)715 PHPAPI void php_output_handler_dtor(php_output_handler *handler)
716 {
717 	if (handler->name) {
718 		zend_string_release_ex(handler->name, 0);
719 	}
720 	if (handler->buffer.data) {
721 		efree(handler->buffer.data);
722 	}
723 	if (handler->flags & PHP_OUTPUT_HANDLER_USER) {
724 		zval_ptr_dtor(&handler->func.user->zoh);
725 		efree(handler->func.user);
726 	}
727 	if (handler->dtor && handler->opaq) {
728 		handler->dtor(handler->opaq);
729 	}
730 	memset(handler, 0, sizeof(*handler));
731 }
732 /* }}} */
733 
734 /* {{{ void php_output_handler_free(php_output_handler **handler)
735  * Destroy and free an output handler */
php_output_handler_free(php_output_handler ** h)736 PHPAPI void php_output_handler_free(php_output_handler **h)
737 {
738 	if (*h) {
739 		php_output_handler_dtor(*h);
740 		efree(*h);
741 		*h = NULL;
742 	}
743 }
744 /* }}} */
745 
746 /* void php_output_set_implicit_flush(int enabled)
747  * Enable or disable implicit flush */
php_output_set_implicit_flush(int flush)748 PHPAPI void php_output_set_implicit_flush(int flush)
749 {
750 	if (flush) {
751 		OG(flags) |= PHP_OUTPUT_IMPLICITFLUSH;
752 	} else {
753 		OG(flags) &= ~PHP_OUTPUT_IMPLICITFLUSH;
754 	}
755 }
756 /* }}} */
757 
758 /* {{{ char *php_output_get_start_filename(void)
759  * Get the file name where output has started */
php_output_get_start_filename(void)760 PHPAPI const char *php_output_get_start_filename(void)
761 {
762 	return OG(output_start_filename) ? ZSTR_VAL(OG(output_start_filename)) : NULL;
763 }
764 /* }}} */
765 
766 /* {{{ int php_output_get_start_lineno(void)
767  * Get the line number where output has started */
php_output_get_start_lineno(void)768 PHPAPI int php_output_get_start_lineno(void)
769 {
770 	return OG(output_start_lineno);
771 }
772 /* }}} */
773 
774 /* {{{ static int php_output_lock_error(int op)
775  * Checks whether an unallowed operation is attempted from within the output handler and issues a fatal error */
php_output_lock_error(int op)776 static inline int php_output_lock_error(int op)
777 {
778 	/* if there's no ob active, ob has been stopped */
779 	if (op && OG(active) && OG(running)) {
780 		/* fatal error */
781 		php_output_deactivate();
782 		php_error_docref("ref.outcontrol", E_ERROR, "Cannot use output buffering in output buffering display handlers");
783 		return 1;
784 	}
785 	return 0;
786 }
787 /* }}} */
788 
789 /* {{{ static php_output_context *php_output_context_init(php_output_context *context, int op)
790  * Initialize a new output context */
php_output_context_init(php_output_context * context,int op)791 static inline void php_output_context_init(php_output_context *context, int op)
792 {
793 	memset(context, 0, sizeof(php_output_context));
794 	context->op = op;
795 }
796 /* }}} */
797 
798 /* {{{ static void php_output_context_reset(php_output_context *context)
799  * Reset an output context */
php_output_context_reset(php_output_context * context)800 static inline void php_output_context_reset(php_output_context *context)
801 {
802 	int op = context->op;
803 	php_output_context_dtor(context);
804 	memset(context, 0, sizeof(php_output_context));
805 	context->op = op;
806 }
807 /* }}} */
808 
809 /* {{{ static void php_output_context_feed(php_output_context *context, char *, size_t, size_t)
810  * Feed output contexts input buffer */
php_output_context_feed(php_output_context * context,char * data,size_t size,size_t used,bool free)811 static inline void php_output_context_feed(php_output_context *context, char *data, size_t size, size_t used, bool free)
812 {
813 	if (context->in.free && context->in.data) {
814 		efree(context->in.data);
815 	}
816 	context->in.data = data;
817 	context->in.used = used;
818 	context->in.free = free;
819 	context->in.size = size;
820 }
821 /* }}} */
822 
823 /* {{{ static void php_output_context_swap(php_output_context *context)
824  * Swap output contexts buffers */
php_output_context_swap(php_output_context * context)825 static inline void php_output_context_swap(php_output_context *context)
826 {
827 	if (context->in.free && context->in.data) {
828 		efree(context->in.data);
829 	}
830 	context->in.data = context->out.data;
831 	context->in.used = context->out.used;
832 	context->in.free = context->out.free;
833 	context->in.size = context->out.size;
834 	context->out.data = NULL;
835 	context->out.used = 0;
836 	context->out.free = 0;
837 	context->out.size = 0;
838 }
839 /* }}} */
840 
841 /* {{{ static void php_output_context_pass(php_output_context *context)
842  * Pass input to output buffer */
php_output_context_pass(php_output_context * context)843 static inline void php_output_context_pass(php_output_context *context)
844 {
845 	context->out.data = context->in.data;
846 	context->out.used = context->in.used;
847 	context->out.size = context->in.size;
848 	context->out.free = context->in.free;
849 	context->in.data = NULL;
850 	context->in.used = 0;
851 	context->in.free = 0;
852 	context->in.size = 0;
853 }
854 /* }}} */
855 
856 /* {{{ static void php_output_context_dtor(php_output_context *context)
857  * Destroy the contents of an output context */
php_output_context_dtor(php_output_context * context)858 static inline void php_output_context_dtor(php_output_context *context)
859 {
860 	if (context->in.free && context->in.data) {
861 		efree(context->in.data);
862 		context->in.data = NULL;
863 	}
864 	if (context->out.free && context->out.data) {
865 		efree(context->out.data);
866 		context->out.data = NULL;
867 	}
868 }
869 /* }}} */
870 
871 /* {{{ static php_output_handler *php_output_handler_init(zval *name, size_t chunk_size, int flags)
872  * Allocates and initializes a php_output_handler structure */
php_output_handler_init(zend_string * name,size_t chunk_size,int flags)873 static inline php_output_handler *php_output_handler_init(zend_string *name, size_t chunk_size, int flags)
874 {
875 	php_output_handler *handler;
876 
877 	handler = ecalloc(1, sizeof(php_output_handler));
878 	handler->name = zend_string_copy(name);
879 	handler->size = chunk_size;
880 	handler->flags = flags;
881 	handler->buffer.size = PHP_OUTPUT_HANDLER_INITBUF_SIZE(chunk_size);
882 	handler->buffer.data = emalloc(handler->buffer.size);
883 
884 	return handler;
885 }
886 /* }}} */
887 
888 /* {{{ static int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf)
889  * 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)890 static inline int php_output_handler_append(php_output_handler *handler, const php_output_buffer *buf)
891 {
892 	if (buf->used) {
893 		OG(flags) |= PHP_OUTPUT_WRITTEN;
894 		/* store it away */
895 		if ((handler->buffer.size - handler->buffer.used) <= buf->used) {
896 			size_t grow_int = PHP_OUTPUT_HANDLER_INITBUF_SIZE(handler->size);
897 			size_t grow_buf = PHP_OUTPUT_HANDLER_INITBUF_SIZE(buf->used - (handler->buffer.size - handler->buffer.used));
898 			size_t grow_max = MAX(grow_int, grow_buf);
899 
900 			handler->buffer.data = safe_erealloc(handler->buffer.data, 1, handler->buffer.size, grow_max);
901 			handler->buffer.size += grow_max;
902 		}
903 		memcpy(handler->buffer.data + handler->buffer.used, buf->data, buf->used);
904 		handler->buffer.used += buf->used;
905 
906 		/* chunked buffering */
907 		if (handler->size && (handler->buffer.used >= handler->size)) {
908 			/* store away errors and/or any intermediate output */
909 			return OG(running) ? 1 : 0;
910 		}
911 	}
912 	return 1;
913 }
914 /* }}} */
915 
916 /* {{{ static php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context)
917  * 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)918 static inline php_output_handler_status_t php_output_handler_op(php_output_handler *handler, php_output_context *context)
919 {
920 	php_output_handler_status_t status;
921 	int original_op = context->op;
922 
923 #if PHP_OUTPUT_DEBUG
924 	fprintf(stderr, ">>> op(%d, "
925 					"handler=%p, "
926 					"name=%s, "
927 					"flags=%d, "
928 					"buffer.data=%s, "
929 					"buffer.used=%zu, "
930 					"buffer.size=%zu, "
931 					"in.data=%s, "
932 					"in.used=%zu)\n",
933 			context->op,
934 			handler,
935 			handler->name,
936 			handler->flags,
937 			handler->buffer.used?handler->buffer.data:"",
938 			handler->buffer.used,
939 			handler->buffer.size,
940 			context->in.used?context->in.data:"",
941 			context->in.used
942 	);
943 #endif
944 
945 	if (php_output_lock_error(context->op)) {
946 		/* fatal error */
947 		return PHP_OUTPUT_HANDLER_FAILURE;
948 	}
949 
950 	/* storable? */
951 	if (php_output_handler_append(handler, &context->in) && !context->op) {
952 		context->op = original_op;
953 		return PHP_OUTPUT_HANDLER_NO_DATA;
954 	} else {
955 		/* need to start? */
956 		if (!(handler->flags & PHP_OUTPUT_HANDLER_STARTED)) {
957 			context->op |= PHP_OUTPUT_HANDLER_START;
958 		}
959 
960 		OG(running) = handler;
961 		if (handler->flags & PHP_OUTPUT_HANDLER_USER) {
962 			zval retval, ob_data, ob_mode;
963 
964 			ZVAL_STRINGL(&ob_data, handler->buffer.data, handler->buffer.used);
965 			ZVAL_LONG(&ob_mode, (zend_long) context->op);
966 			zend_fcall_info_argn(&handler->func.user->fci, 2, &ob_data, &ob_mode);
967 			zval_ptr_dtor(&ob_data);
968 
969 #define PHP_OUTPUT_USER_SUCCESS(retval) ((Z_TYPE(retval) != IS_UNDEF) && !(Z_TYPE(retval) == IS_FALSE))
970 			if (SUCCESS == zend_fcall_info_call(&handler->func.user->fci, &handler->func.user->fcc, &retval, NULL) && PHP_OUTPUT_USER_SUCCESS(retval)) {
971 				/* user handler may have returned TRUE */
972 				status = PHP_OUTPUT_HANDLER_NO_DATA;
973 				if (Z_TYPE(retval) != IS_FALSE && Z_TYPE(retval) != IS_TRUE) {
974 					convert_to_string(&retval);
975 					if (Z_STRLEN(retval)) {
976 						context->out.data = estrndup(Z_STRVAL(retval), Z_STRLEN(retval));
977 						context->out.used = Z_STRLEN(retval);
978 						context->out.free = 1;
979 						status = PHP_OUTPUT_HANDLER_SUCCESS;
980 					}
981 				}
982 			} else {
983 				/* call failed, pass internal buffer along */
984 				status = PHP_OUTPUT_HANDLER_FAILURE;
985 			}
986 
987 			zend_fcall_info_argn(&handler->func.user->fci, 0);
988 			zval_ptr_dtor(&retval);
989 
990 		} else {
991 
992 			php_output_context_feed(context, handler->buffer.data, handler->buffer.size, handler->buffer.used, 0);
993 
994 			if (SUCCESS == handler->func.internal(&handler->opaq, context)) {
995 				if (context->out.used) {
996 					status = PHP_OUTPUT_HANDLER_SUCCESS;
997 				} else {
998 					status = PHP_OUTPUT_HANDLER_NO_DATA;
999 				}
1000 			} else {
1001 				status = PHP_OUTPUT_HANDLER_FAILURE;
1002 			}
1003 		}
1004 		handler->flags |= PHP_OUTPUT_HANDLER_STARTED;
1005 		OG(running) = NULL;
1006 	}
1007 
1008 	switch (status) {
1009 		case PHP_OUTPUT_HANDLER_FAILURE:
1010 			/* disable this handler */
1011 			handler->flags |= PHP_OUTPUT_HANDLER_DISABLED;
1012 			/* discard any output */
1013 			if (context->out.data && context->out.free) {
1014 				efree(context->out.data);
1015 			}
1016 			/* returns handlers buffer */
1017 			context->out.data = handler->buffer.data;
1018 			context->out.used = handler->buffer.used;
1019 			context->out.free = 1;
1020 			handler->buffer.data = NULL;
1021 			handler->buffer.used = 0;
1022 			handler->buffer.size = 0;
1023 			break;
1024 		case PHP_OUTPUT_HANDLER_NO_DATA:
1025 			/* handler ate all */
1026 			php_output_context_reset(context);
1027 			ZEND_FALLTHROUGH;
1028 		case PHP_OUTPUT_HANDLER_SUCCESS:
1029 			/* no more buffered data */
1030 			handler->buffer.used = 0;
1031 			handler->flags |= PHP_OUTPUT_HANDLER_PROCESSED;
1032 			break;
1033 	}
1034 
1035 	context->op = original_op;
1036 	return status;
1037 }
1038 /* }}} */
1039 
1040 
1041 /* {{{ static void php_output_op(int op, const char *str, size_t len)
1042  * 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)1043 static inline void php_output_op(int op, const char *str, size_t len)
1044 {
1045 	php_output_context context;
1046 	php_output_handler **active;
1047 	int obh_cnt;
1048 
1049 	if (php_output_lock_error(op)) {
1050 		return;
1051 	}
1052 
1053 	php_output_context_init(&context, op);
1054 
1055 	/*
1056 	 * broken up for better performance:
1057 	 *  - apply op to the one active handler; note that OG(active) might be popped off the stack on a flush
1058 	 *  - or apply op to the handler stack
1059 	 */
1060 	if (OG(active) && (obh_cnt = zend_stack_count(&OG(handlers)))) {
1061 		context.in.data = (char *) str;
1062 		context.in.used = len;
1063 
1064 		if (obh_cnt > 1) {
1065 			zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_op, &context);
1066 		} else if ((active = zend_stack_top(&OG(handlers))) && (!((*active)->flags & PHP_OUTPUT_HANDLER_DISABLED))) {
1067 			php_output_handler_op(*active, &context);
1068 		} else {
1069 			php_output_context_pass(&context);
1070 		}
1071 	} else {
1072 		context.out.data = (char *) str;
1073 		context.out.used = len;
1074 	}
1075 
1076 	if (context.out.data && context.out.used) {
1077 		php_output_header();
1078 
1079 		if (!(OG(flags) & PHP_OUTPUT_DISABLED)) {
1080 #if PHP_OUTPUT_DEBUG
1081 			fprintf(stderr, "::: sapi_write('%s', %zu)\n", context.out.data, context.out.used);
1082 #endif
1083 			sapi_module.ub_write(context.out.data, context.out.used);
1084 
1085 			if (OG(flags) & PHP_OUTPUT_IMPLICITFLUSH) {
1086 				sapi_flush();
1087 			}
1088 
1089 			OG(flags) |= PHP_OUTPUT_SENT;
1090 		}
1091 	}
1092 	php_output_context_dtor(&context);
1093 }
1094 /* }}} */
1095 
1096 /* {{{ static int php_output_stack_apply_op(void *h, void *c)
1097  * Operation callback for the stack apply function */
php_output_stack_apply_op(void * h,void * c)1098 static int php_output_stack_apply_op(void *h, void *c)
1099 {
1100 	int was_disabled;
1101 	php_output_handler_status_t status;
1102 	php_output_handler *handler = *(php_output_handler **) h;
1103 	php_output_context *context = (php_output_context *) c;
1104 
1105 	if ((was_disabled = (handler->flags & PHP_OUTPUT_HANDLER_DISABLED))) {
1106 		status = PHP_OUTPUT_HANDLER_FAILURE;
1107 	} else {
1108 		status = php_output_handler_op(handler, context);
1109 	}
1110 
1111 	/*
1112 	 * handler ate all => break
1113 	 * handler returned data or failed resp. is disabled => continue
1114 	 */
1115 	switch (status) {
1116 		case PHP_OUTPUT_HANDLER_NO_DATA:
1117 			return 1;
1118 
1119 		case PHP_OUTPUT_HANDLER_SUCCESS:
1120 			/* swap contexts buffers, unless this is the last handler in the stack */
1121 			if (handler->level) {
1122 				php_output_context_swap(context);
1123 			}
1124 			return 0;
1125 
1126 		case PHP_OUTPUT_HANDLER_FAILURE:
1127 		default:
1128 			if (was_disabled) {
1129 				/* pass input along, if it's the last handler in the stack */
1130 				if (!handler->level) {
1131 					php_output_context_pass(context);
1132 				}
1133 			} else {
1134 				/* swap buffers, unless this is the last handler */
1135 				if (handler->level) {
1136 					php_output_context_swap(context);
1137 				}
1138 			}
1139 			return 0;
1140 	}
1141 }
1142 /* }}} */
1143 
1144 /* {{{ static int php_output_stack_apply_clean(void *h, void *c)
1145  * Clean callback for the stack apply function */
php_output_stack_apply_clean(void * h,void * c)1146 static int php_output_stack_apply_clean(void *h, void *c)
1147 {
1148 	php_output_handler *handler = *(php_output_handler **) h;
1149 	php_output_context *context = (php_output_context *) c;
1150 
1151 	handler->buffer.used = 0;
1152 	php_output_handler_op(handler, context);
1153 	php_output_context_reset(context);
1154 	return 0;
1155 }
1156 /* }}} */
1157 
1158 /* {{{ static int php_output_stack_apply_list(void *h, void *z)
1159  * List callback for the stack apply function */
php_output_stack_apply_list(void * h,void * z)1160 static int php_output_stack_apply_list(void *h, void *z)
1161 {
1162 	php_output_handler *handler = *(php_output_handler **) h;
1163 	zval *array = (zval *) z;
1164 
1165 	add_next_index_str(array, zend_string_copy(handler->name));
1166 	return 0;
1167 }
1168 /* }}} */
1169 
1170 /* {{{ static int php_output_stack_apply_status(void *h, void *z)
1171  * Status callback for the stack apply function */
php_output_stack_apply_status(void * h,void * z)1172 static int php_output_stack_apply_status(void *h, void *z)
1173 {
1174 	php_output_handler *handler = *(php_output_handler **) h;
1175 	zval arr, *array = (zval *) z;
1176 
1177 	add_next_index_zval(array, php_output_handler_status(handler, &arr));
1178 
1179 	return 0;
1180 }
1181 
1182 /* {{{ static zval *php_output_handler_status(php_output_handler *handler, zval *entry)
1183  * Returns an array with the status of the output handler */
php_output_handler_status(php_output_handler * handler,zval * entry)1184 static inline zval *php_output_handler_status(php_output_handler *handler, zval *entry)
1185 {
1186 	ZEND_ASSERT(entry != NULL);
1187 
1188 	array_init(entry);
1189 	add_assoc_str(entry, "name", zend_string_copy(handler->name));
1190 	add_assoc_long(entry, "type", (zend_long) (handler->flags & 0xf));
1191 	add_assoc_long(entry, "flags", (zend_long) handler->flags);
1192 	add_assoc_long(entry, "level", (zend_long) handler->level);
1193 	add_assoc_long(entry, "chunk_size", (zend_long) handler->size);
1194 	add_assoc_long(entry, "buffer_size", (zend_long) handler->buffer.size);
1195 	add_assoc_long(entry, "buffer_used", (zend_long) handler->buffer.used);
1196 
1197 	return entry;
1198 }
1199 /* }}} */
1200 
1201 /* {{{ static int php_output_stack_pop(int flags)
1202  * Pops an output handler off the stack */
php_output_stack_pop(int flags)1203 static int php_output_stack_pop(int flags)
1204 {
1205 	php_output_context context;
1206 	php_output_handler **current, *orphan = OG(active);
1207 
1208 	if (!orphan) {
1209 		if (!(flags & PHP_OUTPUT_POP_SILENT)) {
1210 			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");
1211 		}
1212 		return 0;
1213 	} else if (!(flags & PHP_OUTPUT_POP_FORCE) && !(orphan->flags & PHP_OUTPUT_HANDLER_REMOVABLE)) {
1214 		if (!(flags & PHP_OUTPUT_POP_SILENT)) {
1215 			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);
1216 		}
1217 		return 0;
1218 	} else {
1219 		php_output_context_init(&context, PHP_OUTPUT_HANDLER_FINAL);
1220 
1221 		/* don't run the output handler if it's disabled */
1222 		if (!(orphan->flags & PHP_OUTPUT_HANDLER_DISABLED)) {
1223 			/* didn't it start yet? */
1224 			if (!(orphan->flags & PHP_OUTPUT_HANDLER_STARTED)) {
1225 				context.op |= PHP_OUTPUT_HANDLER_START;
1226 			}
1227 			/* signal that we're cleaning up */
1228 			if (flags & PHP_OUTPUT_POP_DISCARD) {
1229 				context.op |= PHP_OUTPUT_HANDLER_CLEAN;
1230 			}
1231 			php_output_handler_op(orphan, &context);
1232 		}
1233 
1234 		/* pop it off the stack */
1235 		zend_stack_del_top(&OG(handlers));
1236 		if ((current = zend_stack_top(&OG(handlers)))) {
1237 			OG(active) = *current;
1238 		} else {
1239 			OG(active) = NULL;
1240 		}
1241 
1242 		/* pass output along */
1243 		if (context.out.data && context.out.used && !(flags & PHP_OUTPUT_POP_DISCARD)) {
1244 			php_output_write(context.out.data, context.out.used);
1245 		}
1246 
1247 		/* destroy the handler (after write!) */
1248 		php_output_handler_free(&orphan);
1249 		php_output_context_dtor(&context);
1250 
1251 		return 1;
1252 	}
1253 }
1254 /* }}} */
1255 
1256 /* {{{ static SUCCESS|FAILURE php_output_handler_compat_func(void *ctx, php_output_context *)
1257  * 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)1258 static int php_output_handler_compat_func(void **handler_context, php_output_context *output_context)
1259 {
1260 	php_output_handler_func_t func = *(php_output_handler_func_t *) handler_context;
1261 
1262 	if (func) {
1263 		char *out_str = NULL;
1264 		size_t out_len = 0;
1265 
1266 		func(output_context->in.data, output_context->in.used, &out_str, &out_len, output_context->op);
1267 
1268 		if (out_str) {
1269 			output_context->out.data = out_str;
1270 			output_context->out.used = out_len;
1271 			output_context->out.free = 1;
1272 		} else {
1273 			php_output_context_pass(output_context);
1274 		}
1275 
1276 		return SUCCESS;
1277 	}
1278 	return FAILURE;
1279 }
1280 /* }}} */
1281 
1282 /* {{{ static SUCCESS|FAILURE php_output_handler_default_func(void *ctx, php_output_context *)
1283  * Default output handler */
php_output_handler_default_func(void ** handler_context,php_output_context * output_context)1284 static int php_output_handler_default_func(void **handler_context, php_output_context *output_context)
1285 {
1286 	php_output_context_pass(output_context);
1287 	return SUCCESS;
1288 }
1289 /* }}} */
1290 
1291 /* {{{ static SUCCESS|FAILURE php_output_handler_devnull_func(void *ctx, php_output_context *)
1292  * Null output handler */
php_output_handler_devnull_func(void ** handler_context,php_output_context * output_context)1293 static int php_output_handler_devnull_func(void **handler_context, php_output_context *output_context)
1294 {
1295 	return SUCCESS;
1296 }
1297 /* }}} */
1298 
1299 /*
1300  * USERLAND (nearly 1:1 of old output.c)
1301  */
1302 
1303 /* {{{ Turn on Output Buffering (specifying an optional output handler). */
PHP_FUNCTION(ob_start)1304 PHP_FUNCTION(ob_start)
1305 {
1306 	zval *output_handler = NULL;
1307 	zend_long chunk_size = 0;
1308 	zend_long flags = PHP_OUTPUT_HANDLER_STDFLAGS;
1309 
1310 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|zll", &output_handler, &chunk_size, &flags) == FAILURE) {
1311 		RETURN_THROWS();
1312 	}
1313 
1314 	if (chunk_size < 0) {
1315 		chunk_size = 0;
1316 	}
1317 
1318 	if (php_output_start_user(output_handler, chunk_size, flags) == FAILURE) {
1319 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to create buffer");
1320 		RETURN_FALSE;
1321 	}
1322 	RETURN_TRUE;
1323 }
1324 /* }}} */
1325 
1326 /* {{{ Flush (send) contents of the output buffer. The last buffer content is sent to next buffer */
PHP_FUNCTION(ob_flush)1327 PHP_FUNCTION(ob_flush)
1328 {
1329 	if (zend_parse_parameters_none() == FAILURE) {
1330 		RETURN_THROWS();
1331 	}
1332 
1333 	if (!OG(active)) {
1334 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to flush buffer. No buffer to flush");
1335 		RETURN_FALSE;
1336 	}
1337 
1338 	if (SUCCESS != php_output_flush()) {
1339 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to flush buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1340 		RETURN_FALSE;
1341 	}
1342 	RETURN_TRUE;
1343 }
1344 /* }}} */
1345 
1346 /* {{{ Clean (delete) the current output buffer */
PHP_FUNCTION(ob_clean)1347 PHP_FUNCTION(ob_clean)
1348 {
1349 	if (zend_parse_parameters_none() == FAILURE) {
1350 		RETURN_THROWS();
1351 	}
1352 
1353 	if (!OG(active)) {
1354 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer. No buffer to delete");
1355 		RETURN_FALSE;
1356 	}
1357 
1358 	if (SUCCESS != php_output_clean()) {
1359 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1360 		RETURN_FALSE;
1361 	}
1362 	RETURN_TRUE;
1363 }
1364 /* }}} */
1365 
1366 /* {{{ Flush (send) the output buffer, and delete current output buffer */
PHP_FUNCTION(ob_end_flush)1367 PHP_FUNCTION(ob_end_flush)
1368 {
1369 	if (zend_parse_parameters_none() == FAILURE) {
1370 		RETURN_THROWS();
1371 	}
1372 
1373 	if (!OG(active)) {
1374 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete and flush buffer. No buffer to delete or flush");
1375 		RETURN_FALSE;
1376 	}
1377 
1378 	RETURN_BOOL(SUCCESS == php_output_end());
1379 }
1380 /* }}} */
1381 
1382 /* {{{ Clean the output buffer, and delete current output buffer */
PHP_FUNCTION(ob_end_clean)1383 PHP_FUNCTION(ob_end_clean)
1384 {
1385 	if (zend_parse_parameters_none() == FAILURE) {
1386 		RETURN_THROWS();
1387 	}
1388 
1389 	if (!OG(active)) {
1390 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer. No buffer to delete");
1391 		RETURN_FALSE;
1392 	}
1393 
1394 	RETURN_BOOL(SUCCESS == php_output_discard());
1395 }
1396 /* }}} */
1397 
1398 /* {{{ Get current buffer contents, flush (send) the output buffer, and delete current output buffer */
PHP_FUNCTION(ob_get_flush)1399 PHP_FUNCTION(ob_get_flush)
1400 {
1401 	if (zend_parse_parameters_none() == FAILURE) {
1402 		RETURN_THROWS();
1403 	}
1404 
1405 	if (php_output_get_contents(return_value) == FAILURE) {
1406 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete and flush buffer. No buffer to delete or flush");
1407 		RETURN_FALSE;
1408 	}
1409 
1410 	if (SUCCESS != php_output_end()) {
1411 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1412 	}
1413 }
1414 /* }}} */
1415 
1416 /* {{{ Get current buffer contents and delete current output buffer */
PHP_FUNCTION(ob_get_clean)1417 PHP_FUNCTION(ob_get_clean)
1418 {
1419 	if (zend_parse_parameters_none() == FAILURE) {
1420 		RETURN_THROWS();
1421 	}
1422 
1423 	if(!OG(active)) {
1424 		RETURN_FALSE;
1425 	}
1426 
1427 	if (php_output_get_contents(return_value) == FAILURE) {
1428 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer. No buffer to delete");
1429 		RETURN_FALSE;
1430 	}
1431 
1432 	if (SUCCESS != php_output_discard()) {
1433 		php_error_docref("ref.outcontrol", E_NOTICE, "Failed to delete buffer of %s (%d)", ZSTR_VAL(OG(active)->name), OG(active)->level);
1434 	}
1435 }
1436 /* }}} */
1437 
1438 /* {{{ Return the contents of the output buffer */
PHP_FUNCTION(ob_get_contents)1439 PHP_FUNCTION(ob_get_contents)
1440 {
1441 	if (zend_parse_parameters_none() == FAILURE) {
1442 		RETURN_THROWS();
1443 	}
1444 
1445 	if (php_output_get_contents(return_value) == FAILURE) {
1446 		RETURN_FALSE;
1447 	}
1448 }
1449 /* }}} */
1450 
1451 /* {{{ Return the nesting level of the output buffer */
PHP_FUNCTION(ob_get_level)1452 PHP_FUNCTION(ob_get_level)
1453 {
1454 	if (zend_parse_parameters_none() == FAILURE) {
1455 		RETURN_THROWS();
1456 	}
1457 
1458 	RETURN_LONG(php_output_get_level());
1459 }
1460 /* }}} */
1461 
1462 /* {{{ Return the length of the output buffer */
PHP_FUNCTION(ob_get_length)1463 PHP_FUNCTION(ob_get_length)
1464 {
1465 	if (zend_parse_parameters_none() == FAILURE) {
1466 		RETURN_THROWS();
1467 	}
1468 
1469 	if (php_output_get_length(return_value) == FAILURE) {
1470 		RETURN_FALSE;
1471 	}
1472 }
1473 /* }}} */
1474 
1475 /* {{{ List all output_buffers in an array */
PHP_FUNCTION(ob_list_handlers)1476 PHP_FUNCTION(ob_list_handlers)
1477 {
1478 	if (zend_parse_parameters_none() == FAILURE) {
1479 		RETURN_THROWS();
1480 	}
1481 
1482 	array_init(return_value);
1483 
1484 	if (!OG(active)) {
1485 		return;
1486 	}
1487 
1488 	zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_list, return_value);
1489 }
1490 /* }}} */
1491 
1492 /* {{{ Return the status of the active or all output buffers */
PHP_FUNCTION(ob_get_status)1493 PHP_FUNCTION(ob_get_status)
1494 {
1495 	bool full_status = 0;
1496 
1497 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &full_status) == FAILURE) {
1498 		RETURN_THROWS();
1499 	}
1500 
1501 	if (!OG(active)) {
1502 		array_init(return_value);
1503 		return;
1504 	}
1505 
1506 	if (full_status) {
1507 		array_init(return_value);
1508 		zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_BOTTOMUP, php_output_stack_apply_status, return_value);
1509 	} else {
1510 		php_output_handler_status(OG(active), return_value);
1511 	}
1512 }
1513 /* }}} */
1514 
1515 /* {{{ Turn implicit flush on/off and is equivalent to calling flush() after every output call */
PHP_FUNCTION(ob_implicit_flush)1516 PHP_FUNCTION(ob_implicit_flush)
1517 {
1518 	zend_long flag = 1;
1519 
1520 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &flag) == FAILURE) {
1521 		RETURN_THROWS();
1522 	}
1523 
1524 	php_output_set_implicit_flush((int) flag);
1525 }
1526 /* }}} */
1527 
1528 /* {{{ Reset(clear) URL rewriter values */
PHP_FUNCTION(output_reset_rewrite_vars)1529 PHP_FUNCTION(output_reset_rewrite_vars)
1530 {
1531 	if (zend_parse_parameters_none() == FAILURE) {
1532 		RETURN_THROWS();
1533 	}
1534 
1535 	if (php_url_scanner_reset_vars() == SUCCESS) {
1536 		RETURN_TRUE;
1537 	} else {
1538 		RETURN_FALSE;
1539 	}
1540 }
1541 /* }}} */
1542 
1543 /* {{{ Add URL rewriter values */
PHP_FUNCTION(output_add_rewrite_var)1544 PHP_FUNCTION(output_add_rewrite_var)
1545 {
1546 	char *name, *value;
1547 	size_t name_len, value_len;
1548 
1549 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ss", &name, &name_len, &value, &value_len) == FAILURE) {
1550 		RETURN_THROWS();
1551 	}
1552 
1553 	if (php_url_scanner_add_var(name, name_len, value, value_len, 1) == SUCCESS) {
1554 		RETURN_TRUE;
1555 	} else {
1556 		RETURN_FALSE;
1557 	}
1558 }
1559 /* }}} */
1560