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.255 2016/10/24 18:02:17 christos Exp $")
54 #if defined(HAVE_LIMITS_H)
59 #define MAXMAGIC_SIZE ((ssize_t)0x7fffffff)
61 #define MAXMAGIC_SIZE SSIZE_MAX
64 #define EATAB {while (isascii((unsigned char) *l) && \
65 isspace((unsigned char) *l)) ++l;}
66 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
67 tolower((unsigned char) (l)) : (l))
69 * Work around a bug in headers on Digital Unix.
70 * At least confirmed for: OSF1 V4.0 878
72 #if defined(__osf__) && defined(__DECC)
79 #define MAP_FAILED (void *) -1
86 #define ALLOC_CHUNK (size_t)10
87 #define ALLOC_INCR (size_t)200
89 #define MAP_TYPE_USER 0
90 #define MAP_TYPE_MALLOC 1
91 #define MAP_TYPE_MMAP 2
99 struct magic_entry_set {
100 struct magic_entry *me;
109 struct magic *magic[MAGIC_SETS];
110 uint32_t nmagic[MAGIC_SETS];
113 int file_formats[FILE_NAMES_SIZE];
114 const size_t file_nformats = FILE_NAMES_SIZE;
115 const char *file_names[FILE_NAMES_SIZE];
116 const size_t file_nnames = FILE_NAMES_SIZE;
118 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
119 private int hextoint(int);
120 private const char *getstr(struct magic_set *, struct magic *, const char *,
122 private int parse(struct magic_set *, struct magic_entry *, const char *,
124 private void eatsize(const char **);
125 private int apprentice_1(struct magic_set *, const char *, int);
126 private size_t apprentice_magic_strength(const struct magic *);
127 private int apprentice_sort(const void *, const void *);
128 private void apprentice_list(struct mlist *, int );
129 private struct magic_map *apprentice_load(struct magic_set *,
131 private struct mlist *mlist_alloc(void);
132 private void mlist_free(struct mlist *);
133 private void byteswap(struct magic *, uint32_t);
134 private void bs1(struct magic *);
135 private uint16_t swap2(uint16_t);
136 private uint32_t swap4(uint32_t);
137 private uint64_t swap8(uint64_t);
138 private char *mkdbname(struct magic_set *, const char *, int);
139 private struct magic_map *apprentice_buf(struct magic_set *, struct magic *,
141 private struct magic_map *apprentice_map(struct magic_set *, const char *);
142 private int check_buffer(struct magic_set *, struct magic_map *, const char *);
143 private void apprentice_unmap(struct magic_map *);
144 private int apprentice_compile(struct magic_set *, struct magic_map *,
146 private int check_format_type(const char *, int, const char **);
147 private int check_format(struct magic_set *, struct magic *);
148 private int get_op(char);
149 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
150 private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
151 private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
152 private int parse_ext(struct magic_set *, struct magic_entry *, const char *);
155 private size_t magicsize = sizeof(struct magic);
157 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
162 int (*fun)(struct magic_set *, struct magic_entry *, const char *);
164 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
166 DECLARE_FIELD(apple),
168 DECLARE_FIELD(strength),
175 int main(int, char *[]);
178 main(int argc, char *argv[])
181 struct magic_set *ms;
184 if ((progname = strrchr(argv[0], '/')) != NULL)
190 (void)fprintf(stderr, "Usage: %s file\n", progname);
194 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
195 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
198 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
200 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
204 #endif /* COMPILE_ONLY */
214 * XXX - the actual Single UNIX Specification says that "long" means "long",
215 * as in the C data type, but we treat it as meaning "4-byte integer".
216 * Given that the OS X version of file 5.04 did the same, I guess that passes
217 * the actual test; having "long" be dependent on how big a "long" is on
218 * the machine running "file" is silly.
220 static const struct type_tbl_s type_tbl[] = {
221 # define XX(s) s, (sizeof(s) - 1)
222 # define XX_NULL "", 0
223 { XX("invalid"), FILE_INVALID, FILE_FMT_NONE },
224 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
225 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
226 { XX("default"), FILE_DEFAULT, FILE_FMT_NONE },
227 { XX("long"), FILE_LONG, FILE_FMT_NUM },
228 { XX("string"), FILE_STRING, FILE_FMT_STR },
229 { XX("date"), FILE_DATE, FILE_FMT_STR },
230 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
231 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
232 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
233 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
234 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
235 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
236 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
237 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
238 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
239 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
240 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
241 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
242 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
243 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
244 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
245 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
246 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
247 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
248 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
249 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
250 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
251 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
252 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
253 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
254 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
255 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
256 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
257 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
258 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
259 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
260 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
261 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
262 { XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
263 { XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
264 { XX("indirect"), FILE_INDIRECT, FILE_FMT_NUM },
265 { XX("qwdate"), FILE_QWDATE, FILE_FMT_STR },
266 { XX("leqwdate"), FILE_LEQWDATE, FILE_FMT_STR },
267 { XX("beqwdate"), FILE_BEQWDATE, FILE_FMT_STR },
268 { XX("name"), FILE_NAME, FILE_FMT_NONE },
269 { XX("use"), FILE_USE, FILE_FMT_NONE },
270 { XX("clear"), FILE_CLEAR, FILE_FMT_NONE },
271 { XX("der"), FILE_DER, FILE_FMT_STR },
272 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
276 * These are not types, and cannot be preceded by "u" to make them
279 static const struct type_tbl_s special_tbl[] = {
280 { XX("der"), FILE_DER, FILE_FMT_STR },
281 { XX("name"), FILE_NAME, FILE_FMT_STR },
282 { XX("use"), FILE_USE, FILE_FMT_STR },
283 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
289 get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
291 const struct type_tbl_s *p;
293 for (p = tbl; p->len; p++) {
294 if (strncmp(l, p->name, p->len) == 0) {
304 get_standard_integer_type(const char *l, const char **t)
308 if (isalpha((unsigned char)l[1])) {
321 * "dI", "dL", "uI", and "uL".
323 * XXX - the actual Single UNIX Specification says
324 * that "L" means "long", as in the C data type,
325 * but we treat it as meaning "4-byte integer".
326 * Given that the OS X version of file 5.04 did
327 * the same, I guess that passes the actual SUS
328 * validation suite; having "dL" be dependent on
329 * how big a "long" is on the machine running
339 /* "d{anything else}", "u{anything else}" */
343 } else if (isdigit((unsigned char)l[1])) {
345 * "d{num}" and "u{num}"; we only support {num} values
346 * of 1, 2, 4, and 8 - the Single UNIX Specification
347 * doesn't say anything about whether arbitrary
348 * values should be supported, but both the Solaris 10
349 * and OS X Mountain Lion versions of file passed the
350 * Single UNIX Specification validation suite, and
351 * neither of them support values bigger than 8 or
352 * non-power-of-2 values.
354 if (isdigit((unsigned char)l[2])) {
355 /* Multi-digit, so > 9 */
372 /* XXX - what about 3, 5, 6, or 7? */
378 * "d" or "u" by itself.
389 init_file_tables(void)
392 const struct type_tbl_s *p;
398 for (p = type_tbl; p->len; p++) {
399 assert(p->type < FILE_NAMES_SIZE);
400 file_names[p->type] = p->name;
401 file_formats[p->type] = p->format;
403 assert(p - type_tbl == FILE_NAMES_SIZE);
407 add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
412 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL)
415 ml->map = idx == 0 ? map : NULL;
416 ml->magic = map->magic[idx];
417 ml->nmagic = map->nmagic[idx];
419 mlp->prev->next = ml;
420 ml->prev = mlp->prev;
427 * Handle one file or directory.
430 apprentice_1(struct magic_set *ms, const char *fn, int action)
432 struct magic_map *map;
438 if (magicsize != FILE_MAGICSIZE) {
439 file_error(ms, 0, "magic element size %lu != %lu",
440 (unsigned long)sizeof(*map->magic[0]),
441 (unsigned long)FILE_MAGICSIZE);
445 if (action == FILE_COMPILE) {
446 map = apprentice_load(ms, fn, action);
449 return apprentice_compile(ms, map, fn);
453 map = apprentice_map(ms, fn);
454 if (map == (struct magic_map *)-1)
457 if (ms->flags & MAGIC_CHECK)
458 file_magwarn(ms, "using regular magic file `%s'", fn);
459 map = apprentice_load(ms, fn, action);
464 for (i = 0; i < MAGIC_SETS; i++) {
465 if (add_mlist(ms->mlist[i], map, i) == -1) {
466 file_oomem(ms, sizeof(*ml));
471 if (action == FILE_LIST) {
472 for (i = 0; i < MAGIC_SETS; i++) {
473 printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
475 apprentice_list(ms->mlist[i], BINTEST);
476 printf("Text patterns:\n");
477 apprentice_list(ms->mlist[i], TEXTTEST);
483 #endif /* COMPILE_ONLY */
487 file_ms_free(struct magic_set *ms)
492 for (i = 0; i < MAGIC_SETS; i++)
493 mlist_free(ms->mlist[i]);
500 protected struct magic_set *
501 file_ms_alloc(int flags)
503 struct magic_set *ms;
506 if ((ms = CAST(struct magic_set *, calloc((size_t)1,
507 sizeof(struct magic_set)))) == NULL)
510 if (magic_setflags(ms, flags) == -1) {
515 ms->o.buf = ms->o.pbuf = NULL;
516 len = (ms->c.len = 10) * sizeof(*ms->c.li);
518 if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
523 for (i = 0; i < MAGIC_SETS; i++)
525 ms->file = "unknown";
527 ms->indir_max = FILE_INDIR_MAX;
528 ms->name_max = FILE_NAME_MAX;
529 ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
530 ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
531 ms->elf_notes_max = FILE_ELF_NOTES_MAX;
532 ms->regex_max = FILE_REGEX_MAX;
533 ms->bytes_max = FILE_BYTES_MAX;
541 apprentice_unmap(struct magic_map *map)
550 case MAP_TYPE_MALLOC:
551 for (i = 0; i < MAGIC_SETS; i++) {
552 if ((char *)map->magic[i] >= (char *)map->p &&
553 (char *)map->magic[i] <= (char *)map->p + map->len)
561 if (map->p && map->p != MAP_FAILED)
562 (void)munmap(map->p, map->len);
571 private struct mlist *
575 if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
578 mlist->next = mlist->prev = mlist;
583 mlist_free(struct mlist *mlist)
585 struct mlist *ml, *next;
591 for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
593 apprentice_unmap(CAST(struct magic_map *, ml->map));
601 /* void **bufs: an array of compiled magic files */
603 buffer_apprentice(struct magic_set *ms, struct magic **bufs,
604 size_t *sizes, size_t nbufs)
608 struct magic_map *map;
613 if (ms->mlist[0] != NULL)
618 for (i = 0; i < MAGIC_SETS; i++) {
619 mlist_free(ms->mlist[i]);
620 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
621 file_oomem(ms, sizeof(*ms->mlist[i]));
626 for (i = 0; i < nbufs; i++) {
627 map = apprentice_buf(ms, bufs[i], sizes[i]);
631 for (j = 0; j < MAGIC_SETS; j++) {
632 if (add_mlist(ms->mlist[j], map, j) == -1) {
633 file_oomem(ms, sizeof(*ml));
641 for (i = 0; i < MAGIC_SETS; i++) {
642 mlist_free(ms->mlist[i]);
649 /* const char *fn: list of magic files and directories */
651 file_apprentice(struct magic_set *ms, const char *fn, int action)
654 int file_err, errs = -1;
657 if (ms->mlist[0] != NULL)
660 if ((fn = magic_getpath(fn, action)) == NULL)
665 if ((mfn = strdup(fn)) == NULL) {
666 file_oomem(ms, strlen(fn));
670 for (i = 0; i < MAGIC_SETS; i++) {
671 mlist_free(ms->mlist[i]);
672 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
673 file_oomem(ms, sizeof(*ms->mlist[i]));
675 mlist_free(ms->mlist[i]);
685 p = strchr(fn, PATHSEP);
690 file_err = apprentice_1(ms, fn, action);
691 errs = MAX(errs, file_err);
698 for (i = 0; i < MAGIC_SETS; i++) {
699 mlist_free(ms->mlist[i]);
702 file_error(ms, 0, "could not find any valid magic files!");
708 * Always leave the database loaded
710 if (action == FILE_LOAD)
713 for (i = 0; i < MAGIC_SETS; i++) {
714 mlist_free(ms->mlist[i]);
726 file_error(ms, 0, "Invalid action %d", action);
732 * Compute the real length of a magic expression, for the purposes
733 * of determining how "strong" a magic expression is (approximating
734 * how specific its matches are):
735 * - magic characters count 0 unless escaped.
736 * - [] expressions count 1
737 * - {} expressions count 0
738 * - regular characters or escaped magic characters count 1
739 * - 0 length expressions count as one
742 nonmagic(const char *str)
747 for (p = str; *p; p++)
749 case '\\': /* Escaped anything counts 1 */
754 case '?': /* Magic characters count 0 */
761 case '[': /* Bracketed expressions count 1 the ']' */
762 while (*p && *p != ']')
766 case '{': /* Braced expressions count 0 */
767 while (*p && *p != '}')
772 default: /* Anything else counts 1 */
777 return rv == 0 ? 1 : rv; /* Return at least 1 */
781 * Get weight of this magic entry, for sorting purposes.
784 apprentice_magic_strength(const struct magic *m)
787 size_t v, val = 2 * MULT; /* baseline strength */
790 case FILE_DEFAULT: /* make sure this sorts last */
791 if (m->factor_op != FILE_FACTOR_OP_NONE)
814 val += m->vallen * MULT;
817 case FILE_BESTRING16:
818 case FILE_LESTRING16:
819 val += m->vallen * MULT / 2;
823 val += m->vallen * MAX(MULT / m->vallen, 1);
827 v = nonmagic(m->value.s);
828 val += v * MAX(MULT / v, 1);
873 (void)fprintf(stderr, "Bad type %d\n", m->type);
878 case 'x': /* matches anything penalize */
879 case '!': /* matches almost anything penalize */
883 case '=': /* Exact match, prefer */
888 case '<': /* comparison match reduce strength */
893 case '&': /* masking bits, we could count them too */
898 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
902 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
905 switch (m->factor_op) {
906 case FILE_FACTOR_OP_NONE:
908 case FILE_FACTOR_OP_PLUS:
911 case FILE_FACTOR_OP_MINUS:
914 case FILE_FACTOR_OP_TIMES:
917 case FILE_FACTOR_OP_DIV:
925 * Magic entries with no description get a bonus because they depend
926 * on subsequent magic entries to print something.
928 if (m->desc[0] == '\0')
934 * Sort callback for sorting entries by "strength" (basically length)
937 apprentice_sort(const void *a, const void *b)
939 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
940 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
941 size_t sa = apprentice_magic_strength(ma->mp);
942 size_t sb = apprentice_magic_strength(mb->mp);
952 * Shows sorted patterns list in the order which is used for the matching
955 apprentice_list(struct mlist *mlist, int mode)
957 uint32_t magindex = 0;
959 for (ml = mlist->next; ml != mlist; ml = ml->next) {
960 for (magindex = 0; magindex < ml->nmagic; magindex++) {
961 struct magic *m = &ml->magic[magindex];
962 if ((m->flag & mode) != mode) {
964 while (magindex + 1 < ml->nmagic &&
965 ml->magic[magindex + 1].cont_level != 0)
967 continue; /* Skip to next top-level test*/
971 * Try to iterate over the tree until we find item with
972 * description/mimetype.
974 while (magindex + 1 < ml->nmagic &&
975 ml->magic[magindex + 1].cont_level != 0 &&
976 *ml->magic[magindex].desc == '\0' &&
977 *ml->magic[magindex].mimetype == '\0')
980 printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
981 apprentice_magic_strength(m),
982 ml->magic[magindex].lineno,
983 ml->magic[magindex].desc,
984 ml->magic[magindex].mimetype);
990 set_test_type(struct magic *mstart, struct magic *m)
1028 mstart->flag |= BINTEST;
1032 case FILE_BESTRING16:
1033 case FILE_LESTRING16:
1034 /* Allow text overrides */
1035 if (mstart->str_flags & STRING_TEXTTEST)
1036 mstart->flag |= TEXTTEST;
1038 mstart->flag |= BINTEST;
1042 /* Check for override */
1043 if (mstart->str_flags & STRING_BINTEST)
1044 mstart->flag |= BINTEST;
1045 if (mstart->str_flags & STRING_TEXTTEST)
1046 mstart->flag |= TEXTTEST;
1048 if (mstart->flag & (TEXTTEST|BINTEST))
1051 /* binary test if pattern is not text */
1052 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
1054 mstart->flag |= BINTEST;
1056 mstart->flag |= TEXTTEST;
1059 /* can't deduce anything; we shouldn't see this at the
1064 /* invalid search type, but no need to complain here */
1070 addentry(struct magic_set *ms, struct magic_entry *me,
1071 struct magic_entry_set *mset)
1073 size_t i = me->mp->type == FILE_NAME ? 1 : 0;
1074 if (mset[i].count == mset[i].max) {
1075 struct magic_entry *mp;
1077 mset[i].max += ALLOC_INCR;
1078 if ((mp = CAST(struct magic_entry *,
1079 realloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
1081 file_oomem(ms, sizeof(*mp) * mset[i].max);
1084 (void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
1088 mset[i].me[mset[i].count++] = *me;
1089 memset(me, 0, sizeof(*me));
1094 * Load and parse one file.
1097 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
1098 struct magic_entry_set *mset)
1100 size_t lineno = 0, llen = 0;
1103 struct magic_entry me;
1105 FILE *f = fopen(ms->file = fn, "r");
1107 if (errno != ENOENT)
1108 file_error(ms, errno, "cannot read magic file `%s'",
1114 memset(&me, 0, sizeof(me));
1115 /* read and parse this file */
1116 for (ms->line = 1; (len = getline(&line, &llen, f)) != -1;
1118 if (len == 0) /* null line, garbage, etc */
1120 if (line[len - 1] == '\n') {
1122 line[len - 1] = '\0'; /* delete newline */
1125 case '\0': /* empty, do not parse */
1126 case '#': /* comment, do not parse */
1129 if (line[1] == ':') {
1132 for (i = 0; bang[i].name != NULL; i++) {
1133 if ((size_t)(len - 2) > bang[i].len &&
1134 memcmp(bang[i].name, line + 2,
1138 if (bang[i].name == NULL) {
1140 "Unknown !: entry `%s'", line);
1144 if (me.mp == NULL) {
1146 "No current entry for :!%s type",
1151 if ((*bang[i].fun)(ms, &me,
1152 line + bang[i].len + 2) != 0) {
1161 switch (parse(ms, &me, line, lineno, action)) {
1165 (void)addentry(ms, &me, mset);
1174 (void)addentry(ms, &me, mset);
1180 * parse a file or directory of files
1181 * const char *fn: name of magic file or directory
1184 cmpstrp(const void *p1, const void *p2)
1186 return strcmp(*(char *const *)p1, *(char *const *)p2);
1191 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1194 static const char text[] = "text";
1195 static const char binary[] = "binary";
1196 static const size_t len = sizeof(text);
1198 uint32_t i = starttest;
1201 set_test_type(me[starttest].mp, me[i].mp);
1202 if ((ms->flags & MAGIC_DEBUG) == 0)
1204 (void)fprintf(stderr, "%s%s%s: %s\n",
1206 me[i].mp->mimetype[0] == '\0' ? "" : "; ",
1207 me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
1208 me[i].mp->flag & BINTEST ? binary : text);
1209 if (me[i].mp->flag & BINTEST) {
1210 char *p = strstr(me[i].mp->desc, text);
1211 if (p && (p == me[i].mp->desc ||
1212 isspace((unsigned char)p[-1])) &&
1213 (p + len - me[i].mp->desc == MAXstring
1214 || (p[len] == '\0' ||
1215 isspace((unsigned char)p[len]))))
1216 (void)fprintf(stderr, "*** Possible "
1217 "binary test for text type\n");
1219 } while (++i < nme && me[i].mp->cont_level != 0);
1224 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
1227 for (i = 0; i < nme; i++) {
1228 if (me[i].mp->cont_level == 0 &&
1229 me[i].mp->type == FILE_DEFAULT) {
1231 if (me[i].mp->cont_level == 0)
1235 ms->line = me[i].mp->lineno;
1237 "level 0 \"default\" did not sort last");
1245 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1246 struct magic **ma, uint32_t *nma)
1248 uint32_t i, mentrycount = 0;
1251 for (i = 0; i < nme; i++)
1252 mentrycount += me[i].cont_count;
1254 slen = sizeof(**ma) * mentrycount;
1255 if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) {
1256 file_oomem(ms, slen);
1261 for (i = 0; i < nme; i++) {
1262 (void)memcpy(*ma + mentrycount, me[i].mp,
1263 me[i].cont_count * sizeof(**ma));
1264 mentrycount += me[i].cont_count;
1271 magic_entry_free(struct magic_entry *me, uint32_t nme)
1276 for (i = 0; i < nme; i++)
1281 private struct magic_map *
1282 apprentice_load(struct magic_set *ms, const char *fn, int action)
1286 size_t files = 0, maxfiles = 0;
1287 char **filearr = NULL, *mfn;
1289 struct magic_map *map;
1290 struct magic_entry_set mset[MAGIC_SETS];
1294 memset(mset, 0, sizeof(mset));
1295 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
1298 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL)
1300 file_oomem(ms, sizeof(*map));
1303 map->type = MAP_TYPE_MALLOC;
1305 /* print silly verbose header for USG compat. */
1306 if (action == FILE_CHECK)
1307 (void)fprintf(stderr, "%s\n", usg_hdr);
1309 /* load directory or file */
1310 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
1316 while ((d = readdir(dir)) != NULL) {
1317 if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) {
1319 strlen(fn) + strlen(d->d_name) + 2);
1324 if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
1328 if (files >= maxfiles) {
1330 maxfiles = (maxfiles + 1) * 2;
1331 mlen = maxfiles * sizeof(*filearr);
1332 if ((filearr = CAST(char **,
1333 realloc(filearr, mlen))) == NULL) {
1334 file_oomem(ms, mlen);
1341 filearr[files++] = mfn;
1344 qsort(filearr, files, sizeof(*filearr), cmpstrp);
1345 for (i = 0; i < files; i++) {
1346 load_1(ms, action, filearr[i], &errs, mset);
1351 load_1(ms, action, fn, &errs, mset);
1355 for (j = 0; j < MAGIC_SETS; j++) {
1356 /* Set types of tests */
1357 for (i = 0; i < mset[j].count; ) {
1358 if (mset[j].me[i].mp->cont_level != 0) {
1362 i = set_text_binary(ms, mset[j].me, mset[j].count, i);
1365 qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
1369 * Make sure that any level 0 "default" line is last
1372 set_last_default(ms, mset[j].me, mset[j].count);
1374 /* coalesce per file arrays into a single one */
1375 if (coalesce_entries(ms, mset[j].me, mset[j].count,
1376 &map->magic[j], &map->nmagic[j]) == -1) {
1383 for (j = 0; j < MAGIC_SETS; j++)
1384 magic_entry_free(mset[j].me, mset[j].count);
1387 apprentice_unmap(map);
1394 * extend the sign bit if the comparison is to be signed
1397 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
1399 if (!(m->flag & UNSIGNED)) {
1402 * Do not remove the casts below. They are
1403 * vital. When later compared with the data,
1404 * the sign extension must have happened.
1407 v = (signed char) v;
1450 case FILE_BESTRING16:
1451 case FILE_LESTRING16:
1462 if (ms->flags & MAGIC_CHECK)
1463 file_magwarn(ms, "cannot happen: m->type=%d\n",
1472 string_modifier_check(struct magic_set *ms, struct magic *m)
1474 if ((ms->flags & MAGIC_CHECK) == 0)
1477 if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
1478 (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
1480 "'/BHhLl' modifiers are only allowed for pascal strings\n");
1484 case FILE_BESTRING16:
1485 case FILE_LESTRING16:
1486 if (m->str_flags != 0) {
1488 "no modifiers allowed for 16-bit strings\n");
1494 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
1496 "'/%c' only allowed on regex and search\n",
1497 CHAR_REGEX_OFFSET_START);
1502 if (m->str_range == 0) {
1504 "missing range; defaulting to %d\n",
1505 STRING_DEFAULT_RANGE);
1506 m->str_range = STRING_DEFAULT_RANGE;
1511 if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
1512 file_magwarn(ms, "'/%c' not allowed on regex\n",
1513 CHAR_COMPACT_WHITESPACE);
1516 if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
1517 file_magwarn(ms, "'/%c' not allowed on regex\n",
1518 CHAR_COMPACT_OPTIONAL_WHITESPACE);
1523 file_magwarn(ms, "coding error: m->type=%d\n",
1543 return FILE_OPMINUS;
1545 return FILE_OPMULTIPLY;
1547 return FILE_OPDIVIDE;
1549 return FILE_OPMODULO;
1555 #ifdef ENABLE_CONDITIONALS
1557 get_cond(const char *l, const char **t)
1559 static const struct cond_tbl_s {
1564 { "if", 2, COND_IF },
1565 { "elif", 4, COND_ELIF },
1566 { "else", 4, COND_ELSE },
1567 { "", 0, COND_NONE },
1569 const struct cond_tbl_s *p;
1571 for (p = cond_tbl; p->len; p++) {
1572 if (strncmp(l, p->name, p->len) == 0 &&
1573 isspace((unsigned char)l[p->len])) {
1583 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1586 last_cond = ms->c.li[cont_level].last_cond;
1590 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1591 if (ms->flags & MAGIC_CHECK)
1592 file_magwarn(ms, "syntax error: `if'");
1595 last_cond = COND_IF;
1599 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1600 if (ms->flags & MAGIC_CHECK)
1601 file_magwarn(ms, "syntax error: `elif'");
1604 last_cond = COND_ELIF;
1608 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1609 if (ms->flags & MAGIC_CHECK)
1610 file_magwarn(ms, "syntax error: `else'");
1613 last_cond = COND_NONE;
1617 last_cond = COND_NONE;
1621 ms->c.li[cont_level].last_cond = last_cond;
1624 #endif /* ENABLE_CONDITIONALS */
1627 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1629 const char *l = *lp;
1631 while (!isspace((unsigned char)*++l))
1633 case CHAR_INDIRECT_RELATIVE:
1634 m->str_flags |= INDIRECT_RELATIVE;
1637 if (ms->flags & MAGIC_CHECK)
1638 file_magwarn(ms, "indirect modifier `%c' "
1648 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
1651 const char *l = *lp;
1657 val = (uint64_t)strtoull(l, &t, 0);
1659 m->num_mask = file_signextend(ms, m, val);
1665 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1667 const char *l = *lp;
1671 while (!isspace((unsigned char)*++l)) {
1673 case '0': case '1': case '2':
1674 case '3': case '4': case '5':
1675 case '6': case '7': case '8':
1677 if (have_range && (ms->flags & MAGIC_CHECK))
1678 file_magwarn(ms, "multiple ranges");
1680 m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
1681 if (m->str_range == 0)
1682 file_magwarn(ms, "zero range");
1685 case CHAR_COMPACT_WHITESPACE:
1686 m->str_flags |= STRING_COMPACT_WHITESPACE;
1688 case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1689 m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
1691 case CHAR_IGNORE_LOWERCASE:
1692 m->str_flags |= STRING_IGNORE_LOWERCASE;
1694 case CHAR_IGNORE_UPPERCASE:
1695 m->str_flags |= STRING_IGNORE_UPPERCASE;
1697 case CHAR_REGEX_OFFSET_START:
1698 m->str_flags |= REGEX_OFFSET_START;
1701 m->str_flags |= STRING_BINTEST;
1704 m->str_flags |= STRING_TEXTTEST;
1707 m->str_flags |= STRING_TRIM;
1709 case CHAR_PSTRING_1_LE:
1710 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
1711 if (m->type != FILE_PSTRING)
1713 SET_LENGTH(PSTRING_1_LE);
1715 case CHAR_PSTRING_2_BE:
1716 if (m->type != FILE_PSTRING)
1718 SET_LENGTH(PSTRING_2_BE);
1720 case CHAR_PSTRING_2_LE:
1721 if (m->type != FILE_PSTRING)
1723 SET_LENGTH(PSTRING_2_LE);
1725 case CHAR_PSTRING_4_BE:
1726 if (m->type != FILE_PSTRING)
1728 SET_LENGTH(PSTRING_4_BE);
1730 case CHAR_PSTRING_4_LE:
1738 SET_LENGTH(PSTRING_4_LE);
1740 case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
1741 if (m->type != FILE_PSTRING)
1743 m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
1747 if (ms->flags & MAGIC_CHECK)
1748 file_magwarn(ms, "string modifier `%c' "
1752 /* allow multiple '/' for readability */
1753 if (l[1] == '/' && !isspace((unsigned char)l[2]))
1756 if (string_modifier_check(ms, m) == -1)
1766 * parse one line from magic file, put into magic[index++] if valid
1769 parse(struct magic_set *ms, struct magic_entry *me, const char *line,
1770 size_t lineno, int action)
1772 #ifdef ENABLE_CONDITIONALS
1773 static uint32_t last_cont_level = 0;
1777 const char *l = line;
1780 uint32_t cont_level;
1789 ++l; /* step over */
1792 #ifdef ENABLE_CONDITIONALS
1793 if (cont_level == 0 || cont_level > last_cont_level)
1794 if (file_check_mem(ms, cont_level) == -1)
1796 last_cont_level = cont_level;
1798 if (cont_level != 0) {
1799 if (me->mp == NULL) {
1800 file_magerror(ms, "No current entry for continuation");
1803 if (me->cont_count == 0) {
1804 file_magerror(ms, "Continuations present with 0 count");
1807 m = &me->mp[me->cont_count - 1];
1808 diff = (int32_t)cont_level - (int32_t)m->cont_level;
1810 file_magwarn(ms, "New continuation level %u is more "
1811 "than one larger than current level %u", cont_level,
1813 if (me->cont_count == me->max_count) {
1815 size_t cnt = me->max_count + ALLOC_CHUNK;
1816 if ((nm = CAST(struct magic *, realloc(me->mp,
1817 sizeof(*nm) * cnt))) == NULL) {
1818 file_oomem(ms, sizeof(*nm) * cnt);
1822 me->max_count = CAST(uint32_t, cnt);
1824 m = &me->mp[me->cont_count++];
1825 (void)memset(m, 0, sizeof(*m));
1826 m->cont_level = cont_level;
1828 static const size_t len = sizeof(*m) * ALLOC_CHUNK;
1831 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1832 file_oomem(ms, len);
1836 me->max_count = ALLOC_CHUNK;
1837 (void)memset(m, 0, sizeof(*m));
1838 m->factor_op = FILE_FACTOR_OP_NONE;
1842 m->lineno = CAST(uint32_t, lineno);
1844 if (*l == '&') { /* m->cont_level == 0 checked below. */
1845 ++l; /* step over */
1849 ++l; /* step over */
1851 if (m->flag & OFFADD)
1852 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1854 if (*l == '&') { /* m->cont_level == 0 checked below */
1855 ++l; /* step over */
1859 /* Indirect offsets are not valid at level 0. */
1860 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
1861 if (ms->flags & MAGIC_CHECK)
1862 file_magwarn(ms, "relative offset at level 0");
1866 /* get offset, then skip over it */
1867 m->offset = (uint32_t)strtoul(l, &t, 0);
1869 if (ms->flags & MAGIC_CHECK)
1870 file_magwarn(ms, "offset `%s' invalid", l);
1875 if (m->flag & INDIR) {
1876 m->in_type = FILE_LONG;
1880 * read [.,lbs][+-]nnnnn)
1882 if (*l == '.' || *l == ',') {
1884 m->in_op |= FILE_OPSIGNED;
1888 m->in_type = FILE_LELONG;
1891 m->in_type = FILE_BELONG;
1894 m->in_type = FILE_MELONG;
1898 m->in_type = FILE_LESHORT;
1902 m->in_type = FILE_BESHORT;
1908 m->in_type = FILE_BYTE;
1913 m->in_type = FILE_LEDOUBLE;
1918 m->in_type = FILE_BEDOUBLE;
1921 m->in_type = FILE_LEID3;
1924 m->in_type = FILE_BEID3;
1927 if (ms->flags & MAGIC_CHECK)
1929 "indirect offset type `%c' invalid",
1937 m->in_op |= FILE_OPINVERSE;
1940 if ((op = get_op(*l)) != -1) {
1945 m->in_op |= FILE_OPINDIRECT;
1948 if (isdigit((unsigned char)*l) || *l == '-') {
1949 m->in_offset = (int32_t)strtol(l, &t, 0);
1951 if (ms->flags & MAGIC_CHECK)
1953 "in_offset `%s' invalid", l);
1959 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
1960 if (ms->flags & MAGIC_CHECK)
1962 "missing ')' in indirect offset");
1968 #ifdef ENABLE_CONDITIONALS
1969 m->cond = get_cond(l, &l);
1970 if (check_cond(ms, m->cond, cont_level) == -1)
1981 * Try it as a keyword type prefixed by "u"; match what
1982 * follows the "u". If that fails, try it as an SUS
1985 m->type = get_type(type_tbl, l + 1, &l);
1986 if (m->type == FILE_INVALID) {
1988 * Not a keyword type; parse it as an SUS type,
1989 * 'u' possibly followed by a number or C/S/L.
1991 m->type = get_standard_integer_type(l, &l);
1993 /* It's unsigned. */
1994 if (m->type != FILE_INVALID)
1995 m->flag |= UNSIGNED;
1998 * Try it as a keyword type. If that fails, try it as
1999 * an SUS integer type if it begins with "d" or as an
2000 * SUS string type if it begins with "s". In any case,
2001 * it's not unsigned.
2003 m->type = get_type(type_tbl, l, &l);
2004 if (m->type == FILE_INVALID) {
2006 * Not a keyword type; parse it as an SUS type,
2007 * either 'd' possibly followed by a number or
2008 * C/S/L, or just 's'.
2011 m->type = get_standard_integer_type(l, &l);
2012 else if (*l == 's' && !isalpha((unsigned char)l[1])) {
2013 m->type = FILE_STRING;
2019 if (m->type == FILE_INVALID) {
2020 /* Not found - try it as a special keyword. */
2021 m->type = get_type(special_tbl, l, &l);
2024 if (m->type == FILE_INVALID) {
2025 if (ms->flags & MAGIC_CHECK)
2026 file_magwarn(ms, "type `%s' invalid", l);
2030 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
2031 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
2035 if (!IS_STRING(m->type))
2036 m->mask_op |= FILE_OPINVERSE;
2037 else if (ms->flags & MAGIC_CHECK)
2038 file_magwarn(ms, "'~' invalid for string types");
2042 m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
2043 if ((op = get_op(*l)) != -1) {
2044 if (IS_STRING(m->type)) {
2047 if (op != FILE_OPDIVIDE) {
2048 if (ms->flags & MAGIC_CHECK)
2050 "invalid string/indirect op: "
2055 if (m->type == FILE_INDIRECT)
2056 r = parse_indirect_modifier(ms, m, &l);
2058 r = parse_string_modifier(ms, m, &l);
2062 parse_op_modifier(ms, m, &l, op);
2066 * We used to set mask to all 1's here, instead let's just not do
2067 * anything if mask = 0 (unless you have a better idea)
2077 if (ms->flags & MAGIC_CHECK) {
2078 file_magwarn(ms, "%c= not supported",
2085 /* Old-style anding: "0 byte &0x80 dynamically linked" */
2092 /* HP compat: ignore &= etc. */
2101 m->reln = '='; /* the default relation */
2102 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
2103 isspace((unsigned char)l[1])) || !l[1])) {
2110 * Grab the value part, except for an 'x' reln.
2112 if (m->reln != 'x' && getvalue(ms, m, &l, action))
2116 * TODO finish this macro and start using it!
2117 * #define offsetcheck {if (offset > ms->bytes_max -1)
2118 * magwarn("offset too big"); }
2122 * Now get last part - the description
2128 } else if ((l[0] == '\\') && (l[1] == 'b')) {
2133 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
2135 if (i == sizeof(m->desc)) {
2136 m->desc[sizeof(m->desc) - 1] = '\0';
2137 if (ms->flags & MAGIC_CHECK)
2138 file_magwarn(ms, "description `%s' truncated", m->desc);
2142 * We only do this check while compiling, or if any of the magic
2143 * files were not compiled.
2145 if (ms->flags & MAGIC_CHECK) {
2146 if (check_format(ms, m) == -1)
2149 #ifndef COMPILE_ONLY
2150 if (action == FILE_CHECK) {
2154 m->mimetype[0] = '\0'; /* initialise MIME type to none */
2159 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
2163 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
2165 const char *l = line;
2167 unsigned long factor;
2168 struct magic *m = &me->mp[0];
2170 if (m->factor_op != FILE_FACTOR_OP_NONE) {
2172 "Current entry already has a strength type: %c %d",
2173 m->factor_op, m->factor);
2176 if (m->type == FILE_NAME) {
2177 file_magwarn(ms, "%s: Strength setting is not supported in "
2178 "\"name\" magic entries", m->value.s);
2183 case FILE_FACTOR_OP_NONE:
2184 case FILE_FACTOR_OP_PLUS:
2185 case FILE_FACTOR_OP_MINUS:
2186 case FILE_FACTOR_OP_TIMES:
2187 case FILE_FACTOR_OP_DIV:
2188 m->factor_op = *l++;
2191 file_magwarn(ms, "Unknown factor op `%c'", *l);
2195 factor = strtoul(l, &el, 0);
2197 file_magwarn(ms, "Too large factor `%lu'", factor);
2200 if (*el && !isspace((unsigned char)*el)) {
2201 file_magwarn(ms, "Bad factor `%s'", l);
2204 m->factor = (uint8_t)factor;
2205 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
2206 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
2207 m->factor_op, m->factor);
2212 m->factor_op = FILE_FACTOR_OP_NONE;
2218 goodchar(unsigned char x, const char *extra)
2220 return (isascii(x) && isalnum(x)) || strchr(extra, x);
2224 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
2225 off_t off, size_t len, const char *name, const char *extra, int nt)
2228 const char *l = line;
2229 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
2230 char *buf = CAST(char *, CAST(void *, m)) + off;
2232 if (buf[0] != '\0') {
2233 len = nt ? strlen(buf) : len;
2234 file_magwarn(ms, "Current entry already has a %s type "
2235 "`%.*s', new type `%s'", name, (int)len, buf, l);
2239 if (*m->desc == '\0') {
2240 file_magwarn(ms, "Current entry does not yet have a "
2241 "description for adding a %s type", name);
2246 for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
2249 if (i == len && *l) {
2251 buf[len - 1] = '\0';
2252 if (ms->flags & MAGIC_CHECK)
2253 file_magwarn(ms, "%s type `%s' truncated %"
2254 SIZE_T_FORMAT "u", name, line, i);
2256 if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
2257 file_magwarn(ms, "%s type `%s' has bad char '%c'",
2266 file_magerror(ms, "Bad magic entry '%s'", line);
2271 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
2275 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
2277 struct magic *m = &me->mp[0];
2279 return parse_extra(ms, me, line,
2280 CAST(off_t, offsetof(struct magic, apple)),
2281 sizeof(m->apple), "APPLE", "!+-./?", 0);
2285 * Parse a comma-separated list of extensions
2288 parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line)
2290 struct magic *m = &me->mp[0];
2292 return parse_extra(ms, me, line,
2293 CAST(off_t, offsetof(struct magic, ext)),
2294 sizeof(m->ext), "EXTENSION", ",!+-/", 0);
2298 * parse a MIME annotation line from magic file, put into magic[index - 1]
2302 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
2304 struct magic *m = &me->mp[0];
2306 return parse_extra(ms, me, line,
2307 CAST(off_t, offsetof(struct magic, mimetype)),
2308 sizeof(m->mimetype), "MIME", "+-/.", 1);
2312 check_format_type(const char *ptr, int type, const char **estr)
2317 /* Missing format string; bad */
2318 *estr = "missing format spec";
2322 switch (file_formats[type]) {
2355 #define CHECKLEN() do { \
2356 for (len = cnt = 0; isdigit((unsigned char)*ptr); ptr++, cnt++) \
2357 len = len * 10 + (*ptr - '0'); \
2358 if (cnt > 5 || len > 1024) \
2360 } while (/*CONSTCOND*/0)
2374 #ifdef STRICT_FORMAT /* "long" formats are int formats for us */
2375 /* so don't accept the 'l' modifier */
2392 * Don't accept h and hh modifiers. They make writing
2393 * magic entries more complicated, for very little benefit
2436 #ifdef STRICT_FORMAT
2447 case FILE_FMT_FLOAT:
2448 case FILE_FMT_DOUBLE:
2474 while (isdigit((unsigned char )*ptr))
2478 while (isdigit((unsigned char )*ptr))
2490 /* internal error */
2494 *estr = "not valid";
2501 * Check that the optional printf format in description matches
2502 * the type of the magic.
2505 check_format(struct magic_set *ms, struct magic *m)
2510 for (ptr = m->desc; *ptr; ptr++)
2514 /* No format string; ok */
2518 assert(file_nformats == file_nnames);
2520 if (m->type >= file_nformats) {
2521 file_magwarn(ms, "Internal error inconsistency between "
2522 "m->type and format strings");
2525 if (file_formats[m->type] == FILE_FMT_NONE) {
2526 file_magwarn(ms, "No format string for `%s' with description "
2527 "`%s'", m->desc, file_names[m->type]);
2532 if (check_format_type(ptr, m->type, &estr) == -1) {
2534 * TODO: this error message is unhelpful if the format
2535 * string is not one character long
2537 file_magwarn(ms, "Printf format is %s for type "
2538 "`%s' in description `%s'", estr,
2539 file_names[m->type], m->desc);
2543 for (; *ptr; ptr++) {
2546 "Too many format strings (should have at most one) "
2547 "for `%s' with description `%s'",
2548 file_names[m->type], m->desc);
2556 * Read a numeric value from a pointer, into the value union of a magic
2557 * pointer, according to the magic type. Update the string pointer to point
2558 * just after the number read. Return 0 for success, non-zero for failure.
2561 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
2564 case FILE_BESTRING16:
2565 case FILE_LESTRING16:
2573 *p = getstr(ms, m, *p, action == FILE_COMPILE);
2575 if (ms->flags & MAGIC_CHECK)
2576 file_magwarn(ms, "cannot get string from `%s'",
2580 if (m->type == FILE_REGEX) {
2582 int rc = file_regcomp(&rx, m->value.s, REG_EXTENDED);
2584 if (ms->flags & MAGIC_CHECK)
2585 file_regerror(&rx, rc, ms);
2594 if (m->reln != 'x') {
2598 m->value.f = strtof(*p, &ep);
2600 m->value.f = (float)strtod(*p, &ep);
2609 if (m->reln != 'x') {
2612 m->value.d = strtod(*p, &ep);
2618 if (m->reln != 'x') {
2621 m->value.q = file_signextend(ms, m,
2622 (uint64_t)strtoull(*p, &ep, 0));
2633 * Convert a string containing C character escapes. Stop at an unescaped
2635 * Copy the converted version to "m->value.s", and the length in m->vallen.
2636 * Return updated scan pointer as function result. Warn if set.
2638 private const char *
2639 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
2641 const char *origs = s;
2642 char *p = m->value.s;
2643 size_t plen = sizeof(m->value.s);
2645 char *pmax = p + plen - 1;
2649 while ((c = *s++) != '\0') {
2650 if (isspace((unsigned char) c))
2653 file_error(ms, 0, "string too long: `%s'", origs);
2661 file_magwarn(ms, "incomplete escape");
2668 "escaped tab found, use \\t instead");
2669 warn = 0; /* already did */
2674 if (isprint((unsigned char)c)) {
2675 /* Allow escaping of
2677 if (strchr("<>&^=!", c) == NULL
2678 && (m->type != FILE_REGEX ||
2679 strchr("[]().*?^$|{}", c)
2681 file_magwarn(ms, "no "
2687 "unknown escape sequence: "
2692 /* space, perhaps force people to use \040? */
2696 * Other things people escape, but shouldn't need to,
2697 * so we disallow them
2710 /* and baskslash itself */
2743 /* \ and up to 3 octal digits */
2753 c = *s++; /* try for 2 */
2754 if (c >= '0' && c <= '7') {
2755 val = (val << 3) | (c - '0');
2756 c = *s++; /* try for 3 */
2757 if (c >= '0' && c <= '7')
2758 val = (val << 3) | (c-'0');
2767 /* \x and up to 2 hex digits */
2769 val = 'x'; /* Default if no digits */
2770 c = hextoint(*s++); /* Get next char */
2775 val = (val << 4) + c;
2789 m->vallen = CAST(unsigned char, (p - origp));
2790 if (m->type == FILE_PSTRING)
2791 m->vallen += (unsigned char)file_pstring_length_size(m);
2796 /* Single hex char to int; -1 if not a hex char. */
2800 if (!isascii((unsigned char) c))
2802 if (isdigit((unsigned char) c))
2804 if ((c >= 'a') && (c <= 'f'))
2805 return c + 10 - 'a';
2806 if (( c>= 'A') && (c <= 'F'))
2807 return c + 10 - 'A';
2813 * Print a string containing C character escapes.
2816 file_showstr(FILE *fp, const char *s, size_t len)
2831 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
2832 (void) fputc(c, fp);
2834 (void) fputc('\\', fp);
2837 (void) fputc('a', fp);
2841 (void) fputc('b', fp);
2845 (void) fputc('f', fp);
2849 (void) fputc('n', fp);
2853 (void) fputc('r', fp);
2857 (void) fputc('t', fp);
2861 (void) fputc('v', fp);
2865 (void) fprintf(fp, "%.3o", c & 0377);
2873 * eatsize(): Eat the size spec from a number [eg. 10UL]
2876 eatsize(const char **p)
2880 if (LOWCASE(*l) == 'u')
2883 switch (LOWCASE(*l)) {
2884 case 'l': /* long */
2885 case 's': /* short */
2886 case 'h': /* short */
2887 case 'b': /* char/byte */
2888 case 'c': /* char/byte */
2899 * handle a buffer containing a compiled file.
2901 private struct magic_map *
2902 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
2904 struct magic_map *map;
2906 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2907 file_oomem(ms, sizeof(*map));
2912 map->type = MAP_TYPE_USER;
2913 if (check_buffer(ms, map, "buffer") != 0) {
2914 apprentice_unmap(map);
2921 * handle a compiled file.
2924 private struct magic_map *
2925 apprentice_map(struct magic_set *ms, const char *fn)
2929 char *dbname = NULL;
2930 struct magic_map *map;
2931 struct magic_map *rv = NULL;
2934 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2935 file_oomem(ms, sizeof(*map));
2938 map->type = MAP_TYPE_USER; /* unspecified */
2940 dbname = mkdbname(ms, fn, 0);
2944 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2947 if (fstat(fd, &st) == -1) {
2948 file_error(ms, errno, "cannot stat `%s'", dbname);
2951 if (st.st_size < 8 || st.st_size > MAXMAGIC_SIZE) {
2952 file_error(ms, 0, "file `%s' is too %s", dbname,
2953 st.st_size < 8 ? "small" : "large");
2957 map->len = (size_t)st.st_size;
2959 map->type = MAP_TYPE_MMAP;
2960 if ((map->p = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2961 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2962 file_error(ms, errno, "cannot map `%s'", dbname);
2966 map->type = MAP_TYPE_MALLOC;
2967 if ((map->p = CAST(void *, malloc(map->len))) == NULL) {
2968 file_oomem(ms, map->len);
2971 if (read(fd, map->p, map->len) != (ssize_t)map->len) {
2980 if (check_buffer(ms, map, dbname) != 0) {
2981 rv = (struct magic_map *)-1;
2985 if (mprotect(map->p, (size_t)st.st_size, PROT_READ) == -1) {
2986 file_error(ms, errno, "cannot mprotect `%s'", dbname);
2997 apprentice_unmap(map);
3003 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
3006 uint32_t entries, nentries;
3008 int i, needsbyteswap;
3010 ptr = CAST(uint32_t *, map->p);
3011 if (*ptr != MAGICNO) {
3012 if (swap4(*ptr) != MAGICNO) {
3013 file_error(ms, 0, "bad magic in `%s'", dbname);
3020 version = swap4(ptr[1]);
3023 if (version != VERSIONNO) {
3024 file_error(ms, 0, "File %s supports only version %d magic "
3025 "files. `%s' is version %d", VERSION,
3026 VERSIONNO, dbname, version);
3029 entries = (uint32_t)(map->len / sizeof(struct magic));
3030 if ((entries * sizeof(struct magic)) != map->len) {
3031 file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
3032 "a multiple of %" SIZE_T_FORMAT "u",
3033 dbname, map->len, sizeof(struct magic));
3036 map->magic[0] = CAST(struct magic *, map->p) + 1;
3038 for (i = 0; i < MAGIC_SETS; i++) {
3040 map->nmagic[i] = swap4(ptr[i + 2]);
3042 map->nmagic[i] = ptr[i + 2];
3043 if (i != MAGIC_SETS - 1)
3044 map->magic[i + 1] = map->magic[i] + map->nmagic[i];
3045 nentries += map->nmagic[i];
3047 if (entries != nentries + 1) {
3048 file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
3049 dbname, entries, nentries + 1);
3053 for (i = 0; i < MAGIC_SETS; i++)
3054 byteswap(map->magic[i], map->nmagic[i]);
3059 * handle an mmaped file.
3062 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
3064 static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
3065 static const size_t m = sizeof(**map->magic);
3073 uint32_t h[2 + MAGIC_SETS];
3076 dbname = mkdbname(ms, fn, 1);
3081 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1)
3083 file_error(ms, errno, "cannot open `%s'", dbname);
3086 memset(&hdr, 0, sizeof(hdr));
3088 hdr.h[1] = VERSIONNO;
3089 memcpy(hdr.h + 2, map->nmagic, nm);
3091 if (write(fd, &hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
3092 file_error(ms, errno, "error writing `%s'", dbname);
3096 for (i = 0; i < MAGIC_SETS; i++) {
3097 len = m * map->nmagic[i];
3098 if (write(fd, map->magic[i], len) != (ssize_t)len) {
3099 file_error(ms, errno, "error writing `%s'", dbname);
3108 apprentice_unmap(map);
3113 private const char ext[] = ".mgc";
3118 mkdbname(struct magic_set *ms, const char *fn, int strip)
3124 if ((p = strrchr(fn, '/')) != NULL)
3128 for (q = fn; *q; q++)
3131 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
3135 /* Did not find .mgc, restore q */
3141 /* Compatibility with old code that looked in .mime */
3142 if (ms->flags & MAGIC_MIME) {
3143 if (asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext) < 0)
3145 if (access(buf, R_OK) != -1) {
3146 ms->flags &= MAGIC_MIME_TYPE;
3151 if (asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext) < 0)
3154 /* Compatibility with old code that looked in .mime */
3155 if (strstr(fn, ".mime") != NULL)
3156 ms->flags &= MAGIC_MIME_TYPE;
3161 * Byteswap an mmap'ed file if needed
3164 byteswap(struct magic *magic, uint32_t nmagic)
3167 for (i = 0; i < nmagic; i++)
3178 uint8_t *s = (uint8_t *)(void *)&sv;
3179 uint8_t *d = (uint8_t *)(void *)&rv;
3192 uint8_t *s = (uint8_t *)(void *)&sv;
3193 uint8_t *d = (uint8_t *)(void *)&rv;
3208 uint8_t *s = (uint8_t *)(void *)&sv;
3209 uint8_t *d = (uint8_t *)(void *)&rv;
3233 * byteswap a single magic entry
3236 bs1(struct magic *m)
3238 m->cont_level = swap2(m->cont_level);
3239 m->offset = swap4((uint32_t)m->offset);
3240 m->in_offset = swap4((uint32_t)m->in_offset);
3241 m->lineno = swap4((uint32_t)m->lineno);
3242 if (IS_STRING(m->type)) {
3243 m->str_range = swap4(m->str_range);
3244 m->str_flags = swap4(m->str_flags);
3247 m->value.q = swap8(m->value.q);
3248 m->num_mask = swap8(m->num_mask);
3253 file_pstring_length_size(const struct magic *m)
3255 switch (m->str_flags & PSTRING_LEN) {
3265 abort(); /* Impossible */
3270 file_pstring_get_length(const struct magic *m, const char *ss)
3273 const unsigned char *s = (const unsigned char *)ss;
3275 switch (m->str_flags & PSTRING_LEN) {
3280 len = (s[1] << 8) | s[0];
3283 len = (s[0] << 8) | s[1];
3286 len = (s[3] << 24) | (s[2] << 16) | (s[1] << 8) | s[0];
3289 len = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
3292 abort(); /* Impossible */
3295 if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
3296 len -= file_pstring_length_size(m);
3302 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
3305 struct mlist *mlist, *ml;
3307 mlist = ms->mlist[1];
3309 for (ml = mlist->next; ml != mlist; ml = ml->next) {
3310 struct magic *ma = ml->magic;
3311 uint32_t nma = ml->nmagic;
3312 for (i = 0; i < nma; i++) {
3313 if (ma[i].type != FILE_NAME)
3315 if (strcmp(ma[i].value.s, name) == 0) {
3317 for (j = i + 1; j < nma; j++)
3318 if (ma[j].cont_level == 0)