xref: /PHP-8.4/ext/fileinfo/php_libmagic.c (revision b8aa2270)
1 /*
2   +----------------------------------------------------------------------+
3   | Copyright (c) The PHP Group                                          |
4   +----------------------------------------------------------------------+
5   | This source file is subject to version 3.01 of the PHP license,      |
6   | that is bundled with this package in the file LICENSE, and is        |
7   | available through the world-wide-web at the following url:           |
8   | https://www.php.net/license/3_01.txt                                 |
9   | If you did not receive a copy of the PHP license and are unable to   |
10   | obtain it through the world-wide-web, please send a note to          |
11   | license@php.net so we can mail you a copy immediately.               |
12   +----------------------------------------------------------------------+
13   | Author: Anatol Belski <ab@php.net>                                   |
14   +----------------------------------------------------------------------+
15 */
16 
17 #include "php.h"
18 #include "php_libmagic.h"
19 
convert_libmagic_pattern(const char * val,size_t len,uint32_t options)20 zend_string* convert_libmagic_pattern(const char *val, size_t len, uint32_t options)
21 {
22 	size_t i, j;
23 	zend_string *t;
24 
25 	for (i = j = 0; i < len; i++) {
26 		switch (val[i]) {
27 			case '~':
28 				j += 2;
29 				break;
30 			case '\0':
31 				j += 4;
32 				break;
33 			default:
34 				j++;
35 				break;
36 		}
37 	}
38 	t = zend_string_alloc(j + 4, 0);
39 
40 	j = 0;
41 	ZSTR_VAL(t)[j++] = '~';
42 
43 	for (i = 0; i < len; i++, j++) {
44 		switch (val[i]) {
45 			case '~':
46 				ZSTR_VAL(t)[j++] = '\\';
47 				ZSTR_VAL(t)[j] = '~';
48 				break;
49 			case '\0':
50 				ZSTR_VAL(t)[j++] = '\\';
51 				ZSTR_VAL(t)[j++] = 'x';
52 				ZSTR_VAL(t)[j++] = '0';
53 				ZSTR_VAL(t)[j] = '0';
54 				break;
55 			default:
56 				ZSTR_VAL(t)[j] = val[i];
57 				break;
58 		}
59 	}
60 	ZSTR_VAL(t)[j++] = '~';
61 
62 	if (options & PCRE2_CASELESS)
63 		ZSTR_VAL(t)[j++] = 'i';
64 
65 	if (options & PCRE2_MULTILINE)
66 		ZSTR_VAL(t)[j++] = 'm';
67 
68 	ZSTR_VAL(t)[j]='\0';
69 	ZSTR_LEN(t) = j;
70 
71 	return t;
72 }
73 
74 
75 
76