xref: /PHP-8.1/main/SAPI.c (revision 3503b1da)
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    | Original design:  Shane Caraveo <shane@caraveo.com>                  |
14    | Authors: Andi Gutmans <andi@php.net>                                 |
15    |          Zeev Suraski <zeev@php.net>                                 |
16    +----------------------------------------------------------------------+
17 */
18 
19 #include <ctype.h>
20 #include <sys/stat.h>
21 
22 #include "php.h"
23 #include "SAPI.h"
24 #include "php_variables.h"
25 #include "php_ini.h"
26 #include "ext/standard/php_string.h"
27 #include "ext/standard/pageinfo.h"
28 #include "ext/pcre/php_pcre.h"
29 #ifdef ZTS
30 #include "TSRM.h"
31 #endif
32 #ifdef HAVE_SYS_TIME_H
33 #include <sys/time.h>
34 #elif defined(PHP_WIN32)
35 #include "win32/time.h"
36 #endif
37 
38 #include "rfc1867.h"
39 
40 #include "php_content_types.h"
41 
42 #ifdef ZTS
43 SAPI_API int sapi_globals_id;
44 SAPI_API size_t sapi_globals_offset;
45 #else
46 sapi_globals_struct sapi_globals;
47 #endif
48 
_type_dtor(zval * zv)49 static void _type_dtor(zval *zv)
50 {
51 	free(Z_PTR_P(zv));
52 }
53 
sapi_globals_ctor(sapi_globals_struct * sapi_globals)54 static void sapi_globals_ctor(sapi_globals_struct *sapi_globals)
55 {
56 	memset(sapi_globals, 0, sizeof(*sapi_globals));
57 	zend_hash_init(&sapi_globals->known_post_content_types, 8, NULL, _type_dtor, 1);
58 	php_setup_sapi_content_types();
59 }
60 
sapi_globals_dtor(sapi_globals_struct * sapi_globals)61 static void sapi_globals_dtor(sapi_globals_struct *sapi_globals)
62 {
63 	zend_hash_destroy(&sapi_globals->known_post_content_types);
64 }
65 
66 /* True globals (no need for thread safety) */
67 SAPI_API sapi_module_struct sapi_module;
68 
69 
sapi_startup(sapi_module_struct * sf)70 SAPI_API void sapi_startup(sapi_module_struct *sf)
71 {
72 	sf->ini_entries = NULL;
73 	sapi_module = *sf;
74 
75 #ifdef ZTS
76 	ts_allocate_fast_id(&sapi_globals_id, &sapi_globals_offset, sizeof(sapi_globals_struct), (ts_allocate_ctor) sapi_globals_ctor, (ts_allocate_dtor) sapi_globals_dtor);
77 # ifdef PHP_WIN32
78 	_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
79 # endif
80 #else
81 	sapi_globals_ctor(&sapi_globals);
82 #endif
83 
84 #ifdef PHP_WIN32
85 	tsrm_win32_startup();
86 #endif
87 
88 	reentrancy_startup();
89 }
90 
sapi_shutdown(void)91 SAPI_API void sapi_shutdown(void)
92 {
93 #ifdef ZTS
94 	ts_free_id(sapi_globals_id);
95 #else
96 	sapi_globals_dtor(&sapi_globals);
97 #endif
98 
99 	reentrancy_shutdown();
100 
101 #ifdef PHP_WIN32
102 	tsrm_win32_shutdown();
103 #endif
104 }
105 
106 
sapi_free_header(sapi_header_struct * sapi_header)107 SAPI_API void sapi_free_header(sapi_header_struct *sapi_header)
108 {
109 	efree(sapi_header->header);
110 }
111 
112 /* {{{ call a header function */
PHP_FUNCTION(header_register_callback)113 PHP_FUNCTION(header_register_callback)
114 {
115 	zend_fcall_info fci;
116 	zend_fcall_info_cache fcc;
117 
118 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "f", &fci, &fcc) == FAILURE) {
119 		RETURN_THROWS();
120 	}
121 
122 	if (Z_TYPE(SG(callback_func)) != IS_UNDEF) {
123 		zval_ptr_dtor(&SG(callback_func));
124 		SG(fci_cache) = empty_fcall_info_cache;
125 	}
126 
127 	/* Don't store callback if headers have already been sent:
128 	 * It won't get used and we won't have a chance to release it. */
129 	if (!SG(headers_sent)) {
130 		ZVAL_COPY(&SG(callback_func), &fci.function_name);
131 	}
132 
133 	RETURN_TRUE;
134 }
135 /* }}} */
136 
sapi_run_header_callback(zval * callback)137 static void sapi_run_header_callback(zval *callback)
138 {
139 	int   error;
140 	zend_fcall_info fci;
141 	char *callback_error = NULL;
142 	zval retval;
143 
144 	if (zend_fcall_info_init(callback, 0, &fci, &SG(fci_cache), NULL, &callback_error) == SUCCESS) {
145 		fci.retval = &retval;
146 
147 		error = zend_call_function(&fci, &SG(fci_cache));
148 		if (error == FAILURE) {
149 			goto callback_failed;
150 		} else {
151 			zval_ptr_dtor(&retval);
152 		}
153 	} else {
154 callback_failed:
155 		php_error_docref(NULL, E_WARNING, "Could not call the sapi_header_callback");
156 	}
157 
158 	if (callback_error) {
159 		efree(callback_error);
160 	}
161 }
162 
sapi_handle_post(void * arg)163 SAPI_API void sapi_handle_post(void *arg)
164 {
165 	if (SG(request_info).post_entry && SG(request_info).content_type_dup) {
166 		SG(request_info).post_entry->post_handler(SG(request_info).content_type_dup, arg);
167 		efree(SG(request_info).content_type_dup);
168 		SG(request_info).content_type_dup = NULL;
169 	}
170 }
171 
sapi_read_post_data(void)172 static void sapi_read_post_data(void)
173 {
174 	sapi_post_entry *post_entry;
175 	uint32_t content_type_length = (uint32_t)strlen(SG(request_info).content_type);
176 	char *content_type = estrndup(SG(request_info).content_type, content_type_length);
177 	char *p;
178 	char oldchar=0;
179 	void (*post_reader_func)(void) = NULL;
180 
181 
182 	/* dedicated implementation for increased performance:
183 	 * - Make the content type lowercase
184 	 * - Trim descriptive data, stay with the content-type only
185 	 */
186 	for (p=content_type; p<content_type+content_type_length; p++) {
187 		switch (*p) {
188 			case ';':
189 			case ',':
190 			case ' ':
191 				content_type_length = p-content_type;
192 				oldchar = *p;
193 				*p = 0;
194 				break;
195 			default:
196 				*p = tolower(*p);
197 				break;
198 		}
199 	}
200 
201 	/* now try to find an appropriate POST content handler */
202 	if ((post_entry = zend_hash_str_find_ptr(&SG(known_post_content_types), content_type,
203 			content_type_length)) != NULL) {
204 		/* found one, register it for use */
205 		SG(request_info).post_entry = post_entry;
206 		post_reader_func = post_entry->post_reader;
207 	} else {
208 		/* fallback */
209 		SG(request_info).post_entry = NULL;
210 		if (!sapi_module.default_post_reader) {
211 			/* no default reader ? */
212 			SG(request_info).content_type_dup = NULL;
213 			sapi_module.sapi_error(E_WARNING, "Unsupported content type:  '%s'", content_type);
214 			return;
215 		}
216 	}
217 	if (oldchar) {
218 		*(p-1) = oldchar;
219 	}
220 
221 	SG(request_info).content_type_dup = content_type;
222 
223 	if(post_reader_func) {
224 		post_reader_func();
225 	}
226 
227 	if(sapi_module.default_post_reader) {
228 		sapi_module.default_post_reader();
229 	}
230 }
231 
sapi_read_post_block(char * buffer,size_t buflen)232 SAPI_API size_t sapi_read_post_block(char *buffer, size_t buflen)
233 {
234 	size_t read_bytes;
235 
236 	if (!sapi_module.read_post) {
237 		return 0;
238 	}
239 
240 	read_bytes = sapi_module.read_post(buffer, buflen);
241 
242 	if (read_bytes > 0) {
243 		/* gogo */
244 		SG(read_post_bytes) += read_bytes;
245 	}
246 	if (read_bytes < buflen) {
247 		/* done */
248 		SG(post_read) = 1;
249 	}
250 
251 	return read_bytes;
252 }
253 
SAPI_POST_READER_FUNC(sapi_read_standard_form_data)254 SAPI_API SAPI_POST_READER_FUNC(sapi_read_standard_form_data)
255 {
256 	if ((SG(post_max_size) > 0) && (SG(request_info).content_length > SG(post_max_size))) {
257 		php_error_docref(NULL, E_WARNING, "POST Content-Length of " ZEND_LONG_FMT " bytes exceeds the limit of " ZEND_LONG_FMT " bytes",
258 					SG(request_info).content_length, SG(post_max_size));
259 		return;
260 	}
261 
262 
263 	SG(request_info).request_body = php_stream_temp_create_ex(TEMP_STREAM_DEFAULT, SAPI_POST_BLOCK_SIZE, PG(upload_tmp_dir));
264 
265 	if (sapi_module.read_post) {
266 		size_t read_bytes;
267 
268 		for (;;) {
269 			char buffer[SAPI_POST_BLOCK_SIZE];
270 
271 			read_bytes = sapi_read_post_block(buffer, SAPI_POST_BLOCK_SIZE);
272 
273 			if (read_bytes > 0) {
274 				if (php_stream_write(SG(request_info).request_body, buffer, read_bytes) != read_bytes) {
275 					/* if parts of the stream can't be written, purge it completely */
276 					php_stream_truncate_set_size(SG(request_info).request_body, 0);
277 					php_error_docref(NULL, E_WARNING, "POST data can't be buffered; all data discarded");
278 					break;
279 				}
280 			}
281 
282 			if ((SG(post_max_size) > 0) && (SG(read_post_bytes) > SG(post_max_size))) {
283 				php_error_docref(NULL, E_WARNING, "Actual POST length does not match Content-Length, and exceeds " ZEND_LONG_FMT " bytes", SG(post_max_size));
284 				break;
285 			}
286 
287 			if (read_bytes < SAPI_POST_BLOCK_SIZE) {
288 				/* done */
289 				break;
290 			}
291 		}
292 		php_stream_rewind(SG(request_info).request_body);
293 	}
294 }
295 
296 
get_default_content_type(uint32_t prefix_len,uint32_t * len)297 static inline char *get_default_content_type(uint32_t prefix_len, uint32_t *len)
298 {
299 	char *mimetype, *charset, *content_type;
300 	uint32_t mimetype_len, charset_len;
301 
302 	if (SG(default_mimetype)) {
303 		mimetype = SG(default_mimetype);
304 		mimetype_len = (uint32_t)strlen(SG(default_mimetype));
305 	} else {
306 		mimetype = SAPI_DEFAULT_MIMETYPE;
307 		mimetype_len = sizeof(SAPI_DEFAULT_MIMETYPE) - 1;
308 	}
309 	if (SG(default_charset)) {
310 		charset = SG(default_charset);
311 		charset_len = (uint32_t)strlen(SG(default_charset));
312 	} else {
313 		charset = SAPI_DEFAULT_CHARSET;
314 		charset_len = sizeof(SAPI_DEFAULT_CHARSET) - 1;
315 	}
316 
317 	if (*charset && strncasecmp(mimetype, "text/", 5) == 0) {
318 		char *p;
319 
320 		*len = prefix_len + mimetype_len + sizeof("; charset=") - 1 + charset_len;
321 		content_type = (char*)emalloc(*len + 1);
322 		p = content_type + prefix_len;
323 		memcpy(p, mimetype, mimetype_len);
324 		p += mimetype_len;
325 		memcpy(p, "; charset=", sizeof("; charset=") - 1);
326 		p += sizeof("; charset=") - 1;
327 		memcpy(p, charset, charset_len + 1);
328 	} else {
329 		*len = prefix_len + mimetype_len;
330 		content_type = (char*)emalloc(*len + 1);
331 		memcpy(content_type + prefix_len, mimetype, mimetype_len + 1);
332 	}
333 	return content_type;
334 }
335 
336 
sapi_get_default_content_type(void)337 SAPI_API char *sapi_get_default_content_type(void)
338 {
339 	uint32_t len;
340 
341 	return get_default_content_type(0, &len);
342 }
343 
344 
sapi_get_default_content_type_header(sapi_header_struct * default_header)345 SAPI_API void sapi_get_default_content_type_header(sapi_header_struct *default_header)
346 {
347 	uint32_t len;
348 
349 	default_header->header = get_default_content_type(sizeof("Content-type: ")-1, &len);
350 	default_header->header_len = len;
351 	memcpy(default_header->header, "Content-type: ", sizeof("Content-type: ") - 1);
352 }
353 
354 /*
355  * Add charset on content-type header if the MIME type starts with
356  * "text/", the default_charset directive is not empty and
357  * there is not already a charset option in there.
358  *
359  * If "mimetype" is non-NULL, it should point to a pointer allocated
360  * with emalloc().  If a charset is added, the string will be
361  * re-allocated and the new length is returned.  If mimetype is
362  * unchanged, 0 is returned.
363  *
364  */
sapi_apply_default_charset(char ** mimetype,size_t len)365 SAPI_API size_t sapi_apply_default_charset(char **mimetype, size_t len)
366 {
367 	char *charset, *newtype;
368 	size_t newlen;
369 	charset = SG(default_charset) ? SG(default_charset) : SAPI_DEFAULT_CHARSET;
370 
371 	if (*mimetype != NULL) {
372 		if (*charset && strncmp(*mimetype, "text/", 5) == 0 && strstr(*mimetype, "charset=") == NULL) {
373 			newlen = len + (sizeof(";charset=")-1) + strlen(charset);
374 			newtype = emalloc(newlen + 1);
375 	 		PHP_STRLCPY(newtype, *mimetype, newlen + 1, len);
376 			strlcat(newtype, ";charset=", newlen + 1);
377 			strlcat(newtype, charset, newlen + 1);
378 			efree(*mimetype);
379 			*mimetype = newtype;
380 			return newlen;
381 		}
382 	}
383 	return 0;
384 }
385 
sapi_activate_headers_only(void)386 SAPI_API void sapi_activate_headers_only(void)
387 {
388 	if (SG(request_info).headers_read == 1)
389 		return;
390 	SG(request_info).headers_read = 1;
391 	zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct),
392 			(void (*)(void *)) sapi_free_header, 0);
393 	SG(sapi_headers).send_default_content_type = 1;
394 
395 	/* SG(sapi_headers).http_response_code = 200; */
396 	SG(sapi_headers).http_status_line = NULL;
397 	SG(sapi_headers).mimetype = NULL;
398 	SG(read_post_bytes) = 0;
399 	SG(request_info).request_body = NULL;
400 	SG(request_info).current_user = NULL;
401 	SG(request_info).current_user_length = 0;
402 	SG(request_info).no_headers = 0;
403 	SG(request_info).post_entry = NULL;
404 	SG(global_request_time) = 0;
405 
406 	/*
407 	 * It's possible to override this general case in the activate() callback,
408 	 * if necessary.
409 	 */
410 	if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) {
411 		SG(request_info).headers_only = 1;
412 	} else {
413 		SG(request_info).headers_only = 0;
414 	}
415 	if (SG(server_context)) {
416 		SG(request_info).cookie_data = sapi_module.read_cookies();
417 		if (sapi_module.activate) {
418 			sapi_module.activate();
419 		}
420 	}
421 	if (sapi_module.input_filter_init ) {
422 		sapi_module.input_filter_init();
423 	}
424 }
425 
426 /*
427  * Called from php_request_startup() for every request.
428  */
429 
sapi_activate(void)430 SAPI_API void sapi_activate(void)
431 {
432 	zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct), (void (*)(void *)) sapi_free_header, 0);
433 	SG(sapi_headers).send_default_content_type = 1;
434 
435 	/*
436 	SG(sapi_headers).http_response_code = 200;
437 	*/
438 	SG(sapi_headers).http_status_line = NULL;
439 	SG(sapi_headers).mimetype = NULL;
440 	SG(headers_sent) = 0;
441 	ZVAL_UNDEF(&SG(callback_func));
442 	SG(read_post_bytes) = 0;
443 	SG(request_info).request_body = NULL;
444 	SG(request_info).current_user = NULL;
445 	SG(request_info).current_user_length = 0;
446 	SG(request_info).no_headers = 0;
447 	SG(request_info).post_entry = NULL;
448 	SG(request_info).proto_num = 1000; /* Default to HTTP 1.0 */
449 	SG(global_request_time) = 0;
450 	SG(post_read) = 0;
451 	/* It's possible to override this general case in the activate() callback, if necessary. */
452 	if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) {
453 		SG(request_info).headers_only = 1;
454 	} else {
455 		SG(request_info).headers_only = 0;
456 	}
457 	SG(rfc1867_uploaded_files) = NULL;
458 
459 	/* Handle request method */
460 	if (SG(server_context)) {
461 		if (PG(enable_post_data_reading)
462 		&& 	SG(request_info).content_type
463 		&&  SG(request_info).request_method
464 		&& !strcmp(SG(request_info).request_method, "POST")) {
465 			/* HTTP POST may contain form data to be processed into variables
466 			 * depending on given content type */
467 			sapi_read_post_data();
468 		} else {
469 			SG(request_info).content_type_dup = NULL;
470 		}
471 
472 		/* Cookies */
473 		SG(request_info).cookie_data = sapi_module.read_cookies();
474 	}
475 	if (sapi_module.activate) {
476 		sapi_module.activate();
477 	}
478 	if (sapi_module.input_filter_init) {
479 		sapi_module.input_filter_init();
480 	}
481 }
482 
483 
sapi_send_headers_free(void)484 static void sapi_send_headers_free(void)
485 {
486 	if (SG(sapi_headers).http_status_line) {
487 		efree(SG(sapi_headers).http_status_line);
488 		SG(sapi_headers).http_status_line = NULL;
489 	}
490 }
491 
sapi_deactivate_module(void)492 SAPI_API void sapi_deactivate_module(void)
493 {
494 	zend_llist_destroy(&SG(sapi_headers).headers);
495 	if (SG(request_info).request_body) {
496 		SG(request_info).request_body = NULL;
497 	} else if (SG(server_context)) {
498 		if (!SG(post_read)) {
499 			/* make sure we've consumed all request input data */
500 			char dummy[SAPI_POST_BLOCK_SIZE];
501 			size_t read_bytes;
502 
503 			do {
504 				read_bytes = sapi_read_post_block(dummy, SAPI_POST_BLOCK_SIZE);
505 			} while (SAPI_POST_BLOCK_SIZE == read_bytes);
506 		}
507 	}
508 	if (SG(request_info).auth_user) {
509 		efree(SG(request_info).auth_user);
510 	}
511 	if (SG(request_info).auth_password) {
512 		efree(SG(request_info).auth_password);
513 	}
514 	if (SG(request_info).auth_digest) {
515 		efree(SG(request_info).auth_digest);
516 	}
517 	if (SG(request_info).content_type_dup) {
518 		efree(SG(request_info).content_type_dup);
519 	}
520 	if (SG(request_info).current_user) {
521 		efree(SG(request_info).current_user);
522 	}
523 	if (sapi_module.deactivate) {
524 		sapi_module.deactivate();
525 	}
526 }
527 
sapi_deactivate_destroy(void)528 SAPI_API void sapi_deactivate_destroy(void)
529 {
530 	if (SG(rfc1867_uploaded_files)) {
531 		destroy_uploaded_files_hash();
532 	}
533 	if (SG(sapi_headers).mimetype) {
534 		efree(SG(sapi_headers).mimetype);
535 		SG(sapi_headers).mimetype = NULL;
536 	}
537 	sapi_send_headers_free();
538 	SG(sapi_started) = 0;
539 	SG(headers_sent) = 0;
540 	SG(request_info).headers_read = 0;
541 	SG(global_request_time) = 0;
542 }
543 
sapi_deactivate(void)544 SAPI_API void sapi_deactivate(void)
545 {
546 	sapi_deactivate_module();
547 	sapi_deactivate_destroy();
548 }
549 
550 
sapi_initialize_empty_request(void)551 SAPI_API void sapi_initialize_empty_request(void)
552 {
553 	SG(server_context) = NULL;
554 	SG(request_info).request_method = NULL;
555 	SG(request_info).auth_digest = SG(request_info).auth_user = SG(request_info).auth_password = NULL;
556 	SG(request_info).content_type_dup = NULL;
557 }
558 
559 
sapi_extract_response_code(const char * header_line)560 static int sapi_extract_response_code(const char *header_line)
561 {
562 	int code = 200;
563 	const char *ptr;
564 
565 	for (ptr = header_line; *ptr; ptr++) {
566 		if (*ptr == ' ' && *(ptr + 1) != ' ') {
567 			code = atoi(ptr + 1);
568 			break;
569 		}
570 	}
571 
572 	return code;
573 }
574 
575 
sapi_update_response_code(int ncode)576 static void sapi_update_response_code(int ncode)
577 {
578 	/* if the status code did not change, we do not want
579 	   to change the status line, and no need to change the code */
580 	if (SG(sapi_headers).http_response_code == ncode) {
581 		return;
582 	}
583 
584 	if (SG(sapi_headers).http_status_line) {
585 		efree(SG(sapi_headers).http_status_line);
586 		SG(sapi_headers).http_status_line = NULL;
587 	}
588 	SG(sapi_headers).http_response_code = ncode;
589 }
590 
591 /*
592  * since zend_llist_del_element only removes one matched item once,
593  * we should remove them manually
594  */
sapi_remove_header(zend_llist * l,char * name,size_t len)595 static void sapi_remove_header(zend_llist *l, char *name, size_t len) {
596 	sapi_header_struct *header;
597 	zend_llist_element *next;
598 	zend_llist_element *current=l->head;
599 
600 	while (current) {
601 		header = (sapi_header_struct *)(current->data);
602 		next = current->next;
603 		if (header->header_len > len && header->header[len] == ':'
604 				&& !strncasecmp(header->header, name, len)) {
605 			if (current->prev) {
606 				current->prev->next = next;
607 			} else {
608 				l->head = next;
609 			}
610 			if (next) {
611 				next->prev = current->prev;
612 			} else {
613 				l->tail = current->prev;
614 			}
615 			sapi_free_header(header);
616 			efree(current);
617 			--l->count;
618 		}
619 		current = next;
620 	}
621 }
622 
sapi_add_header_ex(const char * header_line,size_t header_line_len,bool duplicate,bool replace)623 SAPI_API int sapi_add_header_ex(const char *header_line, size_t header_line_len, bool duplicate, bool replace)
624 {
625 	sapi_header_line ctr = {0};
626 	int r;
627 
628 	ctr.line = header_line;
629 	ctr.line_len = header_line_len;
630 
631 	r = sapi_header_op(replace ? SAPI_HEADER_REPLACE : SAPI_HEADER_ADD,
632 			&ctr);
633 
634 	if (!duplicate)
635 		efree((void *) header_line);
636 
637 	return r;
638 }
639 
sapi_header_add_op(sapi_header_op_enum op,sapi_header_struct * sapi_header)640 static void sapi_header_add_op(sapi_header_op_enum op, sapi_header_struct *sapi_header)
641 {
642 	if (!sapi_module.header_handler ||
643 		(SAPI_HEADER_ADD & sapi_module.header_handler(sapi_header, op, &SG(sapi_headers)))) {
644 		if (op == SAPI_HEADER_REPLACE) {
645 			char *colon_offset = strchr(sapi_header->header, ':');
646 
647 			if (colon_offset) {
648 				char sav = *colon_offset;
649 
650 				*colon_offset = 0;
651 		        sapi_remove_header(&SG(sapi_headers).headers, sapi_header->header, strlen(sapi_header->header));
652 				*colon_offset = sav;
653 			}
654 		}
655 		zend_llist_add_element(&SG(sapi_headers).headers, (void *) sapi_header);
656 	} else {
657 		sapi_free_header(sapi_header);
658 	}
659 }
660 
sapi_header_op(sapi_header_op_enum op,void * arg)661 SAPI_API int sapi_header_op(sapi_header_op_enum op, void *arg)
662 {
663 	sapi_header_struct sapi_header;
664 	char *colon_offset;
665 	char *header_line;
666 	size_t header_line_len;
667 	int http_response_code;
668 
669 	if (SG(headers_sent) && !SG(request_info).no_headers) {
670 		const char *output_start_filename = php_output_get_start_filename();
671 		int output_start_lineno = php_output_get_start_lineno();
672 
673 		if (output_start_filename) {
674 			sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent by (output started at %s:%d)",
675 				output_start_filename, output_start_lineno);
676 		} else {
677 			sapi_module.sapi_error(E_WARNING, "Cannot modify header information - headers already sent");
678 		}
679 		return FAILURE;
680 	}
681 
682 	switch (op) {
683 		case SAPI_HEADER_SET_STATUS:
684 			sapi_update_response_code((int)(zend_intptr_t) arg);
685 			return SUCCESS;
686 
687 		case SAPI_HEADER_ADD:
688 		case SAPI_HEADER_REPLACE:
689 		case SAPI_HEADER_DELETE: {
690 				sapi_header_line *p = arg;
691 
692 				if (!p->line || !p->line_len) {
693 					return FAILURE;
694 				}
695 				header_line = estrndup(p->line, p->line_len);
696 				header_line_len = p->line_len;
697 				http_response_code = p->response_code;
698 				break;
699 			}
700 
701 		case SAPI_HEADER_DELETE_ALL:
702 			if (sapi_module.header_handler) {
703 				sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers));
704 			}
705 			zend_llist_clean(&SG(sapi_headers).headers);
706 			return SUCCESS;
707 
708 		default:
709 			return FAILURE;
710 	}
711 
712 	/* cut off trailing spaces, linefeeds and carriage-returns */
713 	if (header_line_len && isspace(header_line[header_line_len-1])) {
714 		do {
715 			header_line_len--;
716 		} while(header_line_len && isspace(header_line[header_line_len-1]));
717 		header_line[header_line_len]='\0';
718 	}
719 
720 	if (op == SAPI_HEADER_DELETE) {
721 		if (strchr(header_line, ':')) {
722 			efree(header_line);
723 			sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon.");
724 			return FAILURE;
725 		}
726 		if (sapi_module.header_handler) {
727 			sapi_header.header = header_line;
728 			sapi_header.header_len = header_line_len;
729 			sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers));
730 		}
731 		sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len);
732 		efree(header_line);
733 		return SUCCESS;
734 	} else {
735 		/* new line/NUL character safety check */
736 		uint32_t i;
737 		for (i = 0; i < header_line_len; i++) {
738 			/* RFC 7230 ch. 3.2.4 deprecates folding support */
739 			if (header_line[i] == '\n' || header_line[i] == '\r') {
740 				efree(header_line);
741 				sapi_module.sapi_error(E_WARNING, "Header may not contain "
742 						"more than a single header, new line detected");
743 				return FAILURE;
744 			}
745 			if (header_line[i] == '\0') {
746 				efree(header_line);
747 				sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes");
748 				return FAILURE;
749 			}
750 		}
751 	}
752 
753 	sapi_header.header = header_line;
754 	sapi_header.header_len = header_line_len;
755 
756 	/* Check the header for a few cases that we have special support for in SAPI */
757 	if (header_line_len>=5
758 		&& !strncasecmp(header_line, "HTTP/", 5)) {
759 		/* filter out the response code */
760 		sapi_update_response_code(sapi_extract_response_code(header_line));
761 		/* sapi_update_response_code doesn't free the status line if the code didn't change */
762 		if (SG(sapi_headers).http_status_line) {
763 			efree(SG(sapi_headers).http_status_line);
764 		}
765 		SG(sapi_headers).http_status_line = header_line;
766 		return SUCCESS;
767 	} else {
768 		colon_offset = strchr(header_line, ':');
769 		if (colon_offset) {
770 			*colon_offset = 0;
771 			if (!strcasecmp(header_line, "Content-Type")) {
772 				char *ptr = colon_offset+1, *mimetype = NULL, *newheader;
773 				size_t len = header_line_len - (ptr - header_line), newlen;
774 				while (*ptr == ' ') {
775 					ptr++;
776 					len--;
777 				}
778 
779 				mimetype = estrdup(ptr);
780 				newlen = sapi_apply_default_charset(&mimetype, len);
781 				if (!SG(sapi_headers).mimetype){
782 					SG(sapi_headers).mimetype = estrdup(mimetype);
783 				}
784 
785 				if (newlen != 0) {
786 					newlen += sizeof("Content-type: ");
787 					newheader = emalloc(newlen);
788 					PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1);
789 					strlcat(newheader, mimetype, newlen);
790 					sapi_header.header = newheader;
791 					sapi_header.header_len = (uint32_t)(newlen - 1);
792 					efree(header_line);
793 				}
794 				efree(mimetype);
795 				SG(sapi_headers).send_default_content_type = 0;
796 			} else if (!strcasecmp(header_line, "Content-Length")) {
797 				/* Script is setting Content-length. The script cannot reasonably
798 				 * know the size of the message body after compression, so it's best
799 				 * do disable compression altogether. This contributes to making scripts
800 				 * portable between setups that have and don't have zlib compression
801 				 * enabled globally. See req #44164 */
802 				zend_string *key = zend_string_init("zlib.output_compression", sizeof("zlib.output_compression")-1, 0);
803 				zend_alter_ini_entry_chars(key,
804 					"0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
805 				zend_string_release_ex(key, 0);
806 			} else if (!strcasecmp(header_line, "Location")) {
807 				if ((SG(sapi_headers).http_response_code < 300 ||
808 					SG(sapi_headers).http_response_code > 399) &&
809 					SG(sapi_headers).http_response_code != 201) {
810 					/* Return a Found Redirect if one is not already specified */
811 					if (http_response_code) { /* user specified redirect code */
812 						sapi_update_response_code(http_response_code);
813 					} else if (SG(request_info).proto_num > 1000 &&
814 					   SG(request_info).request_method &&
815 					   strcmp(SG(request_info).request_method, "HEAD") &&
816 					   strcmp(SG(request_info).request_method, "GET")) {
817 						sapi_update_response_code(303);
818 					} else {
819 						sapi_update_response_code(302);
820 					}
821 				}
822 			} else if (!strcasecmp(header_line, "WWW-Authenticate")) { /* HTTP Authentication */
823 				sapi_update_response_code(401); /* authentication-required */
824 			}
825 			if (sapi_header.header==header_line) {
826 				*colon_offset = ':';
827 			}
828 		}
829 	}
830 	if (http_response_code) {
831 		sapi_update_response_code(http_response_code);
832 	}
833 	sapi_header_add_op(op, &sapi_header);
834 	return SUCCESS;
835 }
836 
837 
sapi_send_headers(void)838 SAPI_API int sapi_send_headers(void)
839 {
840 	int retval;
841 	int ret = FAILURE;
842 
843 	if (SG(headers_sent) || SG(request_info).no_headers) {
844 		return SUCCESS;
845 	}
846 
847 	/* Success-oriented.  We set headers_sent to 1 here to avoid an infinite loop
848 	 * in case of an error situation.
849 	 */
850 	if (SG(sapi_headers).send_default_content_type && sapi_module.send_headers) {
851 	    uint32_t len = 0;
852 		char *default_mimetype = get_default_content_type(0, &len);
853 
854 		if (default_mimetype && len) {
855 			sapi_header_struct default_header;
856 
857 			SG(sapi_headers).mimetype = default_mimetype;
858 
859 			default_header.header_len = sizeof("Content-type: ") - 1 + len;
860 			default_header.header = emalloc(default_header.header_len + 1);
861 
862 			memcpy(default_header.header, "Content-type: ", sizeof("Content-type: ") - 1);
863 			memcpy(default_header.header + sizeof("Content-type: ") - 1, SG(sapi_headers).mimetype, len + 1);
864 
865 			sapi_header_add_op(SAPI_HEADER_ADD, &default_header);
866 		} else {
867 			efree(default_mimetype);
868 		}
869 		SG(sapi_headers).send_default_content_type = 0;
870 	}
871 
872 	if (Z_TYPE(SG(callback_func)) != IS_UNDEF) {
873 		zval cb;
874 		ZVAL_COPY_VALUE(&cb, &SG(callback_func));
875 		ZVAL_UNDEF(&SG(callback_func));
876 		sapi_run_header_callback(&cb);
877 		zval_ptr_dtor(&cb);
878 	}
879 
880 	SG(headers_sent) = 1;
881 
882 	if (sapi_module.send_headers) {
883 		retval = sapi_module.send_headers(&SG(sapi_headers));
884 	} else {
885 		retval = SAPI_HEADER_DO_SEND;
886 	}
887 
888 	switch (retval) {
889 		case SAPI_HEADER_SENT_SUCCESSFULLY:
890 			ret = SUCCESS;
891 			break;
892 		case SAPI_HEADER_DO_SEND: {
893 				sapi_header_struct http_status_line;
894 				char buf[255];
895 
896 				if (SG(sapi_headers).http_status_line) {
897 					http_status_line.header = SG(sapi_headers).http_status_line;
898 					http_status_line.header_len = (uint32_t)strlen(SG(sapi_headers).http_status_line);
899 				} else {
900 					http_status_line.header = buf;
901 					http_status_line.header_len = slprintf(buf, sizeof(buf), "HTTP/1.0 %d X", SG(sapi_headers).http_response_code);
902 				}
903 				sapi_module.send_header(&http_status_line, SG(server_context));
904 			}
905 			zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t) sapi_module.send_header, SG(server_context));
906 			if(SG(sapi_headers).send_default_content_type) {
907 				sapi_header_struct default_header;
908 
909 				sapi_get_default_content_type_header(&default_header);
910 				sapi_module.send_header(&default_header, SG(server_context));
911 				sapi_free_header(&default_header);
912 			}
913 			sapi_module.send_header(NULL, SG(server_context));
914 			ret = SUCCESS;
915 			break;
916 		case SAPI_HEADER_SEND_FAILED:
917 			SG(headers_sent) = 0;
918 			ret = FAILURE;
919 			break;
920 	}
921 
922 	sapi_send_headers_free();
923 
924 	return ret;
925 }
926 
927 
sapi_register_post_entries(const sapi_post_entry * post_entries)928 SAPI_API int sapi_register_post_entries(const sapi_post_entry *post_entries)
929 {
930 	const sapi_post_entry *p=post_entries;
931 
932 	while (p->content_type) {
933 		if (sapi_register_post_entry(p) == FAILURE) {
934 			return FAILURE;
935 		}
936 		p++;
937 	}
938 	return SUCCESS;
939 }
940 
941 
sapi_register_post_entry(const sapi_post_entry * post_entry)942 SAPI_API int sapi_register_post_entry(const sapi_post_entry *post_entry)
943 {
944 	int ret;
945 	zend_string *key;
946 	if (SG(sapi_started) && EG(current_execute_data)) {
947 		return FAILURE;
948 	}
949 	key = zend_string_init(post_entry->content_type, post_entry->content_type_len, 1);
950 	GC_MAKE_PERSISTENT_LOCAL(key);
951 	ret = zend_hash_add_mem(&SG(known_post_content_types), key,
952 			(void *) post_entry, sizeof(sapi_post_entry)) ? SUCCESS : FAILURE;
953 	zend_string_release_ex(key, 1);
954 	return ret;
955 }
956 
sapi_unregister_post_entry(const sapi_post_entry * post_entry)957 SAPI_API void sapi_unregister_post_entry(const sapi_post_entry *post_entry)
958 {
959 	if (SG(sapi_started) && EG(current_execute_data)) {
960 		return;
961 	}
962 	zend_hash_str_del(&SG(known_post_content_types), post_entry->content_type,
963 			post_entry->content_type_len);
964 }
965 
966 
sapi_register_default_post_reader(void (* default_post_reader)(void))967 SAPI_API int sapi_register_default_post_reader(void (*default_post_reader)(void))
968 {
969 	if (SG(sapi_started) && EG(current_execute_data)) {
970 		return FAILURE;
971 	}
972 	sapi_module.default_post_reader = default_post_reader;
973 	return SUCCESS;
974 }
975 
976 
sapi_register_treat_data(void (* treat_data)(int arg,char * str,zval * destArray))977 SAPI_API int sapi_register_treat_data(void (*treat_data)(int arg, char *str, zval *destArray))
978 {
979 	if (SG(sapi_started) && EG(current_execute_data)) {
980 		return FAILURE;
981 	}
982 	sapi_module.treat_data = treat_data;
983 	return SUCCESS;
984 }
985 
sapi_register_input_filter(unsigned int (* input_filter)(int arg,const char * var,char ** val,size_t val_len,size_t * new_val_len),unsigned int (* input_filter_init)(void))986 SAPI_API int sapi_register_input_filter(unsigned int (*input_filter)(int arg, const char *var, char **val, size_t val_len, size_t *new_val_len), unsigned int (*input_filter_init)(void))
987 {
988 	if (SG(sapi_started) && EG(current_execute_data)) {
989 		return FAILURE;
990 	}
991 	sapi_module.input_filter = input_filter;
992 	sapi_module.input_filter_init = input_filter_init;
993 	return SUCCESS;
994 }
995 
sapi_flush(void)996 SAPI_API int sapi_flush(void)
997 {
998 	if (sapi_module.flush) {
999 		sapi_module.flush(SG(server_context));
1000 		return SUCCESS;
1001 	} else {
1002 		return FAILURE;
1003 	}
1004 }
1005 
sapi_get_stat(void)1006 SAPI_API zend_stat_t *sapi_get_stat(void)
1007 {
1008 	if (sapi_module.get_stat) {
1009 		return sapi_module.get_stat();
1010 	} else {
1011 		if (!SG(request_info).path_translated || (VCWD_STAT(SG(request_info).path_translated, &SG(global_stat)) == -1)) {
1012 			return NULL;
1013 		}
1014 		return &SG(global_stat);
1015 	}
1016 }
1017 
sapi_getenv(const char * name,size_t name_len)1018 SAPI_API char *sapi_getenv(const char *name, size_t name_len)
1019 {
1020 	if (!strncasecmp(name, "HTTP_PROXY", name_len)) {
1021 		/* Ugly fix for HTTP_PROXY issue, see bug #72573 */
1022 		return NULL;
1023 	}
1024 	if (sapi_module.getenv) {
1025 		char *value, *tmp = sapi_module.getenv(name, name_len);
1026 		if (tmp) {
1027 			value = estrdup(tmp);
1028 #ifdef PHP_WIN32
1029 			if (strlen(sapi_module.name) == sizeof("cgi-fcgi") - 1 && !strcmp(sapi_module.name, "cgi-fcgi")) {
1030 				/* XXX more modules to go, if needed. */
1031 				free(tmp);
1032 			}
1033 #endif
1034 		} else {
1035 			return NULL;
1036 		}
1037 		if (sapi_module.input_filter) {
1038 			sapi_module.input_filter(PARSE_STRING, name, &value, strlen(value), NULL);
1039 		}
1040 		return value;
1041 	}
1042 	return NULL;
1043 }
1044 
sapi_get_fd(int * fd)1045 SAPI_API int sapi_get_fd(int *fd)
1046 {
1047 	if (sapi_module.get_fd) {
1048 		return sapi_module.get_fd(fd);
1049 	} else {
1050 		return FAILURE;
1051 	}
1052 }
1053 
sapi_force_http_10(void)1054 SAPI_API int sapi_force_http_10(void)
1055 {
1056 	if (sapi_module.force_http_10) {
1057 		return sapi_module.force_http_10();
1058 	} else {
1059 		return FAILURE;
1060 	}
1061 }
1062 
1063 
sapi_get_target_uid(uid_t * obj)1064 SAPI_API int sapi_get_target_uid(uid_t *obj)
1065 {
1066 	if (sapi_module.get_target_uid) {
1067 		return sapi_module.get_target_uid(obj);
1068 	} else {
1069 		return FAILURE;
1070 	}
1071 }
1072 
sapi_get_target_gid(gid_t * obj)1073 SAPI_API int sapi_get_target_gid(gid_t *obj)
1074 {
1075 	if (sapi_module.get_target_gid) {
1076 		return sapi_module.get_target_gid(obj);
1077 	} else {
1078 		return FAILURE;
1079 	}
1080 }
1081 
sapi_get_request_time(void)1082 SAPI_API double sapi_get_request_time(void)
1083 {
1084 	if(SG(global_request_time)) return SG(global_request_time);
1085 
1086 	if (sapi_module.get_request_time && SG(server_context)) {
1087 		SG(global_request_time) = sapi_module.get_request_time();
1088 	} else {
1089 		struct timeval tp = {0};
1090 		if (!gettimeofday(&tp, NULL)) {
1091 			SG(global_request_time) = (double)(tp.tv_sec + tp.tv_usec / 1000000.00);
1092 		} else {
1093 			SG(global_request_time) = (double)time(0);
1094 		}
1095 	}
1096 	return SG(global_request_time);
1097 }
1098 
sapi_terminate_process(void)1099 SAPI_API void sapi_terminate_process(void) {
1100 	if (sapi_module.terminate_process) {
1101 		sapi_module.terminate_process();
1102 	}
1103 }
1104 
sapi_add_request_header(const char * var,unsigned int var_len,char * val,unsigned int val_len,void * arg)1105 SAPI_API void sapi_add_request_header(const char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg) /* {{{ */
1106 {
1107 	zval *return_value = (zval*)arg;
1108 	char *buf = NULL;
1109 
1110 	ALLOCA_FLAG(use_heap)
1111 
1112 	if (var_len > 5 &&
1113 	    var[0] == 'H' &&
1114 	    var[1] == 'T' &&
1115 	    var[2] == 'T' &&
1116 	    var[3] == 'P' &&
1117 	    var[4] == '_') {
1118 
1119 		const char *p;
1120 		char *str;
1121 
1122 		var_len -= 5;
1123 		p = var + 5;
1124 		var = str = buf = do_alloca(var_len + 1, use_heap);
1125 		*str++ = *p++;
1126 		while (*p) {
1127 			if (*p == '_') {
1128 				*str++ = '-';
1129 				p++;
1130 				if (*p) {
1131 					*str++ = *p++;
1132 				}
1133 			} else if (*p >= 'A' && *p <= 'Z') {
1134 				*str++ = (*p++ - 'A' + 'a');
1135 			} else {
1136 				*str++ = *p++;
1137 			}
1138 		}
1139 		*str = 0;
1140 	} else if (var_len == sizeof("CONTENT_TYPE")-1 &&
1141 	           memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
1142 		var = "Content-Type";
1143 	} else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
1144 	           memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
1145 		var = "Content-Length";
1146 	} else {
1147 		return;
1148 	}
1149 	add_assoc_stringl_ex(return_value, var, var_len, val, val_len);
1150 	if (buf) {
1151 		free_alloca(buf, use_heap);
1152 	}
1153 }
1154 /* }}} */
1155