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