xref: /PHP-7.3/ext/standard/browscap.c (revision 64de5bc2)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) 1997-2018 The PHP Group                                |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Author: Zeev Suraski <zeev@php.net>                                  |
16    +----------------------------------------------------------------------+
17  */
18 
19 #include "php.h"
20 #include "php_browscap.h"
21 #include "php_ini.h"
22 #include "php_string.h"
23 #include "ext/pcre/php_pcre.h"
24 
25 #include "zend_ini_scanner.h"
26 #include "zend_globals.h"
27 
28 #define BROWSCAP_NUM_CONTAINS 5
29 
30 typedef struct {
31 	zend_string *key;
32 	zend_string *value;
33 } browscap_kv;
34 
35 typedef struct {
36 	zend_string *pattern;
37 	zend_string *parent;
38 	uint32_t kv_start;
39 	uint32_t kv_end;
40 	/* We ensure that the length fits in 16 bits, so this is fine */
41 	uint16_t contains_start[BROWSCAP_NUM_CONTAINS];
42 	uint8_t contains_len[BROWSCAP_NUM_CONTAINS];
43 	uint8_t prefix_len;
44 } browscap_entry;
45 
46 typedef struct {
47 	HashTable *htab;
48 	browscap_kv *kv;
49 	uint32_t kv_used;
50 	uint32_t kv_size;
51 	char filename[MAXPATHLEN];
52 } browser_data;
53 
54 /* browser data defined in startup phase, eagerly loaded in MINIT */
55 static browser_data global_bdata = {0};
56 
57 /* browser data defined in activation phase, lazily loaded in get_browser.
58  * Per request and per thread, if applicable */
ZEND_BEGIN_MODULE_GLOBALS(browscap)59 ZEND_BEGIN_MODULE_GLOBALS(browscap)
60 	browser_data activation_bdata;
61 ZEND_END_MODULE_GLOBALS(browscap)
62 
63 ZEND_DECLARE_MODULE_GLOBALS(browscap)
64 #define BROWSCAP_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(browscap, v)
65 
66 #define DEFAULT_SECTION_NAME "Default Browser Capability Settings"
67 
68 /* OBJECTS_FIXME: This whole extension needs going through. The use of objects looks pretty broken here */
69 
70 static void browscap_entry_dtor(zval *zvalue)
71 {
72 	browscap_entry *entry = Z_PTR_P(zvalue);
73 	zend_string_release_ex(entry->pattern, 0);
74 	if (entry->parent) {
75 		zend_string_release_ex(entry->parent, 0);
76 	}
77 	efree(entry);
78 }
79 
browscap_entry_dtor_persistent(zval * zvalue)80 static void browscap_entry_dtor_persistent(zval *zvalue)
81 {
82 	browscap_entry *entry = Z_PTR_P(zvalue);
83 	zend_string_release_ex(entry->pattern, 1);
84 	if (entry->parent) {
85 		zend_string_release_ex(entry->parent, 1);
86 	}
87 	pefree(entry, 1);
88 }
89 
is_placeholder(char c)90 static inline zend_bool is_placeholder(char c) {
91 	return c == '?' || c == '*';
92 }
93 
94 /* Length of prefix not containing any wildcards */
browscap_compute_prefix_len(zend_string * pattern)95 static uint8_t browscap_compute_prefix_len(zend_string *pattern) {
96 	size_t i;
97 	for (i = 0; i < ZSTR_LEN(pattern); i++) {
98 		if (is_placeholder(ZSTR_VAL(pattern)[i])) {
99 			break;
100 		}
101 	}
102 	return (uint8_t)MIN(i, UINT8_MAX);
103 }
104 
browscap_compute_contains(zend_string * pattern,size_t start_pos,uint16_t * contains_start,uint8_t * contains_len)105 static size_t browscap_compute_contains(
106 		zend_string *pattern, size_t start_pos,
107 		uint16_t *contains_start, uint8_t *contains_len) {
108 	size_t i = start_pos;
109 	/* Find first non-placeholder character after prefix */
110 	for (; i < ZSTR_LEN(pattern); i++) {
111 		if (!is_placeholder(ZSTR_VAL(pattern)[i])) {
112 			/* Skip the case of a single non-placeholder character.
113 			 * Let's try to find something longer instead. */
114 			if (i + 1 < ZSTR_LEN(pattern) &&
115 					!is_placeholder(ZSTR_VAL(pattern)[i + 1])) {
116 				break;
117 			}
118 		}
119 	}
120 	*contains_start = (uint16_t)i;
121 
122 	/* Find first placeholder character after that */
123 	for (; i < ZSTR_LEN(pattern); i++) {
124 		if (is_placeholder(ZSTR_VAL(pattern)[i])) {
125 			break;
126 		}
127 	}
128 	*contains_len = (uint8_t)MIN(i - *contains_start, UINT8_MAX);
129 	return i;
130 }
131 
132 /* Length of regex, including escapes, anchors, etc. */
browscap_compute_regex_len(zend_string * pattern)133 static size_t browscap_compute_regex_len(zend_string *pattern) {
134 	size_t i, len = ZSTR_LEN(pattern);
135 	for (i = 0; i < ZSTR_LEN(pattern); i++) {
136 		switch (ZSTR_VAL(pattern)[i]) {
137 			case '*':
138 			case '.':
139 			case '\\':
140 			case '(':
141 			case ')':
142 			case '~':
143 			case '+':
144 				len++;
145 				break;
146 		}
147 	}
148 
149 	return len + sizeof("~^$~")-1;
150 }
151 
browscap_convert_pattern(zend_string * pattern,int persistent)152 static zend_string *browscap_convert_pattern(zend_string *pattern, int persistent) /* {{{ */
153 {
154 	size_t i, j=0;
155 	char *t;
156 	zend_string *res;
157 	char *lc_pattern;
158 	ALLOCA_FLAG(use_heap);
159 
160 	res = zend_string_alloc(browscap_compute_regex_len(pattern), persistent);
161 	t = ZSTR_VAL(res);
162 
163 	lc_pattern = do_alloca(ZSTR_LEN(pattern) + 1, use_heap);
164 	zend_str_tolower_copy(lc_pattern, ZSTR_VAL(pattern), ZSTR_LEN(pattern));
165 
166 	t[j++] = '~';
167 	t[j++] = '^';
168 
169 	for (i = 0; i < ZSTR_LEN(pattern); i++, j++) {
170 		switch (lc_pattern[i]) {
171 			case '?':
172 				t[j] = '.';
173 				break;
174 			case '*':
175 				t[j++] = '.';
176 				t[j] = '*';
177 				break;
178 			case '.':
179 				t[j++] = '\\';
180 				t[j] = '.';
181 				break;
182 			case '\\':
183 				t[j++] = '\\';
184 				t[j] = '\\';
185 				break;
186 			case '(':
187 				t[j++] = '\\';
188 				t[j] = '(';
189 				break;
190 			case ')':
191 				t[j++] = '\\';
192 				t[j] = ')';
193 				break;
194 			case '~':
195 				t[j++] = '\\';
196 				t[j] = '~';
197 				break;
198 			case '+':
199 				t[j++] = '\\';
200 				t[j] = '+';
201 				break;
202 			default:
203 				t[j] = lc_pattern[i];
204 				break;
205 		}
206 	}
207 
208 	t[j++] = '$';
209 	t[j++] = '~';
210 	t[j]=0;
211 
212 	ZSTR_LEN(res) = j;
213 	free_alloca(lc_pattern, use_heap);
214 	return res;
215 }
216 /* }}} */
217 
218 typedef struct _browscap_parser_ctx {
219 	browser_data *bdata;
220 	browscap_entry *current_entry;
221 	zend_string *current_section_name;
222 	HashTable str_interned;
223 } browscap_parser_ctx;
224 
browscap_intern_str(browscap_parser_ctx * ctx,zend_string * str)225 static zend_string *browscap_intern_str(
226 		browscap_parser_ctx *ctx, zend_string *str) {
227 	zend_string *interned = zend_hash_find_ptr(&ctx->str_interned, str);
228 	if (interned) {
229 		zend_string_addref(interned);
230 	} else {
231 		interned = zend_string_copy(str);
232 		zend_hash_add_new_ptr(&ctx->str_interned, interned, interned);
233 	}
234 
235 	return interned;
236 }
237 
browscap_intern_str_ci(browscap_parser_ctx * ctx,zend_string * str,zend_bool persistent)238 static zend_string *browscap_intern_str_ci(
239 		browscap_parser_ctx *ctx, zend_string *str, zend_bool persistent) {
240 	zend_string *lcname;
241 	zend_string *interned;
242 	ALLOCA_FLAG(use_heap);
243 
244 	ZSTR_ALLOCA_ALLOC(lcname, ZSTR_LEN(str), use_heap);
245 	zend_str_tolower_copy(ZSTR_VAL(lcname), ZSTR_VAL(str), ZSTR_LEN(str));
246 	interned = zend_hash_find_ptr(&ctx->str_interned, lcname);
247 
248 	if (interned) {
249 		zend_string_addref(interned);
250 	} else {
251 		interned = zend_string_dup(lcname, persistent);
252 		zend_hash_add_new_ptr(&ctx->str_interned, interned, interned);
253 	}
254 
255 	ZSTR_ALLOCA_FREE(lcname, use_heap);
256 	return interned;
257 }
258 
browscap_add_kv(browser_data * bdata,zend_string * key,zend_string * value,zend_bool persistent)259 static void browscap_add_kv(
260 		browser_data *bdata, zend_string *key, zend_string *value, zend_bool persistent) {
261 	if (bdata->kv_used == bdata->kv_size) {
262 		bdata->kv_size *= 2;
263 		bdata->kv = safe_perealloc(bdata->kv, sizeof(browscap_kv), bdata->kv_size, 0, persistent);
264 	}
265 
266 	bdata->kv[bdata->kv_used].key = key;
267 	bdata->kv[bdata->kv_used].value = value;
268 	bdata->kv_used++;
269 }
270 
browscap_entry_to_array(browser_data * bdata,browscap_entry * entry)271 static HashTable *browscap_entry_to_array(browser_data *bdata, browscap_entry *entry) {
272 	zval tmp;
273 	uint32_t i;
274 
275 	HashTable *ht = zend_new_array(8);
276 
277 	ZVAL_STR(&tmp, browscap_convert_pattern(entry->pattern, 0));
278 	zend_hash_str_add(ht, "browser_name_regex", sizeof("browser_name_regex")-1, &tmp);
279 
280 	ZVAL_STR_COPY(&tmp, entry->pattern);
281 	zend_hash_str_add(ht, "browser_name_pattern", sizeof("browser_name_pattern")-1, &tmp);
282 
283 	if (entry->parent) {
284 		ZVAL_STR_COPY(&tmp, entry->parent);
285 		zend_hash_str_add(ht, "parent", sizeof("parent")-1, &tmp);
286 	}
287 
288 	for (i = entry->kv_start; i < entry->kv_end; i++) {
289 		ZVAL_STR_COPY(&tmp, bdata->kv[i].value);
290 		zend_hash_add(ht, bdata->kv[i].key, &tmp);
291 	}
292 
293 	return ht;
294 }
295 
php_browscap_parser_cb(zval * arg1,zval * arg2,zval * arg3,int callback_type,void * arg)296 static void php_browscap_parser_cb(zval *arg1, zval *arg2, zval *arg3, int callback_type, void *arg) /* {{{ */
297 {
298 	browscap_parser_ctx *ctx = arg;
299 	browser_data *bdata = ctx->bdata;
300 	int persistent = GC_FLAGS(bdata->htab) & IS_ARRAY_PERSISTENT;
301 
302 	if (!arg1) {
303 		return;
304 	}
305 
306 	switch (callback_type) {
307 		case ZEND_INI_PARSER_ENTRY:
308 			if (ctx->current_entry != NULL && arg2) {
309 				zend_string *new_key, *new_value;
310 
311 				/* Set proper value for true/false settings */
312 				if ((Z_STRLEN_P(arg2) == 2 && !strncasecmp(Z_STRVAL_P(arg2), "on", sizeof("on") - 1)) ||
313 					(Z_STRLEN_P(arg2) == 3 && !strncasecmp(Z_STRVAL_P(arg2), "yes", sizeof("yes") - 1)) ||
314 					(Z_STRLEN_P(arg2) == 4 && !strncasecmp(Z_STRVAL_P(arg2), "true", sizeof("true") - 1))
315 				) {
316 					new_value = ZSTR_CHAR('1');
317 				} else if (
318 					(Z_STRLEN_P(arg2) == 2 && !strncasecmp(Z_STRVAL_P(arg2), "no", sizeof("no") - 1)) ||
319 					(Z_STRLEN_P(arg2) == 3 && !strncasecmp(Z_STRVAL_P(arg2), "off", sizeof("off") - 1)) ||
320 					(Z_STRLEN_P(arg2) == 4 && !strncasecmp(Z_STRVAL_P(arg2), "none", sizeof("none") - 1)) ||
321 					(Z_STRLEN_P(arg2) == 5 && !strncasecmp(Z_STRVAL_P(arg2), "false", sizeof("false") - 1))
322 				) {
323 					new_value = ZSTR_EMPTY_ALLOC();
324 				} else { /* Other than true/false setting */
325 					new_value = browscap_intern_str(ctx, Z_STR_P(arg2));
326 
327 					if (persistent) {
328 						new_value = zend_new_interned_string(zend_string_copy(new_value));
329 						if (ZSTR_IS_INTERNED(new_value)) {
330 							if (new_value == Z_STR_P(arg2)) {
331 								Z_TYPE_FLAGS_P(arg2) = 0;
332 							}
333 						} else {
334 							zend_string_release(new_value);
335 						}
336 					}
337 				}
338 
339 				if (!strcasecmp(Z_STRVAL_P(arg1), "parent")) {
340 					/* parent entry can not be same as current section -> causes infinite loop! */
341 					if (ctx->current_section_name != NULL &&
342 						!strcasecmp(ZSTR_VAL(ctx->current_section_name), Z_STRVAL_P(arg2))
343 					) {
344 						zend_error(E_CORE_ERROR, "Invalid browscap ini file: "
345 							"'Parent' value cannot be same as the section name: %s "
346 							"(in file %s)", ZSTR_VAL(ctx->current_section_name), INI_STR("browscap"));
347 						return;
348 					}
349 
350 					if (ctx->current_entry->parent) {
351 						zend_string_release(ctx->current_entry->parent);
352 					}
353 
354 					ctx->current_entry->parent = new_value;
355 				} else {
356 					new_key = browscap_intern_str_ci(ctx, Z_STR_P(arg1), persistent);
357 
358 					if (persistent) {
359 						new_key = zend_new_interned_string(zend_string_copy(new_key));
360 						if (ZSTR_IS_INTERNED(new_key)) {
361 							if (new_key == Z_STR_P(arg1)) {
362 								Z_TYPE_FLAGS_P(arg1) = 0;
363 							}
364 						} else {
365 							zend_string_release(new_key);
366 						}
367 					}
368 
369 					browscap_add_kv(bdata, new_key, new_value, persistent);
370 					ctx->current_entry->kv_end = bdata->kv_used;
371 				}
372 			}
373 			break;
374 		case ZEND_INI_PARSER_SECTION:
375 		{
376 			browscap_entry *entry;
377 			zend_string *pattern = Z_STR_P(arg1);
378 			size_t pos;
379 			int i;
380 
381 			if (ZSTR_LEN(pattern) > UINT16_MAX) {
382 				php_error_docref(NULL, E_WARNING,
383 					"Skipping excessively long pattern of length %zd", ZSTR_LEN(pattern));
384 				break;
385 			}
386 
387 			if (persistent) {
388 				pattern = zend_new_interned_string(zend_string_copy(pattern));
389 				if (ZSTR_IS_INTERNED(pattern)) {
390 					Z_TYPE_FLAGS_P(arg1) = 0;
391 				} else {
392 					zend_string_release(pattern);
393 				}
394 			}
395 
396 			entry = ctx->current_entry
397 				= pemalloc(sizeof(browscap_entry), persistent);
398 			zend_hash_update_ptr(bdata->htab, pattern, entry);
399 
400 			if (ctx->current_section_name) {
401 				zend_string_release(ctx->current_section_name);
402 			}
403 			ctx->current_section_name = zend_string_copy(pattern);
404 
405 			entry->pattern = zend_string_copy(pattern);
406 			entry->kv_end = entry->kv_start = bdata->kv_used;
407 			entry->parent = NULL;
408 
409 			pos = entry->prefix_len = browscap_compute_prefix_len(pattern);
410 			for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
411 				pos = browscap_compute_contains(pattern, pos,
412 					&entry->contains_start[i], &entry->contains_len[i]);
413 			}
414 			break;
415 		}
416 	}
417 }
418 /* }}} */
419 
browscap_read_file(char * filename,browser_data * browdata,int persistent)420 static int browscap_read_file(char *filename, browser_data *browdata, int persistent) /* {{{ */
421 {
422 	zend_file_handle fh;
423 	browscap_parser_ctx ctx = {0};
424 
425 	if (filename == NULL || filename[0] == '\0') {
426 		return FAILURE;
427 	}
428 
429 	fh.handle.fp = VCWD_FOPEN(filename, "r");
430 	fh.opened_path = NULL;
431 	fh.free_filename = 0;
432 	if (!fh.handle.fp) {
433 		zend_error(E_CORE_WARNING, "Cannot open '%s' for reading", filename);
434 		return FAILURE;
435 	}
436 
437 	fh.filename = filename;
438 	fh.type = ZEND_HANDLE_FP;
439 
440 	browdata->htab = pemalloc(sizeof *browdata->htab, persistent);
441 	zend_hash_init_ex(browdata->htab, 0, NULL,
442 		persistent ? browscap_entry_dtor_persistent : browscap_entry_dtor, persistent, 0);
443 
444 	browdata->kv_size = 16 * 1024;
445 	browdata->kv_used = 0;
446 	browdata->kv = pemalloc(sizeof(browscap_kv) * browdata->kv_size, persistent);
447 
448 	/* Create parser context */
449 	ctx.bdata = browdata;
450 	ctx.current_entry = NULL;
451 	ctx.current_section_name = NULL;
452 	zend_hash_init(&ctx.str_interned, 8, NULL, NULL, persistent);
453 
454 	zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_RAW,
455 			(zend_ini_parser_cb_t) php_browscap_parser_cb, &ctx);
456 
457 	/* Destroy parser context */
458 	if (ctx.current_section_name) {
459 		zend_string_release(ctx.current_section_name);
460 	}
461 	zend_hash_destroy(&ctx.str_interned);
462 
463 	return SUCCESS;
464 }
465 /* }}} */
466 
467 #ifdef ZTS
browscap_globals_ctor(zend_browscap_globals * browscap_globals)468 static void browscap_globals_ctor(zend_browscap_globals *browscap_globals) /* {{{ */
469 {
470 	browscap_globals->activation_bdata.htab = NULL;
471 	browscap_globals->activation_bdata.kv = NULL;
472 	browscap_globals->activation_bdata.filename[0] = '\0';
473 }
474 /* }}} */
475 #endif
476 
browscap_bdata_dtor(browser_data * bdata,int persistent)477 static void browscap_bdata_dtor(browser_data *bdata, int persistent) /* {{{ */
478 {
479 	if (bdata->htab != NULL) {
480 		uint32_t i;
481 
482 		zend_hash_destroy(bdata->htab);
483 		pefree(bdata->htab, persistent);
484 		bdata->htab = NULL;
485 
486 		for (i = 0; i < bdata->kv_used; i++) {
487 			zend_string_release(bdata->kv[i].key);
488 			zend_string_release(bdata->kv[i].value);
489 		}
490 		pefree(bdata->kv, persistent);
491 		bdata->kv = NULL;
492 	}
493 	bdata->filename[0] = '\0';
494 }
495 /* }}} */
496 
497 /* {{{ PHP_INI_MH
498  */
PHP_INI_MH(OnChangeBrowscap)499 PHP_INI_MH(OnChangeBrowscap)
500 {
501 	if (stage == PHP_INI_STAGE_STARTUP) {
502 		/* value handled in browscap.c's MINIT */
503 		return SUCCESS;
504 	} else if (stage == PHP_INI_STAGE_ACTIVATE) {
505 		browser_data *bdata = &BROWSCAP_G(activation_bdata);
506 		if (bdata->filename[0] != '\0') {
507 			browscap_bdata_dtor(bdata, 0);
508 		}
509 		if (VCWD_REALPATH(ZSTR_VAL(new_value), bdata->filename) == NULL) {
510 			return FAILURE;
511 		}
512 		return SUCCESS;
513 	}
514 
515 	return FAILURE;
516 }
517 /* }}} */
518 
PHP_MINIT_FUNCTION(browscap)519 PHP_MINIT_FUNCTION(browscap) /* {{{ */
520 {
521 	char *browscap = INI_STR("browscap");
522 
523 #ifdef ZTS
524 	ts_allocate_id(&browscap_globals_id, sizeof(browser_data), (ts_allocate_ctor) browscap_globals_ctor, NULL);
525 #endif
526 	/* ctor call not really needed for non-ZTS */
527 
528 	if (browscap && browscap[0]) {
529 		if (browscap_read_file(browscap, &global_bdata, 1) == FAILURE) {
530 			return FAILURE;
531 		}
532 	}
533 
534 	return SUCCESS;
535 }
536 /* }}} */
537 
PHP_RSHUTDOWN_FUNCTION(browscap)538 PHP_RSHUTDOWN_FUNCTION(browscap) /* {{{ */
539 {
540 	browser_data *bdata = &BROWSCAP_G(activation_bdata);
541 	if (bdata->filename[0] != '\0') {
542 		browscap_bdata_dtor(bdata, 0);
543 	}
544 
545 	return SUCCESS;
546 }
547 /* }}} */
548 
PHP_MSHUTDOWN_FUNCTION(browscap)549 PHP_MSHUTDOWN_FUNCTION(browscap) /* {{{ */
550 {
551 	browscap_bdata_dtor(&global_bdata, 1);
552 
553 	return SUCCESS;
554 }
555 /* }}} */
556 
browscap_get_minimum_length(browscap_entry * entry)557 static inline size_t browscap_get_minimum_length(browscap_entry *entry) {
558 	size_t len = entry->prefix_len;
559 	int i;
560 	for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
561 		len += entry->contains_len[i];
562 	}
563 	return len;
564 }
565 
browser_reg_compare(zval * entry_zv,int num_args,va_list args,zend_hash_key * key)566 static int browser_reg_compare(
567 		zval *entry_zv, int num_args, va_list args, zend_hash_key *key) /* {{{ */
568 {
569 	browscap_entry *entry = Z_PTR_P(entry_zv);
570 	zend_string *agent_name = va_arg(args, zend_string *);
571 	browscap_entry **found_entry_ptr = va_arg(args, browscap_entry **);
572 	browscap_entry *found_entry = *found_entry_ptr;
573 	ALLOCA_FLAG(use_heap)
574 	zend_string *pattern_lc, *regex;
575 	const char *cur;
576 	int i;
577 
578 	pcre2_code *re;
579 	pcre2_match_data *match_data;
580 	uint32_t re_options, capture_count;
581 	int rc;
582 
583 	/* Agent name too short */
584 	if (ZSTR_LEN(agent_name) < browscap_get_minimum_length(entry)) {
585 		return 0;
586 	}
587 
588 	/* Quickly discard patterns where the prefix doesn't match. */
589 	if (zend_binary_strcasecmp(
590 			ZSTR_VAL(agent_name), entry->prefix_len,
591 			ZSTR_VAL(entry->pattern), entry->prefix_len) != 0) {
592 		return 0;
593 	}
594 
595 	/* Lowercase the pattern, the agent name is already lowercase */
596 	ZSTR_ALLOCA_ALLOC(pattern_lc, ZSTR_LEN(entry->pattern), use_heap);
597 	zend_str_tolower_copy(ZSTR_VAL(pattern_lc), ZSTR_VAL(entry->pattern), ZSTR_LEN(entry->pattern));
598 
599 	/* Check if the agent contains the "contains" portions */
600 	cur = ZSTR_VAL(agent_name) + entry->prefix_len;
601 	for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
602 		if (entry->contains_len[i] != 0) {
603 			cur = zend_memnstr(cur,
604 				ZSTR_VAL(pattern_lc) + entry->contains_start[i],
605 				entry->contains_len[i],
606 				ZSTR_VAL(agent_name) + ZSTR_LEN(agent_name));
607 			if (!cur) {
608 				ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
609 				return 0;
610 			}
611 			cur += entry->contains_len[i];
612 		}
613 	}
614 
615 	/* See if we have an exact match, if so, we're done... */
616 	if (zend_string_equals(agent_name, pattern_lc)) {
617 		*found_entry_ptr = entry;
618 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
619 		return ZEND_HASH_APPLY_STOP;
620 	}
621 
622 	regex = browscap_convert_pattern(entry->pattern, 0);
623 	re = pcre_get_compiled_regex(regex, &capture_count, &re_options);
624 	if (re == NULL) {
625 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
626 		zend_string_release(regex);
627 		return 0;
628 	}
629 
630 	match_data = php_pcre_create_match_data(capture_count, re);
631 	if (!match_data) {
632 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
633 		zend_string_release(regex);
634 		return 0;
635 	}
636 	rc = pcre2_match(re, (PCRE2_SPTR)ZSTR_VAL(agent_name), ZSTR_LEN(agent_name), 0, re_options, match_data, php_pcre_mctx());
637 	php_pcre_free_match_data(match_data);
638 	if (PCRE2_ERROR_NOMATCH != rc) {
639 		/* If we've found a possible browser, we need to do a comparison of the
640 		   number of characters changed in the user agent being checked versus
641 		   the previous match found and the current match. */
642 		if (found_entry) {
643 			size_t i, prev_len = 0, curr_len = 0;
644 			zend_string *previous_match = found_entry->pattern;
645 			zend_string *current_match = entry->pattern;
646 
647 			for (i = 0; i < ZSTR_LEN(previous_match); i++) {
648 				switch (ZSTR_VAL(previous_match)[i]) {
649 					case '?':
650 					case '*':
651 						/* do nothing, ignore these characters in the count */
652 					break;
653 
654 					default:
655 						++prev_len;
656 				}
657 			}
658 
659 			for (i = 0; i < ZSTR_LEN(current_match); i++) {
660 				switch (ZSTR_VAL(current_match)[i]) {
661 					case '?':
662 					case '*':
663 						/* do nothing, ignore these characters in the count */
664 					break;
665 
666 					default:
667 						++curr_len;
668 				}
669 			}
670 
671 			/* Pick which browser pattern replaces the least amount of
672 			   characters when compared to the original user agent string... */
673 			if (prev_len < curr_len) {
674 				*found_entry_ptr = entry;
675 			}
676 		} else {
677 			*found_entry_ptr = entry;
678 		}
679 	}
680 
681 	ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
682 	zend_string_release(regex);
683 	return 0;
684 }
685 /* }}} */
686 
browscap_zval_copy_ctor(zval * p)687 static void browscap_zval_copy_ctor(zval *p) /* {{{ */
688 {
689 	if (Z_REFCOUNTED_P(p)) {
690 		zend_string *str;
691 
692 		ZEND_ASSERT(Z_TYPE_P(p) == IS_STRING);
693 		str = Z_STR_P(p);
694 		if (!(GC_FLAGS(str) & GC_PERSISTENT)) {
695 			GC_ADDREF(str);
696 		} else {
697 			ZVAL_NEW_STR(p, zend_string_init(ZSTR_VAL(str), ZSTR_LEN(str), 0));
698 		}
699 	}
700 }
701 /* }}} */
702 
703 /* {{{ proto mixed get_browser([string browser_name [, bool return_array]])
704    Get information about the capabilities of a browser. If browser_name is omitted or null, HTTP_USER_AGENT is used. Returns an object by default; if return_array is true, returns an array. */
PHP_FUNCTION(get_browser)705 PHP_FUNCTION(get_browser)
706 {
707 	zend_string *agent_name = NULL, *lookup_browser_name;
708 	zend_bool return_array = 0;
709 	browser_data *bdata;
710 	browscap_entry *found_entry = NULL;
711 	HashTable *agent_ht;
712 
713 	if (BROWSCAP_G(activation_bdata).filename[0] != '\0') {
714 		bdata = &BROWSCAP_G(activation_bdata);
715 		if (bdata->htab == NULL) { /* not initialized yet */
716 			if (browscap_read_file(bdata->filename, bdata, 0) == FAILURE) {
717 				RETURN_FALSE;
718 			}
719 		}
720 	} else {
721 		if (!global_bdata.htab) {
722 			php_error_docref(NULL, E_WARNING, "browscap ini directive not set");
723 			RETURN_FALSE;
724 		}
725 		bdata = &global_bdata;
726 	}
727 
728 	ZEND_PARSE_PARAMETERS_START(0, 2)
729 		Z_PARAM_OPTIONAL
730 		Z_PARAM_STR_EX(agent_name, 1, 0)
731 		Z_PARAM_BOOL(return_array)
732 	ZEND_PARSE_PARAMETERS_END();
733 
734 	if (agent_name == NULL) {
735 		zval *http_user_agent = NULL;
736 		if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY
737 				|| zend_is_auto_global_str(ZEND_STRL("_SERVER"))) {
738 			http_user_agent = zend_hash_str_find(
739 				Z_ARRVAL_P(&PG(http_globals)[TRACK_VARS_SERVER]),
740 				"HTTP_USER_AGENT", sizeof("HTTP_USER_AGENT")-1);
741 		}
742 		if (http_user_agent == NULL) {
743 			php_error_docref(NULL, E_WARNING, "HTTP_USER_AGENT variable is not set, cannot determine user agent name");
744 			RETURN_FALSE;
745 		}
746 		agent_name = Z_STR_P(http_user_agent);
747 	}
748 
749 	lookup_browser_name = zend_string_tolower(agent_name);
750 	found_entry = zend_hash_find_ptr(bdata->htab, lookup_browser_name);
751 	if (found_entry == NULL) {
752 		zend_hash_apply_with_arguments(bdata->htab, browser_reg_compare, 2, lookup_browser_name, &found_entry);
753 
754 		if (found_entry == NULL) {
755 			found_entry = zend_hash_str_find_ptr(bdata->htab,
756 				DEFAULT_SECTION_NAME, sizeof(DEFAULT_SECTION_NAME)-1);
757 			if (found_entry == NULL) {
758 				zend_string_release(lookup_browser_name);
759 				RETURN_FALSE;
760 			}
761 		}
762 	}
763 
764 	agent_ht = browscap_entry_to_array(bdata, found_entry);
765 
766 	if (return_array) {
767 		RETVAL_ARR(agent_ht);
768 	} else {
769 		object_and_properties_init(return_value, zend_standard_class_def, agent_ht);
770 	}
771 
772 	while (found_entry->parent) {
773 		found_entry = zend_hash_find_ptr(bdata->htab, found_entry->parent);
774 		if (found_entry == NULL) {
775 			break;
776 		}
777 
778 		agent_ht = browscap_entry_to_array(bdata, found_entry);
779 		if (return_array) {
780 			zend_hash_merge(Z_ARRVAL_P(return_value), agent_ht, (copy_ctor_func_t) browscap_zval_copy_ctor, 0);
781 		} else {
782 			zend_hash_merge(Z_OBJPROP_P(return_value), agent_ht, (copy_ctor_func_t) browscap_zval_copy_ctor, 0);
783 		}
784 
785 		zend_hash_destroy(agent_ht);
786 		efree(agent_ht);
787 	}
788 
789 	zend_string_release_ex(lookup_browser_name, 0);
790 }
791 /* }}} */
792 
793 /*
794  * Local variables:
795  * tab-width: 4
796  * c-basic-offset: 4
797  * End:
798  * vim600: sw=4 ts=4 fdm=marker
799  * vim<600: sw=4 ts=4
800  */
801