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    | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca>                       |
16    |          Zeev Suraski <zeev@php.net>                                 |
17    +----------------------------------------------------------------------+
18  */
19 
20 #include <stdio.h>
21 #include "php.h"
22 #include "ext/standard/php_standard.h"
23 #include "ext/standard/credits.h"
24 #include "zend_smart_str.h"
25 #include "php_variables.h"
26 #include "php_globals.h"
27 #include "php_content_types.h"
28 #include "SAPI.h"
29 #include "zend_globals.h"
30 #ifdef PHP_WIN32
31 # include "win32/php_inttypes.h"
32 #endif
33 
34 /* for systems that need to override reading of environment variables */
35 void _php_import_environment_variables(zval *array_ptr);
36 PHPAPI void (*php_import_environment_variables)(zval *array_ptr) = _php_import_environment_variables;
37 
php_register_variable(char * var,char * strval,zval * track_vars_array)38 PHPAPI void php_register_variable(char *var, char *strval, zval *track_vars_array)
39 {
40 	php_register_variable_safe(var, strval, strlen(strval), track_vars_array);
41 }
42 
43 /* binary-safe version */
php_register_variable_safe(char * var,char * strval,size_t str_len,zval * track_vars_array)44 PHPAPI void php_register_variable_safe(char *var, char *strval, size_t str_len, zval *track_vars_array)
45 {
46 	zval new_entry;
47 	assert(strval != NULL);
48 
49 	/* Prepare value */
50 	if (str_len == 0) {
51 		ZVAL_EMPTY_STRING(&new_entry);
52 	} else if (str_len == 1) {
53 		ZVAL_INTERNED_STR(&new_entry, ZSTR_CHAR((zend_uchar)*strval));
54 	} else {
55 		ZVAL_NEW_STR(&new_entry, zend_string_init(strval, str_len, 0));
56 	}
57 	php_register_variable_ex(var, &new_entry, track_vars_array);
58 }
59 
php_register_variable_quick(const char * name,size_t name_len,zval * val,HashTable * ht)60 static zend_always_inline void php_register_variable_quick(const char *name, size_t name_len, zval *val, HashTable *ht)
61 {
62 	zend_string *key = zend_string_init_interned(name, name_len, 0);
63 
64 	zend_hash_update_ind(ht, key, val);
65 	zend_string_release_ex(key, 0);
66 }
67 
php_register_variable_ex(char * var_name,zval * val,zval * track_vars_array)68 PHPAPI void php_register_variable_ex(char *var_name, zval *val, zval *track_vars_array)
69 {
70 	char *p = NULL;
71 	char *ip = NULL;		/* index pointer */
72 	char *index;
73 	char *var, *var_orig;
74 	size_t var_len, index_len;
75 	zval gpc_element, *gpc_element_p;
76 	zend_bool is_array = 0;
77 	HashTable *symtable1 = NULL;
78 	ALLOCA_FLAG(use_heap)
79 
80 	assert(var_name != NULL);
81 
82 	if (track_vars_array && Z_TYPE_P(track_vars_array) == IS_ARRAY) {
83 		symtable1 = Z_ARRVAL_P(track_vars_array);
84 	}
85 
86 	if (!symtable1) {
87 		/* Nothing to do */
88 		zval_ptr_dtor_nogc(val);
89 		return;
90 	}
91 
92 
93 	/* ignore leading spaces in the variable name */
94 	while (*var_name==' ') {
95 		var_name++;
96 	}
97 
98 	/*
99 	 * Prepare variable name
100 	 */
101 	var_len = strlen(var_name);
102 	var = var_orig = do_alloca(var_len + 1, use_heap);
103 	memcpy(var_orig, var_name, var_len + 1);
104 
105 	/* ensure that we don't have spaces or dots in the variable name (not binary safe) */
106 	for (p = var; *p; p++) {
107 		if (*p == ' ' || *p == '.') {
108 			*p='_';
109 		} else if (*p == '[') {
110 			is_array = 1;
111 			ip = p;
112 			*p = 0;
113 			break;
114 		}
115 	}
116 	var_len = p - var;
117 
118 	if (var_len==0) { /* empty variable name, or variable name with a space in it */
119 		zval_ptr_dtor_nogc(val);
120 		free_alloca(var_orig, use_heap);
121 		return;
122 	}
123 
124 	if (var_len == sizeof("this")-1 && EG(current_execute_data)) {
125 		zend_execute_data *ex = EG(current_execute_data);
126 
127 		while (ex) {
128 			if (ex->func && ZEND_USER_CODE(ex->func->common.type)) {
129 				if ((ZEND_CALL_INFO(ex) & ZEND_CALL_HAS_SYMBOL_TABLE)
130 						&& ex->symbol_table == symtable1) {
131 					if (memcmp(var, "this", sizeof("this")-1) == 0) {
132 						zend_throw_error(NULL, "Cannot re-assign $this");
133 						zval_ptr_dtor_nogc(val);
134 						free_alloca(var_orig, use_heap);
135 						return;
136 					}
137 				}
138 				break;
139 			}
140 			ex = ex->prev_execute_data;
141 		}
142 	}
143 
144 	/* GLOBALS hijack attempt, reject parameter */
145 	if (symtable1 == &EG(symbol_table) &&
146 		var_len == sizeof("GLOBALS")-1 &&
147 		!memcmp(var, "GLOBALS", sizeof("GLOBALS")-1)) {
148 		zval_ptr_dtor_nogc(val);
149 		free_alloca(var_orig, use_heap);
150 		return;
151 	}
152 
153 	index = var;
154 	index_len = var_len;
155 
156 	if (is_array) {
157 		int nest_level = 0;
158 		while (1) {
159 			char *index_s;
160 			size_t new_idx_len = 0;
161 
162 			if(++nest_level > PG(max_input_nesting_level)) {
163 				HashTable *ht;
164 				/* too many levels of nesting */
165 
166 				if (track_vars_array) {
167 					ht = Z_ARRVAL_P(track_vars_array);
168 					zend_symtable_str_del(ht, var, var_len);
169 				}
170 
171 				zval_ptr_dtor_nogc(val);
172 
173 				/* do not output the error message to the screen,
174 				 this helps us to to avoid "information disclosure" */
175 				if (!PG(display_errors)) {
176 					php_error_docref(NULL, E_WARNING, "Input variable nesting level exceeded " ZEND_LONG_FMT ". To increase the limit change max_input_nesting_level in php.ini.", PG(max_input_nesting_level));
177 				}
178 				free_alloca(var_orig, use_heap);
179 				return;
180 			}
181 
182 			ip++;
183 			index_s = ip;
184 			if (isspace(*ip)) {
185 				ip++;
186 			}
187 			if (*ip==']') {
188 				index_s = NULL;
189 			} else {
190 				ip = strchr(ip, ']');
191 				if (!ip) {
192 					/* PHP variables cannot contain '[' in their names, so we replace the character with a '_' */
193 					*(index_s - 1) = '_';
194 
195 					index_len = 0;
196 					if (index) {
197 						index_len = strlen(index);
198 					}
199 					goto plain_var;
200 					return;
201 				}
202 				*ip = 0;
203 				new_idx_len = strlen(index_s);
204 			}
205 
206 			if (!index) {
207 				array_init(&gpc_element);
208 				if ((gpc_element_p = zend_hash_next_index_insert(symtable1, &gpc_element)) == NULL) {
209 					zend_array_destroy(Z_ARR(gpc_element));
210 					zval_ptr_dtor_nogc(val);
211 					free_alloca(var_orig, use_heap);
212 					return;
213 				}
214 			} else {
215 				gpc_element_p = zend_symtable_str_find(symtable1, index, index_len);
216 				if (!gpc_element_p) {
217 					zval tmp;
218 					array_init(&tmp);
219 					gpc_element_p = zend_symtable_str_update_ind(symtable1, index, index_len, &tmp);
220 				} else {
221 					if (Z_TYPE_P(gpc_element_p) == IS_INDIRECT) {
222 						gpc_element_p = Z_INDIRECT_P(gpc_element_p);
223 					}
224 					if (Z_TYPE_P(gpc_element_p) != IS_ARRAY) {
225 						zval_ptr_dtor_nogc(gpc_element_p);
226 						array_init(gpc_element_p);
227 					} else {
228 						SEPARATE_ARRAY(gpc_element_p);
229 					}
230 				}
231 			}
232 			symtable1 = Z_ARRVAL_P(gpc_element_p);
233 			/* ip pointed to the '[' character, now obtain the key */
234 			index = index_s;
235 			index_len = new_idx_len;
236 
237 			ip++;
238 			if (*ip == '[') {
239 				is_array = 1;
240 				*ip = 0;
241 			} else {
242 				goto plain_var;
243 			}
244 		}
245 	} else {
246 plain_var:
247 		if (!index) {
248 			if (zend_hash_next_index_insert(symtable1, val) == NULL) {
249 				zval_ptr_dtor_nogc(val);
250 			}
251 		} else {
252 			zend_ulong idx;
253 
254 			/*
255 			 * According to rfc2965, more specific paths are listed above the less specific ones.
256 			 * If we encounter a duplicate cookie name, we should skip it, since it is not possible
257 			 * to have the same (plain text) cookie name for the same path and we should not overwrite
258 			 * more specific cookies with the less specific ones.
259 			 */
260 			if (Z_TYPE(PG(http_globals)[TRACK_VARS_COOKIE]) != IS_UNDEF &&
261 				symtable1 == Z_ARRVAL(PG(http_globals)[TRACK_VARS_COOKIE]) &&
262 				zend_symtable_str_exists(symtable1, index, index_len)) {
263 				zval_ptr_dtor_nogc(val);
264 			} else if (ZEND_HANDLE_NUMERIC_STR(index, index_len, idx)) {
265 				zend_hash_index_update(symtable1, idx, val);
266 			} else {
267 				php_register_variable_quick(index, index_len, val, symtable1);
268 			}
269 		}
270 	}
271 	free_alloca(var_orig, use_heap);
272 }
273 
274 typedef struct post_var_data {
275 	smart_str str;
276 	char *ptr;
277 	char *end;
278 	uint64_t cnt;
279 
280 	/* Bytes in ptr that have already been scanned for '&' */
281 	size_t already_scanned;
282 } post_var_data_t;
283 
add_post_var(zval * arr,post_var_data_t * var,zend_bool eof)284 static zend_bool add_post_var(zval *arr, post_var_data_t *var, zend_bool eof)
285 {
286 	char *start, *ksep, *vsep, *val;
287 	size_t klen, vlen;
288 	size_t new_vlen;
289 
290 	if (var->ptr >= var->end) {
291 		return 0;
292 	}
293 
294 	start = var->ptr + var->already_scanned;
295 	vsep = memchr(start, '&', var->end - start);
296 	if (!vsep) {
297 		if (!eof) {
298 			var->already_scanned = var->end - var->ptr;
299 			return 0;
300 		} else {
301 			vsep = var->end;
302 		}
303 	}
304 
305 	ksep = memchr(var->ptr, '=', vsep - var->ptr);
306 	if (ksep) {
307 		*ksep = '\0';
308 		/* "foo=bar&" or "foo=&" */
309 		klen = ksep - var->ptr;
310 		vlen = vsep - ++ksep;
311 	} else {
312 		ksep = "";
313 		/* "foo&" */
314 		klen = vsep - var->ptr;
315 		vlen = 0;
316 	}
317 
318 	php_url_decode(var->ptr, klen);
319 
320 	val = estrndup(ksep, vlen);
321 	if (vlen) {
322 		vlen = php_url_decode(val, vlen);
323 	}
324 
325 	if (sapi_module.input_filter(PARSE_POST, var->ptr, &val, vlen, &new_vlen)) {
326 		php_register_variable_safe(var->ptr, val, new_vlen, arr);
327 	}
328 	efree(val);
329 
330 	var->ptr = vsep + (vsep != var->end);
331 	var->already_scanned = 0;
332 	return 1;
333 }
334 
add_post_vars(zval * arr,post_var_data_t * vars,zend_bool eof)335 static inline int add_post_vars(zval *arr, post_var_data_t *vars, zend_bool eof)
336 {
337 	uint64_t max_vars = PG(max_input_vars);
338 
339 	vars->ptr = ZSTR_VAL(vars->str.s);
340 	vars->end = ZSTR_VAL(vars->str.s) + ZSTR_LEN(vars->str.s);
341 	while (add_post_var(arr, vars, eof)) {
342 		if (++vars->cnt > max_vars) {
343 			php_error_docref(NULL, E_WARNING,
344 					"Input variables exceeded %" PRIu64 ". "
345 					"To increase the limit change max_input_vars in php.ini.",
346 					max_vars);
347 			return FAILURE;
348 		}
349 	}
350 
351 	if (!eof && ZSTR_VAL(vars->str.s) != vars->ptr) {
352 		memmove(ZSTR_VAL(vars->str.s), vars->ptr, ZSTR_LEN(vars->str.s) = vars->end - vars->ptr);
353 	}
354 	return SUCCESS;
355 }
356 
357 #ifdef PHP_WIN32
358 #define SAPI_POST_HANDLER_BUFSIZ 16384
359 #else
360 # define SAPI_POST_HANDLER_BUFSIZ BUFSIZ
361 #endif
SAPI_POST_HANDLER_FUNC(php_std_post_handler)362 SAPI_API SAPI_POST_HANDLER_FUNC(php_std_post_handler)
363 {
364 	zval *arr = (zval *) arg;
365 	php_stream *s = SG(request_info).request_body;
366 	post_var_data_t post_data;
367 
368 	if (s && SUCCESS == php_stream_rewind(s)) {
369 		memset(&post_data, 0, sizeof(post_data));
370 
371 		while (!php_stream_eof(s)) {
372 			char buf[SAPI_POST_HANDLER_BUFSIZ] = {0};
373 			ssize_t len = php_stream_read(s, buf, SAPI_POST_HANDLER_BUFSIZ);
374 
375 			if (len > 0) {
376 				smart_str_appendl(&post_data.str, buf, len);
377 
378 				if (SUCCESS != add_post_vars(arr, &post_data, 0)) {
379 					smart_str_free(&post_data.str);
380 					return;
381 				}
382 			}
383 
384 			if (len != SAPI_POST_HANDLER_BUFSIZ){
385 				break;
386 			}
387 		}
388 
389 		if (post_data.str.s) {
390 			add_post_vars(arr, &post_data, 1);
391 			smart_str_free(&post_data.str);
392 		}
393 	}
394 }
395 #undef SAPI_POST_HANDLER_BUFSIZ
396 
SAPI_INPUT_FILTER_FUNC(php_default_input_filter)397 SAPI_API SAPI_INPUT_FILTER_FUNC(php_default_input_filter)
398 {
399 	/* TODO: check .ini setting here and apply user-defined input filter */
400 	if(new_val_len) *new_val_len = val_len;
401 	return 1;
402 }
403 
SAPI_TREAT_DATA_FUNC(php_default_treat_data)404 SAPI_API SAPI_TREAT_DATA_FUNC(php_default_treat_data)
405 {
406 	char *res = NULL, *var, *val, *separator = NULL;
407 	const char *c_var;
408 	zval array;
409 	int free_buffer = 0;
410 	char *strtok_buf = NULL;
411 	zend_long count = 0;
412 
413 	ZVAL_UNDEF(&array);
414 	switch (arg) {
415 		case PARSE_POST:
416 		case PARSE_GET:
417 		case PARSE_COOKIE:
418 			array_init(&array);
419 			switch (arg) {
420 				case PARSE_POST:
421 					zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_POST]);
422 					ZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_POST], &array);
423 					break;
424 				case PARSE_GET:
425 					zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_GET]);
426 					ZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_GET], &array);
427 					break;
428 				case PARSE_COOKIE:
429 					zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_COOKIE]);
430 					ZVAL_COPY_VALUE(&PG(http_globals)[TRACK_VARS_COOKIE], &array);
431 					break;
432 			}
433 			break;
434 		default:
435 			ZVAL_COPY_VALUE(&array, destArray);
436 			break;
437 	}
438 
439 	if (arg == PARSE_POST) {
440 		sapi_handle_post(&array);
441 		return;
442 	}
443 
444 	if (arg == PARSE_GET) {		/* GET data */
445 		c_var = SG(request_info).query_string;
446 		if (c_var && *c_var) {
447 			res = (char *) estrdup(c_var);
448 			free_buffer = 1;
449 		} else {
450 			free_buffer = 0;
451 		}
452 	} else if (arg == PARSE_COOKIE) {		/* Cookie data */
453 		c_var = SG(request_info).cookie_data;
454 		if (c_var && *c_var) {
455 			res = (char *) estrdup(c_var);
456 			free_buffer = 1;
457 		} else {
458 			free_buffer = 0;
459 		}
460 	} else if (arg == PARSE_STRING) {		/* String data */
461 		res = str;
462 		free_buffer = 1;
463 	}
464 
465 	if (!res) {
466 		return;
467 	}
468 
469 	switch (arg) {
470 		case PARSE_GET:
471 		case PARSE_STRING:
472 			separator = PG(arg_separator).input;
473 			break;
474 		case PARSE_COOKIE:
475 			separator = ";\0";
476 			break;
477 	}
478 
479 	var = php_strtok_r(res, separator, &strtok_buf);
480 
481 	while (var) {
482 		size_t val_len;
483 		size_t new_val_len;
484 
485 		val = strchr(var, '=');
486 
487 		if (arg == PARSE_COOKIE) {
488 			/* Remove leading spaces from cookie names, needed for multi-cookie header where ; can be followed by a space */
489 			while (isspace(*var)) {
490 				var++;
491 			}
492 			if (var == val || *var == '\0') {
493 				goto next_cookie;
494 			}
495 		}
496 
497 		if (++count > PG(max_input_vars)) {
498 			php_error_docref(NULL, E_WARNING, "Input variables exceeded " ZEND_LONG_FMT ". To increase the limit change max_input_vars in php.ini.", PG(max_input_vars));
499 			break;
500 		}
501 
502 		if (val) { /* have a value */
503 
504 			*val++ = '\0';
505 
506 			if (arg == PARSE_COOKIE) {
507 				val_len = php_raw_url_decode(val, strlen(val));
508 			} else {
509 				val_len = php_url_decode(val, strlen(val));
510 			}
511 		} else {
512 			val     = "";
513 			val_len =  0;
514 		}
515 
516 		val = estrndup(val, val_len);
517 		if (arg != PARSE_COOKIE) {
518 			php_url_decode(var, strlen(var));
519 		}
520 		if (sapi_module.input_filter(arg, var, &val, val_len, &new_val_len)) {
521 			php_register_variable_safe(var, val, new_val_len, &array);
522 		}
523 		efree(val);
524 next_cookie:
525 		var = php_strtok_r(NULL, separator, &strtok_buf);
526 	}
527 
528 	if (free_buffer) {
529 		efree(res);
530 	}
531 }
532 
valid_environment_name(const char * name,const char * end)533 static zend_always_inline int valid_environment_name(const char *name, const char *end)
534 {
535 	const char *s;
536 
537 	for (s = name; s < end; s++) {
538 		if (*s == ' ' || *s == '.' || *s == '[') {
539 			return 0;
540 		}
541 	}
542 	return 1;
543 }
544 
import_environment_variable(HashTable * ht,char * env)545 static zend_always_inline void import_environment_variable(HashTable *ht, char *env)
546 {
547 	char *p;
548 	size_t name_len, len;
549 	zval val;
550 	zend_ulong idx;
551 
552 	p = strchr(env, '=');
553 	if (!p
554 		|| p == env
555 		|| !valid_environment_name(env, p)) {
556 		/* malformed entry? */
557 		return;
558 	}
559 	name_len = p - env;
560 	p++;
561 	len = strlen(p);
562 	if (len == 0) {
563 		ZVAL_EMPTY_STRING(&val);
564 	} else if (len == 1) {
565 		ZVAL_INTERNED_STR(&val, ZSTR_CHAR((zend_uchar)*p));
566 	} else {
567 		ZVAL_NEW_STR(&val, zend_string_init(p, len, 0));
568 	}
569 	if (ZEND_HANDLE_NUMERIC_STR(env, name_len, idx)) {
570 		zend_hash_index_update(ht, idx, &val);
571 	} else {
572 		php_register_variable_quick(env, name_len, &val, ht);
573 	}
574 }
575 
_php_import_environment_variables(zval * array_ptr)576 void _php_import_environment_variables(zval *array_ptr)
577 {
578 #ifndef PHP_WIN32
579 	char **env;
580 #else
581 	char *environment, *env;
582 #endif
583 
584 	tsrm_env_lock();
585 
586 #ifndef PHP_WIN32
587 	for (env = environ; env != NULL && *env != NULL; env++) {
588 		import_environment_variable(Z_ARRVAL_P(array_ptr), *env);
589 	}
590 #else
591 	environment = GetEnvironmentStringsA();
592 	for (env = environment; env != NULL && *env; env += strlen(env) + 1) {
593 		import_environment_variable(Z_ARRVAL_P(array_ptr), env);
594 	}
595 	FreeEnvironmentStringsA(environment);
596 #endif
597 
598 	tsrm_env_unlock();
599 }
600 
php_std_auto_global_callback(char * name,uint32_t name_len)601 zend_bool php_std_auto_global_callback(char *name, uint32_t name_len)
602 {
603 	zend_printf("%s\n", name);
604 	return 0; /* don't rearm */
605 }
606 
607 /* {{{ php_build_argv
608  */
php_build_argv(char * s,zval * track_vars_array)609 PHPAPI void php_build_argv(char *s, zval *track_vars_array)
610 {
611 	zval arr, argc, tmp;
612 	int count = 0;
613 	char *ss, *space;
614 
615 	if (!(SG(request_info).argc || track_vars_array)) {
616 		return;
617 	}
618 
619 	array_init(&arr);
620 
621 	/* Prepare argv */
622 	if (SG(request_info).argc) { /* are we in cli sapi? */
623 		int i;
624 		for (i = 0; i < SG(request_info).argc; i++) {
625 			ZVAL_STRING(&tmp, SG(request_info).argv[i]);
626 			if (zend_hash_next_index_insert(Z_ARRVAL(arr), &tmp) == NULL) {
627 				zend_string_efree(Z_STR(tmp));
628 			}
629 		}
630 	} else 	if (s && *s) {
631 		ss = s;
632 		while (ss) {
633 			space = strchr(ss, '+');
634 			if (space) {
635 				*space = '\0';
636 			}
637 			/* auto-type */
638 			ZVAL_STRING(&tmp, ss);
639 			count++;
640 			if (zend_hash_next_index_insert(Z_ARRVAL(arr), &tmp) == NULL) {
641 				zend_string_efree(Z_STR(tmp));
642 			}
643 			if (space) {
644 				*space = '+';
645 				ss = space + 1;
646 			} else {
647 				ss = space;
648 			}
649 		}
650 	}
651 
652 	/* prepare argc */
653 	if (SG(request_info).argc) {
654 		ZVAL_LONG(&argc, SG(request_info).argc);
655 	} else {
656 		ZVAL_LONG(&argc, count);
657 	}
658 
659 	if (SG(request_info).argc) {
660 		Z_ADDREF(arr);
661 		zend_hash_update(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_ARGV), &arr);
662 		zend_hash_update(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_ARGC), &argc);
663 	}
664 	if (track_vars_array && Z_TYPE_P(track_vars_array) == IS_ARRAY) {
665 		Z_ADDREF(arr);
666 		zend_hash_update(Z_ARRVAL_P(track_vars_array), ZSTR_KNOWN(ZEND_STR_ARGV), &arr);
667 		zend_hash_update(Z_ARRVAL_P(track_vars_array), ZSTR_KNOWN(ZEND_STR_ARGC), &argc);
668 	}
669 	zval_ptr_dtor_nogc(&arr);
670 }
671 /* }}} */
672 
673 /* {{{ php_register_server_variables
674  */
php_register_server_variables(void)675 static inline void php_register_server_variables(void)
676 {
677 	zval tmp;
678 	zval *arr = &PG(http_globals)[TRACK_VARS_SERVER];
679 	HashTable *ht;
680 
681 	zval_ptr_dtor_nogc(arr);
682 	array_init(arr);
683 
684 	/* Server variables */
685 	if (sapi_module.register_server_variables) {
686 		sapi_module.register_server_variables(arr);
687 	}
688 	ht = Z_ARRVAL_P(arr);
689 
690 	/* PHP Authentication support */
691 	if (SG(request_info).auth_user) {
692 		ZVAL_STRING(&tmp, SG(request_info).auth_user);
693 		php_register_variable_quick("PHP_AUTH_USER", sizeof("PHP_AUTH_USER")-1, &tmp, ht);
694 	}
695 	if (SG(request_info).auth_password) {
696 		ZVAL_STRING(&tmp, SG(request_info).auth_password);
697 		php_register_variable_quick("PHP_AUTH_PW", sizeof("PHP_AUTH_PW")-1, &tmp, ht);
698 	}
699 	if (SG(request_info).auth_digest) {
700 		ZVAL_STRING(&tmp, SG(request_info).auth_digest);
701 		php_register_variable_quick("PHP_AUTH_DIGEST", sizeof("PHP_AUTH_DIGEST")-1, &tmp, ht);
702 	}
703 
704 	/* store request init time */
705 	ZVAL_DOUBLE(&tmp, sapi_get_request_time());
706 	php_register_variable_quick("REQUEST_TIME_FLOAT", sizeof("REQUEST_TIME_FLOAT")-1, &tmp, ht);
707 	ZVAL_LONG(&tmp, zend_dval_to_lval(Z_DVAL(tmp)));
708 	php_register_variable_quick("REQUEST_TIME", sizeof("REQUEST_TIME")-1, &tmp, ht);
709 }
710 /* }}} */
711 
712 /* {{{ php_autoglobal_merge
713  */
php_autoglobal_merge(HashTable * dest,HashTable * src)714 static void php_autoglobal_merge(HashTable *dest, HashTable *src)
715 {
716 	zval *src_entry, *dest_entry;
717 	zend_string *string_key;
718 	zend_ulong num_key;
719 	int globals_check = (dest == (&EG(symbol_table)));
720 
721 	ZEND_HASH_FOREACH_KEY_VAL(src, num_key, string_key, src_entry) {
722 		if (Z_TYPE_P(src_entry) != IS_ARRAY
723 			|| (string_key && (dest_entry = zend_hash_find(dest, string_key)) == NULL)
724 			|| (string_key == NULL && (dest_entry = zend_hash_index_find(dest, num_key)) == NULL)
725 			|| Z_TYPE_P(dest_entry) != IS_ARRAY) {
726 			Z_TRY_ADDREF_P(src_entry);
727 			if (string_key) {
728 				if (!globals_check || ZSTR_LEN(string_key) != sizeof("GLOBALS") - 1
729 						|| memcmp(ZSTR_VAL(string_key), "GLOBALS", sizeof("GLOBALS") - 1)) {
730 					zend_hash_update(dest, string_key, src_entry);
731 				} else {
732 					Z_TRY_DELREF_P(src_entry);
733 				}
734 			} else {
735 				zend_hash_index_update(dest, num_key, src_entry);
736 			}
737 		} else {
738 			SEPARATE_ARRAY(dest_entry);
739 			php_autoglobal_merge(Z_ARRVAL_P(dest_entry), Z_ARRVAL_P(src_entry));
740 		}
741 	} ZEND_HASH_FOREACH_END();
742 }
743 /* }}} */
744 
745 /* {{{ php_hash_environment
746  */
php_hash_environment(void)747 PHPAPI int php_hash_environment(void)
748 {
749 	memset(PG(http_globals), 0, sizeof(PG(http_globals)));
750 	zend_activate_auto_globals();
751 	if (PG(register_argc_argv)) {
752 		php_build_argv(SG(request_info).query_string, &PG(http_globals)[TRACK_VARS_SERVER]);
753 	}
754 	return SUCCESS;
755 }
756 /* }}} */
757 
php_auto_globals_create_get(zend_string * name)758 static zend_bool php_auto_globals_create_get(zend_string *name)
759 {
760 	if (PG(variables_order) && (strchr(PG(variables_order),'G') || strchr(PG(variables_order),'g'))) {
761 		sapi_module.treat_data(PARSE_GET, NULL, NULL);
762 	} else {
763 		zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_GET]);
764 		array_init(&PG(http_globals)[TRACK_VARS_GET]);
765 	}
766 
767 	zend_hash_update(&EG(symbol_table), name, &PG(http_globals)[TRACK_VARS_GET]);
768 	Z_ADDREF(PG(http_globals)[TRACK_VARS_GET]);
769 
770 	return 0; /* don't rearm */
771 }
772 
php_auto_globals_create_post(zend_string * name)773 static zend_bool php_auto_globals_create_post(zend_string *name)
774 {
775 	if (PG(variables_order) &&
776 			(strchr(PG(variables_order),'P') || strchr(PG(variables_order),'p')) &&
777 		!SG(headers_sent) &&
778 		SG(request_info).request_method &&
779 		!strcasecmp(SG(request_info).request_method, "POST")) {
780 		sapi_module.treat_data(PARSE_POST, NULL, NULL);
781 	} else {
782 		zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_POST]);
783 		array_init(&PG(http_globals)[TRACK_VARS_POST]);
784 	}
785 
786 	zend_hash_update(&EG(symbol_table), name, &PG(http_globals)[TRACK_VARS_POST]);
787 	Z_ADDREF(PG(http_globals)[TRACK_VARS_POST]);
788 
789 	return 0; /* don't rearm */
790 }
791 
php_auto_globals_create_cookie(zend_string * name)792 static zend_bool php_auto_globals_create_cookie(zend_string *name)
793 {
794 	if (PG(variables_order) && (strchr(PG(variables_order),'C') || strchr(PG(variables_order),'c'))) {
795 		sapi_module.treat_data(PARSE_COOKIE, NULL, NULL);
796 	} else {
797 		zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_COOKIE]);
798 		array_init(&PG(http_globals)[TRACK_VARS_COOKIE]);
799 	}
800 
801 	zend_hash_update(&EG(symbol_table), name, &PG(http_globals)[TRACK_VARS_COOKIE]);
802 	Z_ADDREF(PG(http_globals)[TRACK_VARS_COOKIE]);
803 
804 	return 0; /* don't rearm */
805 }
806 
php_auto_globals_create_files(zend_string * name)807 static zend_bool php_auto_globals_create_files(zend_string *name)
808 {
809 	if (Z_TYPE(PG(http_globals)[TRACK_VARS_FILES]) == IS_UNDEF) {
810 		array_init(&PG(http_globals)[TRACK_VARS_FILES]);
811 	}
812 
813 	zend_hash_update(&EG(symbol_table), name, &PG(http_globals)[TRACK_VARS_FILES]);
814 	Z_ADDREF(PG(http_globals)[TRACK_VARS_FILES]);
815 
816 	return 0; /* don't rearm */
817 }
818 
819 /* Upgly hack to fix HTTP_PROXY issue, see bug #72573 */
check_http_proxy(HashTable * var_table)820 static void check_http_proxy(HashTable *var_table)
821 {
822 	if (zend_hash_str_exists(var_table, "HTTP_PROXY", sizeof("HTTP_PROXY")-1)) {
823 		char *local_proxy = getenv("HTTP_PROXY");
824 
825 		if (!local_proxy) {
826 			zend_hash_str_del(var_table, "HTTP_PROXY", sizeof("HTTP_PROXY")-1);
827 		} else {
828 			zval local_zval;
829 			ZVAL_STRING(&local_zval, local_proxy);
830 			zend_hash_str_update(var_table, "HTTP_PROXY", sizeof("HTTP_PROXY")-1, &local_zval);
831 		}
832 	}
833 }
834 
php_auto_globals_create_server(zend_string * name)835 static zend_bool php_auto_globals_create_server(zend_string *name)
836 {
837 	if (PG(variables_order) && (strchr(PG(variables_order),'S') || strchr(PG(variables_order),'s'))) {
838 		php_register_server_variables();
839 
840 		if (PG(register_argc_argv)) {
841 			if (SG(request_info).argc) {
842 				zval *argc, *argv;
843 
844 				if ((argc = zend_hash_find_ex_ind(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_ARGC), 1)) != NULL &&
845 					(argv = zend_hash_find_ex_ind(&EG(symbol_table), ZSTR_KNOWN(ZEND_STR_ARGV), 1)) != NULL) {
846 					Z_ADDREF_P(argv);
847 					zend_hash_update(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), ZSTR_KNOWN(ZEND_STR_ARGV), argv);
848 					zend_hash_update(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]), ZSTR_KNOWN(ZEND_STR_ARGC), argc);
849 				}
850 			} else {
851 				php_build_argv(SG(request_info).query_string, &PG(http_globals)[TRACK_VARS_SERVER]);
852 			}
853 		}
854 
855 	} else {
856 		zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_SERVER]);
857 		array_init(&PG(http_globals)[TRACK_VARS_SERVER]);
858 	}
859 
860 	check_http_proxy(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]));
861 	zend_hash_update(&EG(symbol_table), name, &PG(http_globals)[TRACK_VARS_SERVER]);
862 	Z_ADDREF(PG(http_globals)[TRACK_VARS_SERVER]);
863 
864 	/* TODO: TRACK_VARS_SERVER is modified in a number of places (e.g. phar) past this point,
865 	 * where rc>1 due to the $_SERVER global. Ideally this shouldn't happen, but for now we
866 	 * ignore this issue, as it would probably require larger changes. */
867 	HT_ALLOW_COW_VIOLATION(Z_ARRVAL(PG(http_globals)[TRACK_VARS_SERVER]));
868 
869 	return 0; /* don't rearm */
870 }
871 
php_auto_globals_create_env(zend_string * name)872 static zend_bool php_auto_globals_create_env(zend_string *name)
873 {
874 	zval_ptr_dtor_nogc(&PG(http_globals)[TRACK_VARS_ENV]);
875 	array_init(&PG(http_globals)[TRACK_VARS_ENV]);
876 
877 	if (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) {
878 		php_import_environment_variables(&PG(http_globals)[TRACK_VARS_ENV]);
879 	}
880 
881 	check_http_proxy(Z_ARRVAL(PG(http_globals)[TRACK_VARS_ENV]));
882 	zend_hash_update(&EG(symbol_table), name, &PG(http_globals)[TRACK_VARS_ENV]);
883 	Z_ADDREF(PG(http_globals)[TRACK_VARS_ENV]);
884 
885 	return 0; /* don't rearm */
886 }
887 
php_auto_globals_create_request(zend_string * name)888 static zend_bool php_auto_globals_create_request(zend_string *name)
889 {
890 	zval form_variables;
891 	unsigned char _gpc_flags[3] = {0, 0, 0};
892 	char *p;
893 
894 	array_init(&form_variables);
895 
896 	if (PG(request_order) != NULL) {
897 		p = PG(request_order);
898 	} else {
899 		p = PG(variables_order);
900 	}
901 
902 	for (; p && *p; p++) {
903 		switch (*p) {
904 			case 'g':
905 			case 'G':
906 				if (!_gpc_flags[0]) {
907 					php_autoglobal_merge(Z_ARRVAL(form_variables), Z_ARRVAL(PG(http_globals)[TRACK_VARS_GET]));
908 					_gpc_flags[0] = 1;
909 				}
910 				break;
911 			case 'p':
912 			case 'P':
913 				if (!_gpc_flags[1]) {
914 					php_autoglobal_merge(Z_ARRVAL(form_variables), Z_ARRVAL(PG(http_globals)[TRACK_VARS_POST]));
915 					_gpc_flags[1] = 1;
916 				}
917 				break;
918 			case 'c':
919 			case 'C':
920 				if (!_gpc_flags[2]) {
921 					php_autoglobal_merge(Z_ARRVAL(form_variables), Z_ARRVAL(PG(http_globals)[TRACK_VARS_COOKIE]));
922 					_gpc_flags[2] = 1;
923 				}
924 				break;
925 		}
926 	}
927 
928 	zend_hash_update(&EG(symbol_table), name, &form_variables);
929 	return 0;
930 }
931 
php_startup_auto_globals(void)932 void php_startup_auto_globals(void)
933 {
934 	zend_register_auto_global(zend_string_init_interned("_GET", sizeof("_GET")-1, 1), 0, php_auto_globals_create_get);
935 	zend_register_auto_global(zend_string_init_interned("_POST", sizeof("_POST")-1, 1), 0, php_auto_globals_create_post);
936 	zend_register_auto_global(zend_string_init_interned("_COOKIE", sizeof("_COOKIE")-1, 1), 0, php_auto_globals_create_cookie);
937 	zend_register_auto_global(zend_string_init_interned("_SERVER", sizeof("_SERVER")-1, 1), PG(auto_globals_jit), php_auto_globals_create_server);
938 	zend_register_auto_global(zend_string_init_interned("_ENV", sizeof("_ENV")-1, 1), PG(auto_globals_jit), php_auto_globals_create_env);
939 	zend_register_auto_global(zend_string_init_interned("_REQUEST", sizeof("_REQUEST")-1, 1), PG(auto_globals_jit), php_auto_globals_create_request);
940 	zend_register_auto_global(zend_string_init_interned("_FILES", sizeof("_FILES")-1, 1), 0, php_auto_globals_create_files);
941 }
942