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