xref: /PHP-8.0/ext/filter/filter.c (revision 46c0c82a)
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   | http://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@php.net>                             |
14   |          Derick Rethans <derick@php.net>                             |
15   |          Pierre-A. Joye <pierre@php.net>                             |
16   |          Ilia Alshanetsky <iliaa@php.net>                            |
17   +----------------------------------------------------------------------+
18 */
19 
20 #ifdef HAVE_CONFIG_H
21 #include "config.h"
22 #endif
23 
24 #include "php_filter.h"
25 
26 ZEND_DECLARE_MODULE_GLOBALS(filter)
27 
28 #include "filter_private.h"
29 #include "filter_arginfo.h"
30 
31 typedef struct filter_list_entry {
32 	const char *name;
33 	int    id;
34 	void (*function)(PHP_INPUT_FILTER_PARAM_DECL);
35 } filter_list_entry;
36 
37 /* {{{ filter_list */
38 static const filter_list_entry filter_list[] = {
39 	{ "int",             FILTER_VALIDATE_INT,           php_filter_int             },
40 	{ "boolean",         FILTER_VALIDATE_BOOL,          php_filter_boolean         },
41 	{ "float",           FILTER_VALIDATE_FLOAT,         php_filter_float           },
42 
43 	{ "validate_regexp", FILTER_VALIDATE_REGEXP,        php_filter_validate_regexp },
44 	{ "validate_domain", FILTER_VALIDATE_DOMAIN,        php_filter_validate_domain },
45 	{ "validate_url",    FILTER_VALIDATE_URL,           php_filter_validate_url    },
46 	{ "validate_email",  FILTER_VALIDATE_EMAIL,         php_filter_validate_email  },
47 	{ "validate_ip",     FILTER_VALIDATE_IP,            php_filter_validate_ip     },
48 	{ "validate_mac",    FILTER_VALIDATE_MAC,           php_filter_validate_mac    },
49 
50 	{ "string",          FILTER_SANITIZE_STRING,        php_filter_string          },
51 	{ "stripped",        FILTER_SANITIZE_STRING,        php_filter_string          },
52 	{ "encoded",         FILTER_SANITIZE_ENCODED,       php_filter_encoded         },
53 	{ "special_chars",   FILTER_SANITIZE_SPECIAL_CHARS, php_filter_special_chars   },
54 	{ "full_special_chars",   FILTER_SANITIZE_FULL_SPECIAL_CHARS, php_filter_full_special_chars   },
55 	{ "unsafe_raw",      FILTER_UNSAFE_RAW,             php_filter_unsafe_raw      },
56 	{ "email",           FILTER_SANITIZE_EMAIL,         php_filter_email           },
57 	{ "url",             FILTER_SANITIZE_URL,           php_filter_url             },
58 	{ "number_int",      FILTER_SANITIZE_NUMBER_INT,    php_filter_number_int      },
59 	{ "number_float",    FILTER_SANITIZE_NUMBER_FLOAT,  php_filter_number_float    },
60 	{ "add_slashes",     FILTER_SANITIZE_ADD_SLASHES,   php_filter_add_slashes     },
61 
62 	{ "callback",        FILTER_CALLBACK,               php_filter_callback        },
63 };
64 /* }}} */
65 
66 #ifndef PARSE_ENV
67 #define PARSE_ENV 4
68 #endif
69 
70 #ifndef PARSE_SERVER
71 #define PARSE_SERVER 5
72 #endif
73 
74 #ifndef PARSE_SESSION
75 #define PARSE_SESSION 6
76 #endif
77 
78 static unsigned int php_sapi_filter(int arg, const char *var, char **val, size_t val_len, size_t *new_val_len);
79 static unsigned int php_sapi_filter_init(void);
80 
81 /* {{{ filter_module_entry */
82 zend_module_entry filter_module_entry = {
83 	STANDARD_MODULE_HEADER,
84 	"filter",
85 	ext_functions,
86 	PHP_MINIT(filter),
87 	PHP_MSHUTDOWN(filter),
88 	NULL,
89 	PHP_RSHUTDOWN(filter),
90 	PHP_MINFO(filter),
91 	PHP_FILTER_VERSION,
92 	STANDARD_MODULE_PROPERTIES
93 };
94 /* }}} */
95 
96 #ifdef COMPILE_DL_FILTER
97 #ifdef ZTS
98 ZEND_TSRMLS_CACHE_DEFINE()
99 #endif
ZEND_GET_MODULE(filter)100 ZEND_GET_MODULE(filter)
101 #endif
102 
103 static PHP_INI_MH(UpdateDefaultFilter) /* {{{ */
104 {
105 	int i, size = sizeof(filter_list) / sizeof(filter_list_entry);
106 
107 	for (i = 0; i < size; ++i) {
108 		if ((strcasecmp(ZSTR_VAL(new_value), filter_list[i].name) == 0)) {
109 			IF_G(default_filter) = filter_list[i].id;
110 			return SUCCESS;
111 		}
112 	}
113 	/* Fallback to the default filter */
114 	IF_G(default_filter) = FILTER_DEFAULT;
115 	return SUCCESS;
116 }
117 /* }}} */
118 
119 /* {{{ PHP_INI */
PHP_INI_MH(OnUpdateFlags)120 static PHP_INI_MH(OnUpdateFlags)
121 {
122 	if (!new_value) {
123 		IF_G(default_filter_flags) = FILTER_FLAG_NO_ENCODE_QUOTES;
124 	} else {
125 		IF_G(default_filter_flags) = atoi(ZSTR_VAL(new_value));
126 	}
127 	return SUCCESS;
128 }
129 
130 PHP_INI_BEGIN()
131 	STD_PHP_INI_ENTRY("filter.default",   "unsafe_raw", PHP_INI_SYSTEM|PHP_INI_PERDIR, UpdateDefaultFilter, default_filter, zend_filter_globals, filter_globals)
132 	PHP_INI_ENTRY("filter.default_flags", NULL,     PHP_INI_SYSTEM|PHP_INI_PERDIR, OnUpdateFlags)
PHP_INI_END()133 PHP_INI_END()
134 /* }}} */
135 
136 static void php_filter_init_globals(zend_filter_globals *filter_globals) /* {{{ */
137 {
138 #if defined(COMPILE_DL_FILTER) && defined(ZTS)
139 ZEND_TSRMLS_CACHE_UPDATE();
140 #endif
141 	ZVAL_UNDEF(&filter_globals->post_array);
142 	ZVAL_UNDEF(&filter_globals->get_array);
143 	ZVAL_UNDEF(&filter_globals->cookie_array);
144 	ZVAL_UNDEF(&filter_globals->env_array);
145 	ZVAL_UNDEF(&filter_globals->server_array);
146 #if 0
147 	ZVAL_UNDEF(&filter_globals->session_array);
148 #endif
149 	filter_globals->default_filter = FILTER_DEFAULT;
150 }
151 /* }}} */
152 
153 #define PARSE_REQUEST 99
154 
155 /* {{{ PHP_MINIT_FUNCTION */
PHP_MINIT_FUNCTION(filter)156 PHP_MINIT_FUNCTION(filter)
157 {
158 	ZEND_INIT_MODULE_GLOBALS(filter, php_filter_init_globals, NULL);
159 
160 	REGISTER_INI_ENTRIES();
161 
162 	REGISTER_LONG_CONSTANT("INPUT_POST",	PARSE_POST, 	CONST_CS | CONST_PERSISTENT);
163 	REGISTER_LONG_CONSTANT("INPUT_GET",		PARSE_GET,		CONST_CS | CONST_PERSISTENT);
164 	REGISTER_LONG_CONSTANT("INPUT_COOKIE",	PARSE_COOKIE, 	CONST_CS | CONST_PERSISTENT);
165 	REGISTER_LONG_CONSTANT("INPUT_ENV",		PARSE_ENV,		CONST_CS | CONST_PERSISTENT);
166 	REGISTER_LONG_CONSTANT("INPUT_SERVER",	PARSE_SERVER, 	CONST_CS | CONST_PERSISTENT);
167 
168 	REGISTER_LONG_CONSTANT("FILTER_FLAG_NONE", FILTER_FLAG_NONE, CONST_CS | CONST_PERSISTENT);
169 
170 	REGISTER_LONG_CONSTANT("FILTER_REQUIRE_SCALAR", FILTER_REQUIRE_SCALAR, CONST_CS | CONST_PERSISTENT);
171 	REGISTER_LONG_CONSTANT("FILTER_REQUIRE_ARRAY", FILTER_REQUIRE_ARRAY, CONST_CS | CONST_PERSISTENT);
172 	REGISTER_LONG_CONSTANT("FILTER_FORCE_ARRAY", FILTER_FORCE_ARRAY, CONST_CS | CONST_PERSISTENT);
173 	REGISTER_LONG_CONSTANT("FILTER_NULL_ON_FAILURE", FILTER_NULL_ON_FAILURE, CONST_CS | CONST_PERSISTENT);
174 
175 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_INT", FILTER_VALIDATE_INT, CONST_CS | CONST_PERSISTENT);
176 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_BOOLEAN", FILTER_VALIDATE_BOOL, CONST_CS | CONST_PERSISTENT);
177 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_BOOL", FILTER_VALIDATE_BOOL, CONST_CS | CONST_PERSISTENT);
178 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_FLOAT", FILTER_VALIDATE_FLOAT, CONST_CS | CONST_PERSISTENT);
179 
180 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_REGEXP", FILTER_VALIDATE_REGEXP, CONST_CS | CONST_PERSISTENT);
181 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_DOMAIN", FILTER_VALIDATE_DOMAIN, CONST_CS | CONST_PERSISTENT);
182 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_URL", FILTER_VALIDATE_URL, CONST_CS | CONST_PERSISTENT);
183 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_EMAIL", FILTER_VALIDATE_EMAIL, CONST_CS | CONST_PERSISTENT);
184 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_IP", FILTER_VALIDATE_IP, CONST_CS | CONST_PERSISTENT);
185 	REGISTER_LONG_CONSTANT("FILTER_VALIDATE_MAC", FILTER_VALIDATE_MAC, CONST_CS | CONST_PERSISTENT);
186 
187 	REGISTER_LONG_CONSTANT("FILTER_DEFAULT", FILTER_DEFAULT, CONST_CS | CONST_PERSISTENT);
188 	REGISTER_LONG_CONSTANT("FILTER_UNSAFE_RAW", FILTER_UNSAFE_RAW, CONST_CS | CONST_PERSISTENT);
189 
190 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRING", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT);
191 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_STRIPPED", FILTER_SANITIZE_STRING, CONST_CS | CONST_PERSISTENT);
192 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_ENCODED", FILTER_SANITIZE_ENCODED, CONST_CS | CONST_PERSISTENT);
193 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_SPECIAL_CHARS", FILTER_SANITIZE_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT);
194 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_FULL_SPECIAL_CHARS", FILTER_SANITIZE_FULL_SPECIAL_CHARS, CONST_CS | CONST_PERSISTENT);
195 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_EMAIL", FILTER_SANITIZE_EMAIL, CONST_CS | CONST_PERSISTENT);
196 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_URL", FILTER_SANITIZE_URL, CONST_CS | CONST_PERSISTENT);
197 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_INT", FILTER_SANITIZE_NUMBER_INT, CONST_CS | CONST_PERSISTENT);
198 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_NUMBER_FLOAT", FILTER_SANITIZE_NUMBER_FLOAT, CONST_CS | CONST_PERSISTENT);
199 	REGISTER_LONG_CONSTANT("FILTER_SANITIZE_ADD_SLASHES", FILTER_SANITIZE_ADD_SLASHES, CONST_CS | CONST_PERSISTENT);
200 
201 	REGISTER_LONG_CONSTANT("FILTER_CALLBACK", FILTER_CALLBACK, CONST_CS | CONST_PERSISTENT);
202 
203 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_OCTAL", FILTER_FLAG_ALLOW_OCTAL, CONST_CS | CONST_PERSISTENT);
204 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_HEX", FILTER_FLAG_ALLOW_HEX, CONST_CS | CONST_PERSISTENT);
205 
206 	REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_LOW", FILTER_FLAG_STRIP_LOW, CONST_CS | CONST_PERSISTENT);
207 	REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_HIGH", FILTER_FLAG_STRIP_HIGH, CONST_CS | CONST_PERSISTENT);
208 	REGISTER_LONG_CONSTANT("FILTER_FLAG_STRIP_BACKTICK", FILTER_FLAG_STRIP_BACKTICK, CONST_CS | CONST_PERSISTENT);
209 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_LOW", FILTER_FLAG_ENCODE_LOW, CONST_CS | CONST_PERSISTENT);
210 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_HIGH", FILTER_FLAG_ENCODE_HIGH, CONST_CS | CONST_PERSISTENT);
211 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ENCODE_AMP", FILTER_FLAG_ENCODE_AMP, CONST_CS | CONST_PERSISTENT);
212 	REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_ENCODE_QUOTES", FILTER_FLAG_NO_ENCODE_QUOTES, CONST_CS | CONST_PERSISTENT);
213 	REGISTER_LONG_CONSTANT("FILTER_FLAG_EMPTY_STRING_NULL", FILTER_FLAG_EMPTY_STRING_NULL, CONST_CS | CONST_PERSISTENT);
214 
215 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_FRACTION", FILTER_FLAG_ALLOW_FRACTION, CONST_CS | CONST_PERSISTENT);
216 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_THOUSAND", FILTER_FLAG_ALLOW_THOUSAND, CONST_CS | CONST_PERSISTENT);
217 	REGISTER_LONG_CONSTANT("FILTER_FLAG_ALLOW_SCIENTIFIC", FILTER_FLAG_ALLOW_SCIENTIFIC, CONST_CS | CONST_PERSISTENT);
218 
219 	REGISTER_LONG_CONSTANT("FILTER_FLAG_PATH_REQUIRED", FILTER_FLAG_PATH_REQUIRED, CONST_CS | CONST_PERSISTENT);
220 	REGISTER_LONG_CONSTANT("FILTER_FLAG_QUERY_REQUIRED", FILTER_FLAG_QUERY_REQUIRED, CONST_CS | CONST_PERSISTENT);
221 
222 	REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV4", FILTER_FLAG_IPV4, CONST_CS | CONST_PERSISTENT);
223 	REGISTER_LONG_CONSTANT("FILTER_FLAG_IPV6", FILTER_FLAG_IPV6, CONST_CS | CONST_PERSISTENT);
224 	REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_RES_RANGE", FILTER_FLAG_NO_RES_RANGE, CONST_CS | CONST_PERSISTENT);
225 	REGISTER_LONG_CONSTANT("FILTER_FLAG_NO_PRIV_RANGE", FILTER_FLAG_NO_PRIV_RANGE, CONST_CS | CONST_PERSISTENT);
226 
227 	REGISTER_LONG_CONSTANT("FILTER_FLAG_HOSTNAME", FILTER_FLAG_HOSTNAME, CONST_CS | CONST_PERSISTENT);
228 
229 	REGISTER_LONG_CONSTANT("FILTER_FLAG_EMAIL_UNICODE", FILTER_FLAG_EMAIL_UNICODE, CONST_CS | CONST_PERSISTENT);
230 
231 	sapi_register_input_filter(php_sapi_filter, php_sapi_filter_init);
232 
233 	return SUCCESS;
234 }
235 /* }}} */
236 
237 /* {{{ PHP_MSHUTDOWN_FUNCTION */
PHP_MSHUTDOWN_FUNCTION(filter)238 PHP_MSHUTDOWN_FUNCTION(filter)
239 {
240 	UNREGISTER_INI_ENTRIES();
241 
242 	return SUCCESS;
243 }
244 /* }}} */
245 
246 /* {{{ PHP_RSHUTDOWN_FUNCTION */
247 #define VAR_ARRAY_COPY_DTOR(a)   \
248 	if (!Z_ISUNDEF(IF_G(a))) {   \
249 		zval_ptr_dtor(&IF_G(a)); \
250 		ZVAL_UNDEF(&IF_G(a));    \
251 	}
252 
PHP_RSHUTDOWN_FUNCTION(filter)253 PHP_RSHUTDOWN_FUNCTION(filter)
254 {
255 	VAR_ARRAY_COPY_DTOR(get_array)
256 	VAR_ARRAY_COPY_DTOR(post_array)
257 	VAR_ARRAY_COPY_DTOR(cookie_array)
258 	VAR_ARRAY_COPY_DTOR(server_array)
259 	VAR_ARRAY_COPY_DTOR(env_array)
260 #if 0
261 	VAR_ARRAY_COPY_DTOR(session_array)
262 #endif
263 	return SUCCESS;
264 }
265 /* }}} */
266 
267 /* {{{ PHP_MINFO_FUNCTION */
PHP_MINFO_FUNCTION(filter)268 PHP_MINFO_FUNCTION(filter)
269 {
270 	php_info_print_table_start();
271 	php_info_print_table_row( 2, "Input Validation and Filtering", "enabled" );
272 	php_info_print_table_end();
273 
274 	DISPLAY_INI_ENTRIES();
275 }
276 /* }}} */
277 
php_find_filter(zend_long id)278 static filter_list_entry php_find_filter(zend_long id) /* {{{ */
279 {
280 	int i, size = sizeof(filter_list) / sizeof(filter_list_entry);
281 
282 	for (i = 0; i < size; ++i) {
283 		if (filter_list[i].id == id) {
284 			return filter_list[i];
285 		}
286 	}
287 	/* Fallback to "string" filter */
288 	for (i = 0; i < size; ++i) {
289 		if (filter_list[i].id == FILTER_DEFAULT) {
290 			return filter_list[i];
291 		}
292 	}
293 	/* To shut up GCC */
294 	return filter_list[0];
295 }
296 /* }}} */
297 
php_sapi_filter_init(void)298 static unsigned int php_sapi_filter_init(void)
299 {
300 	ZVAL_UNDEF(&IF_G(get_array));
301 	ZVAL_UNDEF(&IF_G(post_array));
302 	ZVAL_UNDEF(&IF_G(cookie_array));
303 	ZVAL_UNDEF(&IF_G(server_array));
304 	ZVAL_UNDEF(&IF_G(env_array));
305 #if 0
306 	ZVAL_UNDEF(&IF_G(session_array));
307 #endif
308 	return SUCCESS;
309 }
310 
php_zval_filter(zval * value,zend_long filter,zend_long flags,zval * options,char * charset,zend_bool copy)311 static void php_zval_filter(zval *value, zend_long filter, zend_long flags, zval *options, char* charset, zend_bool copy) /* {{{ */
312 {
313 	filter_list_entry  filter_func;
314 
315 	filter_func = php_find_filter(filter);
316 
317 	if (!filter_func.id) {
318 		/* Find default filter */
319 		filter_func = php_find_filter(FILTER_DEFAULT);
320 	}
321 
322 	/* #49274, fatal error with object without a toString method
323 	  Fails nicely instead of getting a recovarable fatal error. */
324 	if (Z_TYPE_P(value) == IS_OBJECT) {
325 		zend_class_entry *ce;
326 
327 		ce = Z_OBJCE_P(value);
328 		if (!ce->__tostring) {
329 			zval_ptr_dtor(value);
330 			/* #67167: doesn't return null on failure for objects */
331 			if (flags & FILTER_NULL_ON_FAILURE) {
332 				ZVAL_NULL(value);
333 			} else {
334 				ZVAL_FALSE(value);
335 			}
336 			goto handle_default;
337 		}
338 	}
339 
340 	/* Here be strings */
341 	convert_to_string(value);
342 
343 	filter_func.function(value, flags, options, charset);
344 
345 handle_default:
346 	if (options && Z_TYPE_P(options) == IS_ARRAY &&
347 		((flags & FILTER_NULL_ON_FAILURE && Z_TYPE_P(value) == IS_NULL) ||
348 		(!(flags & FILTER_NULL_ON_FAILURE) && Z_TYPE_P(value) == IS_FALSE))) {
349 		zval *tmp;
350 		if ((tmp = zend_hash_str_find(Z_ARRVAL_P(options), "default", sizeof("default") - 1)) != NULL) {
351 			ZVAL_COPY(value, tmp);
352 		}
353 	}
354 }
355 /* }}} */
356 
php_sapi_filter(int arg,const char * var,char ** val,size_t val_len,size_t * new_val_len)357 static unsigned int php_sapi_filter(int arg, const char *var, char **val, size_t val_len, size_t *new_val_len) /* {{{ */
358 {
359 	zval  new_var, raw_var;
360 	zval *array_ptr = NULL, *orig_array_ptr = NULL;
361 	int retval = 0;
362 
363 	assert(*val != NULL);
364 
365 #define PARSE_CASE(s,a,t)                     		\
366 		case s:                               		\
367 			if (Z_ISUNDEF(IF_G(a))) {         		\
368 				array_init(&IF_G(a)); 				\
369 			}										\
370 			array_ptr = &IF_G(a);          			\
371 			orig_array_ptr = &PG(http_globals)[t]; 	\
372 			break;
373 
374 	switch (arg) {
375 		PARSE_CASE(PARSE_POST,    post_array,    TRACK_VARS_POST)
376 		PARSE_CASE(PARSE_GET,     get_array,     TRACK_VARS_GET)
377 		PARSE_CASE(PARSE_COOKIE,  cookie_array,  TRACK_VARS_COOKIE)
378 		PARSE_CASE(PARSE_SERVER,  server_array,  TRACK_VARS_SERVER)
379 		PARSE_CASE(PARSE_ENV,     env_array,     TRACK_VARS_ENV)
380 
381 		case PARSE_STRING: /* PARSE_STRING is used by parse_str() function */
382 			retval = 1;
383 			break;
384 	}
385 
386 	/*
387 	 * According to rfc2965, more specific paths are listed above the less specific ones.
388 	 * If we encounter a duplicate cookie name, we should skip it, since it is not possible
389 	 * to have the same (plain text) cookie name for the same path and we should not overwrite
390 	 * more specific cookies with the less specific ones.
391 	*/
392 	if (arg == PARSE_COOKIE && orig_array_ptr &&
393 			zend_symtable_str_exists(Z_ARRVAL_P(orig_array_ptr), var, strlen(var))) {
394 		return 0;
395 	}
396 
397 	if (array_ptr) {
398 		/* Store the RAW variable internally */
399 		ZVAL_STRINGL(&raw_var, *val, val_len);
400 		php_register_variable_ex(var, &raw_var, array_ptr);
401 	}
402 
403 	if (val_len) {
404 		/* Register mangled variable */
405 		if (IF_G(default_filter) != FILTER_UNSAFE_RAW) {
406 			ZVAL_STRINGL(&new_var, *val, val_len);
407 			php_zval_filter(&new_var, IF_G(default_filter), IF_G(default_filter_flags), NULL, NULL, 0);
408 		} else {
409 			ZVAL_STRINGL(&new_var, *val, val_len);
410 		}
411 	} else { /* empty string */
412 		ZVAL_EMPTY_STRING(&new_var);
413 	}
414 
415 	if (orig_array_ptr) {
416 		php_register_variable_ex(var, &new_var, orig_array_ptr);
417 	}
418 
419 	if (retval) {
420 		if (new_val_len) {
421 			*new_val_len = Z_STRLEN(new_var);
422 		}
423 		efree(*val);
424 		if (Z_STRLEN(new_var)) {
425 			*val = estrndup(Z_STRVAL(new_var), Z_STRLEN(new_var));
426 		} else {
427 			*val = estrdup("");
428 		}
429 		zval_ptr_dtor(&new_var);
430 	}
431 
432 	return retval;
433 }
434 /* }}} */
435 
php_zval_filter_recursive(zval * value,zend_long filter,zend_long flags,zval * options,char * charset,zend_bool copy)436 static void php_zval_filter_recursive(zval *value, zend_long filter, zend_long flags, zval *options, char *charset, zend_bool copy) /* {{{ */
437 {
438 	if (Z_TYPE_P(value) == IS_ARRAY) {
439 		zval *element;
440 
441 		if (Z_IS_RECURSIVE_P(value)) {
442 			return;
443 		}
444 		Z_PROTECT_RECURSION_P(value);
445 
446 		ZEND_HASH_FOREACH_VAL(Z_ARRVAL_P(value), element) {
447 			ZVAL_DEREF(element);
448 			if (Z_TYPE_P(element) == IS_ARRAY) {
449 				SEPARATE_ARRAY(element);
450 				php_zval_filter_recursive(element, filter, flags, options, charset, copy);
451 			} else {
452 				php_zval_filter(element, filter, flags, options, charset, copy);
453 			}
454 		} ZEND_HASH_FOREACH_END();
455 		Z_UNPROTECT_RECURSION_P(value);
456 	} else {
457 		php_zval_filter(value, filter, flags, options, charset, copy);
458 	}
459 }
460 /* }}} */
461 
php_filter_get_storage(zend_long arg)462 static zval *php_filter_get_storage(zend_long arg)/* {{{ */
463 
464 {
465 	zval *array_ptr = NULL;
466 
467 	switch (arg) {
468 		case PARSE_GET:
469 			array_ptr = &IF_G(get_array);
470 			break;
471 		case PARSE_POST:
472 			array_ptr = &IF_G(post_array);
473 			break;
474 		case PARSE_COOKIE:
475 			array_ptr = &IF_G(cookie_array);
476 			break;
477 		case PARSE_SERVER:
478 			if (PG(auto_globals_jit)) {
479 				zend_is_auto_global_str(ZEND_STRL("_SERVER"));
480 			}
481 			array_ptr = &IF_G(server_array);
482 			break;
483 		case PARSE_ENV:
484 			if (PG(auto_globals_jit)) {
485 				zend_is_auto_global_str(ZEND_STRL("_ENV"));
486 			}
487 			array_ptr = !Z_ISUNDEF(IF_G(env_array)) ? &IF_G(env_array) : &PG(http_globals)[TRACK_VARS_ENV];
488 			break;
489 		default:
490 			zend_argument_value_error(1, "must be an INPUT_* constant");
491 			return NULL;
492 	}
493 
494 	if (array_ptr && Z_TYPE_P(array_ptr) != IS_ARRAY) {
495 		/* Storage not initialized */
496 		return NULL;
497 	}
498 
499 	return array_ptr;
500 }
501 /* }}} */
502 
503 /* {{{ Returns true if the variable with the name 'name' exists in source. */
PHP_FUNCTION(filter_has_var)504 PHP_FUNCTION(filter_has_var)
505 {
506 	zend_long         arg;
507 	zend_string *var;
508 	zval        *array_ptr = NULL;
509 
510 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "lS", &arg, &var) == FAILURE) {
511 		RETURN_THROWS();
512 	}
513 
514 	array_ptr = php_filter_get_storage(arg);
515 	if (EG(exception)) {
516 		RETURN_THROWS();
517 	}
518 
519 	if (array_ptr && zend_hash_exists(Z_ARRVAL_P(array_ptr), var)) {
520 		RETURN_TRUE;
521 	}
522 
523 	RETURN_FALSE;
524 }
525 /* }}} */
526 
php_filter_call(zval * filtered,zend_long filter,HashTable * filter_args_ht,zend_long filter_args_long,const int copy,zend_long filter_flags)527 static void php_filter_call(
528 	zval *filtered, zend_long filter, HashTable *filter_args_ht, zend_long filter_args_long,
529 	const int copy, zend_long filter_flags
530 ) /* {{{ */ {
531 	zval *options = NULL;
532 	zval *option;
533 	char *charset = NULL;
534 
535 	if (!filter_args_ht) {
536 		if (filter != -1) { /* handler for array apply */
537 			/* filter_args is the filter_flags */
538 			filter_flags = filter_args_long;
539 
540 			if (!(filter_flags & FILTER_REQUIRE_ARRAY ||  filter_flags & FILTER_FORCE_ARRAY)) {
541 				filter_flags |= FILTER_REQUIRE_SCALAR;
542 			}
543 		} else {
544 			filter = filter_args_long;
545 		}
546 	} else {
547 		if ((option = zend_hash_str_find(filter_args_ht, "filter", sizeof("filter") - 1)) != NULL) {
548 			filter = zval_get_long(option);
549 		}
550 
551 		if ((option = zend_hash_str_find(filter_args_ht, "flags", sizeof("flags") - 1)) != NULL) {
552 			filter_flags = zval_get_long(option);
553 
554 			if (!(filter_flags & FILTER_REQUIRE_ARRAY ||  filter_flags & FILTER_FORCE_ARRAY)) {
555 				filter_flags |= FILTER_REQUIRE_SCALAR;
556 			}
557 		}
558 
559 		if ((option = zend_hash_str_find_deref(filter_args_ht, "options", sizeof("options") - 1)) != NULL) {
560 			if (filter != FILTER_CALLBACK) {
561 				if (Z_TYPE_P(option) == IS_ARRAY) {
562 					options = option;
563 				}
564 			} else {
565 				options = option;
566 				filter_flags = 0;
567 			}
568 		}
569 	}
570 
571 	if (Z_TYPE_P(filtered) == IS_ARRAY) {
572 		if (filter_flags & FILTER_REQUIRE_SCALAR) {
573 			zval_ptr_dtor(filtered);
574 			if (filter_flags & FILTER_NULL_ON_FAILURE) {
575 				ZVAL_NULL(filtered);
576 			} else {
577 				ZVAL_FALSE(filtered);
578 			}
579 			return;
580 		}
581 		php_zval_filter_recursive(filtered, filter, filter_flags, options, charset, copy);
582 		return;
583 	}
584 	if (filter_flags & FILTER_REQUIRE_ARRAY) {
585 		zval_ptr_dtor(filtered);
586 		if (filter_flags & FILTER_NULL_ON_FAILURE) {
587 			ZVAL_NULL(filtered);
588 		} else {
589 			ZVAL_FALSE(filtered);
590 		}
591 		return;
592 	}
593 
594 	php_zval_filter(filtered, filter, filter_flags, options, charset, copy);
595 	if (filter_flags & FILTER_FORCE_ARRAY) {
596 		zval tmp;
597 		ZVAL_COPY_VALUE(&tmp, filtered);
598 		array_init(filtered);
599 		add_next_index_zval(filtered, &tmp);
600 	}
601 }
602 /* }}} */
603 
php_filter_array_handler(zval * input,HashTable * op_ht,zend_long op_long,zval * return_value,zend_bool add_empty)604 static void php_filter_array_handler(zval *input, HashTable *op_ht, zend_long op_long,
605 	zval *return_value, zend_bool add_empty
606 ) /* {{{ */ {
607 	zend_string *arg_key;
608 	zval *tmp, *arg_elm;
609 
610 	if (!op_ht) {
611 		ZVAL_DUP(return_value, input);
612 		php_filter_call(return_value, -1, NULL, op_long, 0, FILTER_REQUIRE_ARRAY);
613 	} else {
614 		array_init(return_value);
615 
616 		ZEND_HASH_FOREACH_STR_KEY_VAL(op_ht, arg_key, arg_elm) {
617 			if (arg_key == NULL) {
618 				zend_argument_type_error(2, "must contain only string keys");
619 				RETURN_THROWS();
620 	 		}
621 			if (ZSTR_LEN(arg_key) == 0) {
622 				zend_argument_value_error(2, "cannot contain empty keys");
623 				RETURN_THROWS();
624 			}
625 			if ((tmp = zend_hash_find(Z_ARRVAL_P(input), arg_key)) == NULL) {
626 				if (add_empty) {
627 					add_assoc_null_ex(return_value, ZSTR_VAL(arg_key), ZSTR_LEN(arg_key));
628 				}
629 			} else {
630 				zval nval;
631 				ZVAL_DEREF(tmp);
632 				ZVAL_DUP(&nval, tmp);
633 				php_filter_call(&nval, -1,
634 					Z_TYPE_P(arg_elm) == IS_ARRAY ? Z_ARRVAL_P(arg_elm) : NULL,
635 					Z_TYPE_P(arg_elm) == IS_ARRAY ? 0 : zval_get_long(arg_elm),
636 					0, FILTER_REQUIRE_SCALAR
637 				);
638 				zend_hash_update(Z_ARRVAL_P(return_value), arg_key, &nval);
639 			}
640 		} ZEND_HASH_FOREACH_END();
641 	}
642 }
643 /* }}} */
644 
645 /* {{{ Returns the filtered variable 'name'* from source `type`. */
PHP_FUNCTION(filter_input)646 PHP_FUNCTION(filter_input)
647 {
648 	zend_long fetch_from, filter = FILTER_DEFAULT;
649 	zval *input = NULL, *tmp;
650 	zend_string *var;
651 	HashTable *filter_args_ht = NULL;
652 	zend_long filter_args_long = 0;
653 
654 	ZEND_PARSE_PARAMETERS_START(2, 4)
655 		Z_PARAM_LONG(fetch_from)
656 		Z_PARAM_STR(var)
657 		Z_PARAM_OPTIONAL
658 		Z_PARAM_LONG(filter)
659 		Z_PARAM_ARRAY_HT_OR_LONG(filter_args_ht, filter_args_long)
660 	ZEND_PARSE_PARAMETERS_END();
661 
662 	if (!PHP_FILTER_ID_EXISTS(filter)) {
663 		php_error_docref(NULL, E_WARNING, "Unknown filter with ID " ZEND_LONG_FMT, filter);
664 		RETURN_FALSE;
665 	}
666 
667 	input = php_filter_get_storage(fetch_from);
668 	if (EG(exception)) {
669 		RETURN_THROWS();
670 	}
671 
672 	if (!input || (tmp = zend_hash_find(Z_ARRVAL_P(input), var)) == NULL) {
673 		zend_long filter_flags = 0;
674 		zval *option, *opt, *def;
675 		if (!filter_args_ht) {
676 			filter_flags = filter_args_long;
677 		} else {
678 			if ((option = zend_hash_str_find(filter_args_ht, "flags", sizeof("flags") - 1)) != NULL) {
679 				filter_flags = zval_get_long(option);
680 			}
681 
682 			if ((opt = zend_hash_str_find_deref(filter_args_ht, "options", sizeof("options") - 1)) != NULL &&
683 				Z_TYPE_P(opt) == IS_ARRAY &&
684 				(def = zend_hash_str_find_deref(Z_ARRVAL_P(opt), "default", sizeof("default") - 1)) != NULL
685 			) {
686 				ZVAL_COPY(return_value, def);
687 				return;
688 			}
689 		}
690 
691 		/* The FILTER_NULL_ON_FAILURE flag inverts the usual return values of
692 		 * the function: normally when validation fails false is returned, and
693 		 * when the input value doesn't exist NULL is returned. With the flag
694 		 * set, NULL and false should be returned, respectively. Ergo, although
695 		 * the code below looks incorrect, it's actually right. */
696 		if (filter_flags & FILTER_NULL_ON_FAILURE) {
697 			RETURN_FALSE;
698 		} else {
699 			RETURN_NULL();
700 		}
701 	}
702 
703 	ZVAL_DUP(return_value, tmp);
704 
705 	php_filter_call(return_value, filter, filter_args_ht, filter_args_long, 1, FILTER_REQUIRE_SCALAR);
706 }
707 /* }}} */
708 
709 /* {{{ Returns the filtered version of the variable. */
PHP_FUNCTION(filter_var)710 PHP_FUNCTION(filter_var)
711 {
712 	zend_long filter = FILTER_DEFAULT;
713 	zval *data;
714 	HashTable *filter_args_ht = NULL;
715 	zend_long filter_args_long = 0;
716 
717 	ZEND_PARSE_PARAMETERS_START(1, 3)
718 		Z_PARAM_ZVAL(data)
719 		Z_PARAM_OPTIONAL
720 		Z_PARAM_LONG(filter)
721 		Z_PARAM_ARRAY_HT_OR_LONG(filter_args_ht, filter_args_long)
722 	ZEND_PARSE_PARAMETERS_END();
723 
724 	if (!PHP_FILTER_ID_EXISTS(filter)) {
725 		php_error_docref(NULL, E_WARNING, "Unknown filter with ID " ZEND_LONG_FMT, filter);
726 		RETURN_FALSE;
727 	}
728 
729 	ZVAL_DUP(return_value, data);
730 
731 	php_filter_call(return_value, filter, filter_args_ht, filter_args_long, 1, FILTER_REQUIRE_SCALAR);
732 }
733 /* }}} */
734 
735 /* {{{ Returns an array with all arguments defined in 'definition'. */
PHP_FUNCTION(filter_input_array)736 PHP_FUNCTION(filter_input_array)
737 {
738 	zend_long    fetch_from;
739 	zval   *array_input = NULL;
740 	zend_bool add_empty = 1;
741 	HashTable *op_ht = NULL;
742 	zend_long op_long = FILTER_DEFAULT;
743 
744 	ZEND_PARSE_PARAMETERS_START(1, 3)
745 		Z_PARAM_LONG(fetch_from)
746 		Z_PARAM_OPTIONAL
747 		Z_PARAM_ARRAY_HT_OR_LONG(op_ht, op_long)
748 		Z_PARAM_BOOL(add_empty)
749 	ZEND_PARSE_PARAMETERS_END();
750 
751 	if (!op_ht && !PHP_FILTER_ID_EXISTS(op_long)) {
752 		php_error_docref(NULL, E_WARNING, "Unknown filter with ID " ZEND_LONG_FMT, op_long);
753 		RETURN_FALSE;
754 	}
755 
756 	array_input = php_filter_get_storage(fetch_from);
757 	if (EG(exception)) {
758 		RETURN_THROWS();
759 	}
760 
761 	if (!array_input) {
762 		zend_long filter_flags = 0;
763 		zval *option;
764 		if (op_long) {
765 			filter_flags = op_long;
766 		} else if (op_ht && (option = zend_hash_str_find(op_ht, "flags", sizeof("flags") - 1)) != NULL) {
767 			filter_flags = zval_get_long(option);
768 		}
769 
770 		/* The FILTER_NULL_ON_FAILURE flag inverts the usual return values of
771 		 * the function: normally when validation fails false is returned, and
772 		 * when the input value doesn't exist NULL is returned. With the flag
773 		 * set, NULL and false should be returned, respectively. Ergo, although
774 		 * the code below looks incorrect, it's actually right. */
775 		if (filter_flags & FILTER_NULL_ON_FAILURE) {
776 			RETURN_FALSE;
777 		} else {
778 			RETURN_NULL();
779 		}
780 	}
781 
782 	php_filter_array_handler(array_input, op_ht, op_long, return_value, add_empty);
783 }
784 /* }}} */
785 
786 /* {{{ Returns an array with all arguments defined in 'definition'. */
PHP_FUNCTION(filter_var_array)787 PHP_FUNCTION(filter_var_array)
788 {
789 	zval *array_input = NULL;
790 	zend_bool add_empty = 1;
791 	HashTable *op_ht = NULL;
792 	zend_long op_long = FILTER_DEFAULT;
793 
794 	ZEND_PARSE_PARAMETERS_START(1, 3)
795 		Z_PARAM_ARRAY(array_input)
796 		Z_PARAM_OPTIONAL
797 		Z_PARAM_ARRAY_HT_OR_LONG(op_ht, op_long)
798 		Z_PARAM_BOOL(add_empty)
799 	ZEND_PARSE_PARAMETERS_END();
800 
801 	if (!op_ht && !PHP_FILTER_ID_EXISTS(op_long)) {
802 		php_error_docref(NULL, E_WARNING, "Unknown filter with ID " ZEND_LONG_FMT, op_long);
803 		RETURN_FALSE;
804 	}
805 
806 	php_filter_array_handler(array_input, op_ht, op_long, return_value, add_empty);
807 }
808 /* }}} */
809 
810 /* {{{ Returns a list of all supported filters */
PHP_FUNCTION(filter_list)811 PHP_FUNCTION(filter_list)
812 {
813 	int i, size = sizeof(filter_list) / sizeof(filter_list_entry);
814 
815 	if (zend_parse_parameters_none() == FAILURE) {
816 		RETURN_THROWS();
817 	}
818 
819 	array_init(return_value);
820 	for (i = 0; i < size; ++i) {
821 		add_next_index_string(return_value, (char *)filter_list[i].name);
822 	}
823 }
824 /* }}} */
825 
826 /* {{{ Returns the filter ID belonging to a named filter */
PHP_FUNCTION(filter_id)827 PHP_FUNCTION(filter_id)
828 {
829 	int i;
830 	size_t filter_len;
831 	int size = sizeof(filter_list) / sizeof(filter_list_entry);
832 	char *filter;
833 
834 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &filter, &filter_len) == FAILURE) {
835 		RETURN_THROWS();
836 	}
837 
838 	for (i = 0; i < size; ++i) {
839 		if (strcmp(filter_list[i].name, filter) == 0) {
840 			RETURN_LONG(filter_list[i].id);
841 		}
842 	}
843 
844 	RETURN_FALSE;
845 }
846 /* }}} */
847