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.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
29 * apprentice - make one pass through /etc/magic, learning its secrets.
35 FILE_RCSID("@(#)$File: apprentice.c,v 1.158 2009/10/19 13:10:20 christos Exp $")
39 #include "patchlevel.h"
53 #define EATAB {while (isascii((unsigned char) *l) && \
54 isspace((unsigned char) *l)) ++l;}
55 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
56 tolower((unsigned char) (l)) : (l))
58 * Work around a bug in headers on Digital Unix.
59 * At least confirmed for: OSF1 V4.0 878
61 #if defined(__osf__) && defined(__DECC)
68 #define MAP_FAILED (void *) -1
76 #define MAXPATHLEN 1024
85 int file_formats[FILE_NAMES_SIZE];
86 const size_t file_nformats = FILE_NAMES_SIZE;
87 const char *file_names[FILE_NAMES_SIZE];
88 const size_t file_nnames = FILE_NAMES_SIZE;
90 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
91 private int hextoint(int);
92 private const char *getstr(struct magic_set *, struct magic *, const char *,
94 private int parse(struct magic_set *, struct magic_entry **, uint32_t *,
95 const char *, size_t, int);
96 private void eatsize(const char **);
97 private int apprentice_1(struct magic_set *, const char *, int, struct mlist *);
98 private size_t apprentice_magic_strength(const struct magic *);
99 private int apprentice_sort(const void *, const void *);
100 private int apprentice_load(struct magic_set *, struct magic **, uint32_t *,
102 private void byteswap(struct magic *, uint32_t);
103 private void bs1(struct magic *);
104 private uint16_t swap2(uint16_t);
105 private uint32_t swap4(uint32_t);
106 private uint64_t swap8(uint64_t);
107 private char *mkdbname(struct magic_set *, const char *, int);
108 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
110 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
112 private int check_format_type(const char *, int);
113 private int check_format(struct magic_set *, struct magic *);
114 private int get_op(char);
115 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
116 private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
117 private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
120 private size_t maxmagic = 0;
121 private size_t magicsize = sizeof(struct magic);
123 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
128 int (*fun)(struct magic_set *, struct magic_entry *, const char *);
130 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
132 DECLARE_FIELD(apple),
133 DECLARE_FIELD(strength),
140 int main(int, char *[]);
143 main(int argc, char *argv[])
146 struct magic_set *ms;
149 if ((progname = strrchr(argv[0], '/')) != NULL)
155 (void)fprintf(stderr, "Usage: %s file\n", progname);
159 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
160 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
163 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
165 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
169 #endif /* COMPILE_ONLY */
171 static const struct type_tbl_s {
177 # define XX(s) s, (sizeof(s) - 1)
178 # define XX_NULL "", 0
179 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
180 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
181 { XX("default"), FILE_DEFAULT, FILE_FMT_STR },
182 { XX("long"), FILE_LONG, FILE_FMT_NUM },
183 { XX("string"), FILE_STRING, FILE_FMT_STR },
184 { XX("date"), FILE_DATE, FILE_FMT_STR },
185 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
186 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
187 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
188 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
189 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
190 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
191 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
192 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
193 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
194 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
195 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
196 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
197 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
198 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
199 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
200 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
201 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
202 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
203 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
204 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
205 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
206 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
207 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
208 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
209 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
210 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
211 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
212 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
213 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
214 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
215 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
216 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
217 { XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
218 { XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
219 { XX("indirect"), FILE_INDIRECT, FILE_FMT_NONE },
220 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
226 get_type(const char *l, const char **t)
228 const struct type_tbl_s *p;
230 for (p = type_tbl; p->len; p++) {
231 if (strncmp(l, p->name, p->len) == 0) {
241 init_file_tables(void)
244 const struct type_tbl_s *p;
250 for (p = type_tbl; p->len; p++) {
251 assert(p->type < FILE_NAMES_SIZE);
252 file_names[p->type] = p->name;
253 file_formats[p->type] = p->format;
258 * Handle one file or directory.
261 apprentice_1(struct magic_set *ms, const char *fn, int action,
264 struct magic *magic = NULL;
270 if (magicsize != FILE_MAGICSIZE) {
271 file_error(ms, 0, "magic element size %lu != %lu",
272 (unsigned long)sizeof(*magic),
273 (unsigned long)FILE_MAGICSIZE);
277 if (action == FILE_COMPILE) {
278 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
281 rv = apprentice_compile(ms, &magic, &nmagic, fn);
287 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
288 if (ms->flags & MAGIC_CHECK)
289 file_magwarn(ms, "using regular magic file `%s'", fn);
290 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
298 file_delmagic(magic, mapped, nmagic);
302 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL) {
303 file_delmagic(magic, mapped, nmagic);
304 file_oomem(ms, sizeof(*ml));
312 mlist->prev->next = ml;
313 ml->prev = mlist->prev;
318 #endif /* COMPILE_ONLY */
322 file_delmagic(struct magic *p, int type, size_t entries)
330 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
348 /* const char *fn: list of magic files and directories */
349 protected struct mlist *
350 file_apprentice(struct magic_set *ms, const char *fn, int action)
353 int file_err, errs = -1;
356 if ((fn = magic_getpath(fn, action)) == NULL)
361 if ((mfn = strdup(fn)) == NULL) {
362 file_oomem(ms, strlen(fn));
367 if ((mlist = CAST(struct mlist *, malloc(sizeof(*mlist)))) == NULL) {
369 file_oomem(ms, sizeof(*mlist));
372 mlist->next = mlist->prev = mlist;
375 p = strchr(fn, PATHSEP);
380 file_err = apprentice_1(ms, fn, action, mlist);
381 errs = MAX(errs, file_err);
388 file_error(ms, 0, "could not find any magic files!");
396 * Get weight of this magic entry, for sorting purposes.
399 apprentice_magic_strength(const struct magic *m)
402 size_t val = 2 * MULT; /* baseline strength */
405 case FILE_DEFAULT: /* make sure this sorts last */
406 if (m->factor_op != FILE_FACTOR_OP_NONE)
429 val += m->vallen * MULT;
432 case FILE_BESTRING16:
433 case FILE_LESTRING16:
434 val += m->vallen * MULT / 2;
439 val += m->vallen * MAX(MULT / m->vallen, 1);
473 (void)fprintf(stderr, "Bad type %d\n", m->type);
478 case 'x': /* matches anything penalize */
479 case '!': /* matches almost anything penalize */
483 case '=': /* Exact match, prefer */
488 case '<': /* comparison match reduce strength */
493 case '&': /* masking bits, we could count them too */
498 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
502 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
505 switch (m->factor_op) {
506 case FILE_FACTOR_OP_NONE:
508 case FILE_FACTOR_OP_PLUS:
511 case FILE_FACTOR_OP_MINUS:
514 case FILE_FACTOR_OP_TIMES:
517 case FILE_FACTOR_OP_DIV:
525 * Magic entries with no description get a bonus because they depend
526 * on subsequent magic entries to print something.
528 if (m->desc[0] == '\0')
534 * Sort callback for sorting entries by "strength" (basically length)
537 apprentice_sort(const void *a, const void *b)
539 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
540 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
541 size_t sa = apprentice_magic_strength(ma->mp);
542 size_t sb = apprentice_magic_strength(mb->mp);
552 set_test_type(struct magic *mstart, struct magic *m)
588 case FILE_BESTRING16:
589 case FILE_LESTRING16:
590 /* binary test, set flag */
591 mstart->flag |= BINTEST;
596 if (mstart->str_flags & STRING_BINTEST)
597 mstart->flag |= BINTEST;
598 if (mstart->str_flags & STRING_TEXTTEST)
599 mstart->flag |= TEXTTEST;
601 if (mstart->flag & (TEXTTEST|BINTEST))
604 /* binary test if pattern is not text */
605 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
607 mstart->flag |= BINTEST;
609 mstart->flag |= TEXTTEST;
613 /* can't deduce anything; we shouldn't see this at the
618 /* invalid search type, but no need to complain here */
624 * Load and parse one file.
627 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
628 struct magic_entry **marray, uint32_t *marraycount)
632 FILE *f = fopen(ms->file = fn, "r");
635 file_error(ms, errno, "cannot read magic file `%s'",
639 /* read and parse this file */
641 fgets(line, CAST(int, sizeof(line)), f) != NULL;
645 if (len == 0) /* null line, garbage, etc */
647 if (line[len - 1] == '\n') {
649 line[len - 1] = '\0'; /* delete newline */
651 if (line[0] == '\0') /* empty, do not parse */
653 if (line[0] == '#') /* comment, do not parse */
655 if (line[0] == '!' && line[1] == ':') {
658 for (i = 0; bang[i].name != NULL; i++) {
659 if (len - 2 > bang[i].len &&
660 memcmp(bang[i].name, line + 2,
664 if (bang[i].name == NULL) {
666 "Unknown !: entry `%s'", line);
670 if (*marraycount == 0) {
672 "No current entry for :!%s type",
677 if ((*bang[i].fun)(ms,
678 &(*marray)[*marraycount - 1],
679 line + bang[i].len + 2) != 0) {
685 if (parse(ms, marray, marraycount, line, lineno,
695 * parse a file or directory of files
696 * const char *fn: name of magic file or directory
699 cmpstrp(const void *p1, const void *p2)
701 return strcmp(*(char *const *)p1, *(char *const *)p2);
705 apprentice_load(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
706 const char *fn, int action)
709 struct magic_entry *marray;
710 uint32_t marraycount, i, mentrycount = 0, starttest;
711 size_t slen, files = 0, maxfiles = 0;
712 char subfn[MAXPATHLEN], **filearr = NULL, *mfn;
717 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
720 if ((marray = CAST(struct magic_entry *, calloc(maxmagic,
721 sizeof(*marray)))) == NULL) {
722 file_oomem(ms, maxmagic * sizeof(*marray));
727 /* print silly verbose header for USG compat. */
728 if (action == FILE_CHECK)
729 (void)fprintf(stderr, "%s\n", usg_hdr);
731 /* load directory or file */
732 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
738 while ((d = readdir(dir)) != NULL) {
739 (void)snprintf(subfn, sizeof(subfn), "%s/%s",
741 if (stat(subfn, &st) == -1 || !S_ISREG(st.st_mode))
743 if ((mfn = strdup(subfn)) == NULL) {
744 file_oomem(ms, strlen(subfn));
748 if (files >= maxfiles) {
750 maxfiles = (maxfiles + 1) * 2;
751 mlen = maxfiles * sizeof(*filearr);
752 if ((filearr = CAST(char **,
753 realloc(filearr, mlen))) == NULL) {
754 file_oomem(ms, mlen);
759 filearr[files++] = mfn;
762 qsort(filearr, files, sizeof(*filearr), cmpstrp);
763 for (i = 0; i < files; i++) {
764 load_1(ms, action, filearr[i], &errs, &marray,
770 load_1(ms, action, fn, &errs, &marray, &marraycount);
774 /* Set types of tests */
775 for (i = 0; i < marraycount; ) {
776 if (marray[i].mp->cont_level != 0) {
783 static const char text[] = "text";
784 static const char binary[] = "binary";
785 static const size_t len = sizeof(text);
786 set_test_type(marray[starttest].mp, marray[i].mp);
787 if ((ms->flags & MAGIC_DEBUG) == 0)
789 (void)fprintf(stderr, "%s%s%s: %s\n",
790 marray[i].mp->mimetype,
791 marray[i].mp->mimetype[0] == '\0' ? "" : "; ",
792 marray[i].mp->desc[0] ? marray[i].mp->desc :
794 marray[i].mp->flag & BINTEST ? binary : text);
795 if (marray[i].mp->flag & BINTEST) {
796 char *p = strstr(marray[i].mp->desc, text);
797 if (p && (p == marray[i].mp->desc ||
798 isspace((unsigned char)p[-1])) &&
799 (p + len - marray[i].mp->desc ==
800 MAXstring || (p[len] == '\0' ||
801 isspace((unsigned char)p[len]))))
802 (void)fprintf(stderr, "*** Possible "
803 "binary test for text type\n");
805 } while (++i < marraycount && marray[i].mp->cont_level != 0);
808 qsort(marray, marraycount, sizeof(*marray), apprentice_sort);
811 * Make sure that any level 0 "default" line is last (if one exists).
813 for (i = 0; i < marraycount; i++) {
814 if (marray[i].mp->cont_level == 0 &&
815 marray[i].mp->type == FILE_DEFAULT) {
816 while (++i < marraycount)
817 if (marray[i].mp->cont_level == 0)
819 if (i != marraycount) {
820 ms->line = marray[i].mp->lineno; /* XXX - Ugh! */
822 "level 0 \"default\" did not sort last");
828 for (i = 0; i < marraycount; i++)
829 mentrycount += marray[i].cont_count;
831 slen = sizeof(**magicp) * mentrycount;
832 if ((*magicp = CAST(struct magic *, malloc(slen))) == NULL) {
833 file_oomem(ms, slen);
839 for (i = 0; i < marraycount; i++) {
840 (void)memcpy(*magicp + mentrycount, marray[i].mp,
841 marray[i].cont_count * sizeof(**magicp));
842 mentrycount += marray[i].cont_count;
845 for (i = 0; i < marraycount; i++)
853 *nmagicp = mentrycount;
860 * extend the sign bit if the comparison is to be signed
863 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
865 if (!(m->flag & UNSIGNED)) {
868 * Do not remove the casts below. They are
869 * vital. When later compared with the data,
870 * the sign extension must have happened.
913 case FILE_BESTRING16:
914 case FILE_LESTRING16:
921 if (ms->flags & MAGIC_CHECK)
922 file_magwarn(ms, "cannot happen: m->type=%d\n",
931 string_modifier_check(struct magic_set *ms, struct magic *m)
933 if ((ms->flags & MAGIC_CHECK) == 0)
937 case FILE_BESTRING16:
938 case FILE_LESTRING16:
939 if (m->str_flags != 0) {
941 "no modifiers allowed for 16-bit strings\n");
947 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
949 "'/%c' only allowed on regex and search\n",
950 CHAR_REGEX_OFFSET_START);
955 if (m->str_range == 0) {
957 "missing range; defaulting to %d\n",
958 STRING_DEFAULT_RANGE);
959 m->str_range = STRING_DEFAULT_RANGE;
964 if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
965 file_magwarn(ms, "'/%c' not allowed on regex\n",
966 CHAR_COMPACT_WHITESPACE);
969 if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
970 file_magwarn(ms, "'/%c' not allowed on regex\n",
971 CHAR_COMPACT_OPTIONAL_WHITESPACE);
976 file_magwarn(ms, "coding error: m->type=%d\n",
998 return FILE_OPMULTIPLY;
1000 return FILE_OPDIVIDE;
1002 return FILE_OPMODULO;
1008 #ifdef ENABLE_CONDITIONALS
1010 get_cond(const char *l, const char **t)
1012 static const struct cond_tbl_s {
1017 { "if", 2, COND_IF },
1018 { "elif", 4, COND_ELIF },
1019 { "else", 4, COND_ELSE },
1020 { "", 0, COND_NONE },
1022 const struct cond_tbl_s *p;
1024 for (p = cond_tbl; p->len; p++) {
1025 if (strncmp(l, p->name, p->len) == 0 &&
1026 isspace((unsigned char)l[p->len])) {
1036 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1039 last_cond = ms->c.li[cont_level].last_cond;
1043 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1044 if (ms->flags & MAGIC_CHECK)
1045 file_magwarn(ms, "syntax error: `if'");
1048 last_cond = COND_IF;
1052 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1053 if (ms->flags & MAGIC_CHECK)
1054 file_magwarn(ms, "syntax error: `elif'");
1057 last_cond = COND_ELIF;
1061 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1062 if (ms->flags & MAGIC_CHECK)
1063 file_magwarn(ms, "syntax error: `else'");
1066 last_cond = COND_NONE;
1070 last_cond = COND_NONE;
1074 ms->c.li[cont_level].last_cond = last_cond;
1077 #endif /* ENABLE_CONDITIONALS */
1080 * parse one line from magic file, put into magic[index++] if valid
1083 parse(struct magic_set *ms, struct magic_entry **mentryp, uint32_t *nmentryp,
1084 const char *line, size_t lineno, int action)
1086 #ifdef ENABLE_CONDITIONALS
1087 static uint32_t last_cont_level = 0;
1090 struct magic_entry *me;
1092 const char *l = line;
1095 uint32_t cont_level;
1100 ++l; /* step over */
1103 #ifdef ENABLE_CONDITIONALS
1104 if (cont_level == 0 || cont_level > last_cont_level)
1105 if (file_check_mem(ms, cont_level) == -1)
1107 last_cont_level = cont_level;
1110 #define ALLOC_CHUNK (size_t)10
1111 #define ALLOC_INCR (size_t)200
1113 if (cont_level != 0) {
1114 if (*nmentryp == 0) {
1115 file_error(ms, 0, "No current entry for continuation");
1118 me = &(*mentryp)[*nmentryp - 1];
1119 if (me->cont_count == me->max_count) {
1121 size_t cnt = me->max_count + ALLOC_CHUNK;
1122 if ((nm = CAST(struct magic *, realloc(me->mp,
1123 sizeof(*nm) * cnt))) == NULL) {
1124 file_oomem(ms, sizeof(*nm) * cnt);
1128 me->max_count = CAST(uint32_t, cnt);
1130 m = &me->mp[me->cont_count++];
1131 (void)memset(m, 0, sizeof(*m));
1132 m->cont_level = cont_level;
1134 if (*nmentryp == maxmagic) {
1135 struct magic_entry *mp;
1137 maxmagic += ALLOC_INCR;
1138 if ((mp = CAST(struct magic_entry *,
1139 realloc(*mentryp, sizeof(*mp) * maxmagic))) ==
1141 file_oomem(ms, sizeof(*mp) * maxmagic);
1144 (void)memset(&mp[*nmentryp], 0, sizeof(*mp) *
1148 me = &(*mentryp)[*nmentryp];
1149 if (me->mp == NULL) {
1150 size_t len = sizeof(*m) * ALLOC_CHUNK;
1151 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1152 file_oomem(ms, len);
1156 me->max_count = ALLOC_CHUNK;
1159 (void)memset(m, 0, sizeof(*m));
1160 m->factor_op = FILE_FACTOR_OP_NONE;
1164 m->lineno = CAST(uint32_t, lineno);
1166 if (*l == '&') { /* m->cont_level == 0 checked below. */
1167 ++l; /* step over */
1171 ++l; /* step over */
1173 if (m->flag & OFFADD)
1174 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1176 if (*l == '&') { /* m->cont_level == 0 checked below */
1177 ++l; /* step over */
1181 /* Indirect offsets are not valid at level 0. */
1182 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
1183 if (ms->flags & MAGIC_CHECK)
1184 file_magwarn(ms, "relative offset at level 0");
1186 /* get offset, then skip over it */
1187 m->offset = (uint32_t)strtoul(l, &t, 0);
1189 if (ms->flags & MAGIC_CHECK)
1190 file_magwarn(ms, "offset `%s' invalid", l);
1193 if (m->flag & INDIR) {
1194 m->in_type = FILE_LONG;
1197 * read [.lbs][+-]nnnnn)
1203 m->in_type = FILE_LELONG;
1206 m->in_type = FILE_BELONG;
1209 m->in_type = FILE_MELONG;
1213 m->in_type = FILE_LESHORT;
1217 m->in_type = FILE_BESHORT;
1223 m->in_type = FILE_BYTE;
1228 m->in_type = FILE_LEDOUBLE;
1233 m->in_type = FILE_BEDOUBLE;
1236 m->in_type = FILE_LEID3;
1239 m->in_type = FILE_BEID3;
1242 if (ms->flags & MAGIC_CHECK)
1244 "indirect offset type `%c' invalid",
1253 m->in_op |= FILE_OPINVERSE;
1256 if ((op = get_op(*l)) != -1) {
1261 m->in_op |= FILE_OPINDIRECT;
1264 if (isdigit((unsigned char)*l) || *l == '-') {
1265 m->in_offset = (int32_t)strtol(l, &t, 0);
1267 if (ms->flags & MAGIC_CHECK)
1269 "in_offset `%s' invalid", l);
1273 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
1274 if (ms->flags & MAGIC_CHECK)
1276 "missing ')' in indirect offset");
1280 #ifdef ENABLE_CONDITIONALS
1281 m->cond = get_cond(l, &l);
1282 if (check_cond(ms, m->cond, cont_level) == -1)
1290 m->flag |= UNSIGNED;
1293 m->type = get_type(l, &l);
1294 if (m->type == FILE_INVALID) {
1295 if (ms->flags & MAGIC_CHECK)
1296 file_magwarn(ms, "type `%s' invalid", l);
1300 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1301 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1305 if (!IS_STRING(m->type))
1306 m->mask_op |= FILE_OPINVERSE;
1307 else if (ms->flags & MAGIC_CHECK)
1308 file_magwarn(ms, "'~' invalid for string types");
1314 if ((op = get_op(*l)) != -1) {
1315 if (!IS_STRING(m->type)) {
1319 val = (uint64_t)strtoull(l, &t, 0);
1321 m->num_mask = file_signextend(ms, m, val);
1324 else if (op == FILE_OPDIVIDE) {
1326 while (!isspace((unsigned char)*++l)) {
1328 case '0': case '1': case '2':
1329 case '3': case '4': case '5':
1330 case '6': case '7': case '8':
1333 (ms->flags & MAGIC_CHECK))
1337 m->str_range = CAST(uint32_t,
1339 if (m->str_range == 0)
1344 case CHAR_COMPACT_WHITESPACE:
1345 m->str_flags |= STRING_COMPACT_WHITESPACE;
1347 case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1349 STRING_COMPACT_OPTIONAL_WHITESPACE;
1351 case CHAR_IGNORE_LOWERCASE:
1352 m->str_flags |= STRING_IGNORE_LOWERCASE;
1354 case CHAR_IGNORE_UPPERCASE:
1355 m->str_flags |= STRING_IGNORE_UPPERCASE;
1357 case CHAR_REGEX_OFFSET_START:
1358 m->str_flags |= REGEX_OFFSET_START;
1361 m->str_flags |= STRING_BINTEST;
1364 m->str_flags |= STRING_TEXTTEST;
1367 if (ms->flags & MAGIC_CHECK)
1369 "string extension `%c' invalid",
1373 /* allow multiple '/' for readability */
1375 !isspace((unsigned char)l[2]))
1378 if (string_modifier_check(ms, m) == -1)
1382 if (ms->flags & MAGIC_CHECK)
1383 file_magwarn(ms, "invalid string op: %c", *t);
1388 * We used to set mask to all 1's here, instead let's just not do
1389 * anything if mask = 0 (unless you have a better idea)
1399 if (ms->flags & MAGIC_CHECK) {
1400 file_magwarn(ms, "%c= not supported",
1407 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1414 /* HP compat: ignore &= etc. */
1423 m->reln = '='; /* the default relation */
1424 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
1425 isspace((unsigned char)l[1])) || !l[1])) {
1432 * Grab the value part, except for an 'x' reln.
1434 if (m->reln != 'x' && getvalue(ms, m, &l, action))
1438 * TODO finish this macro and start using it!
1439 * #define offsetcheck {if (offset > HOWMANY-1)
1440 * magwarn("offset too big"); }
1444 * Now get last part - the description
1450 } else if ((l[0] == '\\') && (l[1] == 'b')) {
1455 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
1457 if (i == sizeof(m->desc)) {
1458 m->desc[sizeof(m->desc) - 1] = '\0';
1459 if (ms->flags & MAGIC_CHECK)
1460 file_magwarn(ms, "description `%s' truncated", m->desc);
1464 * We only do this check while compiling, or if any of the magic
1465 * files were not compiled.
1467 if (ms->flags & MAGIC_CHECK) {
1468 if (check_format(ms, m) == -1)
1471 #ifndef COMPILE_ONLY
1472 if (action == FILE_CHECK) {
1476 m->mimetype[0] = '\0'; /* initialise MIME type to none */
1477 if (m->cont_level == 0)
1478 ++(*nmentryp); /* make room for next */
1483 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
1487 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
1489 const char *l = line;
1491 unsigned long factor;
1492 struct magic *m = &me->mp[0];
1494 if (m->factor_op != FILE_FACTOR_OP_NONE) {
1496 "Current entry already has a strength type: %c %d",
1497 m->factor_op, m->factor);
1502 case FILE_FACTOR_OP_NONE:
1503 case FILE_FACTOR_OP_PLUS:
1504 case FILE_FACTOR_OP_MINUS:
1505 case FILE_FACTOR_OP_TIMES:
1506 case FILE_FACTOR_OP_DIV:
1507 m->factor_op = *l++;
1510 file_magwarn(ms, "Unknown factor op `%c'", *l);
1514 factor = strtoul(l, &el, 0);
1516 file_magwarn(ms, "Too large factor `%lu'", factor);
1519 if (*el && !isspace((unsigned char)*el)) {
1520 file_magwarn(ms, "Bad factor `%s'", l);
1523 m->factor = (uint8_t)factor;
1524 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
1525 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
1526 m->factor_op, m->factor);
1531 m->factor_op = FILE_FACTOR_OP_NONE;
1537 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into magic[index - 1]
1540 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
1543 const char *l = line;
1544 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1546 if (m->apple[0] != '\0') {
1547 file_magwarn(ms, "Current entry already has a APPLE type `%.8s',"
1548 " new type `%s'", m->mimetype, l);
1553 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1554 || strchr("-+/.", *l)) && i < sizeof(m->apple); m->apple[i++] = *l++)
1556 if (i == sizeof(m->apple) && *l) {
1557 /* We don't need to NUL terminate here, printing handles it */
1558 if (ms->flags & MAGIC_CHECK)
1559 file_magwarn(ms, "APPLE type `%s' truncated %zu",
1570 * parse a MIME annotation line from magic file, put into magic[index - 1]
1574 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
1577 const char *l = line;
1578 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1580 if (m->mimetype[0] != '\0') {
1581 file_magwarn(ms, "Current entry already has a MIME type `%s',"
1582 " new type `%s'", m->mimetype, l);
1587 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1588 || strchr("-+/.", *l)) && i < sizeof(m->mimetype); m->mimetype[i++] = *l++)
1590 if (i == sizeof(m->mimetype)) {
1591 m->mimetype[sizeof(m->mimetype) - 1] = '\0';
1592 if (ms->flags & MAGIC_CHECK)
1593 file_magwarn(ms, "MIME type `%s' truncated %zu",
1596 m->mimetype[i] = '\0';
1605 check_format_type(const char *ptr, int type)
1609 /* Missing format string; bad */
1622 while (isdigit((unsigned char)*ptr)) ptr++;
1625 while (isdigit((unsigned char)*ptr)) ptr++;
1677 case FILE_FMT_FLOAT:
1678 case FILE_FMT_DOUBLE:
1683 while (isdigit((unsigned char)*ptr)) ptr++;
1686 while (isdigit((unsigned char)*ptr)) ptr++;
1705 while (isdigit((unsigned char )*ptr))
1709 while (isdigit((unsigned char )*ptr))
1721 /* internal error */
1729 * Check that the optional printf format in description matches
1730 * the type of the magic.
1733 check_format(struct magic_set *ms, struct magic *m)
1737 for (ptr = m->desc; *ptr; ptr++)
1741 /* No format string; ok */
1745 assert(file_nformats == file_nnames);
1747 if (m->type >= file_nformats) {
1748 file_magwarn(ms, "Internal error inconsistency between "
1749 "m->type and format strings");
1752 if (file_formats[m->type] == FILE_FMT_NONE) {
1753 file_magwarn(ms, "No format string for `%s' with description "
1754 "`%s'", m->desc, file_names[m->type]);
1759 if (check_format_type(ptr, file_formats[m->type]) == -1) {
1761 * TODO: this error message is unhelpful if the format
1762 * string is not one character long
1764 file_magwarn(ms, "Printf format `%c' is not valid for type "
1765 "`%s' in description `%s'", *ptr ? *ptr : '?',
1766 file_names[m->type], m->desc);
1770 for (; *ptr; ptr++) {
1773 "Too many format strings (should have at most one) "
1774 "for `%s' with description `%s'",
1775 file_names[m->type], m->desc);
1783 * Read a numeric value from a pointer, into the value union of a magic
1784 * pointer, according to the magic type. Update the string pointer to point
1785 * just after the number read. Return 0 for success, non-zero for failure.
1788 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
1791 case FILE_BESTRING16:
1792 case FILE_LESTRING16:
1797 *p = getstr(ms, m, *p, action == FILE_COMPILE);
1799 if (ms->flags & MAGIC_CHECK)
1800 file_magwarn(ms, "cannot get string from `%s'",
1808 if (m->reln != 'x') {
1810 #if defined(HAVE_STRTOF) && !defined(COMPILE_ONLY)
1811 m->value.f = strtof(*p, &ep);
1813 m->value.f = (float)strtod(*p, &ep);
1821 if (m->reln != 'x') {
1823 m->value.d = strtod(*p, &ep);
1828 if (m->reln != 'x') {
1830 m->value.q = file_signextend(ms, m,
1831 (uint64_t)strtoull(*p, &ep, 0));
1840 * Convert a string containing C character escapes. Stop at an unescaped
1842 * Copy the converted version to "m->value.s", and the length in m->vallen.
1843 * Return updated scan pointer as function result. Warn if set.
1845 private const char *
1846 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
1848 const char *origs = s;
1849 char *p = m->value.s;
1850 size_t plen = sizeof(m->value.s);
1852 char *pmax = p + plen - 1;
1856 while ((c = *s++) != '\0') {
1857 if (isspace((unsigned char) c))
1860 file_error(ms, 0, "string too long: `%s'", origs);
1868 file_magwarn(ms, "incomplete escape");
1874 "escaped tab found, use \\t instead");
1875 warn = 0; /* already did */
1880 if (isprint((unsigned char)c)) {
1881 /* Allow escaping of
1883 if (strchr("<>&^=!", c)
1885 file_magwarn(ms, "no "
1891 "unknown escape sequence: "
1896 /* space, perhaps force people to use \040? */
1900 * Other things people escape, but shouldn't need to,
1901 * so we disallow them
1914 /* and baskslash itself */
1947 /* \ and up to 3 octal digits */
1957 c = *s++; /* try for 2 */
1958 if (c >= '0' && c <= '7') {
1959 val = (val << 3) | (c - '0');
1960 c = *s++; /* try for 3 */
1961 if (c >= '0' && c <= '7')
1962 val = (val << 3) | (c-'0');
1971 /* \x and up to 2 hex digits */
1973 val = 'x'; /* Default if no digits */
1974 c = hextoint(*s++); /* Get next char */
1979 val = (val << 4) + c;
1992 m->vallen = CAST(unsigned char, (p - origp));
1993 if (m->type == FILE_PSTRING)
1999 /* Single hex char to int; -1 if not a hex char. */
2003 if (!isascii((unsigned char) c))
2005 if (isdigit((unsigned char) c))
2007 if ((c >= 'a') && (c <= 'f'))
2008 return c + 10 - 'a';
2009 if (( c>= 'A') && (c <= 'F'))
2010 return c + 10 - 'A';
2016 * Print a string containing C character escapes.
2019 file_showstr(FILE *fp, const char *s, size_t len)
2034 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
2035 (void) fputc(c, fp);
2037 (void) fputc('\\', fp);
2040 (void) fputc('a', fp);
2044 (void) fputc('b', fp);
2048 (void) fputc('f', fp);
2052 (void) fputc('n', fp);
2056 (void) fputc('r', fp);
2060 (void) fputc('t', fp);
2064 (void) fputc('v', fp);
2068 (void) fprintf(fp, "%.3o", c & 0377);
2076 * eatsize(): Eat the size spec from a number [eg. 10UL]
2079 eatsize(const char **p)
2083 if (LOWCASE(*l) == 'u')
2086 switch (LOWCASE(*l)) {
2087 case 'l': /* long */
2088 case 's': /* short */
2089 case 'h': /* short */
2090 case 'b': /* char/byte */
2091 case 'c': /* char/byte */
2102 * handle a compiled file.
2105 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
2113 char *dbname = NULL;
2116 dbname = mkdbname(ms, fn, 0);
2120 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2123 if (fstat(fd, &st) == -1) {
2124 file_error(ms, errno, "cannot stat `%s'", dbname);
2127 if (st.st_size < 8) {
2128 file_error(ms, 0, "file `%s' is too small", dbname);
2133 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2134 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2135 file_error(ms, errno, "cannot map `%s'", dbname);
2140 if ((mm = CAST(void *, malloc((size_t)st.st_size))) == NULL) {
2141 file_oomem(ms, (size_t)st.st_size);
2144 if (read(fd, mm, (size_t)st.st_size) != (ssize_t)st.st_size) {
2150 *magicp = CAST(struct magic *, mm);
2153 ptr = (uint32_t *)(void *)*magicp;
2154 if (*ptr != MAGICNO) {
2155 if (swap4(*ptr) != MAGICNO) {
2156 file_error(ms, 0, "bad magic in `%s'", dbname);
2163 version = swap4(ptr[1]);
2166 if (version != VERSIONNO) {
2167 file_error(ms, 0, "File %d.%d supports only version %d magic "
2168 "files. `%s' is version %d", FILE_VERSION_MAJOR, patchlevel,
2169 VERSIONNO, dbname, version);
2172 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic));
2177 byteswap(*magicp, *nmagicp);
2186 (void)munmap((void *)mm, (size_t)st.st_size);
2199 private const uint32_t ar[] = {
2203 * handle an mmaped file.
2206 apprentice_compile(struct magic_set *ms, struct magic **magicp,
2207 uint32_t *nmagicp, const char *fn)
2213 dbname = mkdbname(ms, fn, 1);
2218 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1) {
2219 file_error(ms, errno, "cannot open `%s'", dbname);
2223 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
2224 file_error(ms, errno, "error writing `%s'", dbname);
2228 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
2229 != sizeof(struct magic)) {
2230 file_error(ms, errno, "error seeking `%s'", dbname);
2234 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
2235 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
2236 file_error(ms, errno, "error writing `%s'", dbname);
2247 private const char ext[] = ".mgc";
2252 mkdbname(struct magic_set *ms, const char *fn, int strip)
2258 if ((p = strrchr(fn, '/')) != NULL)
2262 for (q = fn; *q; q++)
2265 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
2269 /* Did not find .mgc, restore q */
2275 /* Compatibility with old code that looked in .mime */
2276 if (ms->flags & MAGIC_MIME) {
2277 asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext);
2278 if (access(buf, R_OK) != -1) {
2279 ms->flags &= MAGIC_MIME_TYPE;
2284 asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext);
2286 /* Compatibility with old code that looked in .mime */
2287 if (strstr(p, ".mime") != NULL)
2288 ms->flags &= MAGIC_MIME_TYPE;
2293 * Byteswap an mmap'ed file if needed
2296 byteswap(struct magic *magic, uint32_t nmagic)
2299 for (i = 0; i < nmagic; i++)
2310 uint8_t *s = (uint8_t *)(void *)&sv;
2311 uint8_t *d = (uint8_t *)(void *)&rv;
2324 uint8_t *s = (uint8_t *)(void *)&sv;
2325 uint8_t *d = (uint8_t *)(void *)&rv;
2340 uint8_t *s = (uint8_t *)(void *)&sv;
2341 uint8_t *d = (uint8_t *)(void *)&rv;
2365 * byteswap a single magic entry
2368 bs1(struct magic *m)
2370 m->cont_level = swap2(m->cont_level);
2371 m->offset = swap4((uint32_t)m->offset);
2372 m->in_offset = swap4((uint32_t)m->in_offset);
2373 m->lineno = swap4((uint32_t)m->lineno);
2374 if (IS_STRING(m->type)) {
2375 m->str_range = swap4(m->str_range);
2376 m->str_flags = swap4(m->str_flags);
2379 m->value.q = swap8(m->value.q);
2380 m->num_mask = swap8(m->num_mask);