xref: /freebsd/contrib/file/src/apprentice.c (revision fd5e3f3ec6c6248e892c9e7b2f17da3bfe7b6837)
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.255 2016/10/24 18:02:17 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 			if ((char *)map->magic[i] >= (char *)map->p &&
553 			    (char *)map->magic[i] <= (char *)map->p + map->len)
554 				continue;
555 			free(map->magic[i]);
556 		}
557 		free(map->p);
558 		break;
559 #ifdef QUICK
560 	case MAP_TYPE_MMAP:
561 		if (map->p && map->p != MAP_FAILED)
562 			(void)munmap(map->p, map->len);
563 		break;
564 #endif
565 	default:
566 		abort();
567 	}
568 	free(map);
569 }
570 
571 private struct mlist *
572 mlist_alloc(void)
573 {
574 	struct mlist *mlist;
575 	if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
576 		return NULL;
577 	}
578 	mlist->next = mlist->prev = mlist;
579 	return mlist;
580 }
581 
582 private void
583 mlist_free(struct mlist *mlist)
584 {
585 	struct mlist *ml, *next;
586 
587 	if (mlist == NULL)
588 		return;
589 
590 	ml = mlist->next;
591 	for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
592 		if (ml->map)
593 			apprentice_unmap(CAST(struct magic_map *, ml->map));
594 		free(ml);
595 		if (ml == mlist)
596 			break;
597 	}
598 }
599 
600 #ifndef COMPILE_ONLY
601 /* void **bufs: an array of compiled magic files */
602 protected int
603 buffer_apprentice(struct magic_set *ms, struct magic **bufs,
604     size_t *sizes, size_t nbufs)
605 {
606 	size_t i, j;
607 	struct mlist *ml;
608 	struct magic_map *map;
609 
610 	if (nbufs == 0)
611 		return -1;
612 
613 	if (ms->mlist[0] != NULL)
614 		file_reset(ms);
615 
616 	init_file_tables();
617 
618 	for (i = 0; i < MAGIC_SETS; i++) {
619 		mlist_free(ms->mlist[i]);
620 		if ((ms->mlist[i] = mlist_alloc()) == NULL) {
621 			file_oomem(ms, sizeof(*ms->mlist[i]));
622 			goto fail;
623 		}
624 	}
625 
626 	for (i = 0; i < nbufs; i++) {
627 		map = apprentice_buf(ms, bufs[i], sizes[i]);
628 		if (map == NULL)
629 			goto fail;
630 
631 		for (j = 0; j < MAGIC_SETS; j++) {
632 			if (add_mlist(ms->mlist[j], map, j) == -1) {
633 				file_oomem(ms, sizeof(*ml));
634 				goto fail;
635 			}
636 		}
637 	}
638 
639 	return 0;
640 fail:
641 	for (i = 0; i < MAGIC_SETS; i++) {
642 		mlist_free(ms->mlist[i]);
643 		ms->mlist[i] = NULL;
644 	}
645 	return -1;
646 }
647 #endif
648 
649 /* const char *fn: list of magic files and directories */
650 protected int
651 file_apprentice(struct magic_set *ms, const char *fn, int action)
652 {
653 	char *p, *mfn;
654 	int file_err, errs = -1;
655 	size_t i;
656 
657 	if (ms->mlist[0] != NULL)
658 		file_reset(ms);
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  * Get weight of this magic entry, for sorting purposes.
782  */
783 private size_t
784 apprentice_magic_strength(const struct magic *m)
785 {
786 #define MULT 10
787 	size_t v, val = 2 * MULT;	/* baseline strength */
788 
789 	switch (m->type) {
790 	case FILE_DEFAULT:	/* make sure this sorts last */
791 		if (m->factor_op != FILE_FACTOR_OP_NONE)
792 			abort();
793 		return 0;
794 
795 	case FILE_BYTE:
796 		val += 1 * MULT;
797 		break;
798 
799 	case FILE_SHORT:
800 	case FILE_LESHORT:
801 	case FILE_BESHORT:
802 		val += 2 * MULT;
803 		break;
804 
805 	case FILE_LONG:
806 	case FILE_LELONG:
807 	case FILE_BELONG:
808 	case FILE_MELONG:
809 		val += 4 * MULT;
810 		break;
811 
812 	case FILE_PSTRING:
813 	case FILE_STRING:
814 		val += m->vallen * MULT;
815 		break;
816 
817 	case FILE_BESTRING16:
818 	case FILE_LESTRING16:
819 		val += m->vallen * MULT / 2;
820 		break;
821 
822 	case FILE_SEARCH:
823 		val += m->vallen * MAX(MULT / m->vallen, 1);
824 		break;
825 
826 	case FILE_REGEX:
827 		v = nonmagic(m->value.s);
828 		val += v * MAX(MULT / v, 1);
829 		break;
830 
831 	case FILE_DATE:
832 	case FILE_LEDATE:
833 	case FILE_BEDATE:
834 	case FILE_MEDATE:
835 	case FILE_LDATE:
836 	case FILE_LELDATE:
837 	case FILE_BELDATE:
838 	case FILE_MELDATE:
839 	case FILE_FLOAT:
840 	case FILE_BEFLOAT:
841 	case FILE_LEFLOAT:
842 		val += 4 * MULT;
843 		break;
844 
845 	case FILE_QUAD:
846 	case FILE_BEQUAD:
847 	case FILE_LEQUAD:
848 	case FILE_QDATE:
849 	case FILE_LEQDATE:
850 	case FILE_BEQDATE:
851 	case FILE_QLDATE:
852 	case FILE_LEQLDATE:
853 	case FILE_BEQLDATE:
854 	case FILE_QWDATE:
855 	case FILE_LEQWDATE:
856 	case FILE_BEQWDATE:
857 	case FILE_DOUBLE:
858 	case FILE_BEDOUBLE:
859 	case FILE_LEDOUBLE:
860 		val += 8 * MULT;
861 		break;
862 
863 	case FILE_INDIRECT:
864 	case FILE_NAME:
865 	case FILE_USE:
866 		break;
867 
868 	case FILE_DER:
869 		val += MULT;
870 		break;
871 
872 	default:
873 		(void)fprintf(stderr, "Bad type %d\n", m->type);
874 		abort();
875 	}
876 
877 	switch (m->reln) {
878 	case 'x':	/* matches anything penalize */
879 	case '!':       /* matches almost anything penalize */
880 		val = 0;
881 		break;
882 
883 	case '=':	/* Exact match, prefer */
884 		val += MULT;
885 		break;
886 
887 	case '>':
888 	case '<':	/* comparison match reduce strength */
889 		val -= 2 * MULT;
890 		break;
891 
892 	case '^':
893 	case '&':	/* masking bits, we could count them too */
894 		val -= MULT;
895 		break;
896 
897 	default:
898 		(void)fprintf(stderr, "Bad relation %c\n", m->reln);
899 		abort();
900 	}
901 
902 	if (val == 0)	/* ensure we only return 0 for FILE_DEFAULT */
903 		val = 1;
904 
905 	switch (m->factor_op) {
906 	case FILE_FACTOR_OP_NONE:
907 		break;
908 	case FILE_FACTOR_OP_PLUS:
909 		val += m->factor;
910 		break;
911 	case FILE_FACTOR_OP_MINUS:
912 		val -= m->factor;
913 		break;
914 	case FILE_FACTOR_OP_TIMES:
915 		val *= m->factor;
916 		break;
917 	case FILE_FACTOR_OP_DIV:
918 		val /= m->factor;
919 		break;
920 	default:
921 		abort();
922 	}
923 
924 	/*
925 	 * Magic entries with no description get a bonus because they depend
926 	 * on subsequent magic entries to print something.
927 	 */
928 	if (m->desc[0] == '\0')
929 		val++;
930 	return val;
931 }
932 
933 /*
934  * Sort callback for sorting entries by "strength" (basically length)
935  */
936 private int
937 apprentice_sort(const void *a, const void *b)
938 {
939 	const struct magic_entry *ma = CAST(const struct magic_entry *, a);
940 	const struct magic_entry *mb = CAST(const struct magic_entry *, b);
941 	size_t sa = apprentice_magic_strength(ma->mp);
942 	size_t sb = apprentice_magic_strength(mb->mp);
943 	if (sa == sb)
944 		return 0;
945 	else if (sa > sb)
946 		return -1;
947 	else
948 		return 1;
949 }
950 
951 /*
952  * Shows sorted patterns list in the order which is used for the matching
953  */
954 private void
955 apprentice_list(struct mlist *mlist, int mode)
956 {
957 	uint32_t magindex = 0;
958 	struct mlist *ml;
959 	for (ml = mlist->next; ml != mlist; ml = ml->next) {
960 		for (magindex = 0; magindex < ml->nmagic; magindex++) {
961 			struct magic *m = &ml->magic[magindex];
962 			if ((m->flag & mode) != mode) {
963 				/* Skip sub-tests */
964 				while (magindex + 1 < ml->nmagic &&
965 				       ml->magic[magindex + 1].cont_level != 0)
966 					++magindex;
967 				continue; /* Skip to next top-level test*/
968 			}
969 
970 			/*
971 			 * Try to iterate over the tree until we find item with
972 			 * description/mimetype.
973 			 */
974 			while (magindex + 1 < ml->nmagic &&
975 			       ml->magic[magindex + 1].cont_level != 0 &&
976 			       *ml->magic[magindex].desc == '\0' &&
977 			       *ml->magic[magindex].mimetype == '\0')
978 				magindex++;
979 
980 			printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
981 			    apprentice_magic_strength(m),
982 			    ml->magic[magindex].lineno,
983 			    ml->magic[magindex].desc,
984 			    ml->magic[magindex].mimetype);
985 		}
986 	}
987 }
988 
989 private void
990 set_test_type(struct magic *mstart, struct magic *m)
991 {
992 	switch (m->type) {
993 	case FILE_BYTE:
994 	case FILE_SHORT:
995 	case FILE_LONG:
996 	case FILE_DATE:
997 	case FILE_BESHORT:
998 	case FILE_BELONG:
999 	case FILE_BEDATE:
1000 	case FILE_LESHORT:
1001 	case FILE_LELONG:
1002 	case FILE_LEDATE:
1003 	case FILE_LDATE:
1004 	case FILE_BELDATE:
1005 	case FILE_LELDATE:
1006 	case FILE_MEDATE:
1007 	case FILE_MELDATE:
1008 	case FILE_MELONG:
1009 	case FILE_QUAD:
1010 	case FILE_LEQUAD:
1011 	case FILE_BEQUAD:
1012 	case FILE_QDATE:
1013 	case FILE_LEQDATE:
1014 	case FILE_BEQDATE:
1015 	case FILE_QLDATE:
1016 	case FILE_LEQLDATE:
1017 	case FILE_BEQLDATE:
1018 	case FILE_QWDATE:
1019 	case FILE_LEQWDATE:
1020 	case FILE_BEQWDATE:
1021 	case FILE_FLOAT:
1022 	case FILE_BEFLOAT:
1023 	case FILE_LEFLOAT:
1024 	case FILE_DOUBLE:
1025 	case FILE_BEDOUBLE:
1026 	case FILE_LEDOUBLE:
1027 	case FILE_DER:
1028 		mstart->flag |= BINTEST;
1029 		break;
1030 	case FILE_STRING:
1031 	case FILE_PSTRING:
1032 	case FILE_BESTRING16:
1033 	case FILE_LESTRING16:
1034 		/* Allow text overrides */
1035 		if (mstart->str_flags & STRING_TEXTTEST)
1036 			mstart->flag |= TEXTTEST;
1037 		else
1038 			mstart->flag |= BINTEST;
1039 		break;
1040 	case FILE_REGEX:
1041 	case FILE_SEARCH:
1042 		/* Check for override */
1043 		if (mstart->str_flags & STRING_BINTEST)
1044 			mstart->flag |= BINTEST;
1045 		if (mstart->str_flags & STRING_TEXTTEST)
1046 			mstart->flag |= TEXTTEST;
1047 
1048 		if (mstart->flag & (TEXTTEST|BINTEST))
1049 			break;
1050 
1051 		/* binary test if pattern is not text */
1052 		if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
1053 		    NULL) <= 0)
1054 			mstart->flag |= BINTEST;
1055 		else
1056 			mstart->flag |= TEXTTEST;
1057 		break;
1058 	case FILE_DEFAULT:
1059 		/* can't deduce anything; we shouldn't see this at the
1060 		   top level anyway */
1061 		break;
1062 	case FILE_INVALID:
1063 	default:
1064 		/* invalid search type, but no need to complain here */
1065 		break;
1066 	}
1067 }
1068 
1069 private int
1070 addentry(struct magic_set *ms, struct magic_entry *me,
1071    struct magic_entry_set *mset)
1072 {
1073 	size_t i = me->mp->type == FILE_NAME ? 1 : 0;
1074 	if (mset[i].count == mset[i].max) {
1075 		struct magic_entry *mp;
1076 
1077 		mset[i].max += ALLOC_INCR;
1078 		if ((mp = CAST(struct magic_entry *,
1079 		    realloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
1080 		    NULL) {
1081 			file_oomem(ms, sizeof(*mp) * mset[i].max);
1082 			return -1;
1083 		}
1084 		(void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
1085 		    ALLOC_INCR);
1086 		mset[i].me = mp;
1087 	}
1088 	mset[i].me[mset[i].count++] = *me;
1089 	memset(me, 0, sizeof(*me));
1090 	return 0;
1091 }
1092 
1093 /*
1094  * Load and parse one file.
1095  */
1096 private void
1097 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
1098    struct magic_entry_set *mset)
1099 {
1100 	size_t lineno = 0, llen = 0;
1101 	char *line = NULL;
1102 	ssize_t len;
1103 	struct magic_entry me;
1104 
1105 	FILE *f = fopen(ms->file = fn, "r");
1106 	if (f == NULL) {
1107 		if (errno != ENOENT)
1108 			file_error(ms, errno, "cannot read magic file `%s'",
1109 				   fn);
1110 		(*errs)++;
1111 		return;
1112 	}
1113 
1114 	memset(&me, 0, sizeof(me));
1115 	/* read and parse this file */
1116 	for (ms->line = 1; (len = getline(&line, &llen, f)) != -1;
1117 	    ms->line++) {
1118 		if (len == 0) /* null line, garbage, etc */
1119 			continue;
1120 		if (line[len - 1] == '\n') {
1121 			lineno++;
1122 			line[len - 1] = '\0'; /* delete newline */
1123 		}
1124 		switch (line[0]) {
1125 		case '\0':	/* empty, do not parse */
1126 		case '#':	/* comment, do not parse */
1127 			continue;
1128 		case '!':
1129 			if (line[1] == ':') {
1130 				size_t i;
1131 
1132 				for (i = 0; bang[i].name != NULL; i++) {
1133 					if ((size_t)(len - 2) > bang[i].len &&
1134 					    memcmp(bang[i].name, line + 2,
1135 					    bang[i].len) == 0)
1136 						break;
1137 				}
1138 				if (bang[i].name == NULL) {
1139 					file_error(ms, 0,
1140 					    "Unknown !: entry `%s'", line);
1141 					(*errs)++;
1142 					continue;
1143 				}
1144 				if (me.mp == NULL) {
1145 					file_error(ms, 0,
1146 					    "No current entry for :!%s type",
1147 						bang[i].name);
1148 					(*errs)++;
1149 					continue;
1150 				}
1151 				if ((*bang[i].fun)(ms, &me,
1152 				    line + bang[i].len + 2) != 0) {
1153 					(*errs)++;
1154 					continue;
1155 				}
1156 				continue;
1157 			}
1158 			/*FALLTHROUGH*/
1159 		default:
1160 		again:
1161 			switch (parse(ms, &me, line, lineno, action)) {
1162 			case 0:
1163 				continue;
1164 			case 1:
1165 				(void)addentry(ms, &me, mset);
1166 				goto again;
1167 			default:
1168 				(*errs)++;
1169 				break;
1170 			}
1171 		}
1172 	}
1173 	if (me.mp)
1174 		(void)addentry(ms, &me, mset);
1175 	free(line);
1176 	(void)fclose(f);
1177 }
1178 
1179 /*
1180  * parse a file or directory of files
1181  * const char *fn: name of magic file or directory
1182  */
1183 private int
1184 cmpstrp(const void *p1, const void *p2)
1185 {
1186         return strcmp(*(char *const *)p1, *(char *const *)p2);
1187 }
1188 
1189 
1190 private uint32_t
1191 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1192     uint32_t starttest)
1193 {
1194 	static const char text[] = "text";
1195 	static const char binary[] = "binary";
1196 	static const size_t len = sizeof(text);
1197 
1198 	uint32_t i = starttest;
1199 
1200 	do {
1201 		set_test_type(me[starttest].mp, me[i].mp);
1202 		if ((ms->flags & MAGIC_DEBUG) == 0)
1203 			continue;
1204 		(void)fprintf(stderr, "%s%s%s: %s\n",
1205 		    me[i].mp->mimetype,
1206 		    me[i].mp->mimetype[0] == '\0' ? "" : "; ",
1207 		    me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
1208 		    me[i].mp->flag & BINTEST ? binary : text);
1209 		if (me[i].mp->flag & BINTEST) {
1210 			char *p = strstr(me[i].mp->desc, text);
1211 			if (p && (p == me[i].mp->desc ||
1212 			    isspace((unsigned char)p[-1])) &&
1213 			    (p + len - me[i].mp->desc == MAXstring
1214 			    || (p[len] == '\0' ||
1215 			    isspace((unsigned char)p[len]))))
1216 				(void)fprintf(stderr, "*** Possible "
1217 				    "binary test for text type\n");
1218 		}
1219 	} while (++i < nme && me[i].mp->cont_level != 0);
1220 	return i;
1221 }
1222 
1223 private void
1224 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
1225 {
1226 	uint32_t i;
1227 	for (i = 0; i < nme; i++) {
1228 		if (me[i].mp->cont_level == 0 &&
1229 		    me[i].mp->type == FILE_DEFAULT) {
1230 			while (++i < nme)
1231 				if (me[i].mp->cont_level == 0)
1232 					break;
1233 			if (i != nme) {
1234 				/* XXX - Ugh! */
1235 				ms->line = me[i].mp->lineno;
1236 				file_magwarn(ms,
1237 				    "level 0 \"default\" did not sort last");
1238 			}
1239 			return;
1240 		}
1241 	}
1242 }
1243 
1244 private int
1245 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1246     struct magic **ma, uint32_t *nma)
1247 {
1248 	uint32_t i, mentrycount = 0;
1249 	size_t slen;
1250 
1251 	for (i = 0; i < nme; i++)
1252 		mentrycount += me[i].cont_count;
1253 
1254 	slen = sizeof(**ma) * mentrycount;
1255 	if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) {
1256 		file_oomem(ms, slen);
1257 		return -1;
1258 	}
1259 
1260 	mentrycount = 0;
1261 	for (i = 0; i < nme; i++) {
1262 		(void)memcpy(*ma + mentrycount, me[i].mp,
1263 		    me[i].cont_count * sizeof(**ma));
1264 		mentrycount += me[i].cont_count;
1265 	}
1266 	*nma = mentrycount;
1267 	return 0;
1268 }
1269 
1270 private void
1271 magic_entry_free(struct magic_entry *me, uint32_t nme)
1272 {
1273 	uint32_t i;
1274 	if (me == NULL)
1275 		return;
1276 	for (i = 0; i < nme; i++)
1277 		free(me[i].mp);
1278 	free(me);
1279 }
1280 
1281 private struct magic_map *
1282 apprentice_load(struct magic_set *ms, const char *fn, int action)
1283 {
1284 	int errs = 0;
1285 	uint32_t i, j;
1286 	size_t files = 0, maxfiles = 0;
1287 	char **filearr = NULL, *mfn;
1288 	struct stat st;
1289 	struct magic_map *map;
1290 	struct magic_entry_set mset[MAGIC_SETS];
1291 	DIR *dir;
1292 	struct dirent *d;
1293 
1294 	memset(mset, 0, sizeof(mset));
1295 	ms->flags |= MAGIC_CHECK;	/* Enable checks for parsed files */
1296 
1297 
1298 	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL)
1299 	{
1300 		file_oomem(ms, sizeof(*map));
1301 		return NULL;
1302 	}
1303 	map->type = MAP_TYPE_MALLOC;
1304 
1305 	/* print silly verbose header for USG compat. */
1306 	if (action == FILE_CHECK)
1307 		(void)fprintf(stderr, "%s\n", usg_hdr);
1308 
1309 	/* load directory or file */
1310 	if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
1311 		dir = opendir(fn);
1312 		if (!dir) {
1313 			errs++;
1314 			goto out;
1315 		}
1316 		while ((d = readdir(dir)) != NULL) {
1317 			if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) {
1318 				file_oomem(ms,
1319 				    strlen(fn) + strlen(d->d_name) + 2);
1320 				errs++;
1321 				closedir(dir);
1322 				goto out;
1323 			}
1324 			if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
1325 				free(mfn);
1326 				continue;
1327 			}
1328 			if (files >= maxfiles) {
1329 				size_t mlen;
1330 				maxfiles = (maxfiles + 1) * 2;
1331 				mlen = maxfiles * sizeof(*filearr);
1332 				if ((filearr = CAST(char **,
1333 				    realloc(filearr, mlen))) == NULL) {
1334 					file_oomem(ms, mlen);
1335 					free(mfn);
1336 					closedir(dir);
1337 					errs++;
1338 					goto out;
1339 				}
1340 			}
1341 			filearr[files++] = mfn;
1342 		}
1343 		closedir(dir);
1344 		qsort(filearr, files, sizeof(*filearr), cmpstrp);
1345 		for (i = 0; i < files; i++) {
1346 			load_1(ms, action, filearr[i], &errs, mset);
1347 			free(filearr[i]);
1348 		}
1349 		free(filearr);
1350 	} else
1351 		load_1(ms, action, fn, &errs, mset);
1352 	if (errs)
1353 		goto out;
1354 
1355 	for (j = 0; j < MAGIC_SETS; j++) {
1356 		/* Set types of tests */
1357 		for (i = 0; i < mset[j].count; ) {
1358 			if (mset[j].me[i].mp->cont_level != 0) {
1359 				i++;
1360 				continue;
1361 			}
1362 			i = set_text_binary(ms, mset[j].me, mset[j].count, i);
1363 		}
1364 		if (mset[j].me)
1365 			qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
1366 			    apprentice_sort);
1367 
1368 		/*
1369 		 * Make sure that any level 0 "default" line is last
1370 		 * (if one exists).
1371 		 */
1372 		set_last_default(ms, mset[j].me, mset[j].count);
1373 
1374 		/* coalesce per file arrays into a single one */
1375 		if (coalesce_entries(ms, mset[j].me, mset[j].count,
1376 		    &map->magic[j], &map->nmagic[j]) == -1) {
1377 			errs++;
1378 			goto out;
1379 		}
1380 	}
1381 
1382 out:
1383 	for (j = 0; j < MAGIC_SETS; j++)
1384 		magic_entry_free(mset[j].me, mset[j].count);
1385 
1386 	if (errs) {
1387 		apprentice_unmap(map);
1388 		return NULL;
1389 	}
1390 	return map;
1391 }
1392 
1393 /*
1394  * extend the sign bit if the comparison is to be signed
1395  */
1396 protected uint64_t
1397 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
1398 {
1399 	if (!(m->flag & UNSIGNED)) {
1400 		switch(m->type) {
1401 		/*
1402 		 * Do not remove the casts below.  They are
1403 		 * vital.  When later compared with the data,
1404 		 * the sign extension must have happened.
1405 		 */
1406 		case FILE_BYTE:
1407 			v = (signed char) v;
1408 			break;
1409 		case FILE_SHORT:
1410 		case FILE_BESHORT:
1411 		case FILE_LESHORT:
1412 			v = (short) v;
1413 			break;
1414 		case FILE_DATE:
1415 		case FILE_BEDATE:
1416 		case FILE_LEDATE:
1417 		case FILE_MEDATE:
1418 		case FILE_LDATE:
1419 		case FILE_BELDATE:
1420 		case FILE_LELDATE:
1421 		case FILE_MELDATE:
1422 		case FILE_LONG:
1423 		case FILE_BELONG:
1424 		case FILE_LELONG:
1425 		case FILE_MELONG:
1426 		case FILE_FLOAT:
1427 		case FILE_BEFLOAT:
1428 		case FILE_LEFLOAT:
1429 			v = (int32_t) v;
1430 			break;
1431 		case FILE_QUAD:
1432 		case FILE_BEQUAD:
1433 		case FILE_LEQUAD:
1434 		case FILE_QDATE:
1435 		case FILE_QLDATE:
1436 		case FILE_QWDATE:
1437 		case FILE_BEQDATE:
1438 		case FILE_BEQLDATE:
1439 		case FILE_BEQWDATE:
1440 		case FILE_LEQDATE:
1441 		case FILE_LEQLDATE:
1442 		case FILE_LEQWDATE:
1443 		case FILE_DOUBLE:
1444 		case FILE_BEDOUBLE:
1445 		case FILE_LEDOUBLE:
1446 			v = (int64_t) v;
1447 			break;
1448 		case FILE_STRING:
1449 		case FILE_PSTRING:
1450 		case FILE_BESTRING16:
1451 		case FILE_LESTRING16:
1452 		case FILE_REGEX:
1453 		case FILE_SEARCH:
1454 		case FILE_DEFAULT:
1455 		case FILE_INDIRECT:
1456 		case FILE_NAME:
1457 		case FILE_USE:
1458 		case FILE_CLEAR:
1459 		case FILE_DER:
1460 			break;
1461 		default:
1462 			if (ms->flags & MAGIC_CHECK)
1463 			    file_magwarn(ms, "cannot happen: m->type=%d\n",
1464 				    m->type);
1465 			return ~0U;
1466 		}
1467 	}
1468 	return v;
1469 }
1470 
1471 private int
1472 string_modifier_check(struct magic_set *ms, struct magic *m)
1473 {
1474 	if ((ms->flags & MAGIC_CHECK) == 0)
1475 		return 0;
1476 
1477 	if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
1478 	    (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
1479 		file_magwarn(ms,
1480 		    "'/BHhLl' modifiers are only allowed for pascal strings\n");
1481 		return -1;
1482 	}
1483 	switch (m->type) {
1484 	case FILE_BESTRING16:
1485 	case FILE_LESTRING16:
1486 		if (m->str_flags != 0) {
1487 			file_magwarn(ms,
1488 			    "no modifiers allowed for 16-bit strings\n");
1489 			return -1;
1490 		}
1491 		break;
1492 	case FILE_STRING:
1493 	case FILE_PSTRING:
1494 		if ((m->str_flags & REGEX_OFFSET_START) != 0) {
1495 			file_magwarn(ms,
1496 			    "'/%c' only allowed on regex and search\n",
1497 			    CHAR_REGEX_OFFSET_START);
1498 			return -1;
1499 		}
1500 		break;
1501 	case FILE_SEARCH:
1502 		if (m->str_range == 0) {
1503 			file_magwarn(ms,
1504 			    "missing range; defaulting to %d\n",
1505                             STRING_DEFAULT_RANGE);
1506 			m->str_range = STRING_DEFAULT_RANGE;
1507 			return -1;
1508 		}
1509 		break;
1510 	case FILE_REGEX:
1511 		if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
1512 			file_magwarn(ms, "'/%c' not allowed on regex\n",
1513 			    CHAR_COMPACT_WHITESPACE);
1514 			return -1;
1515 		}
1516 		if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
1517 			file_magwarn(ms, "'/%c' not allowed on regex\n",
1518 			    CHAR_COMPACT_OPTIONAL_WHITESPACE);
1519 			return -1;
1520 		}
1521 		break;
1522 	default:
1523 		file_magwarn(ms, "coding error: m->type=%d\n",
1524 		    m->type);
1525 		return -1;
1526 	}
1527 	return 0;
1528 }
1529 
1530 private int
1531 get_op(char c)
1532 {
1533 	switch (c) {
1534 	case '&':
1535 		return FILE_OPAND;
1536 	case '|':
1537 		return FILE_OPOR;
1538 	case '^':
1539 		return FILE_OPXOR;
1540 	case '+':
1541 		return FILE_OPADD;
1542 	case '-':
1543 		return FILE_OPMINUS;
1544 	case '*':
1545 		return FILE_OPMULTIPLY;
1546 	case '/':
1547 		return FILE_OPDIVIDE;
1548 	case '%':
1549 		return FILE_OPMODULO;
1550 	default:
1551 		return -1;
1552 	}
1553 }
1554 
1555 #ifdef ENABLE_CONDITIONALS
1556 private int
1557 get_cond(const char *l, const char **t)
1558 {
1559 	static const struct cond_tbl_s {
1560 		char name[8];
1561 		size_t len;
1562 		int cond;
1563 	} cond_tbl[] = {
1564 		{ "if",		2,	COND_IF },
1565 		{ "elif",	4,	COND_ELIF },
1566 		{ "else",	4,	COND_ELSE },
1567 		{ "",		0,	COND_NONE },
1568 	};
1569 	const struct cond_tbl_s *p;
1570 
1571 	for (p = cond_tbl; p->len; p++) {
1572 		if (strncmp(l, p->name, p->len) == 0 &&
1573 		    isspace((unsigned char)l[p->len])) {
1574 			if (t)
1575 				*t = l + p->len;
1576 			break;
1577 		}
1578 	}
1579 	return p->cond;
1580 }
1581 
1582 private int
1583 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1584 {
1585 	int last_cond;
1586 	last_cond = ms->c.li[cont_level].last_cond;
1587 
1588 	switch (cond) {
1589 	case COND_IF:
1590 		if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1591 			if (ms->flags & MAGIC_CHECK)
1592 				file_magwarn(ms, "syntax error: `if'");
1593 			return -1;
1594 		}
1595 		last_cond = COND_IF;
1596 		break;
1597 
1598 	case COND_ELIF:
1599 		if (last_cond != COND_IF && last_cond != COND_ELIF) {
1600 			if (ms->flags & MAGIC_CHECK)
1601 				file_magwarn(ms, "syntax error: `elif'");
1602 			return -1;
1603 		}
1604 		last_cond = COND_ELIF;
1605 		break;
1606 
1607 	case COND_ELSE:
1608 		if (last_cond != COND_IF && last_cond != COND_ELIF) {
1609 			if (ms->flags & MAGIC_CHECK)
1610 				file_magwarn(ms, "syntax error: `else'");
1611 			return -1;
1612 		}
1613 		last_cond = COND_NONE;
1614 		break;
1615 
1616 	case COND_NONE:
1617 		last_cond = COND_NONE;
1618 		break;
1619 	}
1620 
1621 	ms->c.li[cont_level].last_cond = last_cond;
1622 	return 0;
1623 }
1624 #endif /* ENABLE_CONDITIONALS */
1625 
1626 private int
1627 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1628 {
1629 	const char *l = *lp;
1630 
1631 	while (!isspace((unsigned char)*++l))
1632 		switch (*l) {
1633 		case CHAR_INDIRECT_RELATIVE:
1634 			m->str_flags |= INDIRECT_RELATIVE;
1635 			break;
1636 		default:
1637 			if (ms->flags & MAGIC_CHECK)
1638 				file_magwarn(ms, "indirect modifier `%c' "
1639 					"invalid", *l);
1640 			*lp = l;
1641 			return -1;
1642 		}
1643 	*lp = l;
1644 	return 0;
1645 }
1646 
1647 private void
1648 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
1649     int op)
1650 {
1651 	const char *l = *lp;
1652 	char *t;
1653 	uint64_t val;
1654 
1655 	++l;
1656 	m->mask_op |= op;
1657 	val = (uint64_t)strtoull(l, &t, 0);
1658 	l = t;
1659 	m->num_mask = file_signextend(ms, m, val);
1660 	eatsize(&l);
1661 	*lp = l;
1662 }
1663 
1664 private int
1665 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1666 {
1667 	const char *l = *lp;
1668 	char *t;
1669 	int have_range = 0;
1670 
1671 	while (!isspace((unsigned char)*++l)) {
1672 		switch (*l) {
1673 		case '0':  case '1':  case '2':
1674 		case '3':  case '4':  case '5':
1675 		case '6':  case '7':  case '8':
1676 		case '9':
1677 			if (have_range && (ms->flags & MAGIC_CHECK))
1678 				file_magwarn(ms, "multiple ranges");
1679 			have_range = 1;
1680 			m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
1681 			if (m->str_range == 0)
1682 				file_magwarn(ms, "zero range");
1683 			l = t - 1;
1684 			break;
1685 		case CHAR_COMPACT_WHITESPACE:
1686 			m->str_flags |= STRING_COMPACT_WHITESPACE;
1687 			break;
1688 		case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1689 			m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
1690 			break;
1691 		case CHAR_IGNORE_LOWERCASE:
1692 			m->str_flags |= STRING_IGNORE_LOWERCASE;
1693 			break;
1694 		case CHAR_IGNORE_UPPERCASE:
1695 			m->str_flags |= STRING_IGNORE_UPPERCASE;
1696 			break;
1697 		case CHAR_REGEX_OFFSET_START:
1698 			m->str_flags |= REGEX_OFFSET_START;
1699 			break;
1700 		case CHAR_BINTEST:
1701 			m->str_flags |= STRING_BINTEST;
1702 			break;
1703 		case CHAR_TEXTTEST:
1704 			m->str_flags |= STRING_TEXTTEST;
1705 			break;
1706 		case CHAR_TRIM:
1707 			m->str_flags |= STRING_TRIM;
1708 			break;
1709 		case CHAR_PSTRING_1_LE:
1710 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
1711 			if (m->type != FILE_PSTRING)
1712 				goto bad;
1713 			SET_LENGTH(PSTRING_1_LE);
1714 			break;
1715 		case CHAR_PSTRING_2_BE:
1716 			if (m->type != FILE_PSTRING)
1717 				goto bad;
1718 			SET_LENGTH(PSTRING_2_BE);
1719 			break;
1720 		case CHAR_PSTRING_2_LE:
1721 			if (m->type != FILE_PSTRING)
1722 				goto bad;
1723 			SET_LENGTH(PSTRING_2_LE);
1724 			break;
1725 		case CHAR_PSTRING_4_BE:
1726 			if (m->type != FILE_PSTRING)
1727 				goto bad;
1728 			SET_LENGTH(PSTRING_4_BE);
1729 			break;
1730 		case CHAR_PSTRING_4_LE:
1731 			switch (m->type) {
1732 			case FILE_PSTRING:
1733 			case FILE_REGEX:
1734 				break;
1735 			default:
1736 				goto bad;
1737 			}
1738 			SET_LENGTH(PSTRING_4_LE);
1739 			break;
1740 		case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
1741 			if (m->type != FILE_PSTRING)
1742 				goto bad;
1743 			m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
1744 			break;
1745 		default:
1746 		bad:
1747 			if (ms->flags & MAGIC_CHECK)
1748 				file_magwarn(ms, "string modifier `%c' "
1749 					"invalid", *l);
1750 			goto out;
1751 		}
1752 		/* allow multiple '/' for readability */
1753 		if (l[1] == '/' && !isspace((unsigned char)l[2]))
1754 			l++;
1755 	}
1756 	if (string_modifier_check(ms, m) == -1)
1757 		goto out;
1758 	*lp = l;
1759 	return 0;
1760 out:
1761 	*lp = l;
1762 	return -1;
1763 }
1764 
1765 /*
1766  * parse one line from magic file, put into magic[index++] if valid
1767  */
1768 private int
1769 parse(struct magic_set *ms, struct magic_entry *me, const char *line,
1770     size_t lineno, int action)
1771 {
1772 #ifdef ENABLE_CONDITIONALS
1773 	static uint32_t last_cont_level = 0;
1774 #endif
1775 	size_t i;
1776 	struct magic *m;
1777 	const char *l = line;
1778 	char *t;
1779 	int op;
1780 	uint32_t cont_level;
1781 	int32_t diff;
1782 
1783 	cont_level = 0;
1784 
1785 	/*
1786 	 * Parse the offset.
1787 	 */
1788 	while (*l == '>') {
1789 		++l;		/* step over */
1790 		cont_level++;
1791 	}
1792 #ifdef ENABLE_CONDITIONALS
1793 	if (cont_level == 0 || cont_level > last_cont_level)
1794 		if (file_check_mem(ms, cont_level) == -1)
1795 			return -1;
1796 	last_cont_level = cont_level;
1797 #endif
1798 	if (cont_level != 0) {
1799 		if (me->mp == NULL) {
1800 			file_magerror(ms, "No current entry for continuation");
1801 			return -1;
1802 		}
1803 		if (me->cont_count == 0) {
1804 			file_magerror(ms, "Continuations present with 0 count");
1805 			return -1;
1806 		}
1807 		m = &me->mp[me->cont_count - 1];
1808 		diff = (int32_t)cont_level - (int32_t)m->cont_level;
1809 		if (diff > 1)
1810 			file_magwarn(ms, "New continuation level %u is more "
1811 			    "than one larger than current level %u", cont_level,
1812 			    m->cont_level);
1813 		if (me->cont_count == me->max_count) {
1814 			struct magic *nm;
1815 			size_t cnt = me->max_count + ALLOC_CHUNK;
1816 			if ((nm = CAST(struct magic *, realloc(me->mp,
1817 			    sizeof(*nm) * cnt))) == NULL) {
1818 				file_oomem(ms, sizeof(*nm) * cnt);
1819 				return -1;
1820 			}
1821 			me->mp = m = nm;
1822 			me->max_count = CAST(uint32_t, cnt);
1823 		}
1824 		m = &me->mp[me->cont_count++];
1825 		(void)memset(m, 0, sizeof(*m));
1826 		m->cont_level = cont_level;
1827 	} else {
1828 		static const size_t len = sizeof(*m) * ALLOC_CHUNK;
1829 		if (me->mp != NULL)
1830 			return 1;
1831 		if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1832 			file_oomem(ms, len);
1833 			return -1;
1834 		}
1835 		me->mp = m;
1836 		me->max_count = ALLOC_CHUNK;
1837 		(void)memset(m, 0, sizeof(*m));
1838 		m->factor_op = FILE_FACTOR_OP_NONE;
1839 		m->cont_level = 0;
1840 		me->cont_count = 1;
1841 	}
1842 	m->lineno = CAST(uint32_t, lineno);
1843 
1844 	if (*l == '&') {  /* m->cont_level == 0 checked below. */
1845                 ++l;            /* step over */
1846                 m->flag |= OFFADD;
1847         }
1848 	if (*l == '(') {
1849 		++l;		/* step over */
1850 		m->flag |= INDIR;
1851 		if (m->flag & OFFADD)
1852 			m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1853 
1854 		if (*l == '&') {  /* m->cont_level == 0 checked below */
1855 			++l;            /* step over */
1856 			m->flag |= OFFADD;
1857 		}
1858 	}
1859 	/* Indirect offsets are not valid at level 0. */
1860 	if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
1861 		if (ms->flags & MAGIC_CHECK)
1862 			file_magwarn(ms, "relative offset at level 0");
1863 		return -1;
1864 	}
1865 
1866 	/* get offset, then skip over it */
1867 	m->offset = (uint32_t)strtoul(l, &t, 0);
1868         if (l == t) {
1869 		if (ms->flags & MAGIC_CHECK)
1870 			file_magwarn(ms, "offset `%s' invalid", l);
1871 		return -1;
1872 	}
1873         l = t;
1874 
1875 	if (m->flag & INDIR) {
1876 		m->in_type = FILE_LONG;
1877 		m->in_offset = 0;
1878 		m->in_op = 0;
1879 		/*
1880 		 * read [.,lbs][+-]nnnnn)
1881 		 */
1882 		if (*l == '.' || *l == ',') {
1883 			if (*l == ',')
1884 				m->in_op |= FILE_OPSIGNED;
1885 			l++;
1886 			switch (*l) {
1887 			case 'l':
1888 				m->in_type = FILE_LELONG;
1889 				break;
1890 			case 'L':
1891 				m->in_type = FILE_BELONG;
1892 				break;
1893 			case 'm':
1894 				m->in_type = FILE_MELONG;
1895 				break;
1896 			case 'h':
1897 			case 's':
1898 				m->in_type = FILE_LESHORT;
1899 				break;
1900 			case 'H':
1901 			case 'S':
1902 				m->in_type = FILE_BESHORT;
1903 				break;
1904 			case 'c':
1905 			case 'b':
1906 			case 'C':
1907 			case 'B':
1908 				m->in_type = FILE_BYTE;
1909 				break;
1910 			case 'e':
1911 			case 'f':
1912 			case 'g':
1913 				m->in_type = FILE_LEDOUBLE;
1914 				break;
1915 			case 'E':
1916 			case 'F':
1917 			case 'G':
1918 				m->in_type = FILE_BEDOUBLE;
1919 				break;
1920 			case 'i':
1921 				m->in_type = FILE_LEID3;
1922 				break;
1923 			case 'I':
1924 				m->in_type = FILE_BEID3;
1925 				break;
1926 			default:
1927 				if (ms->flags & MAGIC_CHECK)
1928 					file_magwarn(ms,
1929 					    "indirect offset type `%c' invalid",
1930 					    *l);
1931 				return -1;
1932 			}
1933 			l++;
1934 		}
1935 
1936 		if (*l == '~') {
1937 			m->in_op |= FILE_OPINVERSE;
1938 			l++;
1939 		}
1940 		if ((op = get_op(*l)) != -1) {
1941 			m->in_op |= op;
1942 			l++;
1943 		}
1944 		if (*l == '(') {
1945 			m->in_op |= FILE_OPINDIRECT;
1946 			l++;
1947 		}
1948 		if (isdigit((unsigned char)*l) || *l == '-') {
1949 			m->in_offset = (int32_t)strtol(l, &t, 0);
1950 			if (l == t) {
1951 				if (ms->flags & MAGIC_CHECK)
1952 					file_magwarn(ms,
1953 					    "in_offset `%s' invalid", l);
1954 				return -1;
1955 			}
1956 			l = t;
1957 		}
1958 		if (*l++ != ')' ||
1959 		    ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
1960 			if (ms->flags & MAGIC_CHECK)
1961 				file_magwarn(ms,
1962 				    "missing ')' in indirect offset");
1963 			return -1;
1964 		}
1965 	}
1966 	EATAB;
1967 
1968 #ifdef ENABLE_CONDITIONALS
1969 	m->cond = get_cond(l, &l);
1970 	if (check_cond(ms, m->cond, cont_level) == -1)
1971 		return -1;
1972 
1973 	EATAB;
1974 #endif
1975 
1976 	/*
1977 	 * Parse the type.
1978 	 */
1979 	if (*l == 'u') {
1980 		/*
1981 		 * Try it as a keyword type prefixed by "u"; match what
1982 		 * follows the "u".  If that fails, try it as an SUS
1983 		 * integer type.
1984 		 */
1985 		m->type = get_type(type_tbl, l + 1, &l);
1986 		if (m->type == FILE_INVALID) {
1987 			/*
1988 			 * Not a keyword type; parse it as an SUS type,
1989 			 * 'u' possibly followed by a number or C/S/L.
1990 			 */
1991 			m->type = get_standard_integer_type(l, &l);
1992 		}
1993 		/* It's unsigned. */
1994 		if (m->type != FILE_INVALID)
1995 			m->flag |= UNSIGNED;
1996 	} else {
1997 		/*
1998 		 * Try it as a keyword type.  If that fails, try it as
1999 		 * an SUS integer type if it begins with "d" or as an
2000 		 * SUS string type if it begins with "s".  In any case,
2001 		 * it's not unsigned.
2002 		 */
2003 		m->type = get_type(type_tbl, l, &l);
2004 		if (m->type == FILE_INVALID) {
2005 			/*
2006 			 * Not a keyword type; parse it as an SUS type,
2007 			 * either 'd' possibly followed by a number or
2008 			 * C/S/L, or just 's'.
2009 			 */
2010 			if (*l == 'd')
2011 				m->type = get_standard_integer_type(l, &l);
2012 			else if (*l == 's' && !isalpha((unsigned char)l[1])) {
2013 				m->type = FILE_STRING;
2014 				++l;
2015 			}
2016 		}
2017 	}
2018 
2019 	if (m->type == FILE_INVALID) {
2020 		/* Not found - try it as a special keyword. */
2021 		m->type = get_type(special_tbl, l, &l);
2022 	}
2023 
2024 	if (m->type == FILE_INVALID) {
2025 		if (ms->flags & MAGIC_CHECK)
2026 			file_magwarn(ms, "type `%s' invalid", l);
2027 		return -1;
2028 	}
2029 
2030 	/* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
2031 	/* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
2032 
2033 	m->mask_op = 0;
2034 	if (*l == '~') {
2035 		if (!IS_STRING(m->type))
2036 			m->mask_op |= FILE_OPINVERSE;
2037 		else if (ms->flags & MAGIC_CHECK)
2038 			file_magwarn(ms, "'~' invalid for string types");
2039 		++l;
2040 	}
2041 	m->str_range = 0;
2042 	m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
2043 	if ((op = get_op(*l)) != -1) {
2044 		if (IS_STRING(m->type)) {
2045 			int r;
2046 
2047 			if (op != FILE_OPDIVIDE) {
2048 				if (ms->flags & MAGIC_CHECK)
2049 					file_magwarn(ms,
2050 					    "invalid string/indirect op: "
2051 					    "`%c'", *t);
2052 				return -1;
2053 			}
2054 
2055 			if (m->type == FILE_INDIRECT)
2056 				r = parse_indirect_modifier(ms, m, &l);
2057 			else
2058 				r = parse_string_modifier(ms, m, &l);
2059 			if (r == -1)
2060 				return -1;
2061 		} else
2062 			parse_op_modifier(ms, m, &l, op);
2063 	}
2064 
2065 	/*
2066 	 * We used to set mask to all 1's here, instead let's just not do
2067 	 * anything if mask = 0 (unless you have a better idea)
2068 	 */
2069 	EATAB;
2070 
2071 	switch (*l) {
2072 	case '>':
2073 	case '<':
2074   		m->reln = *l;
2075   		++l;
2076 		if (*l == '=') {
2077 			if (ms->flags & MAGIC_CHECK) {
2078 				file_magwarn(ms, "%c= not supported",
2079 				    m->reln);
2080 				return -1;
2081 			}
2082 		   ++l;
2083 		}
2084 		break;
2085 	/* Old-style anding: "0 byte &0x80 dynamically linked" */
2086 	case '&':
2087 	case '^':
2088 	case '=':
2089   		m->reln = *l;
2090   		++l;
2091 		if (*l == '=') {
2092 		   /* HP compat: ignore &= etc. */
2093 		   ++l;
2094 		}
2095 		break;
2096 	case '!':
2097 		m->reln = *l;
2098 		++l;
2099 		break;
2100 	default:
2101   		m->reln = '=';	/* the default relation */
2102 		if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
2103 		    isspace((unsigned char)l[1])) || !l[1])) {
2104 			m->reln = *l;
2105 			++l;
2106 		}
2107 		break;
2108 	}
2109 	/*
2110 	 * Grab the value part, except for an 'x' reln.
2111 	 */
2112 	if (m->reln != 'x' && getvalue(ms, m, &l, action))
2113 		return -1;
2114 
2115 	/*
2116 	 * TODO finish this macro and start using it!
2117 	 * #define offsetcheck {if (offset > ms->bytes_max -1)
2118 	 *	magwarn("offset too big"); }
2119 	 */
2120 
2121 	/*
2122 	 * Now get last part - the description
2123 	 */
2124 	EATAB;
2125 	if (l[0] == '\b') {
2126 		++l;
2127 		m->flag |= NOSPACE;
2128 	} else if ((l[0] == '\\') && (l[1] == 'b')) {
2129 		++l;
2130 		++l;
2131 		m->flag |= NOSPACE;
2132 	}
2133 	for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
2134 		continue;
2135 	if (i == sizeof(m->desc)) {
2136 		m->desc[sizeof(m->desc) - 1] = '\0';
2137 		if (ms->flags & MAGIC_CHECK)
2138 			file_magwarn(ms, "description `%s' truncated", m->desc);
2139 	}
2140 
2141         /*
2142 	 * We only do this check while compiling, or if any of the magic
2143 	 * files were not compiled.
2144          */
2145         if (ms->flags & MAGIC_CHECK) {
2146 		if (check_format(ms, m) == -1)
2147 			return -1;
2148 	}
2149 #ifndef COMPILE_ONLY
2150 	if (action == FILE_CHECK) {
2151 		file_mdump(m);
2152 	}
2153 #endif
2154 	m->mimetype[0] = '\0';		/* initialise MIME type to none */
2155 	return 0;
2156 }
2157 
2158 /*
2159  * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
2160  * if valid
2161  */
2162 private int
2163 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
2164 {
2165 	const char *l = line;
2166 	char *el;
2167 	unsigned long factor;
2168 	struct magic *m = &me->mp[0];
2169 
2170 	if (m->factor_op != FILE_FACTOR_OP_NONE) {
2171 		file_magwarn(ms,
2172 		    "Current entry already has a strength type: %c %d",
2173 		    m->factor_op, m->factor);
2174 		return -1;
2175 	}
2176 	if (m->type == FILE_NAME) {
2177 		file_magwarn(ms, "%s: Strength setting is not supported in "
2178 		    "\"name\" magic entries", m->value.s);
2179 		return -1;
2180 	}
2181 	EATAB;
2182 	switch (*l) {
2183 	case FILE_FACTOR_OP_NONE:
2184 	case FILE_FACTOR_OP_PLUS:
2185 	case FILE_FACTOR_OP_MINUS:
2186 	case FILE_FACTOR_OP_TIMES:
2187 	case FILE_FACTOR_OP_DIV:
2188 		m->factor_op = *l++;
2189 		break;
2190 	default:
2191 		file_magwarn(ms, "Unknown factor op `%c'", *l);
2192 		return -1;
2193 	}
2194 	EATAB;
2195 	factor = strtoul(l, &el, 0);
2196 	if (factor > 255) {
2197 		file_magwarn(ms, "Too large factor `%lu'", factor);
2198 		goto out;
2199 	}
2200 	if (*el && !isspace((unsigned char)*el)) {
2201 		file_magwarn(ms, "Bad factor `%s'", l);
2202 		goto out;
2203 	}
2204 	m->factor = (uint8_t)factor;
2205 	if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
2206 		file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
2207 		    m->factor_op, m->factor);
2208 		goto out;
2209 	}
2210 	return 0;
2211 out:
2212 	m->factor_op = FILE_FACTOR_OP_NONE;
2213 	m->factor = 0;
2214 	return -1;
2215 }
2216 
2217 private int
2218 goodchar(unsigned char x, const char *extra)
2219 {
2220 	return (isascii(x) && isalnum(x)) || strchr(extra, x);
2221 }
2222 
2223 private int
2224 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
2225     off_t off, size_t len, const char *name, const char *extra, int nt)
2226 {
2227 	size_t i;
2228 	const char *l = line;
2229 	struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
2230 	char *buf = CAST(char *, CAST(void *, m)) + off;
2231 
2232 	if (buf[0] != '\0') {
2233 		len = nt ? strlen(buf) : len;
2234 		file_magwarn(ms, "Current entry already has a %s type "
2235 		    "`%.*s', new type `%s'", name, (int)len, buf, l);
2236 		return -1;
2237 	}
2238 
2239 	if (*m->desc == '\0') {
2240 		file_magwarn(ms, "Current entry does not yet have a "
2241 		    "description for adding a %s type", name);
2242 		return -1;
2243 	}
2244 
2245 	EATAB;
2246 	for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
2247 		continue;
2248 
2249 	if (i == len && *l) {
2250 		if (nt)
2251 			buf[len - 1] = '\0';
2252 		if (ms->flags & MAGIC_CHECK)
2253 			file_magwarn(ms, "%s type `%s' truncated %"
2254 			    SIZE_T_FORMAT "u", name, line, i);
2255 	} else {
2256 		if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
2257 			file_magwarn(ms, "%s type `%s' has bad char '%c'",
2258 			    name, line, *l);
2259 		if (nt)
2260 			buf[i] = '\0';
2261 	}
2262 
2263 	if (i > 0)
2264 		return 0;
2265 
2266 	file_magerror(ms, "Bad magic entry '%s'", line);
2267 	return -1;
2268 }
2269 
2270 /*
2271  * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
2272  * magic[index - 1]
2273  */
2274 private int
2275 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
2276 {
2277 	struct magic *m = &me->mp[0];
2278 
2279 	return parse_extra(ms, me, line,
2280 	    CAST(off_t, offsetof(struct magic, apple)),
2281 	    sizeof(m->apple), "APPLE", "!+-./?", 0);
2282 }
2283 
2284 /*
2285  * Parse a comma-separated list of extensions
2286  */
2287 private int
2288 parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line)
2289 {
2290 	struct magic *m = &me->mp[0];
2291 
2292 	return parse_extra(ms, me, line,
2293 	    CAST(off_t, offsetof(struct magic, ext)),
2294 	    sizeof(m->ext), "EXTENSION", ",!+-/", 0);
2295 }
2296 
2297 /*
2298  * parse a MIME annotation line from magic file, put into magic[index - 1]
2299  * if valid
2300  */
2301 private int
2302 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
2303 {
2304 	struct magic *m = &me->mp[0];
2305 
2306 	return parse_extra(ms, me, line,
2307 	    CAST(off_t, offsetof(struct magic, mimetype)),
2308 	    sizeof(m->mimetype), "MIME", "+-/.", 1);
2309 }
2310 
2311 private int
2312 check_format_type(const char *ptr, int type, const char **estr)
2313 {
2314 	int quad = 0, h;
2315 	size_t len, cnt;
2316 	if (*ptr == '\0') {
2317 		/* Missing format string; bad */
2318 		*estr = "missing format spec";
2319 		return -1;
2320 	}
2321 
2322 	switch (file_formats[type]) {
2323 	case FILE_FMT_QUAD:
2324 		quad = 1;
2325 		/*FALLTHROUGH*/
2326 	case FILE_FMT_NUM:
2327 		if (quad == 0) {
2328 			switch (type) {
2329 			case FILE_BYTE:
2330 				h = 2;
2331 				break;
2332 			case FILE_SHORT:
2333 			case FILE_BESHORT:
2334 			case FILE_LESHORT:
2335 				h = 1;
2336 				break;
2337 			case FILE_LONG:
2338 			case FILE_BELONG:
2339 			case FILE_LELONG:
2340 			case FILE_MELONG:
2341 			case FILE_LEID3:
2342 			case FILE_BEID3:
2343 			case FILE_INDIRECT:
2344 				h = 0;
2345 				break;
2346 			default:
2347 				abort();
2348 			}
2349 		} else
2350 			h = 0;
2351 		if (*ptr == '-')
2352 			ptr++;
2353 		if (*ptr == '.')
2354 			ptr++;
2355 #define CHECKLEN() do { \
2356 	for (len = cnt = 0; isdigit((unsigned char)*ptr); ptr++, cnt++) \
2357 		len = len * 10 + (*ptr - '0'); \
2358 	if (cnt > 5 || len > 1024) \
2359 		goto toolong; \
2360 } while (/*CONSTCOND*/0)
2361 
2362 		CHECKLEN();
2363 		if (*ptr == '.')
2364 			ptr++;
2365 		CHECKLEN();
2366 		if (quad) {
2367 			if (*ptr++ != 'l')
2368 				goto invalid;
2369 			if (*ptr++ != 'l')
2370 				goto invalid;
2371 		}
2372 
2373 		switch (*ptr++) {
2374 #ifdef STRICT_FORMAT 	/* "long" formats are int formats for us */
2375 		/* so don't accept the 'l' modifier */
2376 		case 'l':
2377 			switch (*ptr++) {
2378 			case 'i':
2379 			case 'd':
2380 			case 'u':
2381 			case 'o':
2382 			case 'x':
2383 			case 'X':
2384 				if (h == 0)
2385 					return 0;
2386 				/*FALLTHROUGH*/
2387 			default:
2388 				goto invalid;
2389 			}
2390 
2391 		/*
2392 		 * Don't accept h and hh modifiers. They make writing
2393 		 * magic entries more complicated, for very little benefit
2394 		 */
2395 		case 'h':
2396 			if (h-- <= 0)
2397 				goto invalid;
2398 			switch (*ptr++) {
2399 			case 'h':
2400 				if (h-- <= 0)
2401 					goto invalid;
2402 				switch (*ptr++) {
2403 				case 'i':
2404 				case 'd':
2405 				case 'u':
2406 				case 'o':
2407 				case 'x':
2408 				case 'X':
2409 					return 0;
2410 				default:
2411 					goto invalid;
2412 				}
2413 			case 'i':
2414 			case 'd':
2415 			case 'u':
2416 			case 'o':
2417 			case 'x':
2418 			case 'X':
2419 				if (h == 0)
2420 					return 0;
2421 				/*FALLTHROUGH*/
2422 			default:
2423 				goto invalid;
2424 			}
2425 #endif
2426 		case 'c':
2427 			if (h == 2)
2428 				return 0;
2429 			goto invalid;
2430 		case 'i':
2431 		case 'd':
2432 		case 'u':
2433 		case 'o':
2434 		case 'x':
2435 		case 'X':
2436 #ifdef STRICT_FORMAT
2437 			if (h == 0)
2438 				return 0;
2439 			/*FALLTHROUGH*/
2440 #else
2441 			return 0;
2442 #endif
2443 		default:
2444 			goto invalid;
2445 		}
2446 
2447 	case FILE_FMT_FLOAT:
2448 	case FILE_FMT_DOUBLE:
2449 		if (*ptr == '-')
2450 			ptr++;
2451 		if (*ptr == '.')
2452 			ptr++;
2453 		CHECKLEN();
2454 		if (*ptr == '.')
2455 			ptr++;
2456 		CHECKLEN();
2457 		switch (*ptr++) {
2458 		case 'e':
2459 		case 'E':
2460 		case 'f':
2461 		case 'F':
2462 		case 'g':
2463 		case 'G':
2464 			return 0;
2465 
2466 		default:
2467 			goto invalid;
2468 		}
2469 
2470 
2471 	case FILE_FMT_STR:
2472 		if (*ptr == '-')
2473 			ptr++;
2474 		while (isdigit((unsigned char )*ptr))
2475 			ptr++;
2476 		if (*ptr == '.') {
2477 			ptr++;
2478 			while (isdigit((unsigned char )*ptr))
2479 				ptr++;
2480 		}
2481 
2482 		switch (*ptr++) {
2483 		case 's':
2484 			return 0;
2485 		default:
2486 			goto invalid;
2487 		}
2488 
2489 	default:
2490 		/* internal error */
2491 		abort();
2492 	}
2493 invalid:
2494 	*estr = "not valid";
2495 toolong:
2496 	*estr = "too long";
2497 	return -1;
2498 }
2499 
2500 /*
2501  * Check that the optional printf format in description matches
2502  * the type of the magic.
2503  */
2504 private int
2505 check_format(struct magic_set *ms, struct magic *m)
2506 {
2507 	char *ptr;
2508 	const char *estr;
2509 
2510 	for (ptr = m->desc; *ptr; ptr++)
2511 		if (*ptr == '%')
2512 			break;
2513 	if (*ptr == '\0') {
2514 		/* No format string; ok */
2515 		return 1;
2516 	}
2517 
2518 	assert(file_nformats == file_nnames);
2519 
2520 	if (m->type >= file_nformats) {
2521 		file_magwarn(ms, "Internal error inconsistency between "
2522 		    "m->type and format strings");
2523 		return -1;
2524 	}
2525 	if (file_formats[m->type] == FILE_FMT_NONE) {
2526 		file_magwarn(ms, "No format string for `%s' with description "
2527 		    "`%s'", m->desc, file_names[m->type]);
2528 		return -1;
2529 	}
2530 
2531 	ptr++;
2532 	if (check_format_type(ptr, m->type, &estr) == -1) {
2533 		/*
2534 		 * TODO: this error message is unhelpful if the format
2535 		 * string is not one character long
2536 		 */
2537 		file_magwarn(ms, "Printf format is %s for type "
2538 		    "`%s' in description `%s'", estr,
2539 		    file_names[m->type], m->desc);
2540 		return -1;
2541 	}
2542 
2543 	for (; *ptr; ptr++) {
2544 		if (*ptr == '%') {
2545 			file_magwarn(ms,
2546 			    "Too many format strings (should have at most one) "
2547 			    "for `%s' with description `%s'",
2548 			    file_names[m->type], m->desc);
2549 			return -1;
2550 		}
2551 	}
2552 	return 0;
2553 }
2554 
2555 /*
2556  * Read a numeric value from a pointer, into the value union of a magic
2557  * pointer, according to the magic type.  Update the string pointer to point
2558  * just after the number read.  Return 0 for success, non-zero for failure.
2559  */
2560 private int
2561 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
2562 {
2563 	switch (m->type) {
2564 	case FILE_BESTRING16:
2565 	case FILE_LESTRING16:
2566 	case FILE_STRING:
2567 	case FILE_PSTRING:
2568 	case FILE_REGEX:
2569 	case FILE_SEARCH:
2570 	case FILE_NAME:
2571 	case FILE_USE:
2572 	case FILE_DER:
2573 		*p = getstr(ms, m, *p, action == FILE_COMPILE);
2574 		if (*p == NULL) {
2575 			if (ms->flags & MAGIC_CHECK)
2576 				file_magwarn(ms, "cannot get string from `%s'",
2577 				    m->value.s);
2578 			return -1;
2579 		}
2580 		if (m->type == FILE_REGEX) {
2581 			file_regex_t rx;
2582 			int rc = file_regcomp(&rx, m->value.s, REG_EXTENDED);
2583 			if (rc) {
2584 				if (ms->flags & MAGIC_CHECK)
2585 					file_regerror(&rx, rc, ms);
2586 			}
2587 			file_regfree(&rx);
2588 			return rc ? -1 : 0;
2589 		}
2590 		return 0;
2591 	case FILE_FLOAT:
2592 	case FILE_BEFLOAT:
2593 	case FILE_LEFLOAT:
2594 		if (m->reln != 'x') {
2595 			char *ep;
2596 			errno = 0;
2597 #ifdef HAVE_STRTOF
2598 			m->value.f = strtof(*p, &ep);
2599 #else
2600 			m->value.f = (float)strtod(*p, &ep);
2601 #endif
2602 			if (errno == 0)
2603 				*p = ep;
2604 		}
2605 		return 0;
2606 	case FILE_DOUBLE:
2607 	case FILE_BEDOUBLE:
2608 	case FILE_LEDOUBLE:
2609 		if (m->reln != 'x') {
2610 			char *ep;
2611 			errno = 0;
2612 			m->value.d = strtod(*p, &ep);
2613 			if (errno == 0)
2614 				*p = ep;
2615 		}
2616 		return 0;
2617 	default:
2618 		if (m->reln != 'x') {
2619 			char *ep;
2620 			errno = 0;
2621 			m->value.q = file_signextend(ms, m,
2622 			    (uint64_t)strtoull(*p, &ep, 0));
2623 			if (errno == 0) {
2624 				*p = ep;
2625 				eatsize(p);
2626 			}
2627 		}
2628 		return 0;
2629 	}
2630 }
2631 
2632 /*
2633  * Convert a string containing C character escapes.  Stop at an unescaped
2634  * space or tab.
2635  * Copy the converted version to "m->value.s", and the length in m->vallen.
2636  * Return updated scan pointer as function result. Warn if set.
2637  */
2638 private const char *
2639 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
2640 {
2641 	const char *origs = s;
2642 	char	*p = m->value.s;
2643 	size_t  plen = sizeof(m->value.s);
2644 	char 	*origp = p;
2645 	char	*pmax = p + plen - 1;
2646 	int	c;
2647 	int	val;
2648 
2649 	while ((c = *s++) != '\0') {
2650 		if (isspace((unsigned char) c))
2651 			break;
2652 		if (p >= pmax) {
2653 			file_error(ms, 0, "string too long: `%s'", origs);
2654 			return NULL;
2655 		}
2656 		if (c == '\\') {
2657 			switch(c = *s++) {
2658 
2659 			case '\0':
2660 				if (warn)
2661 					file_magwarn(ms, "incomplete escape");
2662 				s--;
2663 				goto out;
2664 
2665 			case '\t':
2666 				if (warn) {
2667 					file_magwarn(ms,
2668 					    "escaped tab found, use \\t instead");
2669 					warn = 0;	/* already did */
2670 				}
2671 				/*FALLTHROUGH*/
2672 			default:
2673 				if (warn) {
2674 					if (isprint((unsigned char)c)) {
2675 						/* Allow escaping of
2676 						 * ``relations'' */
2677 						if (strchr("<>&^=!", c) == NULL
2678 						    && (m->type != FILE_REGEX ||
2679 						    strchr("[]().*?^$|{}", c)
2680 						    == NULL)) {
2681 							file_magwarn(ms, "no "
2682 							    "need to escape "
2683 							    "`%c'", c);
2684 						}
2685 					} else {
2686 						file_magwarn(ms,
2687 						    "unknown escape sequence: "
2688 						    "\\%03o", c);
2689 					}
2690 				}
2691 				/*FALLTHROUGH*/
2692 			/* space, perhaps force people to use \040? */
2693 			case ' ':
2694 #if 0
2695 			/*
2696 			 * Other things people escape, but shouldn't need to,
2697 			 * so we disallow them
2698 			 */
2699 			case '\'':
2700 			case '"':
2701 			case '?':
2702 #endif
2703 			/* Relations */
2704 			case '>':
2705 			case '<':
2706 			case '&':
2707 			case '^':
2708 			case '=':
2709 			case '!':
2710 			/* and baskslash itself */
2711 			case '\\':
2712 				*p++ = (char) c;
2713 				break;
2714 
2715 			case 'a':
2716 				*p++ = '\a';
2717 				break;
2718 
2719 			case 'b':
2720 				*p++ = '\b';
2721 				break;
2722 
2723 			case 'f':
2724 				*p++ = '\f';
2725 				break;
2726 
2727 			case 'n':
2728 				*p++ = '\n';
2729 				break;
2730 
2731 			case 'r':
2732 				*p++ = '\r';
2733 				break;
2734 
2735 			case 't':
2736 				*p++ = '\t';
2737 				break;
2738 
2739 			case 'v':
2740 				*p++ = '\v';
2741 				break;
2742 
2743 			/* \ and up to 3 octal digits */
2744 			case '0':
2745 			case '1':
2746 			case '2':
2747 			case '3':
2748 			case '4':
2749 			case '5':
2750 			case '6':
2751 			case '7':
2752 				val = c - '0';
2753 				c = *s++;  /* try for 2 */
2754 				if (c >= '0' && c <= '7') {
2755 					val = (val << 3) | (c - '0');
2756 					c = *s++;  /* try for 3 */
2757 					if (c >= '0' && c <= '7')
2758 						val = (val << 3) | (c-'0');
2759 					else
2760 						--s;
2761 				}
2762 				else
2763 					--s;
2764 				*p++ = (char)val;
2765 				break;
2766 
2767 			/* \x and up to 2 hex digits */
2768 			case 'x':
2769 				val = 'x';	/* Default if no digits */
2770 				c = hextoint(*s++);	/* Get next char */
2771 				if (c >= 0) {
2772 					val = c;
2773 					c = hextoint(*s++);
2774 					if (c >= 0)
2775 						val = (val << 4) + c;
2776 					else
2777 						--s;
2778 				} else
2779 					--s;
2780 				*p++ = (char)val;
2781 				break;
2782 			}
2783 		} else
2784 			*p++ = (char)c;
2785 	}
2786 	--s;
2787 out:
2788 	*p = '\0';
2789 	m->vallen = CAST(unsigned char, (p - origp));
2790 	if (m->type == FILE_PSTRING)
2791 		m->vallen += (unsigned char)file_pstring_length_size(m);
2792 	return s;
2793 }
2794 
2795 
2796 /* Single hex char to int; -1 if not a hex char. */
2797 private int
2798 hextoint(int c)
2799 {
2800 	if (!isascii((unsigned char) c))
2801 		return -1;
2802 	if (isdigit((unsigned char) c))
2803 		return c - '0';
2804 	if ((c >= 'a') && (c <= 'f'))
2805 		return c + 10 - 'a';
2806 	if (( c>= 'A') && (c <= 'F'))
2807 		return c + 10 - 'A';
2808 	return -1;
2809 }
2810 
2811 
2812 /*
2813  * Print a string containing C character escapes.
2814  */
2815 protected void
2816 file_showstr(FILE *fp, const char *s, size_t len)
2817 {
2818 	char	c;
2819 
2820 	for (;;) {
2821 		if (len == ~0U) {
2822 			c = *s++;
2823 			if (c == '\0')
2824 				break;
2825 		}
2826 		else  {
2827 			if (len-- == 0)
2828 				break;
2829 			c = *s++;
2830 		}
2831 		if (c >= 040 && c <= 0176)	/* TODO isprint && !iscntrl */
2832 			(void) fputc(c, fp);
2833 		else {
2834 			(void) fputc('\\', fp);
2835 			switch (c) {
2836 			case '\a':
2837 				(void) fputc('a', fp);
2838 				break;
2839 
2840 			case '\b':
2841 				(void) fputc('b', fp);
2842 				break;
2843 
2844 			case '\f':
2845 				(void) fputc('f', fp);
2846 				break;
2847 
2848 			case '\n':
2849 				(void) fputc('n', fp);
2850 				break;
2851 
2852 			case '\r':
2853 				(void) fputc('r', fp);
2854 				break;
2855 
2856 			case '\t':
2857 				(void) fputc('t', fp);
2858 				break;
2859 
2860 			case '\v':
2861 				(void) fputc('v', fp);
2862 				break;
2863 
2864 			default:
2865 				(void) fprintf(fp, "%.3o", c & 0377);
2866 				break;
2867 			}
2868 		}
2869 	}
2870 }
2871 
2872 /*
2873  * eatsize(): Eat the size spec from a number [eg. 10UL]
2874  */
2875 private void
2876 eatsize(const char **p)
2877 {
2878 	const char *l = *p;
2879 
2880 	if (LOWCASE(*l) == 'u')
2881 		l++;
2882 
2883 	switch (LOWCASE(*l)) {
2884 	case 'l':    /* long */
2885 	case 's':    /* short */
2886 	case 'h':    /* short */
2887 	case 'b':    /* char/byte */
2888 	case 'c':    /* char/byte */
2889 		l++;
2890 		/*FALLTHROUGH*/
2891 	default:
2892 		break;
2893 	}
2894 
2895 	*p = l;
2896 }
2897 
2898 /*
2899  * handle a buffer containing a compiled file.
2900  */
2901 private struct magic_map *
2902 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
2903 {
2904 	struct magic_map *map;
2905 
2906 	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2907 		file_oomem(ms, sizeof(*map));
2908 		return NULL;
2909 	}
2910 	map->len = len;
2911 	map->p = buf;
2912 	map->type = MAP_TYPE_USER;
2913 	if (check_buffer(ms, map, "buffer") != 0) {
2914 		apprentice_unmap(map);
2915 		return NULL;
2916 	}
2917 	return map;
2918 }
2919 
2920 /*
2921  * handle a compiled file.
2922  */
2923 
2924 private struct magic_map *
2925 apprentice_map(struct magic_set *ms, const char *fn)
2926 {
2927 	int fd;
2928 	struct stat st;
2929 	char *dbname = NULL;
2930 	struct magic_map *map;
2931 	struct magic_map *rv = NULL;
2932 
2933 	fd = -1;
2934 	if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2935 		file_oomem(ms, sizeof(*map));
2936 		goto error;
2937 	}
2938 	map->type = MAP_TYPE_USER;	/* unspecified */
2939 
2940 	dbname = mkdbname(ms, fn, 0);
2941 	if (dbname == NULL)
2942 		goto error;
2943 
2944 	if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2945 		goto error;
2946 
2947 	if (fstat(fd, &st) == -1) {
2948 		file_error(ms, errno, "cannot stat `%s'", dbname);
2949 		goto error;
2950 	}
2951 	if (st.st_size < 8 || st.st_size > MAXMAGIC_SIZE) {
2952 		file_error(ms, 0, "file `%s' is too %s", dbname,
2953 		    st.st_size < 8 ? "small" : "large");
2954 		goto error;
2955 	}
2956 
2957 	map->len = (size_t)st.st_size;
2958 #ifdef QUICK
2959 	map->type = MAP_TYPE_MMAP;
2960 	if ((map->p = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2961 	    MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2962 		file_error(ms, errno, "cannot map `%s'", dbname);
2963 		goto error;
2964 	}
2965 #else
2966 	map->type = MAP_TYPE_MALLOC;
2967 	if ((map->p = CAST(void *, malloc(map->len))) == NULL) {
2968 		file_oomem(ms, map->len);
2969 		goto error;
2970 	}
2971 	if (read(fd, map->p, map->len) != (ssize_t)map->len) {
2972 		file_badread(ms);
2973 		goto error;
2974 	}
2975 #define RET	1
2976 #endif
2977 	(void)close(fd);
2978 	fd = -1;
2979 
2980 	if (check_buffer(ms, map, dbname) != 0) {
2981 		rv = (struct magic_map *)-1;
2982 		goto error;
2983 	}
2984 #ifdef QUICK
2985 	if (mprotect(map->p, (size_t)st.st_size, PROT_READ) == -1) {
2986 		file_error(ms, errno, "cannot mprotect `%s'", dbname);
2987 		goto error;
2988 	}
2989 #endif
2990 
2991 	free(dbname);
2992 	return map;
2993 
2994 error:
2995 	if (fd != -1)
2996 		(void)close(fd);
2997 	apprentice_unmap(map);
2998 	free(dbname);
2999 	return rv;
3000 }
3001 
3002 private int
3003 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
3004 {
3005 	uint32_t *ptr;
3006 	uint32_t entries, nentries;
3007 	uint32_t version;
3008 	int i, needsbyteswap;
3009 
3010 	ptr = CAST(uint32_t *, map->p);
3011 	if (*ptr != MAGICNO) {
3012 		if (swap4(*ptr) != MAGICNO) {
3013 			file_error(ms, 0, "bad magic in `%s'", dbname);
3014 			return -1;
3015 		}
3016 		needsbyteswap = 1;
3017 	} else
3018 		needsbyteswap = 0;
3019 	if (needsbyteswap)
3020 		version = swap4(ptr[1]);
3021 	else
3022 		version = ptr[1];
3023 	if (version != VERSIONNO) {
3024 		file_error(ms, 0, "File %s supports only version %d magic "
3025 		    "files. `%s' is version %d", VERSION,
3026 		    VERSIONNO, dbname, version);
3027 		return -1;
3028 	}
3029 	entries = (uint32_t)(map->len / sizeof(struct magic));
3030 	if ((entries * sizeof(struct magic)) != map->len) {
3031 		file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
3032 		    "a multiple of %" SIZE_T_FORMAT "u",
3033 		    dbname, map->len, sizeof(struct magic));
3034 		return -1;
3035 	}
3036 	map->magic[0] = CAST(struct magic *, map->p) + 1;
3037 	nentries = 0;
3038 	for (i = 0; i < MAGIC_SETS; i++) {
3039 		if (needsbyteswap)
3040 			map->nmagic[i] = swap4(ptr[i + 2]);
3041 		else
3042 			map->nmagic[i] = ptr[i + 2];
3043 		if (i != MAGIC_SETS - 1)
3044 			map->magic[i + 1] = map->magic[i] + map->nmagic[i];
3045 		nentries += map->nmagic[i];
3046 	}
3047 	if (entries != nentries + 1) {
3048 		file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
3049 		    dbname, entries, nentries + 1);
3050 		return -1;
3051 	}
3052 	if (needsbyteswap)
3053 		for (i = 0; i < MAGIC_SETS; i++)
3054 			byteswap(map->magic[i], map->nmagic[i]);
3055 	return 0;
3056 }
3057 
3058 /*
3059  * handle an mmaped file.
3060  */
3061 private int
3062 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
3063 {
3064 	static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
3065 	static const size_t m = sizeof(**map->magic);
3066 	int fd = -1;
3067 	size_t len;
3068 	char *dbname;
3069 	int rv = -1;
3070 	uint32_t i;
3071 	union {
3072 		struct magic m;
3073 		uint32_t h[2 + MAGIC_SETS];
3074 	} hdr;
3075 
3076 	dbname = mkdbname(ms, fn, 1);
3077 
3078 	if (dbname == NULL)
3079 		goto out;
3080 
3081 	if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1)
3082 	{
3083 		file_error(ms, errno, "cannot open `%s'", dbname);
3084 		goto out;
3085 	}
3086 	memset(&hdr, 0, sizeof(hdr));
3087 	hdr.h[0] = MAGICNO;
3088 	hdr.h[1] = VERSIONNO;
3089 	memcpy(hdr.h + 2, map->nmagic, nm);
3090 
3091 	if (write(fd, &hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
3092 		file_error(ms, errno, "error writing `%s'", dbname);
3093 		goto out;
3094 	}
3095 
3096 	for (i = 0; i < MAGIC_SETS; i++) {
3097 		len = m * map->nmagic[i];
3098 		if (write(fd, map->magic[i], len) != (ssize_t)len) {
3099 			file_error(ms, errno, "error writing `%s'", dbname);
3100 			goto out;
3101 		}
3102 	}
3103 
3104 	if (fd != -1)
3105 		(void)close(fd);
3106 	rv = 0;
3107 out:
3108 	apprentice_unmap(map);
3109 	free(dbname);
3110 	return rv;
3111 }
3112 
3113 private const char ext[] = ".mgc";
3114 /*
3115  * make a dbname
3116  */
3117 private char *
3118 mkdbname(struct magic_set *ms, const char *fn, int strip)
3119 {
3120 	const char *p, *q;
3121 	char *buf;
3122 
3123 	if (strip) {
3124 		if ((p = strrchr(fn, '/')) != NULL)
3125 			fn = ++p;
3126 	}
3127 
3128 	for (q = fn; *q; q++)
3129 		continue;
3130 	/* Look for .mgc */
3131 	for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
3132 		if (*p != *q)
3133 			break;
3134 
3135 	/* Did not find .mgc, restore q */
3136 	if (p >= ext)
3137 		while (*q)
3138 			q++;
3139 
3140 	q++;
3141 	/* Compatibility with old code that looked in .mime */
3142 	if (ms->flags & MAGIC_MIME) {
3143 		if (asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext) < 0)
3144 			return NULL;
3145 		if (access(buf, R_OK) != -1) {
3146 			ms->flags &= MAGIC_MIME_TYPE;
3147 			return buf;
3148 		}
3149 		free(buf);
3150 	}
3151 	if (asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext) < 0)
3152 		return NULL;
3153 
3154 	/* Compatibility with old code that looked in .mime */
3155 	if (strstr(fn, ".mime") != NULL)
3156 		ms->flags &= MAGIC_MIME_TYPE;
3157 	return buf;
3158 }
3159 
3160 /*
3161  * Byteswap an mmap'ed file if needed
3162  */
3163 private void
3164 byteswap(struct magic *magic, uint32_t nmagic)
3165 {
3166 	uint32_t i;
3167 	for (i = 0; i < nmagic; i++)
3168 		bs1(&magic[i]);
3169 }
3170 
3171 /*
3172  * swap a short
3173  */
3174 private uint16_t
3175 swap2(uint16_t sv)
3176 {
3177 	uint16_t rv;
3178 	uint8_t *s = (uint8_t *)(void *)&sv;
3179 	uint8_t *d = (uint8_t *)(void *)&rv;
3180 	d[0] = s[1];
3181 	d[1] = s[0];
3182 	return rv;
3183 }
3184 
3185 /*
3186  * swap an int
3187  */
3188 private uint32_t
3189 swap4(uint32_t sv)
3190 {
3191 	uint32_t rv;
3192 	uint8_t *s = (uint8_t *)(void *)&sv;
3193 	uint8_t *d = (uint8_t *)(void *)&rv;
3194 	d[0] = s[3];
3195 	d[1] = s[2];
3196 	d[2] = s[1];
3197 	d[3] = s[0];
3198 	return rv;
3199 }
3200 
3201 /*
3202  * swap a quad
3203  */
3204 private uint64_t
3205 swap8(uint64_t sv)
3206 {
3207 	uint64_t rv;
3208 	uint8_t *s = (uint8_t *)(void *)&sv;
3209 	uint8_t *d = (uint8_t *)(void *)&rv;
3210 #if 0
3211 	d[0] = s[3];
3212 	d[1] = s[2];
3213 	d[2] = s[1];
3214 	d[3] = s[0];
3215 	d[4] = s[7];
3216 	d[5] = s[6];
3217 	d[6] = s[5];
3218 	d[7] = s[4];
3219 #else
3220 	d[0] = s[7];
3221 	d[1] = s[6];
3222 	d[2] = s[5];
3223 	d[3] = s[4];
3224 	d[4] = s[3];
3225 	d[5] = s[2];
3226 	d[6] = s[1];
3227 	d[7] = s[0];
3228 #endif
3229 	return rv;
3230 }
3231 
3232 /*
3233  * byteswap a single magic entry
3234  */
3235 private void
3236 bs1(struct magic *m)
3237 {
3238 	m->cont_level = swap2(m->cont_level);
3239 	m->offset = swap4((uint32_t)m->offset);
3240 	m->in_offset = swap4((uint32_t)m->in_offset);
3241 	m->lineno = swap4((uint32_t)m->lineno);
3242 	if (IS_STRING(m->type)) {
3243 		m->str_range = swap4(m->str_range);
3244 		m->str_flags = swap4(m->str_flags);
3245 	}
3246 	else {
3247 		m->value.q = swap8(m->value.q);
3248 		m->num_mask = swap8(m->num_mask);
3249 	}
3250 }
3251 
3252 protected size_t
3253 file_pstring_length_size(const struct magic *m)
3254 {
3255 	switch (m->str_flags & PSTRING_LEN) {
3256 	case PSTRING_1_LE:
3257 		return 1;
3258 	case PSTRING_2_LE:
3259 	case PSTRING_2_BE:
3260 		return 2;
3261 	case PSTRING_4_LE:
3262 	case PSTRING_4_BE:
3263 		return 4;
3264 	default:
3265 		abort();	/* Impossible */
3266 		return 1;
3267 	}
3268 }
3269 protected size_t
3270 file_pstring_get_length(const struct magic *m, const char *ss)
3271 {
3272 	size_t len = 0;
3273 	const unsigned char *s = (const unsigned char *)ss;
3274 
3275 	switch (m->str_flags & PSTRING_LEN) {
3276 	case PSTRING_1_LE:
3277 		len = *s;
3278 		break;
3279 	case PSTRING_2_LE:
3280 		len = (s[1] << 8) | s[0];
3281 		break;
3282 	case PSTRING_2_BE:
3283 		len = (s[0] << 8) | s[1];
3284 		break;
3285 	case PSTRING_4_LE:
3286 		len = (s[3] << 24) | (s[2] << 16) | (s[1] << 8) | s[0];
3287 		break;
3288 	case PSTRING_4_BE:
3289 		len = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
3290 		break;
3291 	default:
3292 		abort();	/* Impossible */
3293 	}
3294 
3295 	if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
3296 		len -= file_pstring_length_size(m);
3297 
3298 	return len;
3299 }
3300 
3301 protected int
3302 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
3303 {
3304 	uint32_t i, j;
3305 	struct mlist *mlist, *ml;
3306 
3307 	mlist = ms->mlist[1];
3308 
3309 	for (ml = mlist->next; ml != mlist; ml = ml->next) {
3310 		struct magic *ma = ml->magic;
3311 		uint32_t nma = ml->nmagic;
3312 		for (i = 0; i < nma; i++) {
3313 			if (ma[i].type != FILE_NAME)
3314 				continue;
3315 			if (strcmp(ma[i].value.s, name) == 0) {
3316 				v->magic = &ma[i];
3317 				for (j = i + 1; j < nma; j++)
3318 				    if (ma[j].cont_level == 0)
3319 					    break;
3320 				v->nmagic = j - i;
3321 				return 0;
3322 			}
3323 		}
3324 	}
3325 	return -1;
3326 }
3327