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