xref: /PHP-7.2/ext/fileinfo/libmagic/apprentice.c (revision c621182c)
1 /*
2  * Copyright (c) Ian F. Darwin 1986-1995.
3  * Software written by Ian F. Darwin and others;
4  * maintained 1995-present by Christos Zoulas and others.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice immediately at the beginning of the file, without modification,
11  *    this list of conditions, and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 /*
29  * apprentice - make one pass through /etc/magic, learning its secrets.
30  */
31 
32 #include "php.h"
33 
34 #include "file.h"
35 
36 #ifndef	lint
37 FILE_RCSID("@(#)$File: apprentice.c,v 1.260 2017/04/28 16:27:58 christos Exp $")
38 #endif	/* lint */
39 
40 #include "magic.h"
41 #include "patchlevel.h"
42 #include <stdlib.h>
43 
44 #if defined(__hpux) && !defined(HAVE_STRTOULL)
45 #if SIZEOF_LONG == 8
46 # define strtoull strtoul
47 #else
48 # define strtoull __strtoull
49 #endif
50 #endif
51 
52 #ifdef PHP_WIN32
53 #include "win32/unistd.h"
54 #define strtoull _strtoui64
55 #else
56 #include <unistd.h>
57 #endif
58 #include <string.h>
59 #include <assert.h>
60 #include <ctype.h>
61 #include <fcntl.h>
62 
63 #ifndef SSIZE_MAX
64 #define MAXMAGIC_SIZE        ((ssize_t)0x7fffffff)
65 #else
66 #define MAXMAGIC_SIZE        SSIZE_MAX
67 #endif
68 
69 #define	EATAB {while (isascii((unsigned char) *l) && \
70 		      isspace((unsigned char) *l))  ++l;}
71 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
72 			tolower((unsigned char) (l)) : (l))
73 /*
74  * Work around a bug in headers on Digital Unix.
75  * At least confirmed for: OSF1 V4.0 878
76  */
77 #if defined(__osf__) && defined(__DECC)
78 #ifdef MAP_FAILED
79 #undef MAP_FAILED
80 #endif
81 #endif
82 
83 #ifndef offsetof
84 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
85 #endif
86 
87 #ifndef MAP_FAILED
88 #define MAP_FAILED (void *) -1
89 #endif
90 
91 #ifndef MAP_FILE
92 #define MAP_FILE 0
93 #endif
94 
95 #define ALLOC_CHUNK	(size_t)10
96 #define ALLOC_INCR	(size_t)200
97 
98 #define MAP_TYPE_USER	0
99 #define MAP_TYPE_MALLOC	1
100 #define MAP_TYPE_MMAP	2
101 
102 struct magic_entry {
103 	struct magic *mp;
104 	uint32_t cont_count;
105 	uint32_t max_count;
106 };
107 
108 struct magic_entry_set {
109 	struct magic_entry *me;
110 	uint32_t count;
111 	uint32_t max;
112 };
113 
114 struct magic_map {
115 	void *p;
116 	size_t len;
117 	int type;
118 	struct magic *magic[MAGIC_SETS];
119 	uint32_t nmagic[MAGIC_SETS];
120 };
121 
122 int file_formats[FILE_NAMES_SIZE];
123 const size_t file_nformats = FILE_NAMES_SIZE;
124 const char *file_names[FILE_NAMES_SIZE];
125 const size_t file_nnames = FILE_NAMES_SIZE;
126 
127 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
128 private int hextoint(int);
129 private const char *getstr(struct magic_set *, struct magic *, const char *,
130     int);
131 private int parse(struct magic_set *, struct magic_entry *, const char *,
132     size_t, int);
133 private void eatsize(const char **);
134 private int apprentice_1(struct magic_set *, const char *, int);
135 private size_t apprentice_magic_strength(const struct magic *);
136 private int apprentice_sort(const void *, const void *);
137 private void apprentice_list(struct mlist *, int );
138 private struct magic_map *apprentice_load(struct magic_set *,
139     const char *, int);
140 private struct mlist *mlist_alloc(void);
141 private void mlist_free(struct mlist *);
142 private void byteswap(struct magic *, uint32_t);
143 private void bs1(struct magic *);
144 private uint16_t swap2(uint16_t);
145 private uint32_t swap4(uint32_t);
146 private uint64_t swap8(uint64_t);
147 private char *mkdbname(struct magic_set *, const char *, int);
148 private struct magic_map *apprentice_buf(struct magic_set *, struct magic *,
149     size_t);
150 private struct magic_map *apprentice_map(struct magic_set *, const char *);
151 private int check_buffer(struct magic_set *, struct magic_map *, const char *);
152 private void apprentice_unmap(struct magic_map *);
153 private int apprentice_compile(struct magic_set *, struct magic_map *,
154     const char *);
155 private int check_format_type(const char *, int, const char **);
156 private int check_format(struct magic_set *, struct magic *);
157 private int get_op(char);
158 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
159 private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
160 private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
161 private int parse_ext(struct magic_set *, struct magic_entry *, const char *);
162 
163 
164 private size_t magicsize = sizeof(struct magic);
165 
166 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
167 
168 private struct {
169 	const char *name;
170 	size_t len;
171 	int (*fun)(struct magic_set *, struct magic_entry *, const char *);
172 } bang[] = {
173 #define	DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
174 	DECLARE_FIELD(mime),
175 	DECLARE_FIELD(apple),
176 	DECLARE_FIELD(ext),
177 	DECLARE_FIELD(strength),
178 #undef	DECLARE_FIELD
179 	{ NULL, 0, NULL }
180 };
181 
182 #include "../data_file.c"
183 
184 struct type_tbl_s {
185 	const char name[16];
186 	const size_t len;
187 	const int type;
188 	const int format;
189 };
190 
191 /*
192  * XXX - the actual Single UNIX Specification says that "long" means "long",
193  * as in the C data type, but we treat it as meaning "4-byte integer".
194  * Given that the OS X version of file 5.04 did the same, I guess that passes
195  * the actual test; having "long" be dependent on how big a "long" is on
196  * the machine running "file" is silly.
197  */
198 static const struct type_tbl_s type_tbl[] = {
199 # define XX(s)		s, (sizeof(s) - 1)
200 # define XX_NULL	"", 0
201 	{ XX("invalid"),	FILE_INVALID,		FILE_FMT_NONE },
202 	{ XX("byte"),		FILE_BYTE,		FILE_FMT_NUM },
203 	{ XX("short"),		FILE_SHORT,		FILE_FMT_NUM },
204 	{ XX("default"),	FILE_DEFAULT,		FILE_FMT_NONE },
205 	{ XX("long"),		FILE_LONG,		FILE_FMT_NUM },
206 	{ XX("string"),		FILE_STRING,		FILE_FMT_STR },
207 	{ XX("date"),		FILE_DATE,		FILE_FMT_STR },
208 	{ XX("beshort"),	FILE_BESHORT,		FILE_FMT_NUM },
209 	{ XX("belong"),		FILE_BELONG,		FILE_FMT_NUM },
210 	{ XX("bedate"),		FILE_BEDATE,		FILE_FMT_STR },
211 	{ XX("leshort"),	FILE_LESHORT,		FILE_FMT_NUM },
212 	{ XX("lelong"),		FILE_LELONG,		FILE_FMT_NUM },
213 	{ XX("ledate"),		FILE_LEDATE,		FILE_FMT_STR },
214 	{ XX("pstring"),	FILE_PSTRING,		FILE_FMT_STR },
215 	{ XX("ldate"),		FILE_LDATE,		FILE_FMT_STR },
216 	{ XX("beldate"),	FILE_BELDATE,		FILE_FMT_STR },
217 	{ XX("leldate"),	FILE_LELDATE,		FILE_FMT_STR },
218 	{ XX("regex"),		FILE_REGEX,		FILE_FMT_STR },
219 	{ XX("bestring16"),	FILE_BESTRING16,	FILE_FMT_STR },
220 	{ XX("lestring16"),	FILE_LESTRING16,	FILE_FMT_STR },
221 	{ XX("search"),		FILE_SEARCH,		FILE_FMT_STR },
222 	{ XX("medate"),		FILE_MEDATE,		FILE_FMT_STR },
223 	{ XX("meldate"),	FILE_MELDATE,		FILE_FMT_STR },
224 	{ XX("melong"),		FILE_MELONG,		FILE_FMT_NUM },
225 	{ XX("quad"),		FILE_QUAD,		FILE_FMT_QUAD },
226 	{ XX("lequad"),		FILE_LEQUAD,		FILE_FMT_QUAD },
227 	{ XX("bequad"),		FILE_BEQUAD,		FILE_FMT_QUAD },
228 	{ XX("qdate"),		FILE_QDATE,		FILE_FMT_STR },
229 	{ XX("leqdate"),	FILE_LEQDATE,		FILE_FMT_STR },
230 	{ XX("beqdate"),	FILE_BEQDATE,		FILE_FMT_STR },
231 	{ XX("qldate"),		FILE_QLDATE,		FILE_FMT_STR },
232 	{ XX("leqldate"),	FILE_LEQLDATE,		FILE_FMT_STR },
233 	{ XX("beqldate"),	FILE_BEQLDATE,		FILE_FMT_STR },
234 	{ XX("float"),		FILE_FLOAT,		FILE_FMT_FLOAT },
235 	{ XX("befloat"),	FILE_BEFLOAT,		FILE_FMT_FLOAT },
236 	{ XX("lefloat"),	FILE_LEFLOAT,		FILE_FMT_FLOAT },
237 	{ XX("double"),		FILE_DOUBLE,		FILE_FMT_DOUBLE },
238 	{ XX("bedouble"),	FILE_BEDOUBLE,		FILE_FMT_DOUBLE },
239 	{ XX("ledouble"),	FILE_LEDOUBLE,		FILE_FMT_DOUBLE },
240 	{ XX("leid3"),		FILE_LEID3,		FILE_FMT_NUM },
241 	{ XX("beid3"),		FILE_BEID3,		FILE_FMT_NUM },
242 	{ XX("indirect"),	FILE_INDIRECT,		FILE_FMT_NUM },
243 	{ XX("qwdate"),		FILE_QWDATE,		FILE_FMT_STR },
244 	{ XX("leqwdate"),	FILE_LEQWDATE,		FILE_FMT_STR },
245 	{ XX("beqwdate"),	FILE_BEQWDATE,		FILE_FMT_STR },
246 	{ XX("name"),		FILE_NAME,		FILE_FMT_NONE },
247 	{ XX("use"),		FILE_USE,		FILE_FMT_NONE },
248 	{ XX("clear"),		FILE_CLEAR,		FILE_FMT_NONE },
249 	{ XX("der"),		FILE_DER,		FILE_FMT_STR },
250 	{ XX_NULL,		FILE_INVALID,		FILE_FMT_NONE },
251 };
252 
253 /*
254  * These are not types, and cannot be preceded by "u" to make them
255  * unsigned.
256  */
257 static const struct type_tbl_s special_tbl[] = {
258 	{ XX("der"),		FILE_DER,		FILE_FMT_STR },
259 	{ XX("name"),		FILE_NAME,		FILE_FMT_STR },
260 	{ XX("use"),		FILE_USE,		FILE_FMT_STR },
261 	{ XX_NULL,		FILE_INVALID,		FILE_FMT_NONE },
262 };
263 # undef XX
264 # undef XX_NULL
265 
266 #ifndef S_ISDIR
267 #define S_ISDIR(mode) ((mode) & _S_IFDIR)
268 #endif
269 
270 private int
get_type(const struct type_tbl_s * tbl,const char * l,const char ** t)271 get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
272 {
273 	const struct type_tbl_s *p;
274 
275 	for (p = tbl; p->len; p++) {
276 		if (strncmp(l, p->name, p->len) == 0) {
277 			if (t)
278 				*t = l + p->len;
279 			break;
280 		}
281 	}
282 	return p->type;
283 }
284 
285 private int
get_standard_integer_type(const char * l,const char ** t)286 get_standard_integer_type(const char *l, const char **t)
287 {
288 	int type;
289 
290 	if (isalpha((unsigned char)l[1])) {
291 		switch (l[1]) {
292 		case 'C':
293 			/* "dC" and "uC" */
294 			type = FILE_BYTE;
295 			break;
296 		case 'S':
297 			/* "dS" and "uS" */
298 			type = FILE_SHORT;
299 			break;
300 		case 'I':
301 		case 'L':
302 			/*
303 			 * "dI", "dL", "uI", and "uL".
304 			 *
305 			 * XXX - the actual Single UNIX Specification says
306 			 * that "L" means "long", as in the C data type,
307 			 * but we treat it as meaning "4-byte integer".
308 			 * Given that the OS X version of file 5.04 did
309 			 * the same, I guess that passes the actual SUS
310 			 * validation suite; having "dL" be dependent on
311 			 * how big a "long" is on the machine running
312 			 * "file" is silly.
313 			 */
314 			type = FILE_LONG;
315 			break;
316 		case 'Q':
317 			/* "dQ" and "uQ" */
318 			type = FILE_QUAD;
319 			break;
320 		default:
321 			/* "d{anything else}", "u{anything else}" */
322 			return FILE_INVALID;
323 		}
324 		l += 2;
325 	} else if (isdigit((unsigned char)l[1])) {
326 		/*
327 		 * "d{num}" and "u{num}"; we only support {num} values
328 		 * of 1, 2, 4, and 8 - the Single UNIX Specification
329 		 * doesn't say anything about whether arbitrary
330 		 * values should be supported, but both the Solaris 10
331 		 * and OS X Mountain Lion versions of file passed the
332 		 * Single UNIX Specification validation suite, and
333 		 * neither of them support values bigger than 8 or
334 		 * non-power-of-2 values.
335 		 */
336 		if (isdigit((unsigned char)l[2])) {
337 			/* Multi-digit, so > 9 */
338 			return FILE_INVALID;
339 		}
340 		switch (l[1]) {
341 		case '1':
342 			type = FILE_BYTE;
343 			break;
344 		case '2':
345 			type = FILE_SHORT;
346 			break;
347 		case '4':
348 			type = FILE_LONG;
349 			break;
350 		case '8':
351 			type = FILE_QUAD;
352 			break;
353 		default:
354 			/* XXX - what about 3, 5, 6, or 7? */
355 			return FILE_INVALID;
356 		}
357 		l += 2;
358 	} else {
359 		/*
360 		 * "d" or "u" by itself.
361 		 */
362 		type = FILE_LONG;
363 		++l;
364 	}
365 	if (t)
366 		*t = l;
367 	return type;
368 }
369 
370 private void
init_file_tables(void)371 init_file_tables(void)
372 {
373 	static int done = 0;
374 	const struct type_tbl_s *p;
375 
376 	if (done)
377 		return;
378 	done++;
379 
380 	for (p = type_tbl; p->len; p++) {
381 		assert(p->type < FILE_NAMES_SIZE);
382 		file_names[p->type] = p->name;
383 		file_formats[p->type] = p->format;
384 	}
385 	assert(p - type_tbl == FILE_NAMES_SIZE);
386 }
387 
388 private int
add_mlist(struct mlist * mlp,struct magic_map * map,size_t idx)389 add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
390 {
391 	struct mlist *ml;
392 
393 	mlp->map = NULL;
394 	if ((ml = CAST(struct mlist *, emalloc(sizeof(*ml)))) == NULL)
395 		return -1;
396 
397 	ml->map = idx == 0 ? map : NULL;
398 	ml->magic = map->magic[idx];
399 	ml->nmagic = map->nmagic[idx];
400 
401 	mlp->prev->next = ml;
402 	ml->prev = mlp->prev;
403 	ml->next = mlp;
404 	mlp->prev = ml;
405 	return 0;
406 }
407 
408 /*
409  * Handle one file or directory.
410  */
411 private int
apprentice_1(struct magic_set * ms,const char * fn,int action)412 apprentice_1(struct magic_set *ms, const char *fn, int action)
413 {
414 	struct magic_map *map;
415 	struct mlist *ml;
416 	size_t i;
417 
418 	if (magicsize != FILE_MAGICSIZE) {
419 		file_error(ms, 0, "magic element size %lu != %lu",
420 		    (unsigned long)sizeof(*map->magic[0]),
421 		    (unsigned long)FILE_MAGICSIZE);
422 		return -1;
423 	}
424 
425 	if (action == FILE_COMPILE) {
426 		map = apprentice_load(ms, fn, action);
427 		if (map == NULL)
428 			return -1;
429 		return apprentice_compile(ms, map, fn);
430 	}
431 
432 	map = apprentice_map(ms, fn);
433 	if (map == (struct magic_map *)-1)
434 		return -1;
435 	if (map == NULL) {
436 		if (fn) {
437 			if (ms->flags & MAGIC_CHECK)
438 				file_magwarn(ms, "using regular magic file `%s'", fn);
439 			map = apprentice_load(ms, fn, action);
440 		}
441 		if (map == NULL)
442 			return -1;
443 	}
444 
445 	for (i = 0; i < MAGIC_SETS; i++) {
446 		if (add_mlist(ms->mlist[i], map, i) == -1) {
447 			file_oomem(ms, sizeof(*ml));
448 			return -1;
449 		}
450 	}
451 
452 	if (action == FILE_LIST) {
453 		for (i = 0; i < MAGIC_SETS; i++) {
454 			printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
455 			    i);
456 			apprentice_list(ms->mlist[i], BINTEST);
457 			printf("Text patterns:\n");
458 			apprentice_list(ms->mlist[i], TEXTTEST);
459 		}
460 	}
461 	return 0;
462 }
463 
464 protected void
file_ms_free(struct magic_set * ms)465 file_ms_free(struct magic_set *ms)
466 {
467 	size_t i;
468 	if (ms == NULL)
469 		return;
470 	for (i = 0; i < MAGIC_SETS; i++)
471 		mlist_free(ms->mlist[i]);
472 	if (ms->o.pbuf) {
473 		efree(ms->o.pbuf);
474 	}
475 	if (ms->o.buf) {
476 		efree(ms->o.buf);
477 	}
478 	if (ms->c.li) {
479 		efree(ms->c.li);
480 	}
481 	efree(ms);
482 }
483 
484 protected struct magic_set *
file_ms_alloc(int flags)485 file_ms_alloc(int flags)
486 {
487 	struct magic_set *ms;
488 	size_t i, len;
489 
490 	if ((ms = CAST(struct magic_set *, ecalloc((size_t)1,
491 	    sizeof(struct magic_set)))) == NULL)
492 		return NULL;
493 
494 	if (magic_setflags(ms, flags) == -1) {
495 		errno = EINVAL;
496 		goto free;
497 	}
498 
499 	ms->o.buf = ms->o.pbuf = NULL;
500 	len = (ms->c.len = 10) * sizeof(*ms->c.li);
501 
502 	if ((ms->c.li = CAST(struct level_info *, emalloc(len))) == NULL)
503 		goto free;
504 
505 	ms->event_flags = 0;
506 	ms->error = -1;
507 	for (i = 0; i < MAGIC_SETS; i++)
508 		ms->mlist[i] = NULL;
509 	ms->file = "unknown";
510 	ms->line = 0;
511 	ms->indir_max = FILE_INDIR_MAX;
512 	ms->name_max = FILE_NAME_MAX;
513 	ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
514 	ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
515 	ms->elf_notes_max = FILE_ELF_NOTES_MAX;
516 	ms->regex_max = FILE_REGEX_MAX;
517 	ms->bytes_max = FILE_BYTES_MAX;
518 	return ms;
519 free:
520 	efree(ms);
521 	return NULL;
522 }
523 
524 private void
apprentice_unmap(struct magic_map * map)525 apprentice_unmap(struct magic_map *map)
526 {
527 	if (map == NULL)
528 		return;
529 	if (map->p != php_magic_database) {
530 		if (map->p == NULL) {
531 			int j;
532 			for (j = 0; j < MAGIC_SETS; j++) {
533 				if (map->magic[j]) {
534 					efree(map->magic[j]);
535 				}
536 			}
537 		} else {
538 			efree(map->p);
539 		}
540 	}
541 	efree(map);
542 }
543 
544 private struct mlist *
mlist_alloc(void)545 mlist_alloc(void)
546 {
547 	struct mlist *mlist;
548 	if ((mlist = CAST(struct mlist *, ecalloc(1, sizeof(*mlist)))) == NULL) {
549 		return NULL;
550 	}
551 	mlist->next = mlist->prev = mlist;
552 	return mlist;
553 }
554 
555 private void
mlist_free(struct mlist * mlist)556 mlist_free(struct mlist *mlist)
557 {
558 	struct mlist *ml, *next;
559 
560 	if (mlist == NULL)
561 		return;
562 
563 	ml = mlist->next;
564 	for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
565 		if (ml->map)
566 			apprentice_unmap(CAST(struct magic_map *, ml->map));
567 		efree(ml);
568 		if (ml == mlist)
569 			break;
570 	}
571 }
572 
573 /* const char *fn: list of magic files and directories */
574 protected int
file_apprentice(struct magic_set * ms,const char * fn,int action)575 file_apprentice(struct magic_set *ms, const char *fn, int action)
576 {
577 	char *p, *mfn;
578 	int file_err, errs = -1;
579 	size_t i;
580 
581 	if (ms->mlist[0] != NULL)
582 		file_reset(ms);
583 
584 /* XXX disabling default magic loading so the compiled in data is used */
585 #if 0
586 	if ((fn = magic_getpath(fn, action)) == NULL)
587 		return -1;
588 #endif
589 
590 	init_file_tables();
591 
592 	if (fn == NULL)
593 		fn = getenv("MAGIC");
594 	if (fn == NULL) {
595 		for (i = 0; i < MAGIC_SETS; i++) {
596 			mlist_free(ms->mlist[i]);
597 			if ((ms->mlist[i] = mlist_alloc()) == NULL) {
598 				file_oomem(ms, sizeof(*ms->mlist[i]));
599 				return -1;
600 			}
601 		}
602 		return apprentice_1(ms, fn, action);
603 	}
604 
605 	if ((mfn = estrdup(fn)) == NULL) {
606 		file_oomem(ms, strlen(fn));
607 		return -1;
608 	}
609 
610 	for (i = 0; i < MAGIC_SETS; i++) {
611 		mlist_free(ms->mlist[i]);
612 		if ((ms->mlist[i] = mlist_alloc()) == NULL) {
613 			file_oomem(ms, sizeof(*ms->mlist[i]));
614 			while (i-- > 0) {
615 				mlist_free(ms->mlist[i]);
616 				ms->mlist[i] = NULL;
617 			}
618 			efree(mfn);
619 			return -1;
620 		}
621 	}
622 	fn = mfn;
623 
624 	while (fn) {
625 		p = strchr(fn, PATHSEP);
626 		if (p)
627 			*p++ = '\0';
628 		if (*fn == '\0')
629 			break;
630 		file_err = apprentice_1(ms, fn, action);
631 		errs = MAX(errs, file_err);
632 		fn = p;
633 	}
634 
635 	efree(mfn);
636 
637 	if (errs == -1) {
638 		for (i = 0; i < MAGIC_SETS; i++) {
639 			mlist_free(ms->mlist[i]);
640 			ms->mlist[i] = NULL;
641 		}
642 		file_error(ms, 0, "could not find any valid magic files!");
643 		return -1;
644 	}
645 
646 #if 0
647 	/*
648 	 * Always leave the database loaded
649 	 */
650 	if (action == FILE_LOAD)
651 		return 0;
652 
653 	for (i = 0; i < MAGIC_SETS; i++) {
654 		mlist_free(ms->mlist[i]);
655 		ms->mlist[i] = NULL;
656 	}
657 #endif
658 
659 	switch (action) {
660 	case FILE_LOAD:
661 	case FILE_COMPILE:
662 	case FILE_CHECK:
663 	case FILE_LIST:
664 		return 0;
665 	default:
666 		file_error(ms, 0, "Invalid action %d", action);
667 		return -1;
668 	}
669 }
670 
671 /*
672  * Compute the real length of a magic expression, for the purposes
673  * of determining how "strong" a magic expression is (approximating
674  * how specific its matches are):
675  *	- magic characters count 0 unless escaped.
676  *	- [] expressions count 1
677  *	- {} expressions count 0
678  *	- regular characters or escaped magic characters count 1
679  *	- 0 length expressions count as one
680  */
681 private size_t
nonmagic(const char * str)682 nonmagic(const char *str)
683 {
684 	const char *p;
685 	size_t rv = 0;
686 
687 	for (p = str; *p; p++)
688 		switch (*p) {
689 		case '\\':	/* Escaped anything counts 1 */
690 			if (!*++p)
691 				p--;
692 			rv++;
693 			continue;
694 		case '?':	/* Magic characters count 0 */
695 		case '*':
696 		case '.':
697 		case '+':
698 		case '^':
699 		case '$':
700 			continue;
701 		case '[':	/* Bracketed expressions count 1 the ']' */
702 			while (*p && *p != ']')
703 				p++;
704 			p--;
705 			continue;
706 		case '{':	/* Braced expressions count 0 */
707 			while (*p && *p != '}')
708 				p++;
709 			if (!*p)
710 				p--;
711 			continue;
712 		default:	/* Anything else counts 1 */
713 			rv++;
714 			continue;
715 		}
716 
717 	return rv == 0 ? 1 : rv;	/* Return at least 1 */
718 }
719 
720 /*
721  * Get weight of this magic entry, for sorting purposes.
722  */
723 private size_t
apprentice_magic_strength(const struct magic * m)724 apprentice_magic_strength(const struct magic *m)
725 {
726 #define MULT 10
727 	size_t v, val = 2 * MULT;	/* baseline strength */
728 
729 	switch (m->type) {
730 	case FILE_DEFAULT:	/* make sure this sorts last */
731 		if (m->factor_op != FILE_FACTOR_OP_NONE)
732 			abort();
733 		return 0;
734 
735 	case FILE_BYTE:
736 		val += 1 * MULT;
737 		break;
738 
739 	case FILE_SHORT:
740 	case FILE_LESHORT:
741 	case FILE_BESHORT:
742 		val += 2 * MULT;
743 		break;
744 
745 	case FILE_LONG:
746 	case FILE_LELONG:
747 	case FILE_BELONG:
748 	case FILE_MELONG:
749 		val += 4 * MULT;
750 		break;
751 
752 	case FILE_PSTRING:
753 	case FILE_STRING:
754 		val += m->vallen * MULT;
755 		break;
756 
757 	case FILE_BESTRING16:
758 	case FILE_LESTRING16:
759 		val += m->vallen * MULT / 2;
760 		break;
761 
762 	case FILE_SEARCH:
763 		val += m->vallen * MAX(MULT / m->vallen, 1);
764 		break;
765 
766 	case FILE_REGEX:
767 		v = nonmagic(m->value.s);
768 		val += v * MAX(MULT / v, 1);
769 		break;
770 
771 	case FILE_DATE:
772 	case FILE_LEDATE:
773 	case FILE_BEDATE:
774 	case FILE_MEDATE:
775 	case FILE_LDATE:
776 	case FILE_LELDATE:
777 	case FILE_BELDATE:
778 	case FILE_MELDATE:
779 	case FILE_FLOAT:
780 	case FILE_BEFLOAT:
781 	case FILE_LEFLOAT:
782 		val += 4 * MULT;
783 		break;
784 
785 	case FILE_QUAD:
786 	case FILE_BEQUAD:
787 	case FILE_LEQUAD:
788 	case FILE_QDATE:
789 	case FILE_LEQDATE:
790 	case FILE_BEQDATE:
791 	case FILE_QLDATE:
792 	case FILE_LEQLDATE:
793 	case FILE_BEQLDATE:
794 	case FILE_QWDATE:
795 	case FILE_LEQWDATE:
796 	case FILE_BEQWDATE:
797 	case FILE_DOUBLE:
798 	case FILE_BEDOUBLE:
799 	case FILE_LEDOUBLE:
800 		val += 8 * MULT;
801 		break;
802 
803 	case FILE_INDIRECT:
804 	case FILE_NAME:
805 	case FILE_USE:
806 		break;
807 
808 	case FILE_DER:
809 		val += MULT;
810 		break;
811 
812 	default:
813 		(void)fprintf(stderr, "Bad type %d\n", m->type);
814 		abort();
815 	}
816 
817 	switch (m->reln) {
818 	case 'x':	/* matches anything penalize */
819 	case '!':       /* matches almost anything penalize */
820 		val = 0;
821 		break;
822 
823 	case '=':	/* Exact match, prefer */
824 		val += MULT;
825 		break;
826 
827 	case '>':
828 	case '<':	/* comparison match reduce strength */
829 		val -= 2 * MULT;
830 		break;
831 
832 	case '^':
833 	case '&':	/* masking bits, we could count them too */
834 		val -= MULT;
835 		break;
836 
837 	default:
838 		(void)fprintf(stderr, "Bad relation %c\n", m->reln);
839 		abort();
840 	}
841 
842 	if (val == 0)	/* ensure we only return 0 for FILE_DEFAULT */
843 		val = 1;
844 
845 	switch (m->factor_op) {
846 	case FILE_FACTOR_OP_NONE:
847 		break;
848 	case FILE_FACTOR_OP_PLUS:
849 		val += m->factor;
850 		break;
851 	case FILE_FACTOR_OP_MINUS:
852 		val -= m->factor;
853 		break;
854 	case FILE_FACTOR_OP_TIMES:
855 		val *= m->factor;
856 		break;
857 	case FILE_FACTOR_OP_DIV:
858 		val /= m->factor;
859 		break;
860 	default:
861 		abort();
862 	}
863 
864 	/*
865 	 * Magic entries with no description get a bonus because they depend
866 	 * on subsequent magic entries to print something.
867 	 */
868 	if (m->desc[0] == '\0')
869 		val++;
870 	return val;
871 }
872 
873 /*
874  * Sort callback for sorting entries by "strength" (basically length)
875  */
876 private int
apprentice_sort(const void * a,const void * b)877 apprentice_sort(const void *a, const void *b)
878 {
879 	const struct magic_entry *ma = CAST(const struct magic_entry *, a);
880 	const struct magic_entry *mb = CAST(const struct magic_entry *, b);
881 	size_t sa = apprentice_magic_strength(ma->mp);
882 	size_t sb = apprentice_magic_strength(mb->mp);
883 	if (sa == sb)
884 		return 0;
885 	else if (sa > sb)
886 		return -1;
887 	else
888 		return 1;
889 }
890 
891 /*
892  * Shows sorted patterns list in the order which is used for the matching
893  */
894 private void
apprentice_list(struct mlist * mlist,int mode)895 apprentice_list(struct mlist *mlist, int mode)
896 {
897 	uint32_t magindex = 0;
898 	struct mlist *ml;
899 	for (ml = mlist->next; ml != mlist; ml = ml->next) {
900 		for (magindex = 0; magindex < ml->nmagic; magindex++) {
901 			struct magic *m = &ml->magic[magindex];
902 			if ((m->flag & mode) != mode) {
903 				/* Skip sub-tests */
904 				while (magindex + 1 < ml->nmagic &&
905 				       ml->magic[magindex + 1].cont_level != 0)
906 					++magindex;
907 				continue; /* Skip to next top-level test*/
908 			}
909 
910 			/*
911 			 * Try to iterate over the tree until we find item with
912 			 * description/mimetype.
913 			 */
914 			while (magindex + 1 < ml->nmagic &&
915 			       ml->magic[magindex + 1].cont_level != 0 &&
916 			       *ml->magic[magindex].desc == '\0' &&
917 			       *ml->magic[magindex].mimetype == '\0')
918 				magindex++;
919 
920 			printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
921 			    apprentice_magic_strength(m),
922 			    ml->magic[magindex].lineno,
923 			    ml->magic[magindex].desc,
924 			    ml->magic[magindex].mimetype);
925 		}
926 	}
927 }
928 
929 private void
set_test_type(struct magic * mstart,struct magic * m)930 set_test_type(struct magic *mstart, struct magic *m)
931 {
932 	switch (m->type) {
933 	case FILE_BYTE:
934 	case FILE_SHORT:
935 	case FILE_LONG:
936 	case FILE_DATE:
937 	case FILE_BESHORT:
938 	case FILE_BELONG:
939 	case FILE_BEDATE:
940 	case FILE_LESHORT:
941 	case FILE_LELONG:
942 	case FILE_LEDATE:
943 	case FILE_LDATE:
944 	case FILE_BELDATE:
945 	case FILE_LELDATE:
946 	case FILE_MEDATE:
947 	case FILE_MELDATE:
948 	case FILE_MELONG:
949 	case FILE_QUAD:
950 	case FILE_LEQUAD:
951 	case FILE_BEQUAD:
952 	case FILE_QDATE:
953 	case FILE_LEQDATE:
954 	case FILE_BEQDATE:
955 	case FILE_QLDATE:
956 	case FILE_LEQLDATE:
957 	case FILE_BEQLDATE:
958 	case FILE_QWDATE:
959 	case FILE_LEQWDATE:
960 	case FILE_BEQWDATE:
961 	case FILE_FLOAT:
962 	case FILE_BEFLOAT:
963 	case FILE_LEFLOAT:
964 	case FILE_DOUBLE:
965 	case FILE_BEDOUBLE:
966 	case FILE_LEDOUBLE:
967 	case FILE_DER:
968 		mstart->flag |= BINTEST;
969 		break;
970 	case FILE_STRING:
971 	case FILE_PSTRING:
972 	case FILE_BESTRING16:
973 	case FILE_LESTRING16:
974 		/* Allow text overrides */
975 		if (mstart->str_flags & STRING_TEXTTEST)
976 			mstart->flag |= TEXTTEST;
977 		else
978 			mstart->flag |= BINTEST;
979 		break;
980 	case FILE_REGEX:
981 	case FILE_SEARCH:
982 		/* Check for override */
983 		if (mstart->str_flags & STRING_BINTEST)
984 			mstart->flag |= BINTEST;
985 		if (mstart->str_flags & STRING_TEXTTEST)
986 			mstart->flag |= TEXTTEST;
987 
988 		if (mstart->flag & (TEXTTEST|BINTEST))
989 			break;
990 
991 		/* binary test if pattern is not text */
992 		if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
993 		    NULL) <= 0)
994 			mstart->flag |= BINTEST;
995 		else
996 			mstart->flag |= TEXTTEST;
997 		break;
998 	case FILE_DEFAULT:
999 		/* can't deduce anything; we shouldn't see this at the
1000 		   top level anyway */
1001 		break;
1002 	case FILE_INVALID:
1003 	default:
1004 		/* invalid search type, but no need to complain here */
1005 		break;
1006 	}
1007 }
1008 
1009 private int
addentry(struct magic_set * ms,struct magic_entry * me,struct magic_entry_set * mset)1010 addentry(struct magic_set *ms, struct magic_entry *me,
1011    struct magic_entry_set *mset)
1012 {
1013 	size_t i = me->mp->type == FILE_NAME ? 1 : 0;
1014 	if (mset[i].count == mset[i].max) {
1015 		struct magic_entry *mp;
1016 
1017 		mset[i].max += ALLOC_INCR;
1018 		if ((mp = CAST(struct magic_entry *,
1019 		    erealloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
1020 		    NULL) {
1021 			file_oomem(ms, sizeof(*mp) * mset[i].max);
1022 			return -1;
1023 		}
1024 		(void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
1025 		    ALLOC_INCR);
1026 		mset[i].me = mp;
1027 	}
1028 	mset[i].me[mset[i].count++] = *me;
1029 	memset(me, 0, sizeof(*me));
1030 	return 0;
1031 }
1032 
1033 /*
1034  * Load and parse one file.
1035  */
1036 private void
load_1(struct magic_set * ms,int action,const char * fn,int * errs,struct magic_entry_set * mset)1037 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
1038    struct magic_entry_set *mset)
1039 {
1040 	char buffer[BUFSIZ + 1];
1041 	char *line = NULL;
1042 	size_t len;
1043 	size_t lineno = 0;
1044 	struct magic_entry me;
1045 
1046 	php_stream *stream;
1047 
1048 
1049 	ms->file = fn;
1050 	stream = php_stream_open_wrapper((char *)fn, "rb", REPORT_ERRORS, NULL);
1051 
1052 	if (stream == NULL) {
1053 		if (errno != ENOENT)
1054 			file_error(ms, errno, "cannot read magic file `%s'",
1055 				   fn);
1056 		(*errs)++;
1057 		return;
1058 	}
1059 
1060 	memset(&me, 0, sizeof(me));
1061 	/* read and parse this file */
1062 	for (ms->line = 1; (line = php_stream_get_line(stream, buffer , BUFSIZ, &len)) != NULL; ms->line++) {
1063 		if (len == 0) /* null line, garbage, etc */
1064 			continue;
1065 		if (line[len - 1] == '\n') {
1066 			lineno++;
1067 			line[len - 1] = '\0'; /* delete newline */
1068 		}
1069 		switch (line[0]) {
1070 		case '\0':	/* empty, do not parse */
1071 		case '#':	/* comment, do not parse */
1072 			continue;
1073 		case '!':
1074 			if (line[1] == ':') {
1075 				size_t i;
1076 
1077 				for (i = 0; bang[i].name != NULL; i++) {
1078 					if ((size_t)(len - 2) > bang[i].len &&
1079 					    memcmp(bang[i].name, line + 2,
1080 					    bang[i].len) == 0)
1081 						break;
1082 				}
1083 				if (bang[i].name == NULL) {
1084 					file_error(ms, 0,
1085 					    "Unknown !: entry `%s'", line);
1086 					(*errs)++;
1087 					continue;
1088 				}
1089 				if (me.mp == NULL) {
1090 					file_error(ms, 0,
1091 					    "No current entry for :!%s type",
1092 						bang[i].name);
1093 					(*errs)++;
1094 					continue;
1095 				}
1096 				if ((*bang[i].fun)(ms, &me,
1097 				    line + bang[i].len + 2) != 0) {
1098 					(*errs)++;
1099 					continue;
1100 				}
1101 				continue;
1102 			}
1103 			/*FALLTHROUGH*/
1104 		default:
1105 		again:
1106 			switch (parse(ms, &me, line, lineno, action)) {
1107 			case 0:
1108 				continue;
1109 			case 1:
1110 				(void)addentry(ms, &me, mset);
1111 				goto again;
1112 			default:
1113 				(*errs)++;
1114 				break;
1115 			}
1116 		}
1117 	}
1118 	if (me.mp)
1119 		(void)addentry(ms, &me, mset);
1120     efree(line);
1121 	php_stream_close(stream);
1122 }
1123 
1124 /*
1125  * parse a file or directory of files
1126  * const char *fn: name of magic file or directory
1127  */
1128 private int
cmpstrp(const void * p1,const void * p2)1129 cmpstrp(const void *p1, const void *p2)
1130 {
1131         return strcmp(*(char *const *)p1, *(char *const *)p2);
1132 }
1133 
1134 
1135 private uint32_t
set_text_binary(struct magic_set * ms,struct magic_entry * me,uint32_t nme,uint32_t starttest)1136 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1137     uint32_t starttest)
1138 {
1139 	static const char text[] = "text";
1140 	static const char binary[] = "binary";
1141 	static const size_t len = sizeof(text);
1142 
1143 	uint32_t i = starttest;
1144 
1145 	do {
1146 		set_test_type(me[starttest].mp, me[i].mp);
1147 		if ((ms->flags & MAGIC_DEBUG) == 0)
1148 			continue;
1149 		(void)fprintf(stderr, "%s%s%s: %s\n",
1150 		    me[i].mp->mimetype,
1151 		    me[i].mp->mimetype[0] == '\0' ? "" : "; ",
1152 		    me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
1153 		    me[i].mp->flag & BINTEST ? binary : text);
1154 		if (me[i].mp->flag & BINTEST) {
1155 			char *p = strstr(me[i].mp->desc, text);
1156 			if (p && (p == me[i].mp->desc ||
1157 			    isspace((unsigned char)p[-1])) &&
1158 			    (p + len - me[i].mp->desc == MAXstring
1159 			    || (p[len] == '\0' ||
1160 			    isspace((unsigned char)p[len]))))
1161 				(void)fprintf(stderr, "*** Possible "
1162 				    "binary test for text type\n");
1163 		}
1164 	} while (++i < nme && me[i].mp->cont_level != 0);
1165 	return i;
1166 }
1167 
1168 private void
set_last_default(struct magic_set * ms,struct magic_entry * me,uint32_t nme)1169 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
1170 {
1171 	uint32_t i;
1172 	for (i = 0; i < nme; i++) {
1173 		if (me[i].mp->cont_level == 0 &&
1174 		    me[i].mp->type == FILE_DEFAULT) {
1175 			while (++i < nme)
1176 				if (me[i].mp->cont_level == 0)
1177 					break;
1178 			if (i != nme) {
1179 				/* XXX - Ugh! */
1180 				ms->line = me[i].mp->lineno;
1181 				file_magwarn(ms,
1182 				    "level 0 \"default\" did not sort last");
1183 			}
1184 			return;
1185 		}
1186 	}
1187 }
1188 
1189 private int
coalesce_entries(struct magic_set * ms,struct magic_entry * me,uint32_t nme,struct magic ** ma,uint32_t * nma)1190 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1191     struct magic **ma, uint32_t *nma)
1192 {
1193 	uint32_t i, mentrycount = 0;
1194 	size_t slen;
1195 
1196 	for (i = 0; i < nme; i++)
1197 		mentrycount += me[i].cont_count;
1198 
1199 	slen = sizeof(**ma) * mentrycount;
1200 	if ((*ma = CAST(struct magic *, emalloc(slen))) == NULL) {
1201 		file_oomem(ms, slen);
1202 		return -1;
1203 	}
1204 
1205 	mentrycount = 0;
1206 	for (i = 0; i < nme; i++) {
1207 		(void)memcpy(*ma + mentrycount, me[i].mp,
1208 		    me[i].cont_count * sizeof(**ma));
1209 		mentrycount += me[i].cont_count;
1210 	}
1211 	*nma = mentrycount;
1212 	return 0;
1213 }
1214 
1215 private void
magic_entry_free(struct magic_entry * me,uint32_t nme)1216 magic_entry_free(struct magic_entry *me, uint32_t nme)
1217 {
1218 	uint32_t i;
1219 	if (me == NULL)
1220 		return;
1221 	for (i = 0; i < nme; i++)
1222 		efree(me[i].mp);
1223 	efree(me);
1224 }
1225 
1226 private struct magic_map *
apprentice_load(struct magic_set * ms,const char * fn,int action)1227 apprentice_load(struct magic_set *ms, const char *fn, int action)
1228 {
1229 	int errs = 0;
1230 	uint32_t i, j;
1231 	size_t files = 0, maxfiles = 0;
1232 	char **filearr = NULL;
1233 	zend_stat_t st;
1234 	struct magic_map *map;
1235 	struct magic_entry_set mset[MAGIC_SETS];
1236 	php_stream *dir;
1237 	php_stream_dirent d;
1238 
1239 
1240 	memset(mset, 0, sizeof(mset));
1241 	ms->flags |= MAGIC_CHECK;	/* Enable checks for parsed files */
1242 
1243 
1244 	if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL)
1245 	{
1246 		file_oomem(ms, sizeof(*map));
1247 		return NULL;
1248 	}
1249 	map->type = MAP_TYPE_MALLOC;
1250 
1251 	/* print silly verbose header for USG compat. */
1252 	if (action == FILE_CHECK)
1253 		(void)fprintf(stderr, "%s\n", usg_hdr);
1254 
1255 	/* load directory or file */
1256 	/* FIXME: Read file names and sort them to prevent
1257 	   non-determinism. See Debian bug #488562. */
1258 	if (php_sys_stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
1259 		int mflen;
1260 		char mfn[MAXPATHLEN];
1261 
1262 		dir = php_stream_opendir((char *)fn, REPORT_ERRORS, NULL);
1263 		if (!dir) {
1264 			errs++;
1265 			goto out;
1266 		}
1267 		while (php_stream_readdir(dir, &d)) {
1268 			if ((mflen = snprintf(mfn, sizeof(mfn), "%s/%s", fn, d.d_name)) < 0) {
1269 				file_oomem(ms,
1270 				strlen(fn) + strlen(d.d_name) + 2);
1271 				errs++;
1272 				php_stream_closedir(dir);
1273 				goto out;
1274 			}
1275 			if (zend_stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
1276 				continue;
1277 			}
1278 			if (files >= maxfiles) {
1279 				size_t mlen;
1280 				maxfiles = (maxfiles + 1) * 2;
1281 				mlen = maxfiles * sizeof(*filearr);
1282 				if ((filearr = CAST(char **,
1283 				    erealloc(filearr, mlen))) == NULL) {
1284 					file_oomem(ms, mlen);
1285 					php_stream_closedir(dir);
1286 					errs++;
1287 					goto out;
1288 				}
1289 			}
1290 			filearr[files++] = estrndup(mfn, (mflen > sizeof(mfn) - 1)? sizeof(mfn) - 1: mflen);
1291 		}
1292 		php_stream_closedir(dir);
1293 		qsort(filearr, files, sizeof(*filearr), cmpstrp);
1294 		for (i = 0; i < files; i++) {
1295 			load_1(ms, action, filearr[i], &errs, mset);
1296 			efree(filearr[i]);
1297 		}
1298 		efree(filearr);
1299 	} else
1300 		load_1(ms, action, fn, &errs, mset);
1301 	if (errs)
1302 		goto out;
1303 
1304 	for (j = 0; j < MAGIC_SETS; j++) {
1305 		/* Set types of tests */
1306 		for (i = 0; i < mset[j].count; ) {
1307 			if (mset[j].me[i].mp->cont_level != 0) {
1308 				i++;
1309 				continue;
1310 			}
1311 			i = set_text_binary(ms, mset[j].me, mset[j].count, i);
1312 		}
1313 		if (mset[j].me)
1314 			qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
1315 			    apprentice_sort);
1316 
1317 		/*
1318 		 * Make sure that any level 0 "default" line is last
1319 		 * (if one exists).
1320 		 */
1321 		set_last_default(ms, mset[j].me, mset[j].count);
1322 
1323 		/* coalesce per file arrays into a single one */
1324 		if (coalesce_entries(ms, mset[j].me, mset[j].count,
1325 		    &map->magic[j], &map->nmagic[j]) == -1) {
1326 			errs++;
1327 			goto out;
1328 		}
1329 	}
1330 
1331 out:
1332 	for (j = 0; j < MAGIC_SETS; j++)
1333 		magic_entry_free(mset[j].me, mset[j].count);
1334 
1335 	if (errs) {
1336 		apprentice_unmap(map);
1337 		return NULL;
1338 	}
1339 	return map;
1340 }
1341 
1342 /*
1343  * extend the sign bit if the comparison is to be signed
1344  */
1345 protected uint64_t
file_signextend(struct magic_set * ms,struct magic * m,uint64_t v)1346 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
1347 {
1348 	if (!(m->flag & UNSIGNED)) {
1349 		switch(m->type) {
1350 		/*
1351 		 * Do not remove the casts below.  They are
1352 		 * vital.  When later compared with the data,
1353 		 * the sign extension must have happened.
1354 		 */
1355 		case FILE_BYTE:
1356 			v = (signed char) v;
1357 			break;
1358 		case FILE_SHORT:
1359 		case FILE_BESHORT:
1360 		case FILE_LESHORT:
1361 			v = (short) v;
1362 			break;
1363 		case FILE_DATE:
1364 		case FILE_BEDATE:
1365 		case FILE_LEDATE:
1366 		case FILE_MEDATE:
1367 		case FILE_LDATE:
1368 		case FILE_BELDATE:
1369 		case FILE_LELDATE:
1370 		case FILE_MELDATE:
1371 		case FILE_LONG:
1372 		case FILE_BELONG:
1373 		case FILE_LELONG:
1374 		case FILE_MELONG:
1375 		case FILE_FLOAT:
1376 		case FILE_BEFLOAT:
1377 		case FILE_LEFLOAT:
1378 			v = (int32_t) v;
1379 			break;
1380 		case FILE_QUAD:
1381 		case FILE_BEQUAD:
1382 		case FILE_LEQUAD:
1383 		case FILE_QDATE:
1384 		case FILE_QLDATE:
1385 		case FILE_QWDATE:
1386 		case FILE_BEQDATE:
1387 		case FILE_BEQLDATE:
1388 		case FILE_BEQWDATE:
1389 		case FILE_LEQDATE:
1390 		case FILE_LEQLDATE:
1391 		case FILE_LEQWDATE:
1392 		case FILE_DOUBLE:
1393 		case FILE_BEDOUBLE:
1394 		case FILE_LEDOUBLE:
1395 			v = (int64_t) v;
1396 			break;
1397 		case FILE_STRING:
1398 		case FILE_PSTRING:
1399 		case FILE_BESTRING16:
1400 		case FILE_LESTRING16:
1401 		case FILE_REGEX:
1402 		case FILE_SEARCH:
1403 		case FILE_DEFAULT:
1404 		case FILE_INDIRECT:
1405 		case FILE_NAME:
1406 		case FILE_USE:
1407 		case FILE_CLEAR:
1408 		case FILE_DER:
1409 			break;
1410 		default:
1411 			if (ms->flags & MAGIC_CHECK)
1412 			    file_magwarn(ms, "cannot happen: m->type=%d\n",
1413 				    m->type);
1414 			return ~0U;
1415 		}
1416 	}
1417 	return v;
1418 }
1419 
1420 private int
string_modifier_check(struct magic_set * ms,struct magic * m)1421 string_modifier_check(struct magic_set *ms, struct magic *m)
1422 {
1423 	if ((ms->flags & MAGIC_CHECK) == 0)
1424 		return 0;
1425 
1426 	if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
1427 	    (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
1428 		file_magwarn(ms,
1429 		    "'/BHhLl' modifiers are only allowed for pascal strings\n");
1430 		return -1;
1431 	}
1432 	switch (m->type) {
1433 	case FILE_BESTRING16:
1434 	case FILE_LESTRING16:
1435 		if (m->str_flags != 0) {
1436 			file_magwarn(ms,
1437 			    "no modifiers allowed for 16-bit strings\n");
1438 			return -1;
1439 		}
1440 		break;
1441 	case FILE_STRING:
1442 	case FILE_PSTRING:
1443 		if ((m->str_flags & REGEX_OFFSET_START) != 0) {
1444 			file_magwarn(ms,
1445 			    "'/%c' only allowed on regex and search\n",
1446 			    CHAR_REGEX_OFFSET_START);
1447 			return -1;
1448 		}
1449 		break;
1450 	case FILE_SEARCH:
1451 		if (m->str_range == 0) {
1452 			file_magwarn(ms,
1453 			    "missing range; defaulting to %d\n",
1454                             STRING_DEFAULT_RANGE);
1455 			m->str_range = STRING_DEFAULT_RANGE;
1456 			return -1;
1457 		}
1458 		break;
1459 	case FILE_REGEX:
1460 		if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
1461 			file_magwarn(ms, "'/%c' not allowed on regex\n",
1462 			    CHAR_COMPACT_WHITESPACE);
1463 			return -1;
1464 		}
1465 		if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
1466 			file_magwarn(ms, "'/%c' not allowed on regex\n",
1467 			    CHAR_COMPACT_OPTIONAL_WHITESPACE);
1468 			return -1;
1469 		}
1470 		break;
1471 	default:
1472 		file_magwarn(ms, "coding error: m->type=%d\n",
1473 		    m->type);
1474 		return -1;
1475 	}
1476 	return 0;
1477 }
1478 
1479 private int
get_op(char c)1480 get_op(char c)
1481 {
1482 	switch (c) {
1483 	case '&':
1484 		return FILE_OPAND;
1485 	case '|':
1486 		return FILE_OPOR;
1487 	case '^':
1488 		return FILE_OPXOR;
1489 	case '+':
1490 		return FILE_OPADD;
1491 	case '-':
1492 		return FILE_OPMINUS;
1493 	case '*':
1494 		return FILE_OPMULTIPLY;
1495 	case '/':
1496 		return FILE_OPDIVIDE;
1497 	case '%':
1498 		return FILE_OPMODULO;
1499 	default:
1500 		return -1;
1501 	}
1502 }
1503 
1504 #ifdef ENABLE_CONDITIONALS
1505 private int
get_cond(const char * l,const char ** t)1506 get_cond(const char *l, const char **t)
1507 {
1508 	static const struct cond_tbl_s {
1509 		char name[8];
1510 		size_t len;
1511 		int cond;
1512 	} cond_tbl[] = {
1513 		{ "if",		2,	COND_IF },
1514 		{ "elif",	4,	COND_ELIF },
1515 		{ "else",	4,	COND_ELSE },
1516 		{ "",		0,	COND_NONE },
1517 	};
1518 	const struct cond_tbl_s *p;
1519 
1520 	for (p = cond_tbl; p->len; p++) {
1521 		if (strncmp(l, p->name, p->len) == 0 &&
1522 		    isspace((unsigned char)l[p->len])) {
1523 			if (t)
1524 				*t = l + p->len;
1525 			break;
1526 		}
1527 	}
1528 	return p->cond;
1529 }
1530 
1531 private int
check_cond(struct magic_set * ms,int cond,uint32_t cont_level)1532 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1533 {
1534 	int last_cond;
1535 	last_cond = ms->c.li[cont_level].last_cond;
1536 
1537 	switch (cond) {
1538 	case COND_IF:
1539 		if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1540 			if (ms->flags & MAGIC_CHECK)
1541 				file_magwarn(ms, "syntax error: `if'");
1542 			return -1;
1543 		}
1544 		last_cond = COND_IF;
1545 		break;
1546 
1547 	case COND_ELIF:
1548 		if (last_cond != COND_IF && last_cond != COND_ELIF) {
1549 			if (ms->flags & MAGIC_CHECK)
1550 				file_magwarn(ms, "syntax error: `elif'");
1551 			return -1;
1552 		}
1553 		last_cond = COND_ELIF;
1554 		break;
1555 
1556 	case COND_ELSE:
1557 		if (last_cond != COND_IF && last_cond != COND_ELIF) {
1558 			if (ms->flags & MAGIC_CHECK)
1559 				file_magwarn(ms, "syntax error: `else'");
1560 			return -1;
1561 		}
1562 		last_cond = COND_NONE;
1563 		break;
1564 
1565 	case COND_NONE:
1566 		last_cond = COND_NONE;
1567 		break;
1568 	}
1569 
1570 	ms->c.li[cont_level].last_cond = last_cond;
1571 	return 0;
1572 }
1573 #endif /* ENABLE_CONDITIONALS */
1574 
1575 private int
parse_indirect_modifier(struct magic_set * ms,struct magic * m,const char ** lp)1576 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1577 {
1578 	const char *l = *lp;
1579 
1580 	while (!isspace((unsigned char)*++l))
1581 		switch (*l) {
1582 		case CHAR_INDIRECT_RELATIVE:
1583 			m->str_flags |= INDIRECT_RELATIVE;
1584 			break;
1585 		default:
1586 			if (ms->flags & MAGIC_CHECK)
1587 				file_magwarn(ms, "indirect modifier `%c' "
1588 					"invalid", *l);
1589 			*lp = l;
1590 			return -1;
1591 		}
1592 	*lp = l;
1593 	return 0;
1594 }
1595 
1596 private void
parse_op_modifier(struct magic_set * ms,struct magic * m,const char ** lp,int op)1597 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
1598     int op)
1599 {
1600 	const char *l = *lp;
1601 	char *t;
1602 	uint64_t val;
1603 
1604 	++l;
1605 	m->mask_op |= op;
1606 	val = (uint64_t)strtoull(l, &t, 0);
1607 	l = t;
1608 	m->num_mask = file_signextend(ms, m, val);
1609 	eatsize(&l);
1610 	*lp = l;
1611 }
1612 
1613 private int
parse_string_modifier(struct magic_set * ms,struct magic * m,const char ** lp)1614 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1615 {
1616 	const char *l = *lp;
1617 	char *t;
1618 	int have_range = 0;
1619 
1620 	while (!isspace((unsigned char)*++l)) {
1621 		switch (*l) {
1622 		case '0':  case '1':  case '2':
1623 		case '3':  case '4':  case '5':
1624 		case '6':  case '7':  case '8':
1625 		case '9':
1626 			if (have_range && (ms->flags & MAGIC_CHECK))
1627 				file_magwarn(ms, "multiple ranges");
1628 			have_range = 1;
1629 			m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
1630 			if (m->str_range == 0)
1631 				file_magwarn(ms, "zero range");
1632 			l = t - 1;
1633 			break;
1634 		case CHAR_COMPACT_WHITESPACE:
1635 			m->str_flags |= STRING_COMPACT_WHITESPACE;
1636 			break;
1637 		case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1638 			m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
1639 			break;
1640 		case CHAR_IGNORE_LOWERCASE:
1641 			m->str_flags |= STRING_IGNORE_LOWERCASE;
1642 			break;
1643 		case CHAR_IGNORE_UPPERCASE:
1644 			m->str_flags |= STRING_IGNORE_UPPERCASE;
1645 			break;
1646 		case CHAR_REGEX_OFFSET_START:
1647 			m->str_flags |= REGEX_OFFSET_START;
1648 			break;
1649 		case CHAR_BINTEST:
1650 			m->str_flags |= STRING_BINTEST;
1651 			break;
1652 		case CHAR_TEXTTEST:
1653 			m->str_flags |= STRING_TEXTTEST;
1654 			break;
1655 		case CHAR_TRIM:
1656 			m->str_flags |= STRING_TRIM;
1657 			break;
1658 		case CHAR_PSTRING_1_LE:
1659 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
1660 			if (m->type != FILE_PSTRING)
1661 				goto bad;
1662 			SET_LENGTH(PSTRING_1_LE);
1663 			break;
1664 		case CHAR_PSTRING_2_BE:
1665 			if (m->type != FILE_PSTRING)
1666 				goto bad;
1667 			SET_LENGTH(PSTRING_2_BE);
1668 			break;
1669 		case CHAR_PSTRING_2_LE:
1670 			if (m->type != FILE_PSTRING)
1671 				goto bad;
1672 			SET_LENGTH(PSTRING_2_LE);
1673 			break;
1674 		case CHAR_PSTRING_4_BE:
1675 			if (m->type != FILE_PSTRING)
1676 				goto bad;
1677 			SET_LENGTH(PSTRING_4_BE);
1678 			break;
1679 		case CHAR_PSTRING_4_LE:
1680 			switch (m->type) {
1681 			case FILE_PSTRING:
1682 			case FILE_REGEX:
1683 				break;
1684 			default:
1685 				goto bad;
1686 			}
1687 			SET_LENGTH(PSTRING_4_LE);
1688 			break;
1689 		case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
1690 			if (m->type != FILE_PSTRING)
1691 				goto bad;
1692 			m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
1693 			break;
1694 		default:
1695 		bad:
1696 			if (ms->flags & MAGIC_CHECK)
1697 				file_magwarn(ms, "string modifier `%c' "
1698 					"invalid", *l);
1699 			goto out;
1700 		}
1701 		/* allow multiple '/' for readability */
1702 		if (l[1] == '/' && !isspace((unsigned char)l[2]))
1703 			l++;
1704 	}
1705 	if (string_modifier_check(ms, m) == -1)
1706 		goto out;
1707 	*lp = l;
1708 	return 0;
1709 out:
1710 	*lp = l;
1711 	return -1;
1712 }
1713 
1714 /*
1715  * parse one line from magic file, put into magic[index++] if valid
1716  */
1717 private int
parse(struct magic_set * ms,struct magic_entry * me,const char * line,size_t lineno,int action)1718 parse(struct magic_set *ms, struct magic_entry *me, const char *line,
1719     size_t lineno, int action)
1720 {
1721 #ifdef ENABLE_CONDITIONALS
1722 	static uint32_t last_cont_level = 0;
1723 #endif
1724 	size_t i;
1725 	struct magic *m;
1726 	const char *l = line;
1727 	char *t;
1728 	int op;
1729 	uint32_t cont_level;
1730 	int32_t diff;
1731 
1732 	cont_level = 0;
1733 
1734 	/*
1735 	 * Parse the offset.
1736 	 */
1737 	while (*l == '>') {
1738 		++l;		/* step over */
1739 		cont_level++;
1740 	}
1741 #ifdef ENABLE_CONDITIONALS
1742 	if (cont_level == 0 || cont_level > last_cont_level)
1743 		if (file_check_mem(ms, cont_level) == -1)
1744 			return -1;
1745 	last_cont_level = cont_level;
1746 #endif
1747 	if (cont_level != 0) {
1748 		if (me->mp == NULL) {
1749 			file_magerror(ms, "No current entry for continuation");
1750 			return -1;
1751 		}
1752 		if (me->cont_count == 0) {
1753 			file_magerror(ms, "Continuations present with 0 count");
1754 			return -1;
1755 		}
1756 		m = &me->mp[me->cont_count - 1];
1757 		diff = (int32_t)cont_level - (int32_t)m->cont_level;
1758 		if (diff > 1)
1759 			file_magwarn(ms, "New continuation level %u is more "
1760 			    "than one larger than current level %u", cont_level,
1761 			    m->cont_level);
1762 		if (me->cont_count == me->max_count) {
1763 			struct magic *nm;
1764 			size_t cnt = me->max_count + ALLOC_CHUNK;
1765 			if ((nm = CAST(struct magic *, erealloc(me->mp,
1766 			    sizeof(*nm) * cnt))) == NULL) {
1767 				file_oomem(ms, sizeof(*nm) * cnt);
1768 				return -1;
1769 			}
1770 			me->mp = m = nm;
1771 			me->max_count = CAST(uint32_t, cnt);
1772 		}
1773 		m = &me->mp[me->cont_count++];
1774 		(void)memset(m, 0, sizeof(*m));
1775 		m->cont_level = cont_level;
1776 	} else {
1777 		static const size_t len = sizeof(*m) * ALLOC_CHUNK;
1778 		if (me->mp != NULL)
1779 			return 1;
1780 		if ((m = CAST(struct magic *, emalloc(len))) == NULL) {
1781 			file_oomem(ms, len);
1782 			return -1;
1783 		}
1784 		me->mp = m;
1785 		me->max_count = ALLOC_CHUNK;
1786 		(void)memset(m, 0, sizeof(*m));
1787 		m->factor_op = FILE_FACTOR_OP_NONE;
1788 		m->cont_level = 0;
1789 		me->cont_count = 1;
1790 	}
1791 	m->lineno = CAST(uint32_t, lineno);
1792 
1793 	if (*l == '&') {  /* m->cont_level == 0 checked below. */
1794                 ++l;            /* step over */
1795                 m->flag |= OFFADD;
1796         }
1797 	if (*l == '(') {
1798 		++l;		/* step over */
1799 		m->flag |= INDIR;
1800 		if (m->flag & OFFADD)
1801 			m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1802 
1803 		if (*l == '&') {  /* m->cont_level == 0 checked below */
1804 			++l;            /* step over */
1805 			m->flag |= OFFADD;
1806 		}
1807 	}
1808 	/* Indirect offsets are not valid at level 0. */
1809 	if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
1810 		if (ms->flags & MAGIC_CHECK)
1811 			file_magwarn(ms, "relative offset at level 0");
1812 		return -1;
1813 	}
1814 
1815 	/* get offset, then skip over it */
1816 	m->offset = (uint32_t)strtoul(l, &t, 0);
1817         if (l == t) {
1818 		if (ms->flags & MAGIC_CHECK)
1819 			file_magwarn(ms, "offset `%s' invalid", l);
1820 		return -1;
1821 	}
1822         l = t;
1823 
1824 	if (m->flag & INDIR) {
1825 		m->in_type = FILE_LONG;
1826 		m->in_offset = 0;
1827 		m->in_op = 0;
1828 		/*
1829 		 * read [.,lbs][+-]nnnnn)
1830 		 */
1831 		if (*l == '.' || *l == ',') {
1832 			if (*l == ',')
1833 				m->in_op |= FILE_OPSIGNED;
1834 			l++;
1835 			switch (*l) {
1836 			case 'l':
1837 				m->in_type = FILE_LELONG;
1838 				break;
1839 			case 'L':
1840 				m->in_type = FILE_BELONG;
1841 				break;
1842 			case 'm':
1843 				m->in_type = FILE_MELONG;
1844 				break;
1845 			case 'h':
1846 			case 's':
1847 				m->in_type = FILE_LESHORT;
1848 				break;
1849 			case 'H':
1850 			case 'S':
1851 				m->in_type = FILE_BESHORT;
1852 				break;
1853 			case 'c':
1854 			case 'b':
1855 			case 'C':
1856 			case 'B':
1857 				m->in_type = FILE_BYTE;
1858 				break;
1859 			case 'e':
1860 			case 'f':
1861 			case 'g':
1862 				m->in_type = FILE_LEDOUBLE;
1863 				break;
1864 			case 'E':
1865 			case 'F':
1866 			case 'G':
1867 				m->in_type = FILE_BEDOUBLE;
1868 				break;
1869 			case 'i':
1870 				m->in_type = FILE_LEID3;
1871 				break;
1872 			case 'I':
1873 				m->in_type = FILE_BEID3;
1874 				break;
1875 			default:
1876 				if (ms->flags & MAGIC_CHECK)
1877 					file_magwarn(ms,
1878 					    "indirect offset type `%c' invalid",
1879 					    *l);
1880 				return -1;
1881 			}
1882 			l++;
1883 		}
1884 
1885 		if (*l == '~') {
1886 			m->in_op |= FILE_OPINVERSE;
1887 			l++;
1888 		}
1889 		if ((op = get_op(*l)) != -1) {
1890 			m->in_op |= op;
1891 			l++;
1892 		}
1893 		if (*l == '(') {
1894 			m->in_op |= FILE_OPINDIRECT;
1895 			l++;
1896 		}
1897 		if (isdigit((unsigned char)*l) || *l == '-') {
1898 			m->in_offset = (int32_t)strtol(l, &t, 0);
1899 			if (l == t) {
1900 				if (ms->flags & MAGIC_CHECK)
1901 					file_magwarn(ms,
1902 					    "in_offset `%s' invalid", l);
1903 				return -1;
1904 			}
1905 			l = t;
1906 		}
1907 		if (*l++ != ')' ||
1908 		    ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
1909 			if (ms->flags & MAGIC_CHECK)
1910 				file_magwarn(ms,
1911 				    "missing ')' in indirect offset");
1912 			return -1;
1913 		}
1914 	}
1915 	EATAB;
1916 
1917 #ifdef ENABLE_CONDITIONALS
1918 	m->cond = get_cond(l, &l);
1919 	if (check_cond(ms, m->cond, cont_level) == -1)
1920 		return -1;
1921 
1922 	EATAB;
1923 #endif
1924 
1925 	/*
1926 	 * Parse the type.
1927 	 */
1928 	if (*l == 'u') {
1929 		/*
1930 		 * Try it as a keyword type prefixed by "u"; match what
1931 		 * follows the "u".  If that fails, try it as an SUS
1932 		 * integer type.
1933 		 */
1934 		m->type = get_type(type_tbl, l + 1, &l);
1935 		if (m->type == FILE_INVALID) {
1936 			/*
1937 			 * Not a keyword type; parse it as an SUS type,
1938 			 * 'u' possibly followed by a number or C/S/L.
1939 			 */
1940 			m->type = get_standard_integer_type(l, &l);
1941 		}
1942 		/* It's unsigned. */
1943 		if (m->type != FILE_INVALID)
1944 			m->flag |= UNSIGNED;
1945 	} else {
1946 		/*
1947 		 * Try it as a keyword type.  If that fails, try it as
1948 		 * an SUS integer type if it begins with "d" or as an
1949 		 * SUS string type if it begins with "s".  In any case,
1950 		 * it's not unsigned.
1951 		 */
1952 		m->type = get_type(type_tbl, l, &l);
1953 		if (m->type == FILE_INVALID) {
1954 			/*
1955 			 * Not a keyword type; parse it as an SUS type,
1956 			 * either 'd' possibly followed by a number or
1957 			 * C/S/L, or just 's'.
1958 			 */
1959 			if (*l == 'd')
1960 				m->type = get_standard_integer_type(l, &l);
1961 			else if (*l == 's' && !isalpha((unsigned char)l[1])) {
1962 				m->type = FILE_STRING;
1963 				++l;
1964 			}
1965 		}
1966 	}
1967 
1968 	if (m->type == FILE_INVALID) {
1969 		/* Not found - try it as a special keyword. */
1970 		m->type = get_type(special_tbl, l, &l);
1971 	}
1972 
1973 	if (m->type == FILE_INVALID) {
1974 		if (ms->flags & MAGIC_CHECK)
1975 			file_magwarn(ms, "type `%s' invalid", l);
1976 		return -1;
1977 	}
1978 
1979 	/* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1980 	/* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1981 
1982 	m->mask_op = 0;
1983 	if (*l == '~') {
1984 		if (!IS_LIBMAGIC_STRING(m->type))
1985 			m->mask_op |= FILE_OPINVERSE;
1986 		else if (ms->flags & MAGIC_CHECK)
1987 			file_magwarn(ms, "'~' invalid for string types");
1988 		++l;
1989 	}
1990 	m->str_range = 0;
1991 	m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
1992 	if ((op = get_op(*l)) != -1) {
1993 		if (IS_LIBMAGIC_STRING(m->type)) {
1994 			int r;
1995 
1996 			if (op != FILE_OPDIVIDE) {
1997 				if (ms->flags & MAGIC_CHECK)
1998 					file_magwarn(ms,
1999 					    "invalid string/indirect op: "
2000 					    "`%c'", *t);
2001 				return -1;
2002 			}
2003 
2004 			if (m->type == FILE_INDIRECT)
2005 				r = parse_indirect_modifier(ms, m, &l);
2006 			else
2007 				r = parse_string_modifier(ms, m, &l);
2008 			if (r == -1)
2009 				return -1;
2010 		} else
2011 			parse_op_modifier(ms, m, &l, op);
2012 	}
2013 
2014 	/*
2015 	 * We used to set mask to all 1's here, instead let's just not do
2016 	 * anything if mask = 0 (unless you have a better idea)
2017 	 */
2018 	EATAB;
2019 
2020 	switch (*l) {
2021 	case '>':
2022 	case '<':
2023   		m->reln = *l;
2024   		++l;
2025 		if (*l == '=') {
2026 			if (ms->flags & MAGIC_CHECK) {
2027 				file_magwarn(ms, "%c= not supported",
2028 				    m->reln);
2029 				return -1;
2030 			}
2031 		   ++l;
2032 		}
2033 		break;
2034 	/* Old-style anding: "0 byte &0x80 dynamically linked" */
2035 	case '&':
2036 	case '^':
2037 	case '=':
2038   		m->reln = *l;
2039   		++l;
2040 		if (*l == '=') {
2041 		   /* HP compat: ignore &= etc. */
2042 		   ++l;
2043 		}
2044 		break;
2045 	case '!':
2046 		m->reln = *l;
2047 		++l;
2048 		break;
2049 	default:
2050   		m->reln = '=';	/* the default relation */
2051 		if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
2052 		    isspace((unsigned char)l[1])) || !l[1])) {
2053 			m->reln = *l;
2054 			++l;
2055 		}
2056 		break;
2057 	}
2058 	/*
2059 	 * Grab the value part, except for an 'x' reln.
2060 	 */
2061 	if (m->reln != 'x' && getvalue(ms, m, &l, action))
2062 		return -1;
2063 
2064 	/*
2065 	 * TODO finish this macro and start using it!
2066 	 * #define offsetcheck {if (offset > ms->bytes_max -1)
2067 	 *	magwarn("offset too big"); }
2068 	 */
2069 
2070 	/*
2071 	 * Now get last part - the description
2072 	 */
2073 	EATAB;
2074 	if (l[0] == '\b') {
2075 		++l;
2076 		m->flag |= NOSPACE;
2077 	} else if ((l[0] == '\\') && (l[1] == 'b')) {
2078 		++l;
2079 		++l;
2080 		m->flag |= NOSPACE;
2081 	}
2082 	for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
2083 		continue;
2084 	if (i == sizeof(m->desc)) {
2085 		m->desc[sizeof(m->desc) - 1] = '\0';
2086 		if (ms->flags & MAGIC_CHECK)
2087 			file_magwarn(ms, "description `%s' truncated", m->desc);
2088 	}
2089 
2090         /*
2091 	 * We only do this check while compiling, or if any of the magic
2092 	 * files were not compiled.
2093          */
2094         if (ms->flags & MAGIC_CHECK) {
2095 		if (check_format(ms, m) == -1)
2096 			return -1;
2097 	}
2098 	m->mimetype[0] = '\0';		/* initialise MIME type to none */
2099 	return 0;
2100 }
2101 
2102 /*
2103  * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
2104  * if valid
2105  */
2106 private int
parse_strength(struct magic_set * ms,struct magic_entry * me,const char * line)2107 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
2108 {
2109 	const char *l = line;
2110 	char *el;
2111 	unsigned long factor;
2112 	struct magic *m = &me->mp[0];
2113 
2114 	if (m->factor_op != FILE_FACTOR_OP_NONE) {
2115 		file_magwarn(ms,
2116 		    "Current entry already has a strength type: %c %d",
2117 		    m->factor_op, m->factor);
2118 		return -1;
2119 	}
2120 	if (m->type == FILE_NAME) {
2121 		file_magwarn(ms, "%s: Strength setting is not supported in "
2122 		    "\"name\" magic entries", m->value.s);
2123 		return -1;
2124 	}
2125 	EATAB;
2126 	switch (*l) {
2127 	case FILE_FACTOR_OP_NONE:
2128 	case FILE_FACTOR_OP_PLUS:
2129 	case FILE_FACTOR_OP_MINUS:
2130 	case FILE_FACTOR_OP_TIMES:
2131 	case FILE_FACTOR_OP_DIV:
2132 		m->factor_op = *l++;
2133 		break;
2134 	default:
2135 		file_magwarn(ms, "Unknown factor op `%c'", *l);
2136 		return -1;
2137 	}
2138 	EATAB;
2139 	factor = strtoul(l, &el, 0);
2140 	if (factor > 255) {
2141 		file_magwarn(ms, "Too large factor `%lu'", factor);
2142 		goto out;
2143 	}
2144 	if (*el && !isspace((unsigned char)*el)) {
2145 		file_magwarn(ms, "Bad factor `%s'", l);
2146 		goto out;
2147 	}
2148 	m->factor = (uint8_t)factor;
2149 	if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
2150 		file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
2151 		    m->factor_op, m->factor);
2152 		goto out;
2153 	}
2154 	return 0;
2155 out:
2156 	m->factor_op = FILE_FACTOR_OP_NONE;
2157 	m->factor = 0;
2158 	return -1;
2159 }
2160 
2161 private int
goodchar(unsigned char x,const char * extra)2162 goodchar(unsigned char x, const char *extra)
2163 {
2164 	return (isascii(x) && isalnum(x)) || strchr(extra, x);
2165 }
2166 
2167 private int
parse_extra(struct magic_set * ms,struct magic_entry * me,const char * line,zend_off_t off,size_t len,const char * name,const char * extra,int nt)2168 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
2169     zend_off_t off, size_t len, const char *name, const char *extra, int nt)
2170 {
2171 	size_t i;
2172 	const char *l = line;
2173 	struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
2174 	char *buf = CAST(char *, CAST(void *, m)) + off;
2175 
2176 	if (buf[0] != '\0') {
2177 		len = nt ? strlen(buf) : len;
2178 		file_magwarn(ms, "Current entry already has a %s type "
2179 		    "`%.*s', new type `%s'", name, (int)len, buf, l);
2180 		return -1;
2181 	}
2182 
2183 	if (*m->desc == '\0') {
2184 		file_magwarn(ms, "Current entry does not yet have a "
2185 		    "description for adding a %s type", name);
2186 		return -1;
2187 	}
2188 
2189 	EATAB;
2190 	for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
2191 		continue;
2192 
2193 	if (i == len && *l) {
2194 		if (nt)
2195 			buf[len - 1] = '\0';
2196 		if (ms->flags & MAGIC_CHECK)
2197 			file_magwarn(ms, "%s type `%s' truncated %"
2198 			    SIZE_T_FORMAT "u", name, line, i);
2199 	} else {
2200 		if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
2201 			file_magwarn(ms, "%s type `%s' has bad char '%c'",
2202 			    name, line, *l);
2203 		if (nt)
2204 			buf[i] = '\0';
2205 	}
2206 
2207 	if (i > 0)
2208 		return 0;
2209 
2210 	file_magerror(ms, "Bad magic entry '%s'", line);
2211 	return -1;
2212 }
2213 
2214 /*
2215  * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
2216  * magic[index - 1]
2217  */
2218 private int
parse_apple(struct magic_set * ms,struct magic_entry * me,const char * line)2219 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
2220 {
2221 	struct magic *m = &me->mp[0];
2222 
2223 	return parse_extra(ms, me, line,
2224 	    CAST(off_t, offsetof(struct magic, apple)),
2225 	    sizeof(m->apple), "APPLE", "!+-./?", 0);
2226 }
2227 
2228 /*
2229  * Parse a comma-separated list of extensions
2230  */
2231 private int
parse_ext(struct magic_set * ms,struct magic_entry * me,const char * line)2232 parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line)
2233 {
2234 	struct magic *m = &me->mp[0];
2235 
2236 	return parse_extra(ms, me, line,
2237 	    CAST(off_t, offsetof(struct magic, ext)),
2238 	    sizeof(m->ext), "EXTENSION", ",!+-/@", 0);
2239 }
2240 
2241 /*
2242  * parse a MIME annotation line from magic file, put into magic[index - 1]
2243  * if valid
2244  */
2245 private int
parse_mime(struct magic_set * ms,struct magic_entry * me,const char * line)2246 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
2247 {
2248 	struct magic *m = &me->mp[0];
2249 
2250 	return parse_extra(ms, me, line,
2251 	    CAST(zend_off_t, offsetof(struct magic, mimetype)),
2252 	    sizeof(m->mimetype), "MIME", "+-/.", 1);
2253 }
2254 
2255 private int
check_format_type(const char * ptr,int type,const char ** estr)2256 check_format_type(const char *ptr, int type, const char **estr)
2257 {
2258 	int quad = 0, h;
2259 	size_t len, cnt;
2260 	if (*ptr == '\0') {
2261 		/* Missing format string; bad */
2262 		*estr = "missing format spec";
2263 		return -1;
2264 	}
2265 
2266 	switch (file_formats[type]) {
2267 	case FILE_FMT_QUAD:
2268 		quad = 1;
2269 		/*FALLTHROUGH*/
2270 	case FILE_FMT_NUM:
2271 		if (quad == 0) {
2272 			switch (type) {
2273 			case FILE_BYTE:
2274 				h = 2;
2275 				break;
2276 			case FILE_SHORT:
2277 			case FILE_BESHORT:
2278 			case FILE_LESHORT:
2279 				h = 1;
2280 				break;
2281 			case FILE_LONG:
2282 			case FILE_BELONG:
2283 			case FILE_LELONG:
2284 			case FILE_MELONG:
2285 			case FILE_LEID3:
2286 			case FILE_BEID3:
2287 			case FILE_INDIRECT:
2288 				h = 0;
2289 				break;
2290 			default:
2291 				abort();
2292 			}
2293 		} else
2294 			h = 0;
2295 		if (*ptr == '-')
2296 			ptr++;
2297 		if (*ptr == '.')
2298 			ptr++;
2299 		if (*ptr == '#')
2300 			ptr++;
2301 #define CHECKLEN() do { \
2302 	for (len = cnt = 0; isdigit((unsigned char)*ptr); ptr++, cnt++) \
2303 		len = len * 10 + (*ptr - '0'); \
2304 	if (cnt > 5 || len > 1024) \
2305 		goto toolong; \
2306 } while (/*CONSTCOND*/0)
2307 
2308 		CHECKLEN();
2309 		if (*ptr == '.')
2310 			ptr++;
2311 		CHECKLEN();
2312 		if (quad) {
2313 			if (*ptr++ != 'l')
2314 				goto invalid;
2315 			if (*ptr++ != 'l')
2316 				goto invalid;
2317 		}
2318 
2319 		switch (*ptr++) {
2320 #ifdef STRICT_FORMAT 	/* "long" formats are int formats for us */
2321 		/* so don't accept the 'l' modifier */
2322 		case 'l':
2323 			switch (*ptr++) {
2324 			case 'i':
2325 			case 'd':
2326 			case 'u':
2327 			case 'o':
2328 			case 'x':
2329 			case 'X':
2330 				if (h == 0)
2331 					return 0;
2332 				/*FALLTHROUGH*/
2333 			default:
2334 				goto invalid;
2335 			}
2336 
2337 		/*
2338 		 * Don't accept h and hh modifiers. They make writing
2339 		 * magic entries more complicated, for very little benefit
2340 		 */
2341 		case 'h':
2342 			if (h-- <= 0)
2343 				goto invalid;
2344 			switch (*ptr++) {
2345 			case 'h':
2346 				if (h-- <= 0)
2347 					goto invalid;
2348 				switch (*ptr++) {
2349 				case 'i':
2350 				case 'd':
2351 				case 'u':
2352 				case 'o':
2353 				case 'x':
2354 				case 'X':
2355 					return 0;
2356 				default:
2357 					goto invalid;
2358 				}
2359 			case 'i':
2360 			case 'd':
2361 			case 'u':
2362 			case 'o':
2363 			case 'x':
2364 			case 'X':
2365 				if (h == 0)
2366 					return 0;
2367 				/*FALLTHROUGH*/
2368 			default:
2369 				goto invalid;
2370 			}
2371 #endif
2372 		case 'c':
2373 			if (h == 2)
2374 				return 0;
2375 			goto invalid;
2376 		case 'i':
2377 		case 'd':
2378 		case 'u':
2379 		case 'o':
2380 		case 'x':
2381 		case 'X':
2382 #ifdef STRICT_FORMAT
2383 			if (h == 0)
2384 				return 0;
2385 			/*FALLTHROUGH*/
2386 #else
2387 			return 0;
2388 #endif
2389 		default:
2390 			goto invalid;
2391 		}
2392 
2393 	case FILE_FMT_FLOAT:
2394 	case FILE_FMT_DOUBLE:
2395 		if (*ptr == '-')
2396 			ptr++;
2397 		if (*ptr == '.')
2398 			ptr++;
2399 		CHECKLEN();
2400 		if (*ptr == '.')
2401 			ptr++;
2402 		CHECKLEN();
2403 		switch (*ptr++) {
2404 		case 'e':
2405 		case 'E':
2406 		case 'f':
2407 		case 'F':
2408 		case 'g':
2409 		case 'G':
2410 			return 0;
2411 
2412 		default:
2413 			goto invalid;
2414 		}
2415 
2416 
2417 	case FILE_FMT_STR:
2418 		if (*ptr == '-')
2419 			ptr++;
2420 		while (isdigit((unsigned char )*ptr))
2421 			ptr++;
2422 		if (*ptr == '.') {
2423 			ptr++;
2424 			while (isdigit((unsigned char )*ptr))
2425 				ptr++;
2426 		}
2427 
2428 		switch (*ptr++) {
2429 		case 's':
2430 			return 0;
2431 		default:
2432 			goto invalid;
2433 		}
2434 
2435 	default:
2436 		/* internal error */
2437 		abort();
2438 	}
2439 invalid:
2440 	*estr = "not valid";
2441 toolong:
2442 	*estr = "too long";
2443 	return -1;
2444 }
2445 
2446 /*
2447  * Check that the optional printf format in description matches
2448  * the type of the magic.
2449  */
2450 private int
check_format(struct magic_set * ms,struct magic * m)2451 check_format(struct magic_set *ms, struct magic *m)
2452 {
2453 	char *ptr;
2454 	const char *estr;
2455 
2456 	for (ptr = m->desc; *ptr; ptr++)
2457 		if (*ptr == '%')
2458 			break;
2459 	if (*ptr == '\0') {
2460 		/* No format string; ok */
2461 		return 1;
2462 	}
2463 
2464 	assert(file_nformats == file_nnames);
2465 
2466 	if (m->type >= file_nformats) {
2467 		file_magwarn(ms, "Internal error inconsistency between "
2468 		    "m->type and format strings");
2469 		return -1;
2470 	}
2471 	if (file_formats[m->type] == FILE_FMT_NONE) {
2472 		file_magwarn(ms, "No format string for `%s' with description "
2473 		    "`%s'", m->desc, file_names[m->type]);
2474 		return -1;
2475 	}
2476 
2477 	ptr++;
2478 	if (check_format_type(ptr, m->type, &estr) == -1) {
2479 		/*
2480 		 * TODO: this error message is unhelpful if the format
2481 		 * string is not one character long
2482 		 */
2483 		file_magwarn(ms, "Printf format is %s for type "
2484 		    "`%s' in description `%s'", estr,
2485 		    file_names[m->type], m->desc);
2486 		return -1;
2487 	}
2488 
2489 	for (; *ptr; ptr++) {
2490 		if (*ptr == '%') {
2491 			file_magwarn(ms,
2492 			    "Too many format strings (should have at most one) "
2493 			    "for `%s' with description `%s'",
2494 			    file_names[m->type], m->desc);
2495 			return -1;
2496 		}
2497 	}
2498 	return 0;
2499 }
2500 
2501 /*
2502  * Read a numeric value from a pointer, into the value union of a magic
2503  * pointer, according to the magic type.  Update the string pointer to point
2504  * just after the number read.  Return 0 for success, non-zero for failure.
2505  */
2506 private int
getvalue(struct magic_set * ms,struct magic * m,const char ** p,int action)2507 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
2508 {
2509 	switch (m->type) {
2510 	case FILE_BESTRING16:
2511 	case FILE_LESTRING16:
2512 	case FILE_STRING:
2513 	case FILE_PSTRING:
2514 	case FILE_REGEX:
2515 	case FILE_SEARCH:
2516 	case FILE_NAME:
2517 	case FILE_USE:
2518 	case FILE_DER:
2519 		*p = getstr(ms, m, *p, action == FILE_COMPILE);
2520 		if (*p == NULL) {
2521 			if (ms->flags & MAGIC_CHECK)
2522 				file_magwarn(ms, "cannot get string from `%s'",
2523 				    m->value.s);
2524 			return -1;
2525 		}
2526 		if (m->type == FILE_REGEX) {
2527 			zval pattern;
2528 			int options = 0;
2529 			pcre_cache_entry *pce;
2530 
2531 			convert_libmagic_pattern(&pattern, m->value.s, strlen(m->value.s), options);
2532 
2533 			if ((pce = pcre_get_compiled_regex_cache(Z_STR(pattern))) == NULL) {
2534 				zval_dtor(&pattern);
2535 				return -1;
2536 			}
2537 			zval_dtor(&pattern);
2538 
2539 			return 0;
2540 		}
2541 		return 0;
2542 	case FILE_FLOAT:
2543 	case FILE_BEFLOAT:
2544 	case FILE_LEFLOAT:
2545 		if (m->reln != 'x') {
2546 			char *ep;
2547 			errno = 0;
2548 #ifdef HAVE_STRTOF
2549 			m->value.f = strtof(*p, &ep);
2550 #else
2551 			m->value.f = (float)strtod(*p, &ep);
2552 #endif
2553 			if (errno == 0)
2554 				*p = ep;
2555 		}
2556 		return 0;
2557 	case FILE_DOUBLE:
2558 	case FILE_BEDOUBLE:
2559 	case FILE_LEDOUBLE:
2560 		if (m->reln != 'x') {
2561 			char *ep;
2562 			errno = 0;
2563 			m->value.d = strtod(*p, &ep);
2564 			if (errno == 0)
2565 				*p = ep;
2566 		}
2567 		return 0;
2568 	default:
2569 		if (m->reln != 'x') {
2570 			char *ep;
2571 			errno = 0;
2572 			m->value.q = file_signextend(ms, m,
2573 			    (uint64_t)strtoull(*p, &ep, 0));
2574 			if (errno == 0) {
2575 				*p = ep;
2576 				eatsize(p);
2577 			}
2578 		}
2579 		return 0;
2580 	}
2581 }
2582 
2583 /*
2584  * Convert a string containing C character escapes.  Stop at an unescaped
2585  * space or tab.
2586  * Copy the converted version to "m->value.s", and the length in m->vallen.
2587  * Return updated scan pointer as function result. Warn if set.
2588  */
2589 private const char *
getstr(struct magic_set * ms,struct magic * m,const char * s,int warn)2590 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
2591 {
2592 	const char *origs = s;
2593 	char	*p = m->value.s;
2594 	size_t  plen = sizeof(m->value.s);
2595 	char 	*origp = p;
2596 	char	*pmax = p + plen - 1;
2597 	int	c;
2598 	int	val;
2599 
2600 	while ((c = *s++) != '\0') {
2601 		if (isspace((unsigned char) c))
2602 			break;
2603 		if (p >= pmax) {
2604 			file_error(ms, 0, "string too long: `%s'", origs);
2605 			return NULL;
2606 		}
2607 		if (c == '\\') {
2608 			switch(c = *s++) {
2609 
2610 			case '\0':
2611 				if (warn)
2612 					file_magwarn(ms, "incomplete escape");
2613 				s--;
2614 				goto out;
2615 
2616 			case '\t':
2617 				if (warn) {
2618 					file_magwarn(ms,
2619 					    "escaped tab found, use \\t instead");
2620 					warn = 0;	/* already did */
2621 				}
2622 				/*FALLTHROUGH*/
2623 			default:
2624 				if (warn) {
2625 					if (isprint((unsigned char)c)) {
2626 						/* Allow escaping of
2627 						 * ``relations'' */
2628 						if (strchr("<>&^=!", c) == NULL
2629 						    && (m->type != FILE_REGEX ||
2630 						    strchr("[]().*?^$|{}", c)
2631 						    == NULL)) {
2632 							file_magwarn(ms, "no "
2633 							    "need to escape "
2634 							    "`%c'", c);
2635 						}
2636 					} else {
2637 						file_magwarn(ms,
2638 						    "unknown escape sequence: "
2639 						    "\\%03o", c);
2640 					}
2641 				}
2642 				/*FALLTHROUGH*/
2643 			/* space, perhaps force people to use \040? */
2644 			case ' ':
2645 #if 0
2646 			/*
2647 			 * Other things people escape, but shouldn't need to,
2648 			 * so we disallow them
2649 			 */
2650 			case '\'':
2651 			case '"':
2652 			case '?':
2653 #endif
2654 			/* Relations */
2655 			case '>':
2656 			case '<':
2657 			case '&':
2658 			case '^':
2659 			case '=':
2660 			case '!':
2661 			/* and baskslash itself */
2662 			case '\\':
2663 				*p++ = (char) c;
2664 				break;
2665 
2666 			case 'a':
2667 				*p++ = '\a';
2668 				break;
2669 
2670 			case 'b':
2671 				*p++ = '\b';
2672 				break;
2673 
2674 			case 'f':
2675 				*p++ = '\f';
2676 				break;
2677 
2678 			case 'n':
2679 				*p++ = '\n';
2680 				break;
2681 
2682 			case 'r':
2683 				*p++ = '\r';
2684 				break;
2685 
2686 			case 't':
2687 				*p++ = '\t';
2688 				break;
2689 
2690 			case 'v':
2691 				*p++ = '\v';
2692 				break;
2693 
2694 			/* \ and up to 3 octal digits */
2695 			case '0':
2696 			case '1':
2697 			case '2':
2698 			case '3':
2699 			case '4':
2700 			case '5':
2701 			case '6':
2702 			case '7':
2703 				val = c - '0';
2704 				c = *s++;  /* try for 2 */
2705 				if (c >= '0' && c <= '7') {
2706 					val = (val << 3) | (c - '0');
2707 					c = *s++;  /* try for 3 */
2708 					if (c >= '0' && c <= '7')
2709 						val = (val << 3) | (c-'0');
2710 					else
2711 						--s;
2712 				}
2713 				else
2714 					--s;
2715 				*p++ = (char)val;
2716 				break;
2717 
2718 			/* \x and up to 2 hex digits */
2719 			case 'x':
2720 				val = 'x';	/* Default if no digits */
2721 				c = hextoint(*s++);	/* Get next char */
2722 				if (c >= 0) {
2723 					val = c;
2724 					c = hextoint(*s++);
2725 					if (c >= 0)
2726 						val = (val << 4) + c;
2727 					else
2728 						--s;
2729 				} else
2730 					--s;
2731 				*p++ = (char)val;
2732 				break;
2733 			}
2734 		} else
2735 			*p++ = (char)c;
2736 	}
2737 	--s;
2738 out:
2739 	*p = '\0';
2740 	m->vallen = CAST(unsigned char, (p - origp));
2741 	if (m->type == FILE_PSTRING)
2742 		m->vallen += (unsigned char)file_pstring_length_size(m);
2743 	return s;
2744 }
2745 
2746 
2747 /* Single hex char to int; -1 if not a hex char. */
2748 private int
hextoint(int c)2749 hextoint(int c)
2750 {
2751 	if (!isascii((unsigned char) c))
2752 		return -1;
2753 	if (isdigit((unsigned char) c))
2754 		return c - '0';
2755 	if ((c >= 'a') && (c <= 'f'))
2756 		return c + 10 - 'a';
2757 	if (( c>= 'A') && (c <= 'F'))
2758 		return c + 10 - 'A';
2759 	return -1;
2760 }
2761 
2762 
2763 /*
2764  * Print a string containing C character escapes.
2765  */
2766 protected void
file_showstr(FILE * fp,const char * s,size_t len)2767 file_showstr(FILE *fp, const char *s, size_t len)
2768 {
2769 	char	c;
2770 
2771 	for (;;) {
2772 		if (len == ~0U) {
2773 			c = *s++;
2774 			if (c == '\0')
2775 				break;
2776 		}
2777 		else  {
2778 			if (len-- == 0)
2779 				break;
2780 			c = *s++;
2781 		}
2782 		if (c >= 040 && c <= 0176)	/* TODO isprint && !iscntrl */
2783 			(void) fputc(c, fp);
2784 		else {
2785 			(void) fputc('\\', fp);
2786 			switch (c) {
2787 			case '\a':
2788 				(void) fputc('a', fp);
2789 				break;
2790 
2791 			case '\b':
2792 				(void) fputc('b', fp);
2793 				break;
2794 
2795 			case '\f':
2796 				(void) fputc('f', fp);
2797 				break;
2798 
2799 			case '\n':
2800 				(void) fputc('n', fp);
2801 				break;
2802 
2803 			case '\r':
2804 				(void) fputc('r', fp);
2805 				break;
2806 
2807 			case '\t':
2808 				(void) fputc('t', fp);
2809 				break;
2810 
2811 			case '\v':
2812 				(void) fputc('v', fp);
2813 				break;
2814 
2815 			default:
2816 				(void) fprintf(fp, "%.3o", c & 0377);
2817 				break;
2818 			}
2819 		}
2820 	}
2821 }
2822 
2823 /*
2824  * eatsize(): Eat the size spec from a number [eg. 10UL]
2825  */
2826 private void
eatsize(const char ** p)2827 eatsize(const char **p)
2828 {
2829 	const char *l = *p;
2830 
2831 	if (LOWCASE(*l) == 'u')
2832 		l++;
2833 
2834 	switch (LOWCASE(*l)) {
2835 	case 'l':    /* long */
2836 	case 's':    /* short */
2837 	case 'h':    /* short */
2838 	case 'b':    /* char/byte */
2839 	case 'c':    /* char/byte */
2840 		l++;
2841 		/*FALLTHROUGH*/
2842 	default:
2843 		break;
2844 	}
2845 
2846 	*p = l;
2847 }
2848 
2849 /*
2850  * handle a buffer containing a compiled file.
2851  */
2852 private struct magic_map *
apprentice_buf(struct magic_set * ms,struct magic * buf,size_t len)2853 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
2854 {
2855 	struct magic_map *map;
2856 
2857 	if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) {
2858 		file_oomem(ms, sizeof(*map));
2859 		return NULL;
2860 	}
2861 	map->len = len;
2862 	map->p = buf;
2863 	map->type = MAP_TYPE_USER;
2864 	if (check_buffer(ms, map, "buffer") != 0) {
2865 		apprentice_unmap(map);
2866 		return NULL;
2867 	}
2868 	return map;
2869 }
2870 
2871 /*
2872  * handle a compiled file.
2873  */
2874 
2875 private struct magic_map *
apprentice_map(struct magic_set * ms,const char * fn)2876 apprentice_map(struct magic_set *ms, const char *fn)
2877 {
2878 	uint32_t *ptr;
2879 	uint32_t version, entries, nentries;
2880 	int needsbyteswap;
2881 	char *dbname = NULL;
2882 	struct magic_map *map;
2883 	size_t i;
2884 	php_stream *stream = NULL;
2885 	php_stream_statbuf st;
2886 
2887 
2888 
2889 	if ((map = CAST(struct magic_map *, ecalloc(1, sizeof(*map)))) == NULL) {
2890 		file_oomem(ms, sizeof(*map));
2891 		return NULL;
2892 	}
2893 
2894 	if (fn == NULL) {
2895 		map->p = (void *)&php_magic_database;
2896 		goto internal_loaded;
2897 	}
2898 
2899 #ifdef PHP_WIN32
2900 	/* Don't bother on windows with php_stream_open_wrapper,
2901 	return to give apprentice_load() a chance. */
2902 	if (php_stream_stat_path_ex((char *)fn, 0, &st, NULL) == SUCCESS) {
2903                if (st.sb.st_mode & S_IFDIR) {
2904                        return NULL;
2905                }
2906        }
2907 #endif
2908 
2909 	dbname = mkdbname(ms, fn, 0);
2910 	if (dbname == NULL)
2911 		goto error;
2912 
2913 	stream = php_stream_open_wrapper((char *)fn, "rb", REPORT_ERRORS, NULL);
2914 
2915 	if (!stream) {
2916 		goto error;
2917 	}
2918 
2919 	if (php_stream_stat(stream, &st) < 0) {
2920 		file_error(ms, errno, "cannot stat `%s'", dbname);
2921 		goto error;
2922 	}
2923 	if (st.sb.st_size < 8 || st.sb.st_size > MAXMAGIC_SIZE) {
2924 		file_error(ms, 0, "file `%s' is too %s", dbname,
2925 		    st.sb.st_size < 8 ? "small" : "large");
2926 		goto error;
2927 	}
2928 
2929 	map->len = (size_t)st.sb.st_size;
2930 	if ((map->p = CAST(void *, emalloc(map->len))) == NULL) {
2931 		file_oomem(ms, map->len);
2932 		goto error;
2933 	}
2934 	if (php_stream_read(stream, map->p, (size_t)st.sb.st_size) != (size_t)st.sb.st_size) {
2935 		file_badread(ms);
2936 		goto error;
2937 	}
2938 	map->len = 0;
2939 #define RET	1
2940 
2941 	php_stream_close(stream);
2942 	stream = NULL;
2943 
2944 internal_loaded:
2945 	ptr = (uint32_t *)(void *)map->p;
2946 	if (*ptr != MAGICNO) {
2947 		if (swap4(*ptr) != MAGICNO) {
2948 			file_error(ms, 0, "bad magic in `%s'", dbname);
2949 			goto error;
2950 		}
2951 		needsbyteswap = 1;
2952 	} else
2953 		needsbyteswap = 0;
2954 	if (needsbyteswap)
2955 		version = swap4(ptr[1]);
2956 	else
2957 		version = ptr[1];
2958 	if (version != VERSIONNO) {
2959 		file_error(ms, 0, "File %d.%d supports only version %d magic "
2960 		    "files. `%s' is version %d", FILE_VERSION_MAJOR, patchlevel,
2961 		    VERSIONNO, dbname, version);
2962 		goto error;
2963 	}
2964 
2965 	/* php_magic_database is a const, performing writes will segfault. This is for big-endian
2966 	machines only, PPC and Sparc specifically. Consider static variable or MINIT in
2967 	future. */
2968 	if (needsbyteswap && fn == NULL) {
2969 		map->p = emalloc(sizeof(php_magic_database));
2970 		map->p = memcpy(map->p, php_magic_database, sizeof(php_magic_database));
2971 	}
2972 
2973 	if (NULL != fn) {
2974 		nentries = (uint32_t)(st.sb.st_size / sizeof(struct magic));
2975 		entries = (uint32_t)(st.sb.st_size / sizeof(struct magic));
2976 		if ((zend_off_t)(entries * sizeof(struct magic)) != st.sb.st_size) {
2977 			file_error(ms, 0, "Size of `%s' %llu is not a multiple of %zu",
2978 				dbname, (unsigned long long)st.sb.st_size,
2979 				sizeof(struct magic));
2980 			goto error;
2981 		}
2982 	}
2983 	map->magic[0] = CAST(struct magic *, map->p) + 1;
2984 	nentries = 0;
2985 	for (i = 0; i < MAGIC_SETS; i++) {
2986 		if (needsbyteswap)
2987 			map->nmagic[i] = swap4(ptr[i + 2]);
2988 		else
2989 			map->nmagic[i] = ptr[i + 2];
2990 		if (i != MAGIC_SETS - 1)
2991 			map->magic[i + 1] = map->magic[i] + map->nmagic[i];
2992 		nentries += map->nmagic[i];
2993 	}
2994 	if (NULL != fn && entries != nentries + 1) {
2995 		file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
2996 		    dbname, entries, nentries + 1);
2997 		goto error;
2998 	}
2999 	if (needsbyteswap)
3000 		for (i = 0; i < MAGIC_SETS; i++)
3001 			byteswap(map->magic[i], map->nmagic[i]);
3002 
3003 	if (dbname) {
3004 		efree(dbname);
3005 	}
3006 	return map;
3007 
3008 error:
3009 	if (stream) {
3010 		php_stream_close(stream);
3011 	}
3012 	apprentice_unmap(map);
3013 	if (dbname) {
3014 		efree(dbname);
3015 	}
3016 	return NULL;
3017 }
3018 
3019 private int
check_buffer(struct magic_set * ms,struct magic_map * map,const char * dbname)3020 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
3021 {
3022 	uint32_t *ptr;
3023 	uint32_t entries, nentries;
3024 	uint32_t version;
3025 	int i, needsbyteswap;
3026 
3027 	ptr = CAST(uint32_t *, map->p);
3028 	if (*ptr != MAGICNO) {
3029 		if (swap4(*ptr) != MAGICNO) {
3030 			file_error(ms, 0, "bad magic in `%s'", dbname);
3031 			return -1;
3032 		}
3033 		needsbyteswap = 1;
3034 	} else
3035 		needsbyteswap = 0;
3036 	if (needsbyteswap)
3037 		version = swap4(ptr[1]);
3038 	else
3039 		version = ptr[1];
3040 	if (version != VERSIONNO) {
3041 		file_error(ms, 0, "File %s supports only version %d magic "
3042 		    "files. `%s' is version %d", FILE_VERSION_MAJOR,
3043 		    VERSIONNO, dbname, version);
3044 		return -1;
3045 	}
3046 	entries = (uint32_t)(map->len / sizeof(struct magic));
3047 	if ((entries * sizeof(struct magic)) != map->len) {
3048 		file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
3049 		    "a multiple of %" SIZE_T_FORMAT "u",
3050 		    dbname, map->len, sizeof(struct magic));
3051 		return -1;
3052 	}
3053 	map->magic[0] = CAST(struct magic *, map->p) + 1;
3054 	nentries = 0;
3055 	for (i = 0; i < MAGIC_SETS; i++) {
3056 		if (needsbyteswap)
3057 			map->nmagic[i] = swap4(ptr[i + 2]);
3058 		else
3059 			map->nmagic[i] = ptr[i + 2];
3060 		if (i != MAGIC_SETS - 1)
3061 			map->magic[i + 1] = map->magic[i] + map->nmagic[i];
3062 		nentries += map->nmagic[i];
3063 	}
3064 	if (entries != nentries + 1) {
3065 		file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
3066 		    dbname, entries, nentries + 1);
3067 		return -1;
3068 	}
3069 	if (needsbyteswap)
3070 		for (i = 0; i < MAGIC_SETS; i++)
3071 			byteswap(map->magic[i], map->nmagic[i]);
3072 	return 0;
3073 }
3074 
3075 /*
3076  * handle an mmaped file.
3077  */
3078 private int
apprentice_compile(struct magic_set * ms,struct magic_map * map,const char * fn)3079 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
3080 {
3081 	static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
3082 	static const size_t m = sizeof(**map->magic);
3083 	size_t len;
3084 	char *dbname;
3085 	int rv = -1;
3086 	uint32_t i;
3087 	union {
3088 		struct magic m;
3089 		uint32_t h[2 + MAGIC_SETS];
3090 	} hdr;
3091 	php_stream *stream;
3092 
3093 	dbname = mkdbname(ms, fn, 1);
3094 
3095 	if (dbname == NULL)
3096 		goto out;
3097 
3098 	/* wb+ == O_WRONLY|O_CREAT|O_TRUNC|O_BINARY */
3099 	stream = php_stream_open_wrapper((char *)fn, "wb+", REPORT_ERRORS, NULL);
3100 
3101 	if (!stream) {
3102 		file_error(ms, errno, "cannot open `%s'", dbname);
3103 		goto out;
3104 	}
3105 	memset(&hdr, 0, sizeof(hdr));
3106 	hdr.h[0] = MAGICNO;
3107 	hdr.h[1] = VERSIONNO;
3108 	memcpy(hdr.h + 2, map->nmagic, nm);
3109 
3110 	if (php_stream_write(stream,(const char *)&hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
3111 		file_error(ms, errno, "error writing `%s'", dbname);
3112 		goto out;
3113 	}
3114 
3115 	for (i = 0; i < MAGIC_SETS; i++) {
3116 		len = m * map->nmagic[i];
3117 		if (php_stream_write(stream, (const char *)map->magic[i], len) != (ssize_t)len) {
3118 			file_error(ms, errno, "error writing `%s'", dbname);
3119 			goto out;
3120 		}
3121 	}
3122 
3123 	if (stream) {
3124 		php_stream_close(stream);
3125 	}
3126 	rv = 0;
3127 out:
3128 	efree(dbname);
3129 	return rv;
3130 }
3131 
3132 private const char ext[] = ".mgc";
3133 /*
3134  * make a dbname
3135  */
3136 private char *
mkdbname(struct magic_set * ms,const char * fn,int strip)3137 mkdbname(struct magic_set *ms, const char *fn, int strip)
3138 {
3139 	const char *p, *q;
3140 	char *buf;
3141 
3142 	if (strip) {
3143 		if ((p = strrchr(fn, '/')) != NULL)
3144 			fn = ++p;
3145 	}
3146 
3147 	for (q = fn; *q; q++)
3148 		continue;
3149 	/* Look for .mgc */
3150 	for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
3151 		if (*p != *q)
3152 			break;
3153 
3154 	/* Did not find .mgc, restore q */
3155 	if (p >= ext)
3156 		while (*q)
3157 			q++;
3158 
3159 	q++;
3160 	/* Compatibility with old code that looked in .mime */
3161 	if (ms->flags & MAGIC_MIME) {
3162 		spprintf(&buf, MAXPATHLEN, "%.*s.mime%s", (int)(q - fn), fn, ext);
3163 #ifdef PHP_WIN32
3164 		if (VCWD_ACCESS(buf, R_OK) == 0) {
3165 #else
3166 		if (VCWD_ACCESS(buf, R_OK) != -1) {
3167 #endif
3168 			ms->flags &= MAGIC_MIME_TYPE;
3169 			return buf;
3170 		}
3171 		efree(buf);
3172 	}
3173 	spprintf(&buf, MAXPATHLEN, "%.*s%s", (int)(q - fn), fn, ext);
3174 
3175 	/* Compatibility with old code that looked in .mime */
3176 	if (strstr(fn, ".mime") != NULL)
3177 		ms->flags &= MAGIC_MIME_TYPE;
3178 	return buf;
3179 }
3180 
3181 /*
3182  * Byteswap an mmap'ed file if needed
3183  */
3184 private void
3185 byteswap(struct magic *magic, uint32_t nmagic)
3186 {
3187 	uint32_t i;
3188 	for (i = 0; i < nmagic; i++)
3189 		bs1(&magic[i]);
3190 }
3191 
3192 /*
3193  * swap a short
3194  */
3195 private uint16_t
3196 swap2(uint16_t sv)
3197 {
3198 	uint16_t rv;
3199 	uint8_t *s = (uint8_t *)(void *)&sv;
3200 	uint8_t *d = (uint8_t *)(void *)&rv;
3201 	d[0] = s[1];
3202 	d[1] = s[0];
3203 	return rv;
3204 }
3205 
3206 /*
3207  * swap an int
3208  */
3209 private uint32_t
3210 swap4(uint32_t sv)
3211 {
3212 	uint32_t rv;
3213 	uint8_t *s = (uint8_t *)(void *)&sv;
3214 	uint8_t *d = (uint8_t *)(void *)&rv;
3215 	d[0] = s[3];
3216 	d[1] = s[2];
3217 	d[2] = s[1];
3218 	d[3] = s[0];
3219 	return rv;
3220 }
3221 
3222 /*
3223  * swap a quad
3224  */
3225 private uint64_t
3226 swap8(uint64_t sv)
3227 {
3228 	uint64_t rv;
3229 	uint8_t *s = (uint8_t *)(void *)&sv;
3230 	uint8_t *d = (uint8_t *)(void *)&rv;
3231 #if 0
3232 	d[0] = s[3];
3233 	d[1] = s[2];
3234 	d[2] = s[1];
3235 	d[3] = s[0];
3236 	d[4] = s[7];
3237 	d[5] = s[6];
3238 	d[6] = s[5];
3239 	d[7] = s[4];
3240 #else
3241 	d[0] = s[7];
3242 	d[1] = s[6];
3243 	d[2] = s[5];
3244 	d[3] = s[4];
3245 	d[4] = s[3];
3246 	d[5] = s[2];
3247 	d[6] = s[1];
3248 	d[7] = s[0];
3249 #endif
3250 	return rv;
3251 }
3252 
3253 /*
3254  * byteswap a single magic entry
3255  */
3256 private void
3257 bs1(struct magic *m)
3258 {
3259 	m->cont_level = swap2(m->cont_level);
3260 	m->offset = swap4((uint32_t)m->offset);
3261 	m->in_offset = swap4((uint32_t)m->in_offset);
3262 	m->lineno = swap4((uint32_t)m->lineno);
3263 	if (IS_LIBMAGIC_STRING(m->type)) {
3264 		m->str_range = swap4(m->str_range);
3265 		m->str_flags = swap4(m->str_flags);
3266 	}
3267 	else {
3268 		m->value.q = swap8(m->value.q);
3269 		m->num_mask = swap8(m->num_mask);
3270 	}
3271 }
3272 
3273 protected size_t
3274 file_pstring_length_size(const struct magic *m)
3275 {
3276 	switch (m->str_flags & PSTRING_LEN) {
3277 	case PSTRING_1_LE:
3278 		return 1;
3279 	case PSTRING_2_LE:
3280 	case PSTRING_2_BE:
3281 		return 2;
3282 	case PSTRING_4_LE:
3283 	case PSTRING_4_BE:
3284 		return 4;
3285 	default:
3286 		abort();	/* Impossible */
3287 		return 1;
3288 	}
3289 }
3290 protected size_t
3291 file_pstring_get_length(const struct magic *m, const char *ss)
3292 {
3293 	size_t len = 0;
3294 	const unsigned char *s = (const unsigned char *)ss;
3295 	unsigned int s3, s2, s1, s0;
3296 
3297 	switch (m->str_flags & PSTRING_LEN) {
3298 	case PSTRING_1_LE:
3299 		len = *s;
3300 		break;
3301 	case PSTRING_2_LE:
3302 		s0 = s[0];
3303 		s1 = s[1];
3304 		len = (s1 << 8) | s0;
3305 		break;
3306 	case PSTRING_2_BE:
3307 		s0 = s[0];
3308 		s1 = s[1];
3309 		len = (s0 << 8) | s1;
3310 		break;
3311 	case PSTRING_4_LE:
3312 		s0 = s[0];
3313 		s1 = s[1];
3314 		s2 = s[2];
3315 		s3 = s[3];
3316 		len = (s3 << 24) | (s2 << 16) | (s1 << 8) | s0;
3317 		break;
3318 	case PSTRING_4_BE:
3319 		s0 = s[0];
3320 		s1 = s[1];
3321 		s2 = s[2];
3322 		s3 = s[3];
3323 		len = (s0 << 24) | (s1 << 16) | (s2 << 8) | s3;
3324 		break;
3325 	default:
3326 		abort();	/* Impossible */
3327 	}
3328 
3329 	if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
3330 		len -= file_pstring_length_size(m);
3331 
3332 	return len;
3333 }
3334 
3335 protected int
3336 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
3337 {
3338 	uint32_t i, j;
3339 	struct mlist *mlist, *ml;
3340 
3341 	mlist = ms->mlist[1];
3342 
3343 	for (ml = mlist->next; ml != mlist; ml = ml->next) {
3344 		struct magic *ma = ml->magic;
3345 		uint32_t nma = ml->nmagic;
3346 		for (i = 0; i < nma; i++) {
3347 			if (ma[i].type != FILE_NAME)
3348 				continue;
3349 			if (strcmp(ma[i].value.s, name) == 0) {
3350 				v->magic = &ma[i];
3351 				for (j = i + 1; j < nma; j++)
3352 				    if (ma[j].cont_level == 0)
3353 					    break;
3354 				v->nmagic = j - i;
3355 				return 0;
3356 			}
3357 		}
3358 	}
3359 	return -1;
3360 }
3361