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