xref: /PHP-7.3/main/SAPI.c (revision 9afce019)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2018 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 #if (HAVE_PCRE || HAVE_BUNDLED_PCRE) && !defined(COMPILE_DL_PCRE)
31 #include "ext/pcre/php_pcre.h"
32 #endif
33 #ifdef ZTS
34 #include "TSRM.h"
35 #endif
36 #ifdef HAVE_SYS_TIME_H
37 #include <sys/time.h>
38 #elif defined(PHP_WIN32)
39 #include "win32/time.h"
40 #endif
41 
42 #include "rfc1867.h"
43 
44 #include "php_content_types.h"
45 
46 #ifdef ZTS
47 SAPI_API int sapi_globals_id;
48 #else
49 sapi_globals_struct sapi_globals;
50 #endif
51 
_type_dtor(zval * zv)52 static void _type_dtor(zval *zv)
53 {
54 	free(Z_PTR_P(zv));
55 }
56 
sapi_globals_ctor(sapi_globals_struct * sapi_globals)57 static void sapi_globals_ctor(sapi_globals_struct *sapi_globals)
58 {
59 #ifdef ZTS
60 	ZEND_TSRMLS_CACHE_UPDATE();
61 #endif
62 	memset(sapi_globals, 0, sizeof(*sapi_globals));
63 	zend_hash_init_ex(&sapi_globals->known_post_content_types, 8, NULL, _type_dtor, 1, 0);
64 	php_setup_sapi_content_types();
65 }
66 
sapi_globals_dtor(sapi_globals_struct * sapi_globals)67 static void sapi_globals_dtor(sapi_globals_struct *sapi_globals)
68 {
69 	zend_hash_destroy(&sapi_globals->known_post_content_types);
70 }
71 
72 /* True globals (no need for thread safety) */
73 SAPI_API sapi_module_struct sapi_module;
74 
75 
sapi_startup(sapi_module_struct * sf)76 SAPI_API void sapi_startup(sapi_module_struct *sf)
77 {
78 	sf->ini_entries = NULL;
79 	sapi_module = *sf;
80 
81 #ifdef ZTS
82 	ts_allocate_id(&sapi_globals_id, sizeof(sapi_globals_struct), (ts_allocate_ctor) sapi_globals_ctor, (ts_allocate_dtor) sapi_globals_dtor);
83 # ifdef PHP_WIN32
84 	_configthreadlocale(_ENABLE_PER_THREAD_LOCALE);
85 # endif
86 #else
87 	sapi_globals_ctor(&sapi_globals);
88 #endif
89 
90 #ifdef PHP_WIN32
91 	tsrm_win32_startup();
92 #endif
93 
94 	reentrancy_startup();
95 }
96 
sapi_shutdown(void)97 SAPI_API void sapi_shutdown(void)
98 {
99 #ifdef ZTS
100 	ts_free_id(sapi_globals_id);
101 #else
102 	sapi_globals_dtor(&sapi_globals);
103 #endif
104 
105 	reentrancy_shutdown();
106 
107 #ifdef PHP_WIN32
108 	tsrm_win32_shutdown();
109 #endif
110 }
111 
112 
sapi_free_header(sapi_header_struct * sapi_header)113 SAPI_API void sapi_free_header(sapi_header_struct *sapi_header)
114 {
115 	efree(sapi_header->header);
116 }
117 
118 /* {{{ proto bool header_register_callback(mixed callback)
119    call a header function */
PHP_FUNCTION(header_register_callback)120 PHP_FUNCTION(header_register_callback)
121 {
122 	zval *callback_func;
123 
124 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "z", &callback_func) == FAILURE) {
125 		return;
126 	}
127 
128 	if (!zend_is_callable(callback_func, 0, NULL)) {
129 		RETURN_FALSE;
130 	}
131 
132 	if (Z_TYPE(SG(callback_func)) != IS_UNDEF) {
133 		zval_ptr_dtor(&SG(callback_func));
134 		SG(fci_cache) = empty_fcall_info_cache;
135 	}
136 
137 	ZVAL_COPY(&SG(callback_func), callback_func);
138 
139 	RETURN_TRUE;
140 }
141 /* }}} */
142 
sapi_run_header_callback(zval * callback)143 static void sapi_run_header_callback(zval *callback)
144 {
145 	int   error;
146 	zend_fcall_info fci;
147 	char *callback_error = NULL;
148 	zval retval;
149 
150 	if (zend_fcall_info_init(callback, 0, &fci, &SG(fci_cache), NULL, &callback_error) == SUCCESS) {
151 		fci.retval = &retval;
152 
153 		error = zend_call_function(&fci, &SG(fci_cache));
154 		if (error == FAILURE) {
155 			goto callback_failed;
156 		} else {
157 			zval_ptr_dtor(&retval);
158 		}
159 	} else {
160 callback_failed:
161 		php_error_docref(NULL, E_WARNING, "Could not call the sapi_header_callback");
162 	}
163 
164 	if (callback_error) {
165 		efree(callback_error);
166 	}
167 }
168 
sapi_handle_post(void * arg)169 SAPI_API void sapi_handle_post(void *arg)
170 {
171 	if (SG(request_info).post_entry && SG(request_info).content_type_dup) {
172 		SG(request_info).post_entry->post_handler(SG(request_info).content_type_dup, arg);
173 		efree(SG(request_info).content_type_dup);
174 		SG(request_info).content_type_dup = NULL;
175 	}
176 }
177 
sapi_read_post_data(void)178 static void sapi_read_post_data(void)
179 {
180 	sapi_post_entry *post_entry;
181 	uint32_t content_type_length = (uint32_t)strlen(SG(request_info).content_type);
182 	char *content_type = estrndup(SG(request_info).content_type, content_type_length);
183 	char *p;
184 	char oldchar=0;
185 	void (*post_reader_func)(void) = NULL;
186 
187 
188 	/* dedicated implementation for increased performance:
189 	 * - Make the content type lowercase
190 	 * - Trim descriptive data, stay with the content-type only
191 	 */
192 	for (p=content_type; p<content_type+content_type_length; p++) {
193 		switch (*p) {
194 			case ';':
195 			case ',':
196 			case ' ':
197 				content_type_length = p-content_type;
198 				oldchar = *p;
199 				*p = 0;
200 				break;
201 			default:
202 				*p = tolower(*p);
203 				break;
204 		}
205 	}
206 
207 	/* now try to find an appropriate POST content handler */
208 	if ((post_entry = zend_hash_str_find_ptr(&SG(known_post_content_types), content_type,
209 			content_type_length)) != NULL) {
210 		/* found one, register it for use */
211 		SG(request_info).post_entry = post_entry;
212 		post_reader_func = post_entry->post_reader;
213 	} else {
214 		/* fallback */
215 		SG(request_info).post_entry = NULL;
216 		if (!sapi_module.default_post_reader) {
217 			/* no default reader ? */
218 			SG(request_info).content_type_dup = NULL;
219 			sapi_module.sapi_error(E_WARNING, "Unsupported content type:  '%s'", content_type);
220 			return;
221 		}
222 	}
223 	if (oldchar) {
224 		*(p-1) = oldchar;
225 	}
226 
227 	SG(request_info).content_type_dup = content_type;
228 
229 	if(post_reader_func) {
230 		post_reader_func();
231 	}
232 
233 	if(sapi_module.default_post_reader) {
234 		sapi_module.default_post_reader();
235 	}
236 }
237 
sapi_read_post_block(char * buffer,size_t buflen)238 SAPI_API size_t sapi_read_post_block(char *buffer, size_t buflen)
239 {
240 	size_t read_bytes;
241 
242 	if (!sapi_module.read_post) {
243 		return 0;
244 	}
245 
246 	read_bytes = sapi_module.read_post(buffer, buflen);
247 
248 	if (read_bytes > 0) {
249 		/* gogo */
250 		SG(read_post_bytes) += read_bytes;
251 	}
252 	if (read_bytes < buflen) {
253 		/* done */
254 		SG(post_read) = 1;
255 	}
256 
257 	return read_bytes;
258 }
259 
SAPI_POST_READER_FUNC(sapi_read_standard_form_data)260 SAPI_API SAPI_POST_READER_FUNC(sapi_read_standard_form_data)
261 {
262 	if ((SG(post_max_size) > 0) && (SG(request_info).content_length > SG(post_max_size))) {
263 		php_error_docref(NULL, E_WARNING, "POST Content-Length of " ZEND_LONG_FMT " bytes exceeds the limit of " ZEND_LONG_FMT " bytes",
264 					SG(request_info).content_length, SG(post_max_size));
265 		return;
266 	}
267 
268 
269 	SG(request_info).request_body = php_stream_temp_create_ex(TEMP_STREAM_DEFAULT, SAPI_POST_BLOCK_SIZE, PG(upload_tmp_dir));
270 
271 	if (sapi_module.read_post) {
272 		size_t read_bytes;
273 
274 		for (;;) {
275 			char buffer[SAPI_POST_BLOCK_SIZE];
276 
277 			read_bytes = sapi_read_post_block(buffer, SAPI_POST_BLOCK_SIZE);
278 
279 			if (read_bytes > 0) {
280 				if (php_stream_write(SG(request_info).request_body, buffer, read_bytes) != read_bytes) {
281 					/* if parts of the stream can't be written, purge it completely */
282 					php_stream_truncate_set_size(SG(request_info).request_body, 0);
283 					php_error_docref(NULL, E_WARNING, "POST data can't be buffered; all data discarded");
284 					break;
285 				}
286 			}
287 
288 			if ((SG(post_max_size) > 0) && (SG(read_post_bytes) > SG(post_max_size))) {
289 				php_error_docref(NULL, E_WARNING, "Actual POST length does not match Content-Length, and exceeds " ZEND_LONG_FMT " bytes", SG(post_max_size));
290 				break;
291 			}
292 
293 			if (read_bytes < SAPI_POST_BLOCK_SIZE) {
294 				/* done */
295 				break;
296 			}
297 		}
298 		php_stream_rewind(SG(request_info).request_body);
299 	}
300 }
301 
302 
get_default_content_type(uint32_t prefix_len,uint32_t * len)303 static inline char *get_default_content_type(uint32_t prefix_len, uint32_t *len)
304 {
305 	char *mimetype, *charset, *content_type;
306 	uint32_t mimetype_len, charset_len;
307 
308 	if (SG(default_mimetype)) {
309 		mimetype = SG(default_mimetype);
310 		mimetype_len = (uint32_t)strlen(SG(default_mimetype));
311 	} else {
312 		mimetype = SAPI_DEFAULT_MIMETYPE;
313 		mimetype_len = sizeof(SAPI_DEFAULT_MIMETYPE) - 1;
314 	}
315 	if (SG(default_charset)) {
316 		charset = SG(default_charset);
317 		charset_len = (uint32_t)strlen(SG(default_charset));
318 	} else {
319 		charset = SAPI_DEFAULT_CHARSET;
320 		charset_len = sizeof(SAPI_DEFAULT_CHARSET) - 1;
321 	}
322 
323 	if (*charset && strncasecmp(mimetype, "text/", 5) == 0) {
324 		char *p;
325 
326 		*len = prefix_len + mimetype_len + sizeof("; charset=") - 1 + charset_len;
327 		content_type = (char*)emalloc(*len + 1);
328 		p = content_type + prefix_len;
329 		memcpy(p, mimetype, mimetype_len);
330 		p += mimetype_len;
331 		memcpy(p, "; charset=", sizeof("; charset=") - 1);
332 		p += sizeof("; charset=") - 1;
333 		memcpy(p, charset, charset_len + 1);
334 	} else {
335 		*len = prefix_len + mimetype_len;
336 		content_type = (char*)emalloc(*len + 1);
337 		memcpy(content_type + prefix_len, mimetype, mimetype_len + 1);
338 	}
339 	return content_type;
340 }
341 
342 
sapi_get_default_content_type(void)343 SAPI_API char *sapi_get_default_content_type(void)
344 {
345 	uint32_t len;
346 
347 	return get_default_content_type(0, &len);
348 }
349 
350 
sapi_get_default_content_type_header(sapi_header_struct * default_header)351 SAPI_API void sapi_get_default_content_type_header(sapi_header_struct *default_header)
352 {
353     uint32_t len;
354 
355 	default_header->header = get_default_content_type(sizeof("Content-type: ")-1, &len);
356 	default_header->header_len = len;
357 	memcpy(default_header->header, "Content-type: ", sizeof("Content-type: ") - 1);
358 }
359 
360 /*
361  * Add charset on content-type header if the MIME type starts with
362  * "text/", the default_charset directive is not empty and
363  * there is not already a charset option in there.
364  *
365  * If "mimetype" is non-NULL, it should point to a pointer allocated
366  * with emalloc().  If a charset is added, the string will be
367  * re-allocated and the new length is returned.  If mimetype is
368  * unchanged, 0 is returned.
369  *
370  */
sapi_apply_default_charset(char ** mimetype,size_t len)371 SAPI_API size_t sapi_apply_default_charset(char **mimetype, size_t len)
372 {
373 	char *charset, *newtype;
374 	size_t newlen;
375 	charset = SG(default_charset) ? SG(default_charset) : SAPI_DEFAULT_CHARSET;
376 
377 	if (*mimetype != NULL) {
378 		if (*charset && strncmp(*mimetype, "text/", 5) == 0 && strstr(*mimetype, "charset=") == NULL) {
379 			newlen = len + (sizeof(";charset=")-1) + strlen(charset);
380 			newtype = emalloc(newlen + 1);
381 	 		PHP_STRLCPY(newtype, *mimetype, newlen + 1, len);
382 			strlcat(newtype, ";charset=", newlen + 1);
383 			strlcat(newtype, charset, newlen + 1);
384 			efree(*mimetype);
385 			*mimetype = newtype;
386 			return newlen;
387 		}
388 	}
389 	return 0;
390 }
391 
sapi_activate_headers_only(void)392 SAPI_API void sapi_activate_headers_only(void)
393 {
394 	if (SG(request_info).headers_read == 1)
395 		return;
396 	SG(request_info).headers_read = 1;
397 	zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct),
398 			(void (*)(void *)) sapi_free_header, 0);
399 	SG(sapi_headers).send_default_content_type = 1;
400 
401 	/* SG(sapi_headers).http_response_code = 200; */
402 	SG(sapi_headers).http_status_line = NULL;
403 	SG(sapi_headers).mimetype = NULL;
404 	SG(read_post_bytes) = 0;
405 	SG(request_info).request_body = NULL;
406 	SG(request_info).current_user = NULL;
407 	SG(request_info).current_user_length = 0;
408 	SG(request_info).no_headers = 0;
409 	SG(request_info).post_entry = NULL;
410 	SG(global_request_time) = 0;
411 
412 	/*
413 	 * It's possible to override this general case in the activate() callback,
414 	 * if necessary.
415 	 */
416 	if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) {
417 		SG(request_info).headers_only = 1;
418 	} else {
419 		SG(request_info).headers_only = 0;
420 	}
421 	if (SG(server_context)) {
422 		SG(request_info).cookie_data = sapi_module.read_cookies();
423 		if (sapi_module.activate) {
424 			sapi_module.activate();
425 		}
426 	}
427 	if (sapi_module.input_filter_init ) {
428 		sapi_module.input_filter_init();
429 	}
430 }
431 
432 /*
433  * Called from php_request_startup() for every request.
434  */
435 
sapi_activate(void)436 SAPI_API void sapi_activate(void)
437 {
438 	zend_llist_init(&SG(sapi_headers).headers, sizeof(sapi_header_struct), (void (*)(void *)) sapi_free_header, 0);
439 	SG(sapi_headers).send_default_content_type = 1;
440 
441 	/*
442 	SG(sapi_headers).http_response_code = 200;
443 	*/
444 	SG(sapi_headers).http_status_line = NULL;
445 	SG(sapi_headers).mimetype = NULL;
446 	SG(headers_sent) = 0;
447 	ZVAL_UNDEF(&SG(callback_func));
448 	SG(read_post_bytes) = 0;
449 	SG(request_info).request_body = NULL;
450 	SG(request_info).current_user = NULL;
451 	SG(request_info).current_user_length = 0;
452 	SG(request_info).no_headers = 0;
453 	SG(request_info).post_entry = NULL;
454 	SG(request_info).proto_num = 1000; /* Default to HTTP 1.0 */
455 	SG(global_request_time) = 0;
456 	SG(post_read) = 0;
457 	/* It's possible to override this general case in the activate() callback, if necessary. */
458 	if (SG(request_info).request_method && !strcmp(SG(request_info).request_method, "HEAD")) {
459 		SG(request_info).headers_only = 1;
460 	} else {
461 		SG(request_info).headers_only = 0;
462 	}
463 	SG(rfc1867_uploaded_files) = NULL;
464 
465 	/* Handle request method */
466 	if (SG(server_context)) {
467 		if (PG(enable_post_data_reading)
468 		&& 	SG(request_info).content_type
469 		&&  SG(request_info).request_method
470 		&& !strcmp(SG(request_info).request_method, "POST")) {
471 			/* HTTP POST may contain form data to be processed into variables
472 			 * depending on given content type */
473 			sapi_read_post_data();
474 		} else {
475 			SG(request_info).content_type_dup = NULL;
476 		}
477 
478 		/* Cookies */
479 		SG(request_info).cookie_data = sapi_module.read_cookies();
480 	}
481 	if (sapi_module.activate) {
482 		sapi_module.activate();
483 	}
484 	if (sapi_module.input_filter_init) {
485 		sapi_module.input_filter_init();
486 	}
487 }
488 
489 
sapi_send_headers_free(void)490 static void sapi_send_headers_free(void)
491 {
492 	if (SG(sapi_headers).http_status_line) {
493 		efree(SG(sapi_headers).http_status_line);
494 		SG(sapi_headers).http_status_line = NULL;
495 	}
496 }
497 
sapi_deactivate(void)498 SAPI_API void sapi_deactivate(void)
499 {
500 	zend_llist_destroy(&SG(sapi_headers).headers);
501 	if (SG(request_info).request_body) {
502 		SG(request_info).request_body = NULL;
503 	} else if (SG(server_context)) {
504 		if (!SG(post_read)) {
505 			/* make sure we've consumed all request input data */
506 			char dummy[SAPI_POST_BLOCK_SIZE];
507 			size_t read_bytes;
508 
509 			do {
510 				read_bytes = sapi_read_post_block(dummy, SAPI_POST_BLOCK_SIZE);
511 			} while (SAPI_POST_BLOCK_SIZE == read_bytes);
512 		}
513 	}
514 	if (SG(request_info).auth_user) {
515 		efree(SG(request_info).auth_user);
516 	}
517 	if (SG(request_info).auth_password) {
518 		efree(SG(request_info).auth_password);
519 	}
520 	if (SG(request_info).auth_digest) {
521 		efree(SG(request_info).auth_digest);
522 	}
523 	if (SG(request_info).content_type_dup) {
524 		efree(SG(request_info).content_type_dup);
525 	}
526 	if (SG(request_info).current_user) {
527 		efree(SG(request_info).current_user);
528 	}
529 	if (sapi_module.deactivate) {
530 		sapi_module.deactivate();
531 	}
532 	if (SG(rfc1867_uploaded_files)) {
533 		destroy_uploaded_files_hash();
534 	}
535 	if (SG(sapi_headers).mimetype) {
536 		efree(SG(sapi_headers).mimetype);
537 		SG(sapi_headers).mimetype = NULL;
538 	}
539 	sapi_send_headers_free();
540 	SG(sapi_started) = 0;
541 	SG(headers_sent) = 0;
542 	SG(request_info).headers_read = 0;
543 	SG(global_request_time) = 0;
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(char * header_line,size_t header_line_len,zend_bool duplicate,zend_bool replace)619 SAPI_API int sapi_add_header_ex(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(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 = p->line;
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 	header_line = estrndup(header_line, header_line_len);
709 
710 	/* cut off trailing spaces, linefeeds and carriage-returns */
711 	if (header_line_len && isspace(header_line[header_line_len-1])) {
712 		do {
713 			header_line_len--;
714 		} while(header_line_len && isspace(header_line[header_line_len-1]));
715 		header_line[header_line_len]='\0';
716 	}
717 
718 	if (op == SAPI_HEADER_DELETE) {
719 		if (strchr(header_line, ':')) {
720 			efree(header_line);
721 			sapi_module.sapi_error(E_WARNING, "Header to delete may not contain colon.");
722 			return FAILURE;
723 		}
724 		if (sapi_module.header_handler) {
725 			sapi_header.header = header_line;
726 			sapi_header.header_len = header_line_len;
727 			sapi_module.header_handler(&sapi_header, op, &SG(sapi_headers));
728 		}
729 		sapi_remove_header(&SG(sapi_headers).headers, header_line, header_line_len);
730 		efree(header_line);
731 		return SUCCESS;
732 	} else {
733 		/* new line/NUL character safety check */
734 		uint32_t i;
735 		for (i = 0; i < header_line_len; i++) {
736 			/* RFC 7230 ch. 3.2.4 deprecates folding support */
737 			if (header_line[i] == '\n' || header_line[i] == '\r') {
738 				efree(header_line);
739 				sapi_module.sapi_error(E_WARNING, "Header may not contain "
740 						"more than a single header, new line detected");
741 				return FAILURE;
742 			}
743 			if (header_line[i] == '\0') {
744 				efree(header_line);
745 				sapi_module.sapi_error(E_WARNING, "Header may not contain NUL bytes");
746 				return FAILURE;
747 			}
748 		}
749 	}
750 
751 	sapi_header.header = header_line;
752 	sapi_header.header_len = header_line_len;
753 
754 	/* Check the header for a few cases that we have special support for in SAPI */
755 	if (header_line_len>=5
756 		&& !strncasecmp(header_line, "HTTP/", 5)) {
757 		/* filter out the response code */
758 		sapi_update_response_code(sapi_extract_response_code(header_line));
759 		/* sapi_update_response_code doesn't free the status line if the code didn't change */
760 		if (SG(sapi_headers).http_status_line) {
761 			efree(SG(sapi_headers).http_status_line);
762 		}
763 		SG(sapi_headers).http_status_line = header_line;
764 		return SUCCESS;
765 	} else {
766 		colon_offset = strchr(header_line, ':');
767 		if (colon_offset) {
768 			*colon_offset = 0;
769 			if (!strcasecmp(header_line, "Content-Type")) {
770 				char *ptr = colon_offset+1, *mimetype = NULL, *newheader;
771 				size_t len = header_line_len - (ptr - header_line), newlen;
772 				while (*ptr == ' ') {
773 					ptr++;
774 					len--;
775 				}
776 
777 				/* Disable possible output compression for images */
778 				if (!strncmp(ptr, "image/", sizeof("image/")-1)) {
779 					zend_string *key = zend_string_init("zlib.output_compression", sizeof("zlib.output_compression")-1, 0);
780 					zend_alter_ini_entry_chars(key, "0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
781 					zend_string_release_ex(key, 0);
782 				}
783 
784 				mimetype = estrdup(ptr);
785 				newlen = sapi_apply_default_charset(&mimetype, len);
786 				if (!SG(sapi_headers).mimetype){
787 					SG(sapi_headers).mimetype = estrdup(mimetype);
788 				}
789 
790 				if (newlen != 0) {
791 					newlen += sizeof("Content-type: ");
792 					newheader = emalloc(newlen);
793 					PHP_STRLCPY(newheader, "Content-type: ", newlen, sizeof("Content-type: ")-1);
794 					strlcat(newheader, mimetype, newlen);
795 					sapi_header.header = newheader;
796 					sapi_header.header_len = (uint32_t)(newlen - 1);
797 					efree(header_line);
798 				}
799 				efree(mimetype);
800 				SG(sapi_headers).send_default_content_type = 0;
801 			} else if (!strcasecmp(header_line, "Content-Length")) {
802 				/* Script is setting Content-length. The script cannot reasonably
803 				 * know the size of the message body after compression, so it's best
804 				 * do disable compression altogether. This contributes to making scripts
805 				 * portable between setups that have and don't have zlib compression
806 				 * enabled globally. See req #44164 */
807 				zend_string *key = zend_string_init("zlib.output_compression", sizeof("zlib.output_compression")-1, 0);
808 				zend_alter_ini_entry_chars(key,
809 					"0", sizeof("0") - 1, PHP_INI_USER, PHP_INI_STAGE_RUNTIME);
810 				zend_string_release_ex(key, 0);
811 			} else if (!strcasecmp(header_line, "Location")) {
812 				if ((SG(sapi_headers).http_response_code < 300 ||
813 					SG(sapi_headers).http_response_code > 399) &&
814 					SG(sapi_headers).http_response_code != 201) {
815 					/* Return a Found Redirect if one is not already specified */
816 					if (http_response_code) { /* user specified redirect code */
817 						sapi_update_response_code(http_response_code);
818 					} else if (SG(request_info).proto_num > 1000 &&
819 					   SG(request_info).request_method &&
820 					   strcmp(SG(request_info).request_method, "HEAD") &&
821 					   strcmp(SG(request_info).request_method, "GET")) {
822 						sapi_update_response_code(303);
823 					} else {
824 						sapi_update_response_code(302);
825 					}
826 				}
827 			} else if (!strcasecmp(header_line, "WWW-Authenticate")) { /* HTTP Authentication */
828 				sapi_update_response_code(401); /* authentication-required */
829 			}
830 			if (sapi_header.header==header_line) {
831 				*colon_offset = ':';
832 			}
833 		}
834 	}
835 	if (http_response_code) {
836 		sapi_update_response_code(http_response_code);
837 	}
838 	sapi_header_add_op(op, &sapi_header);
839 	return SUCCESS;
840 }
841 
842 
sapi_send_headers(void)843 SAPI_API int sapi_send_headers(void)
844 {
845 	int retval;
846 	int ret = FAILURE;
847 
848 	if (SG(headers_sent) || SG(request_info).no_headers) {
849 		return SUCCESS;
850 	}
851 
852 	/* Success-oriented.  We set headers_sent to 1 here to avoid an infinite loop
853 	 * in case of an error situation.
854 	 */
855 	if (SG(sapi_headers).send_default_content_type && sapi_module.send_headers) {
856 	    uint32_t len = 0;
857 		char *default_mimetype = get_default_content_type(0, &len);
858 
859 		if (default_mimetype && len) {
860 			sapi_header_struct default_header;
861 
862 			SG(sapi_headers).mimetype = default_mimetype;
863 
864 			default_header.header_len = sizeof("Content-type: ") - 1 + len;
865 			default_header.header = emalloc(default_header.header_len + 1);
866 
867 			memcpy(default_header.header, "Content-type: ", sizeof("Content-type: ") - 1);
868 			memcpy(default_header.header + sizeof("Content-type: ") - 1, SG(sapi_headers).mimetype, len + 1);
869 
870 			sapi_header_add_op(SAPI_HEADER_ADD, &default_header);
871 		} else {
872 			efree(default_mimetype);
873 		}
874 		SG(sapi_headers).send_default_content_type = 0;
875 	}
876 
877 	if (Z_TYPE(SG(callback_func)) != IS_UNDEF) {
878 		zval cb;
879 		ZVAL_COPY_VALUE(&cb, &SG(callback_func));
880 		ZVAL_UNDEF(&SG(callback_func));
881 		sapi_run_header_callback(&cb);
882 		zval_ptr_dtor(&cb);
883 	}
884 
885 	SG(headers_sent) = 1;
886 
887 	if (sapi_module.send_headers) {
888 		retval = sapi_module.send_headers(&SG(sapi_headers));
889 	} else {
890 		retval = SAPI_HEADER_DO_SEND;
891 	}
892 
893 	switch (retval) {
894 		case SAPI_HEADER_SENT_SUCCESSFULLY:
895 			ret = SUCCESS;
896 			break;
897 		case SAPI_HEADER_DO_SEND: {
898 				sapi_header_struct http_status_line;
899 				char buf[255];
900 
901 				if (SG(sapi_headers).http_status_line) {
902 					http_status_line.header = SG(sapi_headers).http_status_line;
903 					http_status_line.header_len = (uint32_t)strlen(SG(sapi_headers).http_status_line);
904 				} else {
905 					http_status_line.header = buf;
906 					http_status_line.header_len = slprintf(buf, sizeof(buf), "HTTP/1.0 %d X", SG(sapi_headers).http_response_code);
907 				}
908 				sapi_module.send_header(&http_status_line, SG(server_context));
909 			}
910 			zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t) sapi_module.send_header, SG(server_context));
911 			if(SG(sapi_headers).send_default_content_type) {
912 				sapi_header_struct default_header;
913 
914 				sapi_get_default_content_type_header(&default_header);
915 				sapi_module.send_header(&default_header, SG(server_context));
916 				sapi_free_header(&default_header);
917 			}
918 			sapi_module.send_header(NULL, SG(server_context));
919 			ret = SUCCESS;
920 			break;
921 		case SAPI_HEADER_SEND_FAILED:
922 			SG(headers_sent) = 0;
923 			ret = FAILURE;
924 			break;
925 	}
926 
927 	sapi_send_headers_free();
928 
929 	return ret;
930 }
931 
932 
sapi_register_post_entries(const sapi_post_entry * post_entries)933 SAPI_API int sapi_register_post_entries(const sapi_post_entry *post_entries)
934 {
935 	const sapi_post_entry *p=post_entries;
936 
937 	while (p->content_type) {
938 		if (sapi_register_post_entry(p) == FAILURE) {
939 			return FAILURE;
940 		}
941 		p++;
942 	}
943 	return SUCCESS;
944 }
945 
946 
sapi_register_post_entry(const sapi_post_entry * post_entry)947 SAPI_API int sapi_register_post_entry(const sapi_post_entry *post_entry)
948 {
949 	int ret;
950 	zend_string *key;
951 	if (SG(sapi_started) && EG(current_execute_data)) {
952 		return FAILURE;
953 	}
954 	key = zend_string_init(post_entry->content_type, post_entry->content_type_len, 1);
955 	GC_MAKE_PERSISTENT_LOCAL(key);
956 	ret = zend_hash_add_mem(&SG(known_post_content_types), key,
957 			(void *) post_entry, sizeof(sapi_post_entry)) ? SUCCESS : FAILURE;
958 	zend_string_release_ex(key, 1);
959 	return ret;
960 }
961 
sapi_unregister_post_entry(const sapi_post_entry * post_entry)962 SAPI_API void sapi_unregister_post_entry(const sapi_post_entry *post_entry)
963 {
964 	if (SG(sapi_started) && EG(current_execute_data)) {
965 		return;
966 	}
967 	zend_hash_str_del(&SG(known_post_content_types), post_entry->content_type,
968 			post_entry->content_type_len);
969 }
970 
971 
sapi_register_default_post_reader(void (* default_post_reader)(void))972 SAPI_API int sapi_register_default_post_reader(void (*default_post_reader)(void))
973 {
974 	if (SG(sapi_started) && EG(current_execute_data)) {
975 		return FAILURE;
976 	}
977 	sapi_module.default_post_reader = default_post_reader;
978 	return SUCCESS;
979 }
980 
981 
sapi_register_treat_data(void (* treat_data)(int arg,char * str,zval * destArray))982 SAPI_API int sapi_register_treat_data(void (*treat_data)(int arg, char *str, zval *destArray))
983 {
984 	if (SG(sapi_started) && EG(current_execute_data)) {
985 		return FAILURE;
986 	}
987 	sapi_module.treat_data = treat_data;
988 	return SUCCESS;
989 }
990 
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))991 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))
992 {
993 	if (SG(sapi_started) && EG(current_execute_data)) {
994 		return FAILURE;
995 	}
996 	sapi_module.input_filter = input_filter;
997 	sapi_module.input_filter_init = input_filter_init;
998 	return SUCCESS;
999 }
1000 
sapi_flush(void)1001 SAPI_API int sapi_flush(void)
1002 {
1003 	if (sapi_module.flush) {
1004 		sapi_module.flush(SG(server_context));
1005 		return SUCCESS;
1006 	} else {
1007 		return FAILURE;
1008 	}
1009 }
1010 
sapi_get_stat(void)1011 SAPI_API zend_stat_t *sapi_get_stat(void)
1012 {
1013 	if (sapi_module.get_stat) {
1014 		return sapi_module.get_stat();
1015 	} else {
1016 		if (!SG(request_info).path_translated || (VCWD_STAT(SG(request_info).path_translated, &SG(global_stat)) == -1)) {
1017 			return NULL;
1018 		}
1019 		return &SG(global_stat);
1020 	}
1021 }
1022 
sapi_getenv(char * name,size_t name_len)1023 SAPI_API char *sapi_getenv(char *name, size_t name_len)
1024 {
1025 	if (!strncasecmp(name, "HTTP_PROXY", name_len)) {
1026 		/* Ugly fix for HTTP_PROXY issue, see bug #72573 */
1027 		return NULL;
1028 	}
1029 	if (sapi_module.getenv) {
1030 		char *value, *tmp = sapi_module.getenv(name, name_len);
1031 		if (tmp) {
1032 			value = estrdup(tmp);
1033 #ifdef PHP_WIN32
1034 			if (strlen(sapi_module.name) == sizeof("cgi-fcgi") - 1 && !strcmp(sapi_module.name, "cgi-fcgi")) {
1035 				/* XXX more modules to go, if needed. */
1036 				free(tmp);
1037 			}
1038 #endif
1039 		} else {
1040 			return NULL;
1041 		}
1042 		if (sapi_module.input_filter) {
1043 			sapi_module.input_filter(PARSE_STRING, name, &value, strlen(value), NULL);
1044 		}
1045 		return value;
1046 	}
1047 	return NULL;
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 && SG(server_context)) {
1092 		SG(global_request_time) = sapi_module.get_request_time();
1093 	} else {
1094 		struct timeval tp = {0};
1095 		if (!gettimeofday(&tp, NULL)) {
1096 			SG(global_request_time) = (double)(tp.tv_sec + tp.tv_usec / 1000000.00);
1097 		} else {
1098 			SG(global_request_time) = (double)time(0);
1099 		}
1100 	}
1101 	return SG(global_request_time);
1102 }
1103 
sapi_terminate_process(void)1104 SAPI_API void sapi_terminate_process(void) {
1105 	if (sapi_module.terminate_process) {
1106 		sapi_module.terminate_process();
1107 	}
1108 }
1109 
sapi_add_request_header(char * var,unsigned int var_len,char * val,unsigned int val_len,void * arg)1110 SAPI_API void sapi_add_request_header(char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg) /* {{{ */
1111 {
1112 	zval *return_value = (zval*)arg;
1113 	char *str = NULL;
1114 
1115 	ALLOCA_FLAG(use_heap)
1116 
1117 	if (var_len > 5 &&
1118 	    var[0] == 'H' &&
1119 	    var[1] == 'T' &&
1120 	    var[2] == 'T' &&
1121 	    var[3] == 'P' &&
1122 	    var[4] == '_') {
1123 
1124 		char *p;
1125 
1126 		var_len -= 5;
1127 		p = var + 5;
1128 		var = str = 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 (str) {
1155 		free_alloca(var, use_heap);
1156 	}
1157 }
1158 /* }}} */
1159 
1160 /*
1161  * Local variables:
1162  * tab-width: 4
1163  * c-basic-offset: 4
1164  * End:
1165  * vim600: sw=4 ts=4 fdm=marker
1166  * vim<600: sw=4 ts=4
1167  */
1168