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