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