xref: /PHP-7.1/ext/standard/browscap.c (revision 7f6387b5)
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 	if (browdata->htab == NULL) {
415 		return FAILURE;
416 	}
417 
418 	zend_hash_init_ex(browdata->htab, 0, NULL,
419 		persistent ? browscap_entry_dtor_persistent : browscap_entry_dtor, persistent, 0);
420 
421 	browdata->kv_size = 16 * 1024;
422 	browdata->kv_used = 0;
423 	browdata->kv = pemalloc(sizeof(browscap_kv) * browdata->kv_size, persistent);
424 
425 	/* Create parser context */
426 	ctx.bdata = browdata;
427 	ctx.current_entry = NULL;
428 	ctx.current_section_name = NULL;
429 	ctx.str_empty = zend_string_init("", sizeof("")-1, persistent);
430 	ctx.str_one = zend_string_init("1", sizeof("1")-1, persistent);
431 	zend_hash_init(&ctx.str_interned, 8, NULL, NULL, persistent);
432 
433 	zend_parse_ini_file(&fh, 1, ZEND_INI_SCANNER_RAW,
434 			(zend_ini_parser_cb_t) php_browscap_parser_cb, &ctx);
435 
436 	/* Destroy parser context */
437 	if (ctx.current_section_name) {
438 		zend_string_release(ctx.current_section_name);
439 	}
440 	zend_string_release(ctx.str_one);
441 	zend_string_release(ctx.str_empty);
442 	zend_hash_destroy(&ctx.str_interned);
443 
444 	return SUCCESS;
445 }
446 /* }}} */
447 
448 #ifdef ZTS
browscap_globals_ctor(zend_browscap_globals * browscap_globals)449 static void browscap_globals_ctor(zend_browscap_globals *browscap_globals) /* {{{ */
450 {
451 	browscap_globals->activation_bdata.htab = NULL;
452 	browscap_globals->activation_bdata.kv = NULL;
453 	browscap_globals->activation_bdata.filename[0] = '\0';
454 }
455 /* }}} */
456 #endif
457 
browscap_bdata_dtor(browser_data * bdata,int persistent)458 static void browscap_bdata_dtor(browser_data *bdata, int persistent) /* {{{ */
459 {
460 	if (bdata->htab != NULL) {
461 		uint32_t i;
462 
463 		zend_hash_destroy(bdata->htab);
464 		pefree(bdata->htab, persistent);
465 		bdata->htab = NULL;
466 
467 		for (i = 0; i < bdata->kv_used; i++) {
468 			zend_string_release(bdata->kv[i].key);
469 			zend_string_release(bdata->kv[i].value);
470 		}
471 		pefree(bdata->kv, persistent);
472 		bdata->kv = NULL;
473 	}
474 	bdata->filename[0] = '\0';
475 }
476 /* }}} */
477 
478 /* {{{ PHP_INI_MH
479  */
PHP_INI_MH(OnChangeBrowscap)480 PHP_INI_MH(OnChangeBrowscap)
481 {
482 	if (stage == PHP_INI_STAGE_STARTUP) {
483 		/* value handled in browscap.c's MINIT */
484 		return SUCCESS;
485 	} else if (stage == PHP_INI_STAGE_ACTIVATE) {
486 		browser_data *bdata = &BROWSCAP_G(activation_bdata);
487 		if (bdata->filename[0] != '\0') {
488 			browscap_bdata_dtor(bdata, 0);
489 		}
490 		if (VCWD_REALPATH(ZSTR_VAL(new_value), bdata->filename) == NULL) {
491 			return FAILURE;
492 		}
493 		return SUCCESS;
494 	}
495 
496 	return FAILURE;
497 }
498 /* }}} */
499 
PHP_MINIT_FUNCTION(browscap)500 PHP_MINIT_FUNCTION(browscap) /* {{{ */
501 {
502 	char *browscap = INI_STR("browscap");
503 
504 #ifdef ZTS
505 	ts_allocate_id(&browscap_globals_id, sizeof(browser_data), (ts_allocate_ctor) browscap_globals_ctor, NULL);
506 #endif
507 	/* ctor call not really needed for non-ZTS */
508 
509 	if (browscap && browscap[0]) {
510 		if (browscap_read_file(browscap, &global_bdata, 1) == FAILURE) {
511 			return FAILURE;
512 		}
513 	}
514 
515 	return SUCCESS;
516 }
517 /* }}} */
518 
PHP_RSHUTDOWN_FUNCTION(browscap)519 PHP_RSHUTDOWN_FUNCTION(browscap) /* {{{ */
520 {
521 	browser_data *bdata = &BROWSCAP_G(activation_bdata);
522 	if (bdata->filename[0] != '\0') {
523 		browscap_bdata_dtor(bdata, 0);
524 	}
525 
526 	return SUCCESS;
527 }
528 /* }}} */
529 
PHP_MSHUTDOWN_FUNCTION(browscap)530 PHP_MSHUTDOWN_FUNCTION(browscap) /* {{{ */
531 {
532 	browscap_bdata_dtor(&global_bdata, 1);
533 
534 	return SUCCESS;
535 }
536 /* }}} */
537 
browscap_get_minimum_length(browscap_entry * entry)538 static inline size_t browscap_get_minimum_length(browscap_entry *entry) {
539 	size_t len = entry->prefix_len;
540 	int i;
541 	for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
542 		len += entry->contains_len[i];
543 	}
544 	return len;
545 }
546 
browser_reg_compare(zval * entry_zv,int num_args,va_list args,zend_hash_key * key)547 static int browser_reg_compare(
548 		zval *entry_zv, int num_args, va_list args, zend_hash_key *key) /* {{{ */
549 {
550 	browscap_entry *entry = Z_PTR_P(entry_zv);
551 	zend_string *agent_name = va_arg(args, zend_string *);
552 	browscap_entry **found_entry_ptr = va_arg(args, browscap_entry **);
553 	browscap_entry *found_entry = *found_entry_ptr;
554 	ALLOCA_FLAG(use_heap);
555 	zend_string *pattern_lc, *regex;
556 	const char *cur;
557 	int i;
558 
559 	pcre *re;
560 	int re_options;
561 	pcre_extra *re_extra;
562 
563 	/* Agent name too short */
564 	if (ZSTR_LEN(agent_name) < browscap_get_minimum_length(entry)) {
565 		return 0;
566 	}
567 
568 	/* Quickly discard patterns where the prefix doesn't match. */
569 	if (zend_binary_strcasecmp(
570 			ZSTR_VAL(agent_name), entry->prefix_len,
571 			ZSTR_VAL(entry->pattern), entry->prefix_len) != 0) {
572 		return 0;
573 	}
574 
575 	/* Lowercase the pattern, the agent name is already lowercase */
576 	ZSTR_ALLOCA_ALLOC(pattern_lc, ZSTR_LEN(entry->pattern), use_heap);
577 	zend_str_tolower_copy(ZSTR_VAL(pattern_lc), ZSTR_VAL(entry->pattern), ZSTR_LEN(entry->pattern));
578 
579 	/* Check if the agent contains the "contains" portions */
580 	cur = ZSTR_VAL(agent_name) + entry->prefix_len;
581 	for (i = 0; i < BROWSCAP_NUM_CONTAINS; i++) {
582 		if (entry->contains_len[i] != 0) {
583 			cur = zend_memnstr(cur,
584 				ZSTR_VAL(pattern_lc) + entry->contains_start[i],
585 				entry->contains_len[i],
586 				ZSTR_VAL(agent_name) + ZSTR_LEN(agent_name));
587 			if (!cur) {
588 				ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
589 				return 0;
590 			}
591 			cur += entry->contains_len[i];
592 		}
593 	}
594 
595 	/* See if we have an exact match, if so, we're done... */
596 	if (zend_string_equals(agent_name, pattern_lc)) {
597 		*found_entry_ptr = entry;
598 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
599 		return ZEND_HASH_APPLY_STOP;
600 	}
601 
602 	regex = browscap_convert_pattern(entry->pattern, 0);
603 	re = pcre_get_compiled_regex(regex, &re_extra, &re_options);
604 	if (re == NULL) {
605 		ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
606 		zend_string_release(regex);
607 		return 0;
608 	}
609 
610 	if (pcre_exec(re, re_extra, ZSTR_VAL(agent_name), ZSTR_LEN(agent_name), 0, re_options, NULL, 0) == 0) {
611 		/* If we've found a possible browser, we need to do a comparison of the
612 		   number of characters changed in the user agent being checked versus
613 		   the previous match found and the current match. */
614 		if (found_entry) {
615 			size_t i, prev_len = 0, curr_len = 0;
616 			zend_string *previous_match = found_entry->pattern;
617 			zend_string *current_match = entry->pattern;
618 
619 			for (i = 0; i < ZSTR_LEN(previous_match); i++) {
620 				switch (ZSTR_VAL(previous_match)[i]) {
621 					case '?':
622 					case '*':
623 						/* do nothing, ignore these characters in the count */
624 					break;
625 
626 					default:
627 						++prev_len;
628 				}
629 			}
630 
631 			for (i = 0; i < ZSTR_LEN(current_match); i++) {
632 				switch (ZSTR_VAL(current_match)[i]) {
633 					case '?':
634 					case '*':
635 						/* do nothing, ignore these characters in the count */
636 					break;
637 
638 					default:
639 						++curr_len;
640 				}
641 			}
642 
643 			/* Pick which browser pattern replaces the least amount of
644 			   characters when compared to the original user agent string... */
645 			if (prev_len < curr_len) {
646 				*found_entry_ptr = entry;
647 			}
648 		} else {
649 			*found_entry_ptr = entry;
650 		}
651 	}
652 
653 	ZSTR_ALLOCA_FREE(pattern_lc, use_heap);
654 	zend_string_release(regex);
655 	return 0;
656 }
657 /* }}} */
658 
browscap_zval_copy_ctor(zval * p)659 static void browscap_zval_copy_ctor(zval *p) /* {{{ */
660 {
661 	zval_copy_ctor(p);
662 }
663 /* }}} */
664 
665 /* {{{ proto mixed get_browser([string browser_name [, bool return_array]])
666    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)667 PHP_FUNCTION(get_browser)
668 {
669 	zend_string *agent_name = NULL, *lookup_browser_name;
670 	zend_bool return_array = 0;
671 	browser_data *bdata;
672 	browscap_entry *found_entry = NULL;
673 	HashTable *agent_ht;
674 
675 	if (BROWSCAP_G(activation_bdata).filename[0] != '\0') {
676 		bdata = &BROWSCAP_G(activation_bdata);
677 		if (bdata->htab == NULL) { /* not initialized yet */
678 			if (browscap_read_file(bdata->filename, bdata, 0) == FAILURE) {
679 				RETURN_FALSE;
680 			}
681 		}
682 	} else {
683 		if (!global_bdata.htab) {
684 			php_error_docref(NULL, E_WARNING, "browscap ini directive not set");
685 			RETURN_FALSE;
686 		}
687 		bdata = &global_bdata;
688 	}
689 
690 	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|S!b", &agent_name, &return_array) == FAILURE) {
691 		return;
692 	}
693 
694 	if (agent_name == NULL) {
695 		zval *http_user_agent = NULL;
696 		if (Z_TYPE(PG(http_globals)[TRACK_VARS_SERVER]) == IS_ARRAY
697 				|| zend_is_auto_global_str(ZEND_STRL("_SERVER"))) {
698 			http_user_agent = zend_hash_str_find(
699 				Z_ARRVAL_P(&PG(http_globals)[TRACK_VARS_SERVER]),
700 				"HTTP_USER_AGENT", sizeof("HTTP_USER_AGENT")-1);
701 		}
702 		if (http_user_agent == NULL) {
703 			php_error_docref(NULL, E_WARNING, "HTTP_USER_AGENT variable is not set, cannot determine user agent name");
704 			RETURN_FALSE;
705 		}
706 		agent_name = Z_STR_P(http_user_agent);
707 	}
708 
709 	lookup_browser_name = zend_string_tolower(agent_name);
710 	found_entry = zend_hash_find_ptr(bdata->htab, lookup_browser_name);
711 	if (found_entry == NULL) {
712 		zend_hash_apply_with_arguments(bdata->htab, browser_reg_compare, 2, lookup_browser_name, &found_entry);
713 
714 		if (found_entry == NULL) {
715 			found_entry = zend_hash_str_find_ptr(bdata->htab,
716 				DEFAULT_SECTION_NAME, sizeof(DEFAULT_SECTION_NAME)-1);
717 			if (found_entry == NULL) {
718 				efree(lookup_browser_name);
719 				RETURN_FALSE;
720 			}
721 		}
722 	}
723 
724 	agent_ht = browscap_entry_to_array(bdata, found_entry);
725 
726 	if (return_array) {
727 		RETVAL_ARR(agent_ht);
728 	} else {
729 		object_and_properties_init(return_value, zend_standard_class_def, agent_ht);
730 	}
731 
732 	while (found_entry->parent) {
733 		found_entry = zend_hash_find_ptr(bdata->htab, found_entry->parent);
734 		if (found_entry == NULL) {
735 			break;
736 		}
737 
738 		agent_ht = browscap_entry_to_array(bdata, found_entry);
739 		if (return_array) {
740 			zend_hash_merge(Z_ARRVAL_P(return_value), agent_ht, (copy_ctor_func_t) browscap_zval_copy_ctor, 0);
741 		} else {
742 			zend_hash_merge(Z_OBJPROP_P(return_value), agent_ht, (copy_ctor_func_t) browscap_zval_copy_ctor, 0);
743 		}
744 
745 		zend_hash_destroy(agent_ht);
746 		efree(agent_ht);
747 	}
748 
749 	zend_string_release(lookup_browser_name);
750 }
751 /* }}} */
752 
753 /*
754  * Local variables:
755  * tab-width: 4
756  * c-basic-offset: 4
757  * End:
758  * vim600: sw=4 ts=4 fdm=marker
759  * vim<600: sw=4 ts=4
760  */
761