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