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