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