xref: /PHP-7.4/ext/standard/browscap.c (revision 46faf8f0)
1 /*
2    +----------------------------------------------------------------------+
3    | PHP Version 7                                                        |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | http://www.php.net/license/3_01.txt                                  |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | 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,zend_bool persistent)225 static zend_string *browscap_intern_str(
226 		browscap_parser_ctx *ctx, zend_string *str, zend_bool persistent) {
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 		if (persistent) {
233 			interned = zend_new_interned_string(str);
234 		}
235 		zend_hash_add_new_ptr(&ctx->str_interned, interned, interned);
236 	}
237 
238 	return interned;
239 }
240 
browscap_intern_str_ci(browscap_parser_ctx * ctx,zend_string * str,zend_bool persistent)241 static zend_string *browscap_intern_str_ci(
242 		browscap_parser_ctx *ctx, zend_string *str, zend_bool persistent) {
243 	zend_string *lcname;
244 	zend_string *interned;
245 	ALLOCA_FLAG(use_heap);
246 
247 	ZSTR_ALLOCA_ALLOC(lcname, ZSTR_LEN(str), use_heap);
248 	zend_str_tolower_copy(ZSTR_VAL(lcname), ZSTR_VAL(str), ZSTR_LEN(str));
249 	interned = zend_hash_find_ptr(&ctx->str_interned, lcname);
250 
251 	if (interned) {
252 		zend_string_addref(interned);
253 	} else {
254 		interned = zend_string_dup(lcname, persistent);
255 		if (persistent) {
256 			interned = zend_new_interned_string(interned);
257 		}
258 		zend_hash_add_new_ptr(&ctx->str_interned, interned, interned);
259 	}
260 
261 	ZSTR_ALLOCA_FREE(lcname, use_heap);
262 	return interned;
263 }
264 
browscap_add_kv(browser_data * bdata,zend_string * key,zend_string * value,zend_bool persistent)265 static void browscap_add_kv(
266 		browser_data *bdata, zend_string *key, zend_string *value, zend_bool persistent) {
267 	if (bdata->kv_used == bdata->kv_size) {
268 		bdata->kv_size *= 2;
269 		bdata->kv = safe_perealloc(bdata->kv, sizeof(browscap_kv), bdata->kv_size, 0, persistent);
270 	}
271 
272 	bdata->kv[bdata->kv_used].key = key;
273 	bdata->kv[bdata->kv_used].value = value;
274 	bdata->kv_used++;
275 }
276 
browscap_entry_to_array(browser_data * bdata,browscap_entry * entry)277 static HashTable *browscap_entry_to_array(browser_data *bdata, browscap_entry *entry) {
278 	zval tmp;
279 	uint32_t i;
280 
281 	HashTable *ht = zend_new_array(8);
282 
283 	ZVAL_STR(&tmp, browscap_convert_pattern(entry->pattern, 0));
284 	zend_hash_str_add(ht, "browser_name_regex", sizeof("browser_name_regex")-1, &tmp);
285 
286 	ZVAL_STR_COPY(&tmp, entry->pattern);
287 	zend_hash_str_add(ht, "browser_name_pattern", sizeof("browser_name_pattern")-1, &tmp);
288 
289 	if (entry->parent) {
290 		ZVAL_STR_COPY(&tmp, entry->parent);
291 		zend_hash_str_add(ht, "parent", sizeof("parent")-1, &tmp);
292 	}
293 
294 	for (i = entry->kv_start; i < entry->kv_end; i++) {
295 		ZVAL_STR_COPY(&tmp, bdata->kv[i].value);
296 		zend_hash_add(ht, bdata->kv[i].key, &tmp);
297 	}
298 
299 	return ht;
300 }
301 
php_browscap_parser_cb(zval * arg1,zval * arg2,zval * arg3,int callback_type,void * arg)302 static void php_browscap_parser_cb(zval *arg1, zval *arg2, zval *arg3, int callback_type, void *arg) /* {{{ */
303 {
304 	browscap_parser_ctx *ctx = arg;
305 	browser_data *bdata = ctx->bdata;
306 	int persistent = GC_FLAGS(bdata->htab) & IS_ARRAY_PERSISTENT;
307 
308 	if (!arg1) {
309 		return;
310 	}
311 
312 	switch (callback_type) {
313 		case ZEND_INI_PARSER_ENTRY:
314 			if (ctx->current_entry != NULL && arg2) {
315 				zend_string *new_key, *new_value;
316 
317 				/* Set proper value for true/false settings */
318 				if ((Z_STRLEN_P(arg2) == 2 && !strncasecmp(Z_STRVAL_P(arg2), "on", sizeof("on") - 1)) ||
319 					(Z_STRLEN_P(arg2) == 3 && !strncasecmp(Z_STRVAL_P(arg2), "yes", sizeof("yes") - 1)) ||
320 					(Z_STRLEN_P(arg2) == 4 && !strncasecmp(Z_STRVAL_P(arg2), "true", sizeof("true") - 1))
321 				) {
322 					new_value = ZSTR_CHAR('1');
323 				} else if (
324 					(Z_STRLEN_P(arg2) == 2 && !strncasecmp(Z_STRVAL_P(arg2), "no", sizeof("no") - 1)) ||
325 					(Z_STRLEN_P(arg2) == 3 && !strncasecmp(Z_STRVAL_P(arg2), "off", sizeof("off") - 1)) ||
326 					(Z_STRLEN_P(arg2) == 4 && !strncasecmp(Z_STRVAL_P(arg2), "none", sizeof("none") - 1)) ||
327 					(Z_STRLEN_P(arg2) == 5 && !strncasecmp(Z_STRVAL_P(arg2), "false", sizeof("false") - 1))
328 				) {
329 					new_value = ZSTR_EMPTY_ALLOC();
330 				} else { /* Other than true/false setting */
331 					new_value = browscap_intern_str(ctx, Z_STR_P(arg2), persistent);
332 				}
333 
334 				if (!strcasecmp(Z_STRVAL_P(arg1), "parent")) {
335 					/* parent entry can not be same as current section -> causes infinite loop! */
336 					if (ctx->current_section_name != NULL &&
337 						!strcasecmp(ZSTR_VAL(ctx->current_section_name), Z_STRVAL_P(arg2))
338 					) {
339 						zend_error(E_CORE_ERROR, "Invalid browscap ini file: "
340 							"'Parent' value cannot be same as the section name: %s "
341 							"(in file %s)", ZSTR_VAL(ctx->current_section_name), INI_STR("browscap"));
342 						return;
343 					}
344 
345 					if (ctx->current_entry->parent) {
346 						zend_string_release(ctx->current_entry->parent);
347 					}
348 
349 					ctx->current_entry->parent = new_value;
350 				} else {
351 					new_key = browscap_intern_str_ci(ctx, Z_STR_P(arg1), persistent);
352 					browscap_add_kv(bdata, new_key, new_value, persistent);
353 					ctx->current_entry->kv_end = bdata->kv_used;
354 				}
355 			}
356 			break;
357 		case ZEND_INI_PARSER_SECTION:
358 		{
359 			browscap_entry *entry;
360 			zend_string *pattern = Z_STR_P(arg1);
361 			size_t pos;
362 			int i;
363 
364 			if (ZSTR_LEN(pattern) > UINT16_MAX) {
365 				php_error_docref(NULL, E_WARNING,
366 					"Skipping excessively long pattern of length %zd", ZSTR_LEN(pattern));
367 				break;
368 			}
369 
370 			if (persistent) {
371 				pattern = zend_new_interned_string(zend_string_copy(pattern));
372 				if (ZSTR_IS_INTERNED(pattern)) {
373 					Z_TYPE_FLAGS_P(arg1) = 0;
374 				} else {
375 					zend_string_release(pattern);
376 				}
377 			}
378 
379 			entry = ctx->current_entry
380 				= pemalloc(sizeof(browscap_entry), persistent);
381 			zend_hash_update_ptr(bdata->htab, pattern, entry);
382 
383 			if (ctx->current_section_name) {
384 				zend_string_release(ctx->current_section_name);
385 			}
386 			ctx->current_section_name = zend_string_copy(pattern);
387 
388 			entry->pattern = zend_string_copy(pattern);
389 			entry->kv_end = entry->kv_start = bdata->kv_used;
390 			entry->parent = NULL;
391 
392 			pos = entry->prefix_len = browscap_compute_prefix_len(pattern);
393 			for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
394 				pos = browscap_compute_contains(pattern, pos,
395 					&entry->contains_start[i], &entry->contains_len[i]);
396 			}
397 			break;
398 		}
399 	}
400 }
401 /* }}} */
402 
str_interned_dtor(zval * zv)403 static void str_interned_dtor(zval *zv) {
404 	zend_string_release(Z_STR_P(zv));
405 }
406 
browscap_read_file(char * filename,browser_data * browdata,int persistent)407 static int browscap_read_file(char *filename, browser_data *browdata, int persistent) /* {{{ */
408 {
409 	zend_file_handle fh;
410 	browscap_parser_ctx ctx = {0};
411 
412 	if (filename == NULL || filename[0] == '\0') {
413 		return FAILURE;
414 	}
415 
416 	zend_stream_init_fp(&fh, VCWD_FOPEN(filename, "r"), filename);
417 	if (!fh.handle.fp) {
418 		zend_error(E_CORE_WARNING, "Cannot open '%s' for reading", filename);
419 		return FAILURE;
420 	}
421 
422 	browdata->htab = pemalloc(sizeof *browdata->htab, persistent);
423 	zend_hash_init_ex(browdata->htab, 0, NULL,
424 		persistent ? browscap_entry_dtor_persistent : browscap_entry_dtor, persistent, 0);
425 
426 	browdata->kv_size = 16 * 1024;
427 	browdata->kv_used = 0;
428 	browdata->kv = pemalloc(sizeof(browscap_kv) * browdata->kv_size, persistent);
429 
430 	/* Create parser context */
431 	ctx.bdata = browdata;
432 	ctx.current_entry = NULL;
433 	ctx.current_section_name = NULL;
434 	zend_hash_init(&ctx.str_interned, 8, NULL, str_interned_dtor, persistent);
435 
436 	zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_RAW,
437 			(zend_ini_parser_cb_t) php_browscap_parser_cb, &ctx);
438 
439 	/* Destroy parser context */
440 	if (ctx.current_section_name) {
441 		zend_string_release(ctx.current_section_name);
442 	}
443 	zend_hash_destroy(&ctx.str_interned);
444 
445 	return SUCCESS;
446 }
447 /* }}} */
448 
449 #ifdef ZTS
browscap_globals_ctor(zend_browscap_globals * browscap_globals)450 static void browscap_globals_ctor(zend_browscap_globals *browscap_globals) /* {{{ */
451 {
452 	browscap_globals->activation_bdata.htab = NULL;
453 	browscap_globals->activation_bdata.kv = NULL;
454 	browscap_globals->activation_bdata.filename[0] = '\0';
455 }
456 /* }}} */
457 #endif
458 
browscap_bdata_dtor(browser_data * bdata,int persistent)459 static void browscap_bdata_dtor(browser_data *bdata, int persistent) /* {{{ */
460 {
461 	if (bdata->htab != NULL) {
462 		uint32_t i;
463 
464 		zend_hash_destroy(bdata->htab);
465 		pefree(bdata->htab, persistent);
466 		bdata->htab = NULL;
467 
468 		for (i = 0; i < bdata->kv_used; i++) {
469 			zend_string_release(bdata->kv[i].key);
470 			zend_string_release(bdata->kv[i].value);
471 		}
472 		pefree(bdata->kv, persistent);
473 		bdata->kv = NULL;
474 	}
475 	bdata->filename[0] = '\0';
476 }
477 /* }}} */
478 
479 /* {{{ PHP_INI_MH
480  */
PHP_INI_MH(OnChangeBrowscap)481 PHP_INI_MH(OnChangeBrowscap)
482 {
483 	if (stage == PHP_INI_STAGE_STARTUP) {
484 		/* value handled in browscap.c's MINIT */
485 		return SUCCESS;
486 	} else if (stage == PHP_INI_STAGE_ACTIVATE) {
487 		browser_data *bdata = &BROWSCAP_G(activation_bdata);
488 		if (bdata->filename[0] != '\0') {
489 			browscap_bdata_dtor(bdata, 0);
490 		}
491 		if (VCWD_REALPATH(ZSTR_VAL(new_value), bdata->filename) == NULL) {
492 			return FAILURE;
493 		}
494 		return SUCCESS;
495 	}
496 
497 	return FAILURE;
498 }
499 /* }}} */
500 
PHP_MINIT_FUNCTION(browscap)501 PHP_MINIT_FUNCTION(browscap) /* {{{ */
502 {
503 	char *browscap = INI_STR("browscap");
504 
505 #ifdef ZTS
506 	ts_allocate_id(&browscap_globals_id, sizeof(browser_data), (ts_allocate_ctor) browscap_globals_ctor, NULL);
507 #endif
508 	/* ctor call not really needed for non-ZTS */
509 
510 	if (browscap && browscap[0]) {
511 		if (browscap_read_file(browscap, &global_bdata, 1) == FAILURE) {
512 			return FAILURE;
513 		}
514 	}
515 
516 	return SUCCESS;
517 }
518 /* }}} */
519 
PHP_RSHUTDOWN_FUNCTION(browscap)520 PHP_RSHUTDOWN_FUNCTION(browscap) /* {{{ */
521 {
522 	browser_data *bdata = &BROWSCAP_G(activation_bdata);
523 	if (bdata->filename[0] != '\0') {
524 		browscap_bdata_dtor(bdata, 0);
525 	}
526 
527 	return SUCCESS;
528 }
529 /* }}} */
530 
PHP_MSHUTDOWN_FUNCTION(browscap)531 PHP_MSHUTDOWN_FUNCTION(browscap) /* {{{ */
532 {
533 	browscap_bdata_dtor(&global_bdata, 1);
534 
535 	return SUCCESS;
536 }
537 /* }}} */
538 
browscap_get_minimum_length(browscap_entry * entry)539 static inline size_t browscap_get_minimum_length(browscap_entry *entry) {
540 	size_t len = entry->prefix_len;
541 	int i;
542 	for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
543 		len += entry->contains_len[i];
544 	}
545 	return len;
546 }
547 
browser_reg_compare(browscap_entry * entry,zend_string * agent_name,browscap_entry ** found_entry_ptr)548 static int browser_reg_compare(browscap_entry *entry, zend_string *agent_name, browscap_entry **found_entry_ptr) /* {{{ */
549 {
550 	browscap_entry *found_entry = *found_entry_ptr;
551 	ALLOCA_FLAG(use_heap)
552 	zend_string *pattern_lc, *regex;
553 	const char *cur;
554 	int i;
555 
556 	pcre2_code *re;
557 	pcre2_match_data *match_data;
558 	uint32_t capture_count;
559 	int rc;
560 
561 	/* Agent name too short */
562 	if (ZSTR_LEN(agent_name) < browscap_get_minimum_length(entry)) {
563 		return 0;
564 	}
565 
566 	/* Quickly discard patterns where the prefix doesn't match. */
567 	if (zend_binary_strcasecmp(
568 			ZSTR_VAL(agent_name), entry->prefix_len,
569 			ZSTR_VAL(entry->pattern), entry->prefix_len) != 0) {
570 		return 0;
571 	}
572 
573 	/* Lowercase the pattern, the agent name is already lowercase */
574 	ZSTR_ALLOCA_ALLOC(pattern_lc, ZSTR_LEN(entry->pattern), use_heap);
575 	zend_str_tolower_copy(ZSTR_VAL(pattern_lc), ZSTR_VAL(entry->pattern), ZSTR_LEN(entry->pattern));
576 
577 	/* Check if the agent contains the "contains" portions */
578 	cur = ZSTR_VAL(agent_name) + entry->prefix_len;
579 	for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
580 		if (entry->contains_len[i] != 0) {
581 			cur = zend_memnstr(cur,
582 				ZSTR_VAL(pattern_lc) + entry->contains_start[i],
583 				entry->contains_len[i],
584 				ZSTR_VAL(agent_name) + ZSTR_LEN(agent_name));
585 			if (!cur) {
586 				ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
587 				return 0;
588 			}
589 			cur += entry->contains_len[i];
590 		}
591 	}
592 
593 	/* See if we have an exact match, if so, we're done... */
594 	if (zend_string_equals(agent_name, pattern_lc)) {
595 		*found_entry_ptr = entry;
596 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
597 		return 1;
598 	}
599 
600 	regex = browscap_convert_pattern(entry->pattern, 0);
601 	re = pcre_get_compiled_regex(regex, &capture_count);
602 	if (re == NULL) {
603 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
604 		zend_string_release(regex);
605 		return 0;
606 	}
607 
608 	match_data = php_pcre_create_match_data(capture_count, re);
609 	if (!match_data) {
610 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
611 		zend_string_release(regex);
612 		return 0;
613 	}
614 	rc = pcre2_match(re, (PCRE2_SPTR)ZSTR_VAL(agent_name), ZSTR_LEN(agent_name), 0, 0, match_data, php_pcre_mctx());
615 	php_pcre_free_match_data(match_data);
616 	if (PCRE2_ERROR_NOMATCH != rc) {
617 		/* If we've found a possible browser, we need to do a comparison of the
618 		   number of characters changed in the user agent being checked versus
619 		   the previous match found and the current match. */
620 		if (found_entry) {
621 			size_t i, prev_len = 0, curr_len = 0;
622 			zend_string *previous_match = found_entry->pattern;
623 			zend_string *current_match = entry->pattern;
624 
625 			for (i = 0; i < ZSTR_LEN(previous_match); i++) {
626 				switch (ZSTR_VAL(previous_match)[i]) {
627 					case '?':
628 					case '*':
629 						/* do nothing, ignore these characters in the count */
630 					break;
631 
632 					default:
633 						++prev_len;
634 				}
635 			}
636 
637 			for (i = 0; i < ZSTR_LEN(current_match); i++) {
638 				switch (ZSTR_VAL(current_match)[i]) {
639 					case '?':
640 					case '*':
641 						/* do nothing, ignore these characters in the count */
642 					break;
643 
644 					default:
645 						++curr_len;
646 				}
647 			}
648 
649 			/* Pick which browser pattern replaces the least amount of
650 			   characters when compared to the original user agent string... */
651 			if (prev_len < curr_len) {
652 				*found_entry_ptr = entry;
653 			}
654 		} else {
655 			*found_entry_ptr = entry;
656 		}
657 	}
658 
659 	ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
660 	zend_string_release(regex);
661 	return 0;
662 }
663 /* }}} */
664 
browscap_zval_copy_ctor(zval * p)665 static void browscap_zval_copy_ctor(zval *p) /* {{{ */
666 {
667 	if (Z_REFCOUNTED_P(p)) {
668 		zend_string *str;
669 
670 		ZEND_ASSERT(Z_TYPE_P(p) == IS_STRING);
671 		str = Z_STR_P(p);
672 		if (!(GC_FLAGS(str) & GC_PERSISTENT)) {
673 			GC_ADDREF(str);
674 		} else {
675 			ZVAL_NEW_STR(p, zend_string_init(ZSTR_VAL(str), ZSTR_LEN(str), 0));
676 		}
677 	}
678 }
679 /* }}} */
680 
681 /* {{{ proto mixed get_browser([string browser_name [, bool return_array]])
682    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)683 PHP_FUNCTION(get_browser)
684 {
685 	zend_string *agent_name = NULL, *lookup_browser_name;
686 	zend_bool return_array = 0;
687 	browser_data *bdata;
688 	browscap_entry *found_entry = NULL;
689 	HashTable *agent_ht;
690 
691 	if (BROWSCAP_G(activation_bdata).filename[0] != '\0') {
692 		bdata = &BROWSCAP_G(activation_bdata);
693 		if (bdata->htab == NULL) { /* not initialized yet */
694 			if (browscap_read_file(bdata->filename, bdata, 0) == FAILURE) {
695 				RETURN_FALSE;
696 			}
697 		}
698 	} else {
699 		if (!global_bdata.htab) {
700 			php_error_docref(NULL, E_WARNING, "browscap ini directive not set");
701 			RETURN_FALSE;
702 		}
703 		bdata = &global_bdata;
704 	}
705 
706 	ZEND_PARSE_PARAMETERS_START(0, 2)
707 		Z_PARAM_OPTIONAL
708 		Z_PARAM_STR_EX(agent_name, 1, 0)
709 		Z_PARAM_BOOL(return_array)
710 	ZEND_PARSE_PARAMETERS_END();
711 
712 	if (agent_name == NULL) {
713 		zval *http_user_agent = NULL;
714 		if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY
715 				|| zend_is_auto_global_str(ZEND_STRL("_SERVER"))) {
716 			http_user_agent = zend_hash_str_find(
717 				Z_ARRVAL_P(&PG(http_globals)[TRACK_VARS_SERVER]),
718 				"HTTP_USER_AGENT", sizeof("HTTP_USER_AGENT")-1);
719 		}
720 		if (http_user_agent == NULL) {
721 			php_error_docref(NULL, E_WARNING, "HTTP_USER_AGENT variable is not set, cannot determine user agent name");
722 			RETURN_FALSE;
723 		}
724 		agent_name = Z_STR_P(http_user_agent);
725 	}
726 
727 	lookup_browser_name = zend_string_tolower(agent_name);
728 	found_entry = zend_hash_find_ptr(bdata->htab, lookup_browser_name);
729 	if (found_entry == NULL) {
730 		browscap_entry *entry;
731 
732 		ZEND_HASH_FOREACH_PTR(bdata->htab, entry) {
733 			if (browser_reg_compare(entry, lookup_browser_name, &found_entry)) {
734 				break;
735 			}
736 		} ZEND_HASH_FOREACH_END();
737 
738 		if (found_entry == NULL) {
739 			found_entry = zend_hash_str_find_ptr(bdata->htab,
740 				DEFAULT_SECTION_NAME, sizeof(DEFAULT_SECTION_NAME)-1);
741 			if (found_entry == NULL) {
742 				zend_string_release(lookup_browser_name);
743 				RETURN_FALSE;
744 			}
745 		}
746 	}
747 
748 	agent_ht = browscap_entry_to_array(bdata, found_entry);
749 
750 	if (return_array) {
751 		RETVAL_ARR(agent_ht);
752 	} else {
753 		object_and_properties_init(return_value, zend_standard_class_def, agent_ht);
754 	}
755 
756 	while (found_entry->parent) {
757 		found_entry = zend_hash_find_ptr(bdata->htab, found_entry->parent);
758 		if (found_entry == NULL) {
759 			break;
760 		}
761 
762 		agent_ht = browscap_entry_to_array(bdata, found_entry);
763 		if (return_array) {
764 			zend_hash_merge(Z_ARRVAL_P(return_value), agent_ht, (copy_ctor_func_t) browscap_zval_copy_ctor, 0);
765 		} else {
766 			zend_hash_merge(Z_OBJPROP_P(return_value), agent_ht, (copy_ctor_func_t) browscap_zval_copy_ctor, 0);
767 		}
768 
769 		zend_hash_destroy(agent_ht);
770 		efree(agent_ht);
771 	}
772 
773 	zend_string_release_ex(lookup_browser_name, 0);
774 }
775 /* }}} */
776