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