No empty .Rs/.Re
[netbsd-mini2440.git] / external / bsd / file / dist / src / apprentice.c
blob40543ef543667e64c2d1169d2a2c8d59e5750ab7
1 /* $NetBSD: apprentice.c,v 1.1.1.1 2009/05/08 16:35:05 christos Exp $ */
3 /*
4 * Copyright (c) Ian F. Darwin 1986-1995.
5 * Software written by Ian F. Darwin and others;
6 * maintained 1995-present by Christos Zoulas and others.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice immediately at the beginning of the file, without modification,
13 * this list of conditions, and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28 * SUCH DAMAGE.
31 * apprentice - make one pass through /etc/magic, learning its secrets.
34 #include "file.h"
36 #ifndef lint
37 #if 0
38 FILE_RCSID("@(#)$File: apprentice.c,v 1.151 2009/03/18 15:19:23 christos Exp $")
39 #else
40 __RCSID("$NetBSD: apprentice.c,v 1.1.1.1 2009/05/08 16:35:05 christos Exp $");
41 #endif
42 #endif /* lint */
44 #include "magic.h"
45 #include "patchlevel.h"
46 #include <stdlib.h>
47 #ifdef HAVE_UNISTD_H
48 #include <unistd.h>
49 #endif
50 #include <string.h>
51 #include <assert.h>
52 #include <ctype.h>
53 #include <fcntl.h>
54 #ifdef QUICK
55 #include <sys/mman.h>
56 #endif
57 #include <dirent.h>
59 #define EATAB {while (isascii((unsigned char) *l) && \
60 isspace((unsigned char) *l)) ++l;}
61 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
62 tolower((unsigned char) (l)) : (l))
64 * Work around a bug in headers on Digital Unix.
65 * At least confirmed for: OSF1 V4.0 878
67 #if defined(__osf__) && defined(__DECC)
68 #ifdef MAP_FAILED
69 #undef MAP_FAILED
70 #endif
71 #endif
73 #ifndef MAP_FAILED
74 #define MAP_FAILED (void *) -1
75 #endif
77 #ifndef MAP_FILE
78 #define MAP_FILE 0
79 #endif
81 #ifndef MAXPATHLEN
82 #define MAXPATHLEN 1024
83 #endif
85 struct magic_entry {
86 struct magic *mp;
87 uint32_t cont_count;
88 uint32_t max_count;
91 int file_formats[FILE_NAMES_SIZE];
92 const size_t file_nformats = FILE_NAMES_SIZE;
93 const char *file_names[FILE_NAMES_SIZE];
94 const size_t file_nnames = FILE_NAMES_SIZE;
96 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
97 private int hextoint(int);
98 private const char *getstr(struct magic_set *, struct magic *, const char *,
99 int);
100 private int parse(struct magic_set *, struct magic_entry **, uint32_t *,
101 const char *, size_t, int);
102 private void eatsize(const char **);
103 private int apprentice_1(struct magic_set *, const char *, int, struct mlist *);
104 private size_t apprentice_magic_strength(const struct magic *);
105 private int apprentice_sort(const void *, const void *);
106 private int apprentice_load(struct magic_set *, struct magic **, uint32_t *,
107 const char *, int);
108 private void byteswap(struct magic *, uint32_t);
109 private void bs1(struct magic *);
110 private uint16_t swap2(uint16_t);
111 private uint32_t swap4(uint32_t);
112 private uint64_t swap8(uint64_t);
113 private char *mkdbname(struct magic_set *, const char *, int);
114 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
115 const char *);
116 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
117 const char *);
118 private int check_format_type(const char *, int);
119 private int check_format(struct magic_set *, struct magic *);
120 private int get_op(char);
121 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
122 private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
123 private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
126 private size_t maxmagic = 0;
127 private size_t magicsize = sizeof(struct magic);
129 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
131 private struct {
132 const char *name;
133 size_t len;
134 int (*fun)(struct magic_set *, struct magic_entry *, const char *);
135 } bang[] = {
136 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
137 DECLARE_FIELD(mime),
138 DECLARE_FIELD(apple),
139 DECLARE_FIELD(strength),
140 #undef DECLARE_FIELD
141 { NULL, 0, NULL }
144 #ifdef COMPILE_ONLY
146 int main(int, char *[]);
149 main(int argc, char *argv[])
151 int ret;
152 struct magic_set *ms;
153 char *progname;
155 if ((progname = strrchr(argv[0], '/')) != NULL)
156 progname++;
157 else
158 progname = argv[0];
160 if (argc != 2) {
161 (void)fprintf(stderr, "Usage: %s file\n", progname);
162 return 1;
165 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
166 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
167 return 1;
169 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
170 if (ret == 1)
171 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
172 magic_close(ms);
173 return ret;
175 #endif /* COMPILE_ONLY */
177 static const struct type_tbl_s {
178 const char name[16];
179 const size_t len;
180 const int type;
181 const int format;
182 } type_tbl[] = {
183 # define XX(s) s, (sizeof(s) - 1)
184 # define XX_NULL "", 0
185 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
186 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
187 { XX("default"), FILE_DEFAULT, FILE_FMT_STR },
188 { XX("long"), FILE_LONG, FILE_FMT_NUM },
189 { XX("string"), FILE_STRING, FILE_FMT_STR },
190 { XX("date"), FILE_DATE, FILE_FMT_STR },
191 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
192 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
193 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
194 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
195 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
196 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
197 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
198 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
199 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
200 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
201 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
202 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
203 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
204 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
205 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
206 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
207 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
208 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
209 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
210 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
211 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
212 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
213 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
214 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
215 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
216 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
217 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
218 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
219 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
220 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
221 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
222 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
223 { XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
224 { XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
225 { XX("indirect"), FILE_INDIRECT, FILE_FMT_NONE },
226 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
227 # undef XX
228 # undef XX_NULL
231 private int
232 get_type(const char *l, const char **t)
234 const struct type_tbl_s *p;
236 for (p = type_tbl; p->len; p++) {
237 if (strncmp(l, p->name, p->len) == 0) {
238 if (t)
239 *t = l + p->len;
240 break;
243 return p->type;
246 private void
247 init_file_tables(void)
249 static int done = 0;
250 const struct type_tbl_s *p;
252 if (done)
253 return;
254 done++;
256 for (p = type_tbl; p->len; p++) {
257 assert(p->type < FILE_NAMES_SIZE);
258 file_names[p->type] = p->name;
259 file_formats[p->type] = p->format;
264 * Handle one file or directory.
266 private int
267 apprentice_1(struct magic_set *ms, const char *fn, int action,
268 struct mlist *mlist)
270 struct magic *magic = NULL;
271 uint32_t nmagic = 0;
272 struct mlist *ml;
273 int rv = -1;
274 int mapped;
276 if (magicsize != FILE_MAGICSIZE) {
277 file_error(ms, 0, "magic element size %lu != %lu",
278 (unsigned long)sizeof(*magic),
279 (unsigned long)FILE_MAGICSIZE);
280 return -1;
283 if (action == FILE_COMPILE) {
284 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
285 if (rv != 0)
286 return -1;
287 rv = apprentice_compile(ms, &magic, &nmagic, fn);
288 free(magic);
289 return rv;
292 #ifndef COMPILE_ONLY
293 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
294 if (ms->flags & MAGIC_CHECK)
295 file_magwarn(ms, "using regular magic file `%s'", fn);
296 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
297 if (rv != 0)
298 return -1;
301 mapped = rv;
303 if (magic == NULL) {
304 file_delmagic(magic, mapped, nmagic);
305 return -1;
308 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL) {
309 file_delmagic(magic, mapped, nmagic);
310 file_oomem(ms, sizeof(*ml));
311 return -1;
314 ml->magic = magic;
315 ml->nmagic = nmagic;
316 ml->mapped = mapped;
318 mlist->prev->next = ml;
319 ml->prev = mlist->prev;
320 ml->next = mlist;
321 mlist->prev = ml;
323 return 0;
324 #endif /* COMPILE_ONLY */
327 protected void
328 file_delmagic(struct magic *p, int type, size_t entries)
330 if (p == NULL)
331 return;
332 switch (type) {
333 case 2:
334 #ifdef QUICK
335 p--;
336 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
337 break;
338 #else
339 (void)&entries;
340 abort();
341 /*NOTREACHED*/
342 #endif
343 case 1:
344 p--;
345 /*FALLTHROUGH*/
346 case 0:
347 free(p);
348 break;
349 default:
350 abort();
354 /* const char *fn: list of magic files and directories */
355 protected struct mlist *
356 file_apprentice(struct magic_set *ms, const char *fn, int action)
358 char *p, *mfn;
359 int file_err, errs = -1;
360 struct mlist *mlist;
362 init_file_tables();
364 if (fn == NULL)
365 fn = getenv("MAGIC");
366 if (fn == NULL)
367 fn = MAGIC;
369 if ((mfn = strdup(fn)) == NULL) {
370 file_oomem(ms, strlen(fn));
371 return NULL;
373 fn = mfn;
375 if ((mlist = CAST(struct mlist *, malloc(sizeof(*mlist)))) == NULL) {
376 free(mfn);
377 file_oomem(ms, sizeof(*mlist));
378 return NULL;
380 mlist->next = mlist->prev = mlist;
382 while (fn) {
383 p = strchr(fn, PATHSEP);
384 if (p)
385 *p++ = '\0';
386 if (*fn == '\0')
387 break;
388 file_err = apprentice_1(ms, fn, action, mlist);
389 errs = MAX(errs, file_err);
390 fn = p;
392 if (errs == -1) {
393 free(mfn);
394 free(mlist);
395 mlist = NULL;
396 file_error(ms, 0, "could not find any magic files!");
397 return NULL;
399 free(mfn);
400 return mlist;
404 * Get weight of this magic entry, for sorting purposes.
406 private size_t
407 apprentice_magic_strength(const struct magic *m)
409 #define MULT 10
410 size_t val = 2 * MULT; /* baseline strength */
412 switch (m->type) {
413 case FILE_DEFAULT: /* make sure this sorts last */
414 if (m->factor_op != FILE_FACTOR_OP_NONE)
415 abort();
416 return 0;
418 case FILE_BYTE:
419 val += 1 * MULT;
420 break;
422 case FILE_SHORT:
423 case FILE_LESHORT:
424 case FILE_BESHORT:
425 val += 2 * MULT;
426 break;
428 case FILE_LONG:
429 case FILE_LELONG:
430 case FILE_BELONG:
431 case FILE_MELONG:
432 val += 4 * MULT;
433 break;
435 case FILE_PSTRING:
436 case FILE_STRING:
437 val += m->vallen * MULT;
438 break;
440 case FILE_BESTRING16:
441 case FILE_LESTRING16:
442 val += m->vallen * MULT / 2;
443 break;
445 case FILE_SEARCH:
446 case FILE_REGEX:
447 val += m->vallen * MAX(MULT / m->vallen, 1);
448 break;
450 case FILE_DATE:
451 case FILE_LEDATE:
452 case FILE_BEDATE:
453 case FILE_MEDATE:
454 case FILE_LDATE:
455 case FILE_LELDATE:
456 case FILE_BELDATE:
457 case FILE_MELDATE:
458 case FILE_FLOAT:
459 case FILE_BEFLOAT:
460 case FILE_LEFLOAT:
461 val += 4 * MULT;
462 break;
464 case FILE_QUAD:
465 case FILE_BEQUAD:
466 case FILE_LEQUAD:
467 case FILE_QDATE:
468 case FILE_LEQDATE:
469 case FILE_BEQDATE:
470 case FILE_QLDATE:
471 case FILE_LEQLDATE:
472 case FILE_BEQLDATE:
473 case FILE_DOUBLE:
474 case FILE_BEDOUBLE:
475 case FILE_LEDOUBLE:
476 val += 8 * MULT;
477 break;
479 default:
480 val = 0;
481 (void)fprintf(stderr, "Bad type %d\n", m->type);
482 abort();
485 switch (m->reln) {
486 case 'x': /* matches anything penalize */
487 case '!': /* matches almost anything penalize */
488 val = 0;
489 break;
491 case '=': /* Exact match, prefer */
492 val += MULT;
493 break;
495 case '>':
496 case '<': /* comparison match reduce strength */
497 val -= 2 * MULT;
498 break;
500 case '^':
501 case '&': /* masking bits, we could count them too */
502 val -= MULT;
503 break;
505 default:
506 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
507 abort();
510 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
511 val = 1;
513 switch (m->factor_op) {
514 case FILE_FACTOR_OP_NONE:
515 break;
516 case FILE_FACTOR_OP_PLUS:
517 val += m->factor;
518 break;
519 case FILE_FACTOR_OP_MINUS:
520 val -= m->factor;
521 break;
522 case FILE_FACTOR_OP_TIMES:
523 val *= m->factor;
524 break;
525 case FILE_FACTOR_OP_DIV:
526 val /= m->factor;
527 break;
528 default:
529 abort();
533 * Magic entries with no description get a bonus because they depend
534 * on subsequent magic entries to print something.
536 if (m->desc[0] == '\0')
537 val++;
538 return val;
542 * Sort callback for sorting entries by "strength" (basically length)
544 private int
545 apprentice_sort(const void *a, const void *b)
547 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
548 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
549 size_t sa = apprentice_magic_strength(ma->mp);
550 size_t sb = apprentice_magic_strength(mb->mp);
551 if (sa == sb)
552 return 0;
553 else if (sa > sb)
554 return -1;
555 else
556 return 1;
559 private void
560 set_test_type(struct magic *mstart, struct magic *m)
562 switch (m->type) {
563 case FILE_BYTE:
564 case FILE_SHORT:
565 case FILE_LONG:
566 case FILE_DATE:
567 case FILE_BESHORT:
568 case FILE_BELONG:
569 case FILE_BEDATE:
570 case FILE_LESHORT:
571 case FILE_LELONG:
572 case FILE_LEDATE:
573 case FILE_LDATE:
574 case FILE_BELDATE:
575 case FILE_LELDATE:
576 case FILE_MEDATE:
577 case FILE_MELDATE:
578 case FILE_MELONG:
579 case FILE_QUAD:
580 case FILE_LEQUAD:
581 case FILE_BEQUAD:
582 case FILE_QDATE:
583 case FILE_LEQDATE:
584 case FILE_BEQDATE:
585 case FILE_QLDATE:
586 case FILE_LEQLDATE:
587 case FILE_BEQLDATE:
588 case FILE_FLOAT:
589 case FILE_BEFLOAT:
590 case FILE_LEFLOAT:
591 case FILE_DOUBLE:
592 case FILE_BEDOUBLE:
593 case FILE_LEDOUBLE:
594 case FILE_STRING:
595 case FILE_PSTRING:
596 case FILE_BESTRING16:
597 case FILE_LESTRING16:
598 /* binary test, set flag */
599 mstart->flag |= BINTEST;
600 break;
601 case FILE_REGEX:
602 case FILE_SEARCH:
603 /* binary test if pattern is not text */
604 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
605 NULL) <= 0)
606 mstart->flag |= BINTEST;
607 break;
608 case FILE_DEFAULT:
609 /* can't deduce anything; we shouldn't see this at the
610 top level anyway */
611 break;
612 case FILE_INVALID:
613 default:
614 /* invalid search type, but no need to complain here */
615 break;
620 * Load and parse one file.
622 private void
623 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
624 struct magic_entry **marray, uint32_t *marraycount)
626 char line[BUFSIZ];
627 size_t lineno = 0;
628 FILE *f = fopen(ms->file = fn, "r");
629 if (f == NULL) {
630 if (errno != ENOENT)
631 file_error(ms, errno, "cannot read magic file `%s'",
632 fn);
633 (*errs)++;
634 } else {
635 /* read and parse this file */
636 for (ms->line = 1;
637 fgets(line, CAST(int, sizeof(line)), f) != NULL;
638 ms->line++) {
639 size_t len;
640 len = strlen(line);
641 if (len == 0) /* null line, garbage, etc */
642 continue;
643 if (line[len - 1] == '\n') {
644 lineno++;
645 line[len - 1] = '\0'; /* delete newline */
647 if (line[0] == '\0') /* empty, do not parse */
648 continue;
649 if (line[0] == '#') /* comment, do not parse */
650 continue;
651 if (line[0] == '!' && line[1] == ':') {
652 size_t i;
654 for (i = 0; bang[i].name != NULL; i++) {
655 if (len - 2 > bang[i].len &&
656 memcmp(bang[i].name, line + 2,
657 bang[i].len) == 0)
658 break;
660 if (bang[i].name == NULL) {
661 file_error(ms, 0,
662 "Unknown !: entry `%s'", line);
663 (*errs)++;
664 continue;
666 if (*marraycount == 0) {
667 file_error(ms, 0,
668 "No current entry for :!%s type",
669 bang[i].name);
670 (*errs)++;
671 continue;
673 if ((*bang[i].fun)(ms,
674 &(*marray)[*marraycount - 1],
675 line + bang[i].len + 2) != 0) {
676 (*errs)++;
677 continue;
679 continue;
681 if (parse(ms, marray, marraycount, line, lineno,
682 action) != 0)
683 (*errs)++;
686 (void)fclose(f);
691 * parse a file or directory of files
692 * const char *fn: name of magic file or directory
694 private int
695 apprentice_load(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
696 const char *fn, int action)
698 int errs = 0;
699 struct magic_entry *marray;
700 uint32_t marraycount, i, mentrycount = 0, starttest;
701 size_t slen;
702 char subfn[MAXPATHLEN];
703 struct stat st;
704 DIR *dir;
705 struct dirent *d;
707 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
709 maxmagic = MAXMAGIS;
710 if ((marray = CAST(struct magic_entry *, calloc(maxmagic,
711 sizeof(*marray)))) == NULL) {
712 file_oomem(ms, maxmagic * sizeof(*marray));
713 return -1;
715 marraycount = 0;
717 /* print silly verbose header for USG compat. */
718 if (action == FILE_CHECK)
719 (void)fprintf(stderr, "%s\n", usg_hdr);
721 /* load directory or file */
722 /* FIXME: Read file names and sort them to prevent
723 non-determinism. See Debian bug #488562. */
724 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
725 dir = opendir(fn);
726 if (dir) {
727 while ((d = readdir(dir)) != NULL) {
728 snprintf(subfn, sizeof(subfn), "%s/%s",
729 fn, d->d_name);
730 if (stat(subfn, &st) == 0 &&
731 S_ISREG(st.st_mode)) {
732 load_1(ms, action, subfn, &errs,
733 &marray, &marraycount);
736 closedir(dir);
737 } else
738 errs++;
739 } else
740 load_1(ms, action, fn, &errs, &marray, &marraycount);
741 if (errs)
742 goto out;
744 /* Set types of tests */
745 for (i = 0; i < marraycount; ) {
746 if (marray[i].mp->cont_level != 0) {
747 i++;
748 continue;
751 starttest = i;
752 do {
753 static const char text[] = "text";
754 static const char binary[] = "binary";
755 static const size_t len = sizeof(text);
756 set_test_type(marray[starttest].mp, marray[i].mp);
757 if ((ms->flags & MAGIC_DEBUG) == 0)
758 continue;
759 (void)fprintf(stderr, "%s%s%s: %s\n",
760 marray[i].mp->mimetype,
761 marray[i].mp->mimetype[0] == '\0' ? "" : "; ",
762 marray[i].mp->desc[0] ? marray[i].mp->desc :
763 "(no description)",
764 marray[i].mp->flag & BINTEST ? binary : text);
765 if (marray[i].mp->flag & BINTEST) {
766 char *p = strstr(marray[i].mp->desc, text);
767 if (p && (p == marray[i].mp->desc ||
768 isspace((unsigned char)p[-1])) &&
769 (p + len - marray[i].mp->desc ==
770 MAXstring || (p[len] == '\0' ||
771 isspace((unsigned char)p[len]))))
772 (void)fprintf(stderr, "*** Possible "
773 "binary test for text type\n");
775 } while (++i < marraycount && marray[i].mp->cont_level != 0);
778 qsort(marray, marraycount, sizeof(*marray), apprentice_sort);
781 * Make sure that any level 0 "default" line is last (if one exists).
783 for (i = 0; i < marraycount; i++) {
784 if (marray[i].mp->cont_level == 0 &&
785 marray[i].mp->type == FILE_DEFAULT) {
786 while (++i < marraycount)
787 if (marray[i].mp->cont_level == 0)
788 break;
789 if (i != marraycount) {
790 ms->line = marray[i].mp->lineno; /* XXX - Ugh! */
791 file_magwarn(ms,
792 "level 0 \"default\" did not sort last");
794 break;
798 for (i = 0; i < marraycount; i++)
799 mentrycount += marray[i].cont_count;
801 slen = sizeof(**magicp) * mentrycount;
802 if ((*magicp = CAST(struct magic *, malloc(slen))) == NULL) {
803 file_oomem(ms, slen);
804 errs++;
805 goto out;
808 mentrycount = 0;
809 for (i = 0; i < marraycount; i++) {
810 (void)memcpy(*magicp + mentrycount, marray[i].mp,
811 marray[i].cont_count * sizeof(**magicp));
812 mentrycount += marray[i].cont_count;
814 out:
815 for (i = 0; i < marraycount; i++)
816 free(marray[i].mp);
817 free(marray);
818 if (errs) {
819 *magicp = NULL;
820 *nmagicp = 0;
821 return errs;
822 } else {
823 *nmagicp = mentrycount;
824 return 0;
830 * extend the sign bit if the comparison is to be signed
832 protected uint64_t
833 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
835 if (!(m->flag & UNSIGNED)) {
836 switch(m->type) {
838 * Do not remove the casts below. They are
839 * vital. When later compared with the data,
840 * the sign extension must have happened.
842 case FILE_BYTE:
843 v = (char) v;
844 break;
845 case FILE_SHORT:
846 case FILE_BESHORT:
847 case FILE_LESHORT:
848 v = (short) v;
849 break;
850 case FILE_DATE:
851 case FILE_BEDATE:
852 case FILE_LEDATE:
853 case FILE_MEDATE:
854 case FILE_LDATE:
855 case FILE_BELDATE:
856 case FILE_LELDATE:
857 case FILE_MELDATE:
858 case FILE_LONG:
859 case FILE_BELONG:
860 case FILE_LELONG:
861 case FILE_MELONG:
862 case FILE_FLOAT:
863 case FILE_BEFLOAT:
864 case FILE_LEFLOAT:
865 v = (int32_t) v;
866 break;
867 case FILE_QUAD:
868 case FILE_BEQUAD:
869 case FILE_LEQUAD:
870 case FILE_QDATE:
871 case FILE_QLDATE:
872 case FILE_BEQDATE:
873 case FILE_BEQLDATE:
874 case FILE_LEQDATE:
875 case FILE_LEQLDATE:
876 case FILE_DOUBLE:
877 case FILE_BEDOUBLE:
878 case FILE_LEDOUBLE:
879 v = (int64_t) v;
880 break;
881 case FILE_STRING:
882 case FILE_PSTRING:
883 case FILE_BESTRING16:
884 case FILE_LESTRING16:
885 case FILE_REGEX:
886 case FILE_SEARCH:
887 case FILE_DEFAULT:
888 case FILE_INDIRECT:
889 break;
890 default:
891 if (ms->flags & MAGIC_CHECK)
892 file_magwarn(ms, "cannot happen: m->type=%d\n",
893 m->type);
894 return ~0U;
897 return v;
900 private int
901 string_modifier_check(struct magic_set *ms, struct magic *m)
903 if ((ms->flags & MAGIC_CHECK) == 0)
904 return 0;
906 switch (m->type) {
907 case FILE_BESTRING16:
908 case FILE_LESTRING16:
909 if (m->str_flags != 0) {
910 file_magwarn(ms,
911 "no modifiers allowed for 16-bit strings\n");
912 return -1;
914 break;
915 case FILE_STRING:
916 case FILE_PSTRING:
917 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
918 file_magwarn(ms,
919 "'/%c' only allowed on regex and search\n",
920 CHAR_REGEX_OFFSET_START);
921 return -1;
923 break;
924 case FILE_SEARCH:
925 if (m->str_range == 0) {
926 file_magwarn(ms,
927 "missing range; defaulting to %d\n",
928 STRING_DEFAULT_RANGE);
929 m->str_range = STRING_DEFAULT_RANGE;
930 return -1;
932 break;
933 case FILE_REGEX:
934 if ((m->str_flags & STRING_COMPACT_BLANK) != 0) {
935 file_magwarn(ms, "'/%c' not allowed on regex\n",
936 CHAR_COMPACT_BLANK);
937 return -1;
939 if ((m->str_flags & STRING_COMPACT_OPTIONAL_BLANK) != 0) {
940 file_magwarn(ms, "'/%c' not allowed on regex\n",
941 CHAR_COMPACT_OPTIONAL_BLANK);
942 return -1;
944 break;
945 default:
946 file_magwarn(ms, "coding error: m->type=%d\n",
947 m->type);
948 return -1;
950 return 0;
953 private int
954 get_op(char c)
956 switch (c) {
957 case '&':
958 return FILE_OPAND;
959 case '|':
960 return FILE_OPOR;
961 case '^':
962 return FILE_OPXOR;
963 case '+':
964 return FILE_OPADD;
965 case '-':
966 return FILE_OPMINUS;
967 case '*':
968 return FILE_OPMULTIPLY;
969 case '/':
970 return FILE_OPDIVIDE;
971 case '%':
972 return FILE_OPMODULO;
973 default:
974 return -1;
978 #ifdef ENABLE_CONDITIONALS
979 private int
980 get_cond(const char *l, const char **t)
982 static const struct cond_tbl_s {
983 char name[8];
984 size_t len;
985 int cond;
986 } cond_tbl[] = {
987 { "if", 2, COND_IF },
988 { "elif", 4, COND_ELIF },
989 { "else", 4, COND_ELSE },
990 { "", 0, COND_NONE },
992 const struct cond_tbl_s *p;
994 for (p = cond_tbl; p->len; p++) {
995 if (strncmp(l, p->name, p->len) == 0 &&
996 isspace((unsigned char)l[p->len])) {
997 if (t)
998 *t = l + p->len;
999 break;
1002 return p->cond;
1005 private int
1006 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1008 int last_cond;
1009 last_cond = ms->c.li[cont_level].last_cond;
1011 switch (cond) {
1012 case COND_IF:
1013 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1014 if (ms->flags & MAGIC_CHECK)
1015 file_magwarn(ms, "syntax error: `if'");
1016 return -1;
1018 last_cond = COND_IF;
1019 break;
1021 case COND_ELIF:
1022 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1023 if (ms->flags & MAGIC_CHECK)
1024 file_magwarn(ms, "syntax error: `elif'");
1025 return -1;
1027 last_cond = COND_ELIF;
1028 break;
1030 case COND_ELSE:
1031 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1032 if (ms->flags & MAGIC_CHECK)
1033 file_magwarn(ms, "syntax error: `else'");
1034 return -1;
1036 last_cond = COND_NONE;
1037 break;
1039 case COND_NONE:
1040 last_cond = COND_NONE;
1041 break;
1044 ms->c.li[cont_level].last_cond = last_cond;
1045 return 0;
1047 #endif /* ENABLE_CONDITIONALS */
1050 * parse one line from magic file, put into magic[index++] if valid
1052 private int
1053 parse(struct magic_set *ms, struct magic_entry **mentryp, uint32_t *nmentryp,
1054 const char *line, size_t lineno, int action)
1056 #ifdef ENABLE_CONDITIONALS
1057 static uint32_t last_cont_level = 0;
1058 #endif
1059 size_t i;
1060 struct magic_entry *me;
1061 struct magic *m;
1062 const char *l = line;
1063 char *t;
1064 int op;
1065 uint32_t cont_level;
1067 cont_level = 0;
1069 while (*l == '>') {
1070 ++l; /* step over */
1071 cont_level++;
1073 #ifdef ENABLE_CONDITIONALS
1074 if (cont_level == 0 || cont_level > last_cont_level)
1075 if (file_check_mem(ms, cont_level) == -1)
1076 return -1;
1077 last_cont_level = cont_level;
1078 #endif
1080 #define ALLOC_CHUNK (size_t)10
1081 #define ALLOC_INCR (size_t)200
1083 if (cont_level != 0) {
1084 if (*nmentryp == 0) {
1085 file_error(ms, 0, "No current entry for continuation");
1086 return -1;
1088 me = &(*mentryp)[*nmentryp - 1];
1089 if (me->cont_count == me->max_count) {
1090 struct magic *nm;
1091 size_t cnt = me->max_count + ALLOC_CHUNK;
1092 if ((nm = CAST(struct magic *, realloc(me->mp,
1093 sizeof(*nm) * cnt))) == NULL) {
1094 file_oomem(ms, sizeof(*nm) * cnt);
1095 return -1;
1097 me->mp = m = nm;
1098 me->max_count = CAST(uint32_t, cnt);
1100 m = &me->mp[me->cont_count++];
1101 (void)memset(m, 0, sizeof(*m));
1102 m->cont_level = cont_level;
1103 } else {
1104 if (*nmentryp == maxmagic) {
1105 struct magic_entry *mp;
1107 maxmagic += ALLOC_INCR;
1108 if ((mp = CAST(struct magic_entry *,
1109 realloc(*mentryp, sizeof(*mp) * maxmagic))) ==
1110 NULL) {
1111 file_oomem(ms, sizeof(*mp) * maxmagic);
1112 return -1;
1114 (void)memset(&mp[*nmentryp], 0, sizeof(*mp) *
1115 ALLOC_INCR);
1116 *mentryp = mp;
1118 me = &(*mentryp)[*nmentryp];
1119 if (me->mp == NULL) {
1120 size_t len = sizeof(*m) * ALLOC_CHUNK;
1121 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1122 file_oomem(ms, len);
1123 return -1;
1125 me->mp = m;
1126 me->max_count = ALLOC_CHUNK;
1127 } else
1128 m = me->mp;
1129 (void)memset(m, 0, sizeof(*m));
1130 m->factor_op = FILE_FACTOR_OP_NONE;
1131 m->cont_level = 0;
1132 me->cont_count = 1;
1134 m->lineno = CAST(uint32_t, lineno);
1136 if (*l == '&') { /* m->cont_level == 0 checked below. */
1137 ++l; /* step over */
1138 m->flag |= OFFADD;
1140 if (*l == '(') {
1141 ++l; /* step over */
1142 m->flag |= INDIR;
1143 if (m->flag & OFFADD)
1144 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1146 if (*l == '&') { /* m->cont_level == 0 checked below */
1147 ++l; /* step over */
1148 m->flag |= OFFADD;
1151 /* Indirect offsets are not valid at level 0. */
1152 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
1153 if (ms->flags & MAGIC_CHECK)
1154 file_magwarn(ms, "relative offset at level 0");
1156 /* get offset, then skip over it */
1157 m->offset = (uint32_t)strtoul(l, &t, 0);
1158 if (l == t)
1159 if (ms->flags & MAGIC_CHECK)
1160 file_magwarn(ms, "offset `%s' invalid", l);
1161 l = t;
1163 if (m->flag & INDIR) {
1164 m->in_type = FILE_LONG;
1165 m->in_offset = 0;
1167 * read [.lbs][+-]nnnnn)
1169 if (*l == '.') {
1170 l++;
1171 switch (*l) {
1172 case 'l':
1173 m->in_type = FILE_LELONG;
1174 break;
1175 case 'L':
1176 m->in_type = FILE_BELONG;
1177 break;
1178 case 'm':
1179 m->in_type = FILE_MELONG;
1180 break;
1181 case 'h':
1182 case 's':
1183 m->in_type = FILE_LESHORT;
1184 break;
1185 case 'H':
1186 case 'S':
1187 m->in_type = FILE_BESHORT;
1188 break;
1189 case 'c':
1190 case 'b':
1191 case 'C':
1192 case 'B':
1193 m->in_type = FILE_BYTE;
1194 break;
1195 case 'e':
1196 case 'f':
1197 case 'g':
1198 m->in_type = FILE_LEDOUBLE;
1199 break;
1200 case 'E':
1201 case 'F':
1202 case 'G':
1203 m->in_type = FILE_BEDOUBLE;
1204 break;
1205 case 'i':
1206 m->in_type = FILE_LEID3;
1207 break;
1208 case 'I':
1209 m->in_type = FILE_BEID3;
1210 break;
1211 default:
1212 if (ms->flags & MAGIC_CHECK)
1213 file_magwarn(ms,
1214 "indirect offset type `%c' invalid",
1215 *l);
1216 break;
1218 l++;
1221 m->in_op = 0;
1222 if (*l == '~') {
1223 m->in_op |= FILE_OPINVERSE;
1224 l++;
1226 if ((op = get_op(*l)) != -1) {
1227 m->in_op |= op;
1228 l++;
1230 if (*l == '(') {
1231 m->in_op |= FILE_OPINDIRECT;
1232 l++;
1234 if (isdigit((unsigned char)*l) || *l == '-') {
1235 m->in_offset = (int32_t)strtol(l, &t, 0);
1236 if (l == t)
1237 if (ms->flags & MAGIC_CHECK)
1238 file_magwarn(ms,
1239 "in_offset `%s' invalid", l);
1240 l = t;
1242 if (*l++ != ')' ||
1243 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
1244 if (ms->flags & MAGIC_CHECK)
1245 file_magwarn(ms,
1246 "missing ')' in indirect offset");
1248 EATAB;
1250 #ifdef ENABLE_CONDITIONALS
1251 m->cond = get_cond(l, &l);
1252 if (check_cond(ms, m->cond, cont_level) == -1)
1253 return -1;
1255 EATAB;
1256 #endif
1258 if (*l == 'u') {
1259 ++l;
1260 m->flag |= UNSIGNED;
1263 m->type = get_type(l, &l);
1264 if (m->type == FILE_INVALID) {
1265 if (ms->flags & MAGIC_CHECK)
1266 file_magwarn(ms, "type `%s' invalid", l);
1267 return -1;
1270 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1271 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1273 m->mask_op = 0;
1274 if (*l == '~') {
1275 if (!IS_STRING(m->type))
1276 m->mask_op |= FILE_OPINVERSE;
1277 else if (ms->flags & MAGIC_CHECK)
1278 file_magwarn(ms, "'~' invalid for string types");
1279 ++l;
1281 m->str_range = 0;
1282 m->str_flags = 0;
1283 m->num_mask = 0;
1284 if ((op = get_op(*l)) != -1) {
1285 if (!IS_STRING(m->type)) {
1286 uint64_t val;
1287 ++l;
1288 m->mask_op |= op;
1289 val = (uint64_t)strtoull(l, &t, 0);
1290 l = t;
1291 m->num_mask = file_signextend(ms, m, val);
1292 eatsize(&l);
1294 else if (op == FILE_OPDIVIDE) {
1295 int have_range = 0;
1296 while (!isspace((unsigned char)*++l)) {
1297 switch (*l) {
1298 case '0': case '1': case '2':
1299 case '3': case '4': case '5':
1300 case '6': case '7': case '8':
1301 case '9':
1302 if (have_range &&
1303 (ms->flags & MAGIC_CHECK))
1304 file_magwarn(ms,
1305 "multiple ranges");
1306 have_range = 1;
1307 m->str_range = CAST(uint32_t,
1308 strtoul(l, &t, 0));
1309 if (m->str_range == 0)
1310 file_magwarn(ms,
1311 "zero range");
1312 l = t - 1;
1313 break;
1314 case CHAR_COMPACT_BLANK:
1315 m->str_flags |= STRING_COMPACT_BLANK;
1316 break;
1317 case CHAR_COMPACT_OPTIONAL_BLANK:
1318 m->str_flags |=
1319 STRING_COMPACT_OPTIONAL_BLANK;
1320 break;
1321 case CHAR_IGNORE_LOWERCASE:
1322 m->str_flags |= STRING_IGNORE_LOWERCASE;
1323 break;
1324 case CHAR_IGNORE_UPPERCASE:
1325 m->str_flags |= STRING_IGNORE_UPPERCASE;
1326 break;
1327 case CHAR_REGEX_OFFSET_START:
1328 m->str_flags |= REGEX_OFFSET_START;
1329 break;
1330 default:
1331 if (ms->flags & MAGIC_CHECK)
1332 file_magwarn(ms,
1333 "string extension `%c' invalid",
1334 *l);
1335 return -1;
1337 /* allow multiple '/' for readability */
1338 if (l[1] == '/' &&
1339 !isspace((unsigned char)l[2]))
1340 l++;
1342 if (string_modifier_check(ms, m) == -1)
1343 return -1;
1345 else {
1346 if (ms->flags & MAGIC_CHECK)
1347 file_magwarn(ms, "invalid string op: %c", *t);
1348 return -1;
1352 * We used to set mask to all 1's here, instead let's just not do
1353 * anything if mask = 0 (unless you have a better idea)
1355 EATAB;
1357 switch (*l) {
1358 case '>':
1359 case '<':
1360 m->reln = *l;
1361 ++l;
1362 if (*l == '=') {
1363 if (ms->flags & MAGIC_CHECK) {
1364 file_magwarn(ms, "%c= not supported",
1365 m->reln);
1366 return -1;
1368 ++l;
1370 break;
1371 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1372 case '&':
1373 case '^':
1374 case '=':
1375 m->reln = *l;
1376 ++l;
1377 if (*l == '=') {
1378 /* HP compat: ignore &= etc. */
1379 ++l;
1381 break;
1382 case '!':
1383 m->reln = *l;
1384 ++l;
1385 break;
1386 default:
1387 m->reln = '='; /* the default relation */
1388 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
1389 isspace((unsigned char)l[1])) || !l[1])) {
1390 m->reln = *l;
1391 ++l;
1393 break;
1396 * Grab the value part, except for an 'x' reln.
1398 if (m->reln != 'x' && getvalue(ms, m, &l, action))
1399 return -1;
1402 * TODO finish this macro and start using it!
1403 * #define offsetcheck {if (offset > HOWMANY-1)
1404 * magwarn("offset too big"); }
1408 * Now get last part - the description
1410 EATAB;
1411 if (l[0] == '\b') {
1412 ++l;
1413 m->flag |= NOSPACE;
1414 } else if ((l[0] == '\\') && (l[1] == 'b')) {
1415 ++l;
1416 ++l;
1417 m->flag |= NOSPACE;
1419 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
1420 continue;
1421 if (i == sizeof(m->desc)) {
1422 m->desc[sizeof(m->desc) - 1] = '\0';
1423 if (ms->flags & MAGIC_CHECK)
1424 file_magwarn(ms, "description `%s' truncated", m->desc);
1428 * We only do this check while compiling, or if any of the magic
1429 * files were not compiled.
1431 if (ms->flags & MAGIC_CHECK) {
1432 if (check_format(ms, m) == -1)
1433 return -1;
1435 #ifndef COMPILE_ONLY
1436 if (action == FILE_CHECK) {
1437 file_mdump(m);
1439 #endif
1440 m->mimetype[0] = '\0'; /* initialise MIME type to none */
1441 if (m->cont_level == 0)
1442 ++(*nmentryp); /* make room for next */
1443 return 0;
1447 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
1448 * if valid
1450 private int
1451 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
1453 const char *l = line;
1454 char *el;
1455 unsigned long factor;
1456 struct magic *m = &me->mp[0];
1458 if (m->factor_op != FILE_FACTOR_OP_NONE) {
1459 file_magwarn(ms,
1460 "Current entry already has a strength type: %c %d",
1461 m->factor_op, m->factor);
1462 return -1;
1464 EATAB;
1465 switch (*l) {
1466 case FILE_FACTOR_OP_NONE:
1467 case FILE_FACTOR_OP_PLUS:
1468 case FILE_FACTOR_OP_MINUS:
1469 case FILE_FACTOR_OP_TIMES:
1470 case FILE_FACTOR_OP_DIV:
1471 m->factor_op = *l++;
1472 break;
1473 default:
1474 file_magwarn(ms, "Unknown factor op `%c'", *l);
1475 return -1;
1477 EATAB;
1478 factor = strtoul(l, &el, 0);
1479 if (factor > 255) {
1480 file_magwarn(ms, "Too large factor `%lu'", factor);
1481 goto out;
1483 if (*el && !isspace((unsigned char)*el)) {
1484 file_magwarn(ms, "Bad factor `%s'", l);
1485 goto out;
1487 m->factor = (uint8_t)factor;
1488 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
1489 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
1490 m->factor_op, m->factor);
1491 goto out;
1493 return 0;
1494 out:
1495 m->factor_op = FILE_FACTOR_OP_NONE;
1496 m->factor = 0;
1497 return -1;
1501 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into magic[index - 1]
1503 private int
1504 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
1506 size_t i;
1507 const char *l = line;
1508 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1510 if (m->apple[0] != '\0') {
1511 file_magwarn(ms, "Current entry already has a APPLE type `%.8s',"
1512 " new type `%s'", m->mimetype, l);
1513 return -1;
1516 EATAB;
1517 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1518 || strchr("-+/.", *l)) && i < sizeof(m->apple); m->apple[i++] = *l++)
1519 continue;
1520 if (i == sizeof(m->apple) && *l) {
1521 if (ms->flags & MAGIC_CHECK)
1522 file_magwarn(ms, "APPLE type `%s' truncated %zu",
1523 line, i);
1526 if (i > 0)
1527 return 0;
1528 else
1529 return -1;
1533 * parse a MIME annotation line from magic file, put into magic[index - 1]
1534 * if valid
1536 private int
1537 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
1539 size_t i;
1540 const char *l = line;
1541 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1543 if (m->mimetype[0] != '\0') {
1544 file_magwarn(ms, "Current entry already has a MIME type `%s',"
1545 " new type `%s'", m->mimetype, l);
1546 return -1;
1549 EATAB;
1550 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1551 || strchr("-+/.", *l)) && i < sizeof(m->mimetype); m->mimetype[i++] = *l++)
1552 continue;
1553 if (i == sizeof(m->mimetype)) {
1554 m->desc[sizeof(m->mimetype) - 1] = '\0';
1555 if (ms->flags & MAGIC_CHECK)
1556 file_magwarn(ms, "MIME type `%s' truncated %zu",
1557 m->mimetype, i);
1558 } else
1559 m->mimetype[i] = '\0';
1561 if (i > 0)
1562 return 0;
1563 else
1564 return -1;
1567 private int
1568 check_format_type(const char *ptr, int type)
1570 int quad = 0;
1571 if (*ptr == '\0') {
1572 /* Missing format string; bad */
1573 return -1;
1576 switch (type) {
1577 case FILE_FMT_QUAD:
1578 quad = 1;
1579 /*FALLTHROUGH*/
1580 case FILE_FMT_NUM:
1581 if (*ptr == '-')
1582 ptr++;
1583 if (*ptr == '.')
1584 ptr++;
1585 while (isdigit((unsigned char)*ptr)) ptr++;
1586 if (*ptr == '.')
1587 ptr++;
1588 while (isdigit((unsigned char)*ptr)) ptr++;
1589 if (quad) {
1590 if (*ptr++ != 'l')
1591 return -1;
1592 if (*ptr++ != 'l')
1593 return -1;
1596 switch (*ptr++) {
1597 case 'l':
1598 switch (*ptr++) {
1599 case 'i':
1600 case 'd':
1601 case 'u':
1602 case 'x':
1603 case 'X':
1604 return 0;
1605 default:
1606 return -1;
1609 case 'h':
1610 switch (*ptr++) {
1611 case 'h':
1612 switch (*ptr++) {
1613 case 'i':
1614 case 'd':
1615 case 'u':
1616 case 'x':
1617 case 'X':
1618 return 0;
1619 default:
1620 return -1;
1622 case 'd':
1623 return 0;
1624 default:
1625 return -1;
1628 case 'i':
1629 case 'c':
1630 case 'd':
1631 case 'u':
1632 case 'x':
1633 case 'X':
1634 return 0;
1636 default:
1637 return -1;
1640 case FILE_FMT_FLOAT:
1641 case FILE_FMT_DOUBLE:
1642 if (*ptr == '-')
1643 ptr++;
1644 if (*ptr == '.')
1645 ptr++;
1646 while (isdigit((unsigned char)*ptr)) ptr++;
1647 if (*ptr == '.')
1648 ptr++;
1649 while (isdigit((unsigned char)*ptr)) ptr++;
1651 switch (*ptr++) {
1652 case 'e':
1653 case 'E':
1654 case 'f':
1655 case 'F':
1656 case 'g':
1657 case 'G':
1658 return 0;
1660 default:
1661 return -1;
1665 case FILE_FMT_STR:
1666 if (*ptr == '-')
1667 ptr++;
1668 while (isdigit((unsigned char )*ptr))
1669 ptr++;
1670 if (*ptr == '.') {
1671 ptr++;
1672 while (isdigit((unsigned char )*ptr))
1673 ptr++;
1676 switch (*ptr++) {
1677 case 's':
1678 return 0;
1679 default:
1680 return -1;
1683 default:
1684 /* internal error */
1685 abort();
1687 /*NOTREACHED*/
1688 return -1;
1692 * Check that the optional printf format in description matches
1693 * the type of the magic.
1695 private int
1696 check_format(struct magic_set *ms, struct magic *m)
1698 char *ptr;
1700 for (ptr = m->desc; *ptr; ptr++)
1701 if (*ptr == '%')
1702 break;
1703 if (*ptr == '\0') {
1704 /* No format string; ok */
1705 return 1;
1708 assert(file_nformats == file_nnames);
1710 if (m->type >= file_nformats) {
1711 file_magwarn(ms, "Internal error inconsistency between "
1712 "m->type and format strings");
1713 return -1;
1715 if (file_formats[m->type] == FILE_FMT_NONE) {
1716 file_magwarn(ms, "No format string for `%s' with description "
1717 "`%s'", m->desc, file_names[m->type]);
1718 return -1;
1721 ptr++;
1722 if (check_format_type(ptr, file_formats[m->type]) == -1) {
1724 * TODO: this error message is unhelpful if the format
1725 * string is not one character long
1727 file_magwarn(ms, "Printf format `%c' is not valid for type "
1728 "`%s' in description `%s'", *ptr ? *ptr : '?',
1729 file_names[m->type], m->desc);
1730 return -1;
1733 for (; *ptr; ptr++) {
1734 if (*ptr == '%') {
1735 file_magwarn(ms,
1736 "Too many format strings (should have at most one) "
1737 "for `%s' with description `%s'",
1738 file_names[m->type], m->desc);
1739 return -1;
1742 return 0;
1746 * Read a numeric value from a pointer, into the value union of a magic
1747 * pointer, according to the magic type. Update the string pointer to point
1748 * just after the number read. Return 0 for success, non-zero for failure.
1750 private int
1751 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
1753 switch (m->type) {
1754 case FILE_BESTRING16:
1755 case FILE_LESTRING16:
1756 case FILE_STRING:
1757 case FILE_PSTRING:
1758 case FILE_REGEX:
1759 case FILE_SEARCH:
1760 *p = getstr(ms, m, *p, action == FILE_COMPILE);
1761 if (*p == NULL) {
1762 if (ms->flags & MAGIC_CHECK)
1763 file_magwarn(ms, "cannot get string from `%s'",
1764 m->value.s);
1765 return -1;
1767 return 0;
1768 case FILE_FLOAT:
1769 case FILE_BEFLOAT:
1770 case FILE_LEFLOAT:
1771 if (m->reln != 'x') {
1772 char *ep;
1773 #ifdef HAVE_STRTOF
1774 m->value.f = strtof(*p, &ep);
1775 #else
1776 m->value.f = (float)strtod(*p, &ep);
1777 #endif
1778 *p = ep;
1780 return 0;
1781 case FILE_DOUBLE:
1782 case FILE_BEDOUBLE:
1783 case FILE_LEDOUBLE:
1784 if (m->reln != 'x') {
1785 char *ep;
1786 m->value.d = strtod(*p, &ep);
1787 *p = ep;
1789 return 0;
1790 default:
1791 if (m->reln != 'x') {
1792 char *ep;
1793 m->value.q = file_signextend(ms, m,
1794 (uint64_t)strtoull(*p, &ep, 0));
1795 *p = ep;
1796 eatsize(p);
1798 return 0;
1803 * Convert a string containing C character escapes. Stop at an unescaped
1804 * space or tab.
1805 * Copy the converted version to "m->value.s", and the length in m->vallen.
1806 * Return updated scan pointer as function result. Warn if set.
1808 private const char *
1809 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
1811 const char *origs = s;
1812 char *p = m->value.s;
1813 size_t plen = sizeof(m->value.s);
1814 char *origp = p;
1815 char *pmax = p + plen - 1;
1816 int c;
1817 int val;
1819 while ((c = *s++) != '\0') {
1820 if (isspace((unsigned char) c))
1821 break;
1822 if (p >= pmax) {
1823 file_error(ms, 0, "string too long: `%s'", origs);
1824 return NULL;
1826 if (c == '\\') {
1827 switch(c = *s++) {
1829 case '\0':
1830 if (warn)
1831 file_magwarn(ms, "incomplete escape");
1832 goto out;
1834 case '\t':
1835 if (warn) {
1836 file_magwarn(ms,
1837 "escaped tab found, use \\t instead");
1838 warn = 0; /* already did */
1840 /*FALLTHROUGH*/
1841 default:
1842 if (warn) {
1843 if (isprint((unsigned char)c)) {
1844 /* Allow escaping of
1845 * ``relations'' */
1846 if (strchr("<>&^=!", c)
1847 == NULL) {
1848 file_magwarn(ms, "no "
1849 "need to escape "
1850 "`%c'", c);
1852 } else {
1853 file_magwarn(ms,
1854 "unknown escape sequence: "
1855 "\\%03o", c);
1858 /*FALLTHROUGH*/
1859 /* space, perhaps force people to use \040? */
1860 case ' ':
1861 #if 0
1863 * Other things people escape, but shouldn't need to,
1864 * so we disallow them
1866 case '\'':
1867 case '"':
1868 case '?':
1869 #endif
1870 /* Relations */
1871 case '>':
1872 case '<':
1873 case '&':
1874 case '^':
1875 case '=':
1876 case '!':
1877 /* and baskslash itself */
1878 case '\\':
1879 *p++ = (char) c;
1880 break;
1882 case 'a':
1883 *p++ = '\a';
1884 break;
1886 case 'b':
1887 *p++ = '\b';
1888 break;
1890 case 'f':
1891 *p++ = '\f';
1892 break;
1894 case 'n':
1895 *p++ = '\n';
1896 break;
1898 case 'r':
1899 *p++ = '\r';
1900 break;
1902 case 't':
1903 *p++ = '\t';
1904 break;
1906 case 'v':
1907 *p++ = '\v';
1908 break;
1910 /* \ and up to 3 octal digits */
1911 case '0':
1912 case '1':
1913 case '2':
1914 case '3':
1915 case '4':
1916 case '5':
1917 case '6':
1918 case '7':
1919 val = c - '0';
1920 c = *s++; /* try for 2 */
1921 if (c >= '0' && c <= '7') {
1922 val = (val << 3) | (c - '0');
1923 c = *s++; /* try for 3 */
1924 if (c >= '0' && c <= '7')
1925 val = (val << 3) | (c-'0');
1926 else
1927 --s;
1929 else
1930 --s;
1931 *p++ = (char)val;
1932 break;
1934 /* \x and up to 2 hex digits */
1935 case 'x':
1936 val = 'x'; /* Default if no digits */
1937 c = hextoint(*s++); /* Get next char */
1938 if (c >= 0) {
1939 val = c;
1940 c = hextoint(*s++);
1941 if (c >= 0)
1942 val = (val << 4) + c;
1943 else
1944 --s;
1945 } else
1946 --s;
1947 *p++ = (char)val;
1948 break;
1950 } else
1951 *p++ = (char)c;
1953 out:
1954 *p = '\0';
1955 m->vallen = CAST(unsigned char, (p - origp));
1956 if (m->type == FILE_PSTRING)
1957 m->vallen++;
1958 return s;
1962 /* Single hex char to int; -1 if not a hex char. */
1963 private int
1964 hextoint(int c)
1966 if (!isascii((unsigned char) c))
1967 return -1;
1968 if (isdigit((unsigned char) c))
1969 return c - '0';
1970 if ((c >= 'a') && (c <= 'f'))
1971 return c + 10 - 'a';
1972 if (( c>= 'A') && (c <= 'F'))
1973 return c + 10 - 'A';
1974 return -1;
1979 * Print a string containing C character escapes.
1981 protected void
1982 file_showstr(FILE *fp, const char *s, size_t len)
1984 char c;
1986 for (;;) {
1987 c = *s++;
1988 if (len == ~0U) {
1989 if (c == '\0')
1990 break;
1992 else {
1993 if (len-- == 0)
1994 break;
1996 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
1997 (void) fputc(c, fp);
1998 else {
1999 (void) fputc('\\', fp);
2000 switch (c) {
2001 case '\a':
2002 (void) fputc('a', fp);
2003 break;
2005 case '\b':
2006 (void) fputc('b', fp);
2007 break;
2009 case '\f':
2010 (void) fputc('f', fp);
2011 break;
2013 case '\n':
2014 (void) fputc('n', fp);
2015 break;
2017 case '\r':
2018 (void) fputc('r', fp);
2019 break;
2021 case '\t':
2022 (void) fputc('t', fp);
2023 break;
2025 case '\v':
2026 (void) fputc('v', fp);
2027 break;
2029 default:
2030 (void) fprintf(fp, "%.3o", c & 0377);
2031 break;
2038 * eatsize(): Eat the size spec from a number [eg. 10UL]
2040 private void
2041 eatsize(const char **p)
2043 const char *l = *p;
2045 if (LOWCASE(*l) == 'u')
2046 l++;
2048 switch (LOWCASE(*l)) {
2049 case 'l': /* long */
2050 case 's': /* short */
2051 case 'h': /* short */
2052 case 'b': /* char/byte */
2053 case 'c': /* char/byte */
2054 l++;
2055 /*FALLTHROUGH*/
2056 default:
2057 break;
2060 *p = l;
2064 * handle a compiled file.
2066 private int
2067 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
2068 const char *fn)
2070 int fd;
2071 struct stat st;
2072 uint32_t *ptr;
2073 uint32_t version;
2074 int needsbyteswap;
2075 char *dbname = NULL;
2076 void *mm = NULL;
2078 dbname = mkdbname(ms, fn, 0);
2079 if (dbname == NULL)
2080 goto error2;
2082 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2083 goto error2;
2085 if (fstat(fd, &st) == -1) {
2086 file_error(ms, errno, "cannot stat `%s'", dbname);
2087 goto error1;
2089 if (st.st_size < 8) {
2090 file_error(ms, 0, "file `%s' is too small", dbname);
2091 goto error1;
2094 #ifdef QUICK
2095 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2096 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2097 file_error(ms, errno, "cannot map `%s'", dbname);
2098 goto error1;
2100 #define RET 2
2101 #else
2102 if ((mm = CAST(void *, malloc((size_t)st.st_size))) == NULL) {
2103 file_oomem(ms, (size_t)st.st_size);
2104 goto error1;
2106 if (read(fd, mm, (size_t)st.st_size) != (ssize_t)st.st_size) {
2107 file_badread(ms);
2108 goto error1;
2110 #define RET 1
2111 #endif
2112 *magicp = CAST(struct magic *, mm);
2113 (void)close(fd);
2114 fd = -1;
2115 ptr = (uint32_t *)(void *)*magicp;
2116 if (*ptr != MAGICNO) {
2117 if (swap4(*ptr) != MAGICNO) {
2118 file_error(ms, 0, "bad magic in `%s'", dbname);
2119 goto error1;
2121 needsbyteswap = 1;
2122 } else
2123 needsbyteswap = 0;
2124 if (needsbyteswap)
2125 version = swap4(ptr[1]);
2126 else
2127 version = ptr[1];
2128 if (version != VERSIONNO) {
2129 file_error(ms, 0, "File %d.%d supports only version %d magic "
2130 "files. `%s' is version %d", FILE_VERSION_MAJOR, patchlevel,
2131 VERSIONNO, dbname, version);
2132 goto error1;
2134 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic));
2135 if (*nmagicp > 0)
2136 (*nmagicp)--;
2137 (*magicp)++;
2138 if (needsbyteswap)
2139 byteswap(*magicp, *nmagicp);
2140 free(dbname);
2141 return RET;
2143 error1:
2144 if (fd != -1)
2145 (void)close(fd);
2146 if (mm) {
2147 #ifdef QUICK
2148 (void)munmap((void *)mm, (size_t)st.st_size);
2149 #else
2150 free(mm);
2151 #endif
2152 } else {
2153 *magicp = NULL;
2154 *nmagicp = 0;
2156 error2:
2157 free(dbname);
2158 return -1;
2161 private const uint32_t ar[] = {
2162 MAGICNO, VERSIONNO
2165 * handle an mmaped file.
2167 private int
2168 apprentice_compile(struct magic_set *ms, struct magic **magicp,
2169 uint32_t *nmagicp, const char *fn)
2171 int fd;
2172 char *dbname;
2173 int rv = -1;
2175 dbname = mkdbname(ms, fn, 1);
2177 if (dbname == NULL)
2178 goto out;
2180 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1) {
2181 file_error(ms, errno, "cannot open `%s'", dbname);
2182 goto out;
2185 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
2186 file_error(ms, errno, "error writing `%s'", dbname);
2187 goto out;
2190 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
2191 != sizeof(struct magic)) {
2192 file_error(ms, errno, "error seeking `%s'", dbname);
2193 goto out;
2196 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
2197 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
2198 file_error(ms, errno, "error writing `%s'", dbname);
2199 goto out;
2202 (void)close(fd);
2203 rv = 0;
2204 out:
2205 free(dbname);
2206 return rv;
2209 private const char ext[] = ".mgc";
2211 * make a dbname
2213 private char *
2214 mkdbname(struct magic_set *ms, const char *fn, int strip)
2216 const char *p, *q;
2217 char *buf;
2219 if (strip) {
2220 if ((p = strrchr(fn, '/')) != NULL)
2221 fn = ++p;
2224 for (q = fn; *q; q++)
2225 continue;
2226 /* Look for .mgc */
2227 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
2228 if (*p != *q)
2229 break;
2231 /* Did not find .mgc, restore q */
2232 if (p >= ext)
2233 while (*q)
2234 q++;
2236 q++;
2237 /* Compatibility with old code that looked in .mime */
2238 if (ms->flags & MAGIC_MIME) {
2239 asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext);
2240 if (access(buf, R_OK) != -1) {
2241 ms->flags &= MAGIC_MIME_TYPE;
2242 return buf;
2244 free(buf);
2246 asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext);
2248 /* Compatibility with old code that looked in .mime */
2249 if (strstr(p, ".mime") != NULL)
2250 ms->flags &= MAGIC_MIME_TYPE;
2251 return buf;
2255 * Byteswap an mmap'ed file if needed
2257 private void
2258 byteswap(struct magic *magic, uint32_t nmagic)
2260 uint32_t i;
2261 for (i = 0; i < nmagic; i++)
2262 bs1(&magic[i]);
2266 * swap a short
2268 private uint16_t
2269 swap2(uint16_t sv)
2271 uint16_t rv;
2272 uint8_t *s = (uint8_t *)(void *)&sv;
2273 uint8_t *d = (uint8_t *)(void *)&rv;
2274 d[0] = s[1];
2275 d[1] = s[0];
2276 return rv;
2280 * swap an int
2282 private uint32_t
2283 swap4(uint32_t sv)
2285 uint32_t rv;
2286 uint8_t *s = (uint8_t *)(void *)&sv;
2287 uint8_t *d = (uint8_t *)(void *)&rv;
2288 d[0] = s[3];
2289 d[1] = s[2];
2290 d[2] = s[1];
2291 d[3] = s[0];
2292 return rv;
2296 * swap a quad
2298 private uint64_t
2299 swap8(uint64_t sv)
2301 uint64_t rv;
2302 uint8_t *s = (uint8_t *)(void *)&sv;
2303 uint8_t *d = (uint8_t *)(void *)&rv;
2304 #if 0
2305 d[0] = s[3];
2306 d[1] = s[2];
2307 d[2] = s[1];
2308 d[3] = s[0];
2309 d[4] = s[7];
2310 d[5] = s[6];
2311 d[6] = s[5];
2312 d[7] = s[4];
2313 #else
2314 d[0] = s[7];
2315 d[1] = s[6];
2316 d[2] = s[5];
2317 d[3] = s[4];
2318 d[4] = s[3];
2319 d[5] = s[2];
2320 d[6] = s[1];
2321 d[7] = s[0];
2322 #endif
2323 return rv;
2327 * byteswap a single magic entry
2329 private void
2330 bs1(struct magic *m)
2332 m->cont_level = swap2(m->cont_level);
2333 m->offset = swap4((uint32_t)m->offset);
2334 m->in_offset = swap4((uint32_t)m->in_offset);
2335 m->lineno = swap4((uint32_t)m->lineno);
2336 if (IS_STRING(m->type)) {
2337 m->str_range = swap4(m->str_range);
2338 m->str_flags = swap4(m->str_flags);
2340 else {
2341 m->value.q = swap8(m->value.q);
2342 m->num_mask = swap8(m->num_mask);