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.238 2015/09/12 18:10:42 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_MMAP 0
90 #define MAP_TYPE_MALLOC 1
91 #define MAP_TYPE_USER 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);
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_NULL, FILE_INVALID, FILE_FMT_NONE },
275 * These are not types, and cannot be preceded by "u" to make them
278 static const struct type_tbl_s special_tbl[] = {
279 { XX("name"), FILE_NAME, FILE_FMT_STR },
280 { XX("use"), FILE_USE, FILE_FMT_STR },
281 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
287 get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
289 const struct type_tbl_s *p;
291 for (p = tbl; p->len; p++) {
292 if (strncmp(l, p->name, p->len) == 0) {
302 get_standard_integer_type(const char *l, const char **t)
306 if (isalpha((unsigned char)l[1])) {
319 * "dI", "dL", "uI", and "uL".
321 * XXX - the actual Single UNIX Specification says
322 * that "L" means "long", as in the C data type,
323 * but we treat it as meaning "4-byte integer".
324 * Given that the OS X version of file 5.04 did
325 * the same, I guess that passes the actual SUS
326 * validation suite; having "dL" be dependent on
327 * how big a "long" is on the machine running
337 /* "d{anything else}", "u{anything else}" */
341 } else if (isdigit((unsigned char)l[1])) {
343 * "d{num}" and "u{num}"; we only support {num} values
344 * of 1, 2, 4, and 8 - the Single UNIX Specification
345 * doesn't say anything about whether arbitrary
346 * values should be supported, but both the Solaris 10
347 * and OS X Mountain Lion versions of file passed the
348 * Single UNIX Specification validation suite, and
349 * neither of them support values bigger than 8 or
350 * non-power-of-2 values.
352 if (isdigit((unsigned char)l[2])) {
353 /* Multi-digit, so > 9 */
370 /* XXX - what about 3, 5, 6, or 7? */
376 * "d" or "u" by itself.
387 init_file_tables(void)
390 const struct type_tbl_s *p;
396 for (p = type_tbl; p->len; p++) {
397 assert(p->type < FILE_NAMES_SIZE);
398 file_names[p->type] = p->name;
399 file_formats[p->type] = p->format;
401 assert(p - type_tbl == FILE_NAMES_SIZE);
405 add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
409 mlp->map = idx == 0 ? map : NULL;
410 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL)
414 ml->magic = map->magic[idx];
415 ml->nmagic = map->nmagic[idx];
417 mlp->prev->next = ml;
418 ml->prev = mlp->prev;
425 * Handle one file or directory.
428 apprentice_1(struct magic_set *ms, const char *fn, int action)
430 struct magic_map *map;
436 if (magicsize != FILE_MAGICSIZE) {
437 file_error(ms, 0, "magic element size %lu != %lu",
438 (unsigned long)sizeof(*map->magic[0]),
439 (unsigned long)FILE_MAGICSIZE);
443 if (action == FILE_COMPILE) {
444 map = apprentice_load(ms, fn, action);
447 return apprentice_compile(ms, map, fn);
451 map = apprentice_map(ms, fn);
453 if (ms->flags & MAGIC_CHECK)
454 file_magwarn(ms, "using regular magic file `%s'", fn);
455 map = apprentice_load(ms, fn, action);
460 for (i = 0; i < MAGIC_SETS; i++) {
461 if (add_mlist(ms->mlist[i], map, i) == -1) {
462 file_oomem(ms, sizeof(*ml));
467 if (action == FILE_LIST) {
468 for (i = 0; i < MAGIC_SETS; i++) {
469 printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
471 apprentice_list(ms->mlist[i], BINTEST);
472 printf("Text patterns:\n");
473 apprentice_list(ms->mlist[i], TEXTTEST);
478 for (i = 0; i < MAGIC_SETS; i++) {
479 mlist_free(ms->mlist[i]);
485 #endif /* COMPILE_ONLY */
489 file_ms_free(struct magic_set *ms)
494 for (i = 0; i < MAGIC_SETS; i++)
495 mlist_free(ms->mlist[i]);
502 protected struct magic_set *
503 file_ms_alloc(int flags)
505 struct magic_set *ms;
508 if ((ms = CAST(struct magic_set *, calloc((size_t)1,
509 sizeof(struct magic_set)))) == NULL)
512 if (magic_setflags(ms, flags) == -1) {
517 ms->o.buf = ms->o.pbuf = NULL;
518 len = (ms->c.len = 10) * sizeof(*ms->c.li);
520 if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
525 for (i = 0; i < MAGIC_SETS; i++)
527 ms->file = "unknown";
529 ms->indir_max = FILE_INDIR_MAX;
530 ms->name_max = FILE_NAME_MAX;
531 ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
532 ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
533 ms->elf_notes_max = FILE_ELF_NOTES_MAX;
534 ms->regex_max = FILE_REGEX_MAX;
542 apprentice_unmap(struct magic_map *map)
552 (void)munmap(map->p, map->len);
555 case MAP_TYPE_MALLOC:
557 for (i = 0; i < MAGIC_SETS; i++)
568 private struct mlist *
572 if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
575 mlist->next = mlist->prev = mlist;
580 mlist_free(struct mlist *mlist)
582 struct mlist *ml, *next;
588 for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
590 apprentice_unmap(ml->map);
598 /* void **bufs: an array of compiled magic files */
600 buffer_apprentice(struct magic_set *ms, struct magic **bufs,
601 size_t *sizes, size_t nbufs)
605 struct magic_map *map;
610 if (ms->mlist[0] != NULL)
615 for (i = 0; i < MAGIC_SETS; i++) {
616 mlist_free(ms->mlist[i]);
617 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
618 file_oomem(ms, sizeof(*ms->mlist[i]));
623 for (i = 0; i < nbufs; i++) {
624 map = apprentice_buf(ms, bufs[i], sizes[i]);
628 for (j = 0; j < MAGIC_SETS; j++) {
629 if (add_mlist(ms->mlist[j], map, j) == -1) {
630 file_oomem(ms, sizeof(*ml));
638 for (i = 0; i < MAGIC_SETS; i++) {
639 mlist_free(ms->mlist[i]);
646 /* const char *fn: list of magic files and directories */
648 file_apprentice(struct magic_set *ms, const char *fn, int action)
651 int file_err, errs = -1;
654 if (ms->mlist[0] != NULL)
657 if ((fn = magic_getpath(fn, action)) == NULL)
662 if ((mfn = strdup(fn)) == NULL) {
663 file_oomem(ms, strlen(fn));
667 for (i = 0; i < MAGIC_SETS; i++) {
668 mlist_free(ms->mlist[i]);
669 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
670 file_oomem(ms, sizeof(*ms->mlist[i]));
672 mlist_free(ms->mlist[i]);
682 p = strchr(fn, PATHSEP);
687 file_err = apprentice_1(ms, fn, action);
688 errs = MAX(errs, file_err);
695 for (i = 0; i < MAGIC_SETS; i++) {
696 mlist_free(ms->mlist[i]);
699 file_error(ms, 0, "could not find any valid magic files!");
705 * Always leave the database loaded
707 if (action == FILE_LOAD)
710 for (i = 0; i < MAGIC_SETS; i++) {
711 mlist_free(ms->mlist[i]);
723 file_error(ms, 0, "Invalid action %d", action);
729 * Compute the real length of a magic expression, for the purposes
730 * of determining how "strong" a magic expression is (approximating
731 * how specific its matches are):
732 * - magic characters count 0 unless escaped.
733 * - [] expressions count 1
734 * - {} expressions count 0
735 * - regular characters or escaped magic characters count 1
736 * - 0 length expressions count as one
739 nonmagic(const char *str)
744 for (p = str; *p; p++)
746 case '\\': /* Escaped anything counts 1 */
751 case '?': /* Magic characters count 0 */
758 case '[': /* Bracketed expressions count 1 the ']' */
759 while (*p && *p != ']')
763 case '{': /* Braced expressions count 0 */
764 while (*p && *p != '}')
769 default: /* Anything else counts 1 */
774 return rv == 0 ? 1 : rv; /* Return at least 1 */
778 * Get weight of this magic entry, for sorting purposes.
781 apprentice_magic_strength(const struct magic *m)
784 size_t v, val = 2 * MULT; /* baseline strength */
787 case FILE_DEFAULT: /* make sure this sorts last */
788 if (m->factor_op != FILE_FACTOR_OP_NONE)
811 val += m->vallen * MULT;
814 case FILE_BESTRING16:
815 case FILE_LESTRING16:
816 val += m->vallen * MULT / 2;
820 val += m->vallen * MAX(MULT / m->vallen, 1);
824 v = nonmagic(m->value.s);
825 val += v * MAX(MULT / v, 1);
866 (void)fprintf(stderr, "Bad type %d\n", m->type);
871 case 'x': /* matches anything penalize */
872 case '!': /* matches almost anything penalize */
876 case '=': /* Exact match, prefer */
881 case '<': /* comparison match reduce strength */
886 case '&': /* masking bits, we could count them too */
891 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
895 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
898 switch (m->factor_op) {
899 case FILE_FACTOR_OP_NONE:
901 case FILE_FACTOR_OP_PLUS:
904 case FILE_FACTOR_OP_MINUS:
907 case FILE_FACTOR_OP_TIMES:
910 case FILE_FACTOR_OP_DIV:
918 * Magic entries with no description get a bonus because they depend
919 * on subsequent magic entries to print something.
921 if (m->desc[0] == '\0')
927 * Sort callback for sorting entries by "strength" (basically length)
930 apprentice_sort(const void *a, const void *b)
932 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
933 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
934 size_t sa = apprentice_magic_strength(ma->mp);
935 size_t sb = apprentice_magic_strength(mb->mp);
945 * Shows sorted patterns list in the order which is used for the matching
948 apprentice_list(struct mlist *mlist, int mode)
950 uint32_t magindex = 0;
952 for (ml = mlist->next; ml != mlist; ml = ml->next) {
953 for (magindex = 0; magindex < ml->nmagic; magindex++) {
954 struct magic *m = &ml->magic[magindex];
955 if ((m->flag & mode) != mode) {
957 while (magindex + 1 < ml->nmagic &&
958 ml->magic[magindex + 1].cont_level != 0)
960 continue; /* Skip to next top-level test*/
964 * Try to iterate over the tree until we find item with
965 * description/mimetype.
967 while (magindex + 1 < ml->nmagic &&
968 ml->magic[magindex + 1].cont_level != 0 &&
969 *ml->magic[magindex].desc == '\0' &&
970 *ml->magic[magindex].mimetype == '\0')
973 printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
974 apprentice_magic_strength(m),
975 ml->magic[magindex].lineno,
976 ml->magic[magindex].desc,
977 ml->magic[magindex].mimetype);
983 set_test_type(struct magic *mstart, struct magic *m)
1020 mstart->flag |= BINTEST;
1024 case FILE_BESTRING16:
1025 case FILE_LESTRING16:
1026 /* Allow text overrides */
1027 if (mstart->str_flags & STRING_TEXTTEST)
1028 mstart->flag |= TEXTTEST;
1030 mstart->flag |= BINTEST;
1034 /* Check for override */
1035 if (mstart->str_flags & STRING_BINTEST)
1036 mstart->flag |= BINTEST;
1037 if (mstart->str_flags & STRING_TEXTTEST)
1038 mstart->flag |= TEXTTEST;
1040 if (mstart->flag & (TEXTTEST|BINTEST))
1043 /* binary test if pattern is not text */
1044 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
1046 mstart->flag |= BINTEST;
1048 mstart->flag |= TEXTTEST;
1051 /* can't deduce anything; we shouldn't see this at the
1056 /* invalid search type, but no need to complain here */
1062 addentry(struct magic_set *ms, struct magic_entry *me,
1063 struct magic_entry_set *mset)
1065 size_t i = me->mp->type == FILE_NAME ? 1 : 0;
1066 if (mset[i].count == mset[i].max) {
1067 struct magic_entry *mp;
1069 mset[i].max += ALLOC_INCR;
1070 if ((mp = CAST(struct magic_entry *,
1071 realloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
1073 file_oomem(ms, sizeof(*mp) * mset[i].max);
1076 (void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
1080 mset[i].me[mset[i].count++] = *me;
1081 memset(me, 0, sizeof(*me));
1086 * Load and parse one file.
1089 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
1090 struct magic_entry_set *mset)
1092 size_t lineno = 0, llen = 0;
1095 struct magic_entry me;
1097 FILE *f = fopen(ms->file = fn, "r");
1099 if (errno != ENOENT)
1100 file_error(ms, errno, "cannot read magic file `%s'",
1106 memset(&me, 0, sizeof(me));
1107 /* read and parse this file */
1108 for (ms->line = 1; (len = getline(&line, &llen, f)) != -1;
1110 if (len == 0) /* null line, garbage, etc */
1112 if (line[len - 1] == '\n') {
1114 line[len - 1] = '\0'; /* delete newline */
1117 case '\0': /* empty, do not parse */
1118 case '#': /* comment, do not parse */
1121 if (line[1] == ':') {
1124 for (i = 0; bang[i].name != NULL; i++) {
1125 if ((size_t)(len - 2) > bang[i].len &&
1126 memcmp(bang[i].name, line + 2,
1130 if (bang[i].name == NULL) {
1132 "Unknown !: entry `%s'", line);
1136 if (me.mp == NULL) {
1138 "No current entry for :!%s type",
1143 if ((*bang[i].fun)(ms, &me,
1144 line + bang[i].len + 2) != 0) {
1153 switch (parse(ms, &me, line, lineno, action)) {
1157 (void)addentry(ms, &me, mset);
1166 (void)addentry(ms, &me, mset);
1172 * parse a file or directory of files
1173 * const char *fn: name of magic file or directory
1176 cmpstrp(const void *p1, const void *p2)
1178 return strcmp(*(char *const *)p1, *(char *const *)p2);
1183 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1186 static const char text[] = "text";
1187 static const char binary[] = "binary";
1188 static const size_t len = sizeof(text);
1190 uint32_t i = starttest;
1193 set_test_type(me[starttest].mp, me[i].mp);
1194 if ((ms->flags & MAGIC_DEBUG) == 0)
1196 (void)fprintf(stderr, "%s%s%s: %s\n",
1198 me[i].mp->mimetype[0] == '\0' ? "" : "; ",
1199 me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
1200 me[i].mp->flag & BINTEST ? binary : text);
1201 if (me[i].mp->flag & BINTEST) {
1202 char *p = strstr(me[i].mp->desc, text);
1203 if (p && (p == me[i].mp->desc ||
1204 isspace((unsigned char)p[-1])) &&
1205 (p + len - me[i].mp->desc == MAXstring
1206 || (p[len] == '\0' ||
1207 isspace((unsigned char)p[len]))))
1208 (void)fprintf(stderr, "*** Possible "
1209 "binary test for text type\n");
1211 } while (++i < nme && me[i].mp->cont_level != 0);
1216 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
1219 for (i = 0; i < nme; i++) {
1220 if (me[i].mp->cont_level == 0 &&
1221 me[i].mp->type == FILE_DEFAULT) {
1223 if (me[i].mp->cont_level == 0)
1227 ms->line = me[i].mp->lineno;
1229 "level 0 \"default\" did not sort last");
1237 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1238 struct magic **ma, uint32_t *nma)
1240 uint32_t i, mentrycount = 0;
1243 for (i = 0; i < nme; i++)
1244 mentrycount += me[i].cont_count;
1246 slen = sizeof(**ma) * mentrycount;
1247 if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) {
1248 file_oomem(ms, slen);
1253 for (i = 0; i < nme; i++) {
1254 (void)memcpy(*ma + mentrycount, me[i].mp,
1255 me[i].cont_count * sizeof(**ma));
1256 mentrycount += me[i].cont_count;
1263 magic_entry_free(struct magic_entry *me, uint32_t nme)
1268 for (i = 0; i < nme; i++)
1273 private struct magic_map *
1274 apprentice_load(struct magic_set *ms, const char *fn, int action)
1278 size_t files = 0, maxfiles = 0;
1279 char **filearr = NULL, *mfn;
1281 struct magic_map *map;
1282 struct magic_entry_set mset[MAGIC_SETS];
1286 memset(mset, 0, sizeof(mset));
1287 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
1290 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL)
1292 file_oomem(ms, sizeof(*map));
1295 map->type = MAP_TYPE_MALLOC;
1297 /* print silly verbose header for USG compat. */
1298 if (action == FILE_CHECK)
1299 (void)fprintf(stderr, "%s\n", usg_hdr);
1301 /* load directory or file */
1302 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
1308 while ((d = readdir(dir)) != NULL) {
1309 if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) {
1311 strlen(fn) + strlen(d->d_name) + 2);
1316 if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
1320 if (files >= maxfiles) {
1322 maxfiles = (maxfiles + 1) * 2;
1323 mlen = maxfiles * sizeof(*filearr);
1324 if ((filearr = CAST(char **,
1325 realloc(filearr, mlen))) == NULL) {
1326 file_oomem(ms, mlen);
1333 filearr[files++] = mfn;
1336 qsort(filearr, files, sizeof(*filearr), cmpstrp);
1337 for (i = 0; i < files; i++) {
1338 load_1(ms, action, filearr[i], &errs, mset);
1343 load_1(ms, action, fn, &errs, mset);
1347 for (j = 0; j < MAGIC_SETS; j++) {
1348 /* Set types of tests */
1349 for (i = 0; i < mset[j].count; ) {
1350 if (mset[j].me[i].mp->cont_level != 0) {
1354 i = set_text_binary(ms, mset[j].me, mset[j].count, i);
1357 qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
1361 * Make sure that any level 0 "default" line is last
1364 set_last_default(ms, mset[j].me, mset[j].count);
1366 /* coalesce per file arrays into a single one */
1367 if (coalesce_entries(ms, mset[j].me, mset[j].count,
1368 &map->magic[j], &map->nmagic[j]) == -1) {
1375 for (j = 0; j < MAGIC_SETS; j++)
1376 magic_entry_free(mset[j].me, mset[j].count);
1379 apprentice_unmap(map);
1386 * extend the sign bit if the comparison is to be signed
1389 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
1391 if (!(m->flag & UNSIGNED)) {
1394 * Do not remove the casts below. They are
1395 * vital. When later compared with the data,
1396 * the sign extension must have happened.
1399 v = (signed char) v;
1442 case FILE_BESTRING16:
1443 case FILE_LESTRING16:
1453 if (ms->flags & MAGIC_CHECK)
1454 file_magwarn(ms, "cannot happen: m->type=%d\n",
1463 string_modifier_check(struct magic_set *ms, struct magic *m)
1465 if ((ms->flags & MAGIC_CHECK) == 0)
1468 if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
1469 (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
1471 "'/BHhLl' modifiers are only allowed for pascal strings\n");
1475 case FILE_BESTRING16:
1476 case FILE_LESTRING16:
1477 if (m->str_flags != 0) {
1479 "no modifiers allowed for 16-bit strings\n");
1485 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
1487 "'/%c' only allowed on regex and search\n",
1488 CHAR_REGEX_OFFSET_START);
1493 if (m->str_range == 0) {
1495 "missing range; defaulting to %d\n",
1496 STRING_DEFAULT_RANGE);
1497 m->str_range = STRING_DEFAULT_RANGE;
1502 if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
1503 file_magwarn(ms, "'/%c' not allowed on regex\n",
1504 CHAR_COMPACT_WHITESPACE);
1507 if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
1508 file_magwarn(ms, "'/%c' not allowed on regex\n",
1509 CHAR_COMPACT_OPTIONAL_WHITESPACE);
1514 file_magwarn(ms, "coding error: m->type=%d\n",
1534 return FILE_OPMINUS;
1536 return FILE_OPMULTIPLY;
1538 return FILE_OPDIVIDE;
1540 return FILE_OPMODULO;
1546 #ifdef ENABLE_CONDITIONALS
1548 get_cond(const char *l, const char **t)
1550 static const struct cond_tbl_s {
1555 { "if", 2, COND_IF },
1556 { "elif", 4, COND_ELIF },
1557 { "else", 4, COND_ELSE },
1558 { "", 0, COND_NONE },
1560 const struct cond_tbl_s *p;
1562 for (p = cond_tbl; p->len; p++) {
1563 if (strncmp(l, p->name, p->len) == 0 &&
1564 isspace((unsigned char)l[p->len])) {
1574 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1577 last_cond = ms->c.li[cont_level].last_cond;
1581 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1582 if (ms->flags & MAGIC_CHECK)
1583 file_magwarn(ms, "syntax error: `if'");
1586 last_cond = COND_IF;
1590 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1591 if (ms->flags & MAGIC_CHECK)
1592 file_magwarn(ms, "syntax error: `elif'");
1595 last_cond = COND_ELIF;
1599 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1600 if (ms->flags & MAGIC_CHECK)
1601 file_magwarn(ms, "syntax error: `else'");
1604 last_cond = COND_NONE;
1608 last_cond = COND_NONE;
1612 ms->c.li[cont_level].last_cond = last_cond;
1615 #endif /* ENABLE_CONDITIONALS */
1618 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1620 const char *l = *lp;
1622 while (!isspace((unsigned char)*++l))
1624 case CHAR_INDIRECT_RELATIVE:
1625 m->str_flags |= INDIRECT_RELATIVE;
1628 if (ms->flags & MAGIC_CHECK)
1629 file_magwarn(ms, "indirect modifier `%c' "
1639 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
1642 const char *l = *lp;
1648 val = (uint64_t)strtoull(l, &t, 0);
1650 m->num_mask = file_signextend(ms, m, val);
1656 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1658 const char *l = *lp;
1662 while (!isspace((unsigned char)*++l)) {
1664 case '0': case '1': case '2':
1665 case '3': case '4': case '5':
1666 case '6': case '7': case '8':
1668 if (have_range && (ms->flags & MAGIC_CHECK))
1669 file_magwarn(ms, "multiple ranges");
1671 m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
1672 if (m->str_range == 0)
1673 file_magwarn(ms, "zero range");
1676 case CHAR_COMPACT_WHITESPACE:
1677 m->str_flags |= STRING_COMPACT_WHITESPACE;
1679 case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1680 m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
1682 case CHAR_IGNORE_LOWERCASE:
1683 m->str_flags |= STRING_IGNORE_LOWERCASE;
1685 case CHAR_IGNORE_UPPERCASE:
1686 m->str_flags |= STRING_IGNORE_UPPERCASE;
1688 case CHAR_REGEX_OFFSET_START:
1689 m->str_flags |= REGEX_OFFSET_START;
1692 m->str_flags |= STRING_BINTEST;
1695 m->str_flags |= STRING_TEXTTEST;
1698 m->str_flags |= STRING_TRIM;
1700 case CHAR_PSTRING_1_LE:
1701 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
1702 if (m->type != FILE_PSTRING)
1704 SET_LENGTH(PSTRING_1_LE);
1706 case CHAR_PSTRING_2_BE:
1707 if (m->type != FILE_PSTRING)
1709 SET_LENGTH(PSTRING_2_BE);
1711 case CHAR_PSTRING_2_LE:
1712 if (m->type != FILE_PSTRING)
1714 SET_LENGTH(PSTRING_2_LE);
1716 case CHAR_PSTRING_4_BE:
1717 if (m->type != FILE_PSTRING)
1719 SET_LENGTH(PSTRING_4_BE);
1721 case CHAR_PSTRING_4_LE:
1729 SET_LENGTH(PSTRING_4_LE);
1731 case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
1732 if (m->type != FILE_PSTRING)
1734 m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
1738 if (ms->flags & MAGIC_CHECK)
1739 file_magwarn(ms, "string modifier `%c' "
1743 /* allow multiple '/' for readability */
1744 if (l[1] == '/' && !isspace((unsigned char)l[2]))
1747 if (string_modifier_check(ms, m) == -1)
1757 * parse one line from magic file, put into magic[index++] if valid
1760 parse(struct magic_set *ms, struct magic_entry *me, const char *line,
1761 size_t lineno, int action)
1763 #ifdef ENABLE_CONDITIONALS
1764 static uint32_t last_cont_level = 0;
1768 const char *l = line;
1771 uint32_t cont_level;
1780 ++l; /* step over */
1783 #ifdef ENABLE_CONDITIONALS
1784 if (cont_level == 0 || cont_level > last_cont_level)
1785 if (file_check_mem(ms, cont_level) == -1)
1787 last_cont_level = cont_level;
1789 if (cont_level != 0) {
1790 if (me->mp == NULL) {
1791 file_magerror(ms, "No current entry for continuation");
1794 if (me->cont_count == 0) {
1795 file_magerror(ms, "Continuations present with 0 count");
1798 m = &me->mp[me->cont_count - 1];
1799 diff = (int32_t)cont_level - (int32_t)m->cont_level;
1801 file_magwarn(ms, "New continuation level %u is more "
1802 "than one larger than current level %u", cont_level,
1804 if (me->cont_count == me->max_count) {
1806 size_t cnt = me->max_count + ALLOC_CHUNK;
1807 if ((nm = CAST(struct magic *, realloc(me->mp,
1808 sizeof(*nm) * cnt))) == NULL) {
1809 file_oomem(ms, sizeof(*nm) * cnt);
1813 me->max_count = CAST(uint32_t, cnt);
1815 m = &me->mp[me->cont_count++];
1816 (void)memset(m, 0, sizeof(*m));
1817 m->cont_level = cont_level;
1819 static const size_t len = sizeof(*m) * ALLOC_CHUNK;
1822 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1823 file_oomem(ms, len);
1827 me->max_count = ALLOC_CHUNK;
1828 (void)memset(m, 0, sizeof(*m));
1829 m->factor_op = FILE_FACTOR_OP_NONE;
1833 m->lineno = CAST(uint32_t, lineno);
1835 if (*l == '&') { /* m->cont_level == 0 checked below. */
1836 ++l; /* step over */
1840 ++l; /* step over */
1842 if (m->flag & OFFADD)
1843 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1845 if (*l == '&') { /* m->cont_level == 0 checked below */
1846 ++l; /* step over */
1850 /* Indirect offsets are not valid at level 0. */
1851 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
1852 if (ms->flags & MAGIC_CHECK)
1853 file_magwarn(ms, "relative offset at level 0");
1857 /* get offset, then skip over it */
1858 m->offset = (uint32_t)strtoul(l, &t, 0);
1860 if (ms->flags & MAGIC_CHECK)
1861 file_magwarn(ms, "offset `%s' invalid", l);
1866 if (m->flag & INDIR) {
1867 m->in_type = FILE_LONG;
1870 * read [.lbs][+-]nnnnn)
1876 m->in_type = FILE_LELONG;
1879 m->in_type = FILE_BELONG;
1882 m->in_type = FILE_MELONG;
1886 m->in_type = FILE_LESHORT;
1890 m->in_type = FILE_BESHORT;
1896 m->in_type = FILE_BYTE;
1901 m->in_type = FILE_LEDOUBLE;
1906 m->in_type = FILE_BEDOUBLE;
1909 m->in_type = FILE_LEID3;
1912 m->in_type = FILE_BEID3;
1915 if (ms->flags & MAGIC_CHECK)
1917 "indirect offset type `%c' invalid",
1926 m->in_op |= FILE_OPINVERSE;
1929 if ((op = get_op(*l)) != -1) {
1934 m->in_op |= FILE_OPINDIRECT;
1937 if (isdigit((unsigned char)*l) || *l == '-') {
1938 m->in_offset = (int32_t)strtol(l, &t, 0);
1940 if (ms->flags & MAGIC_CHECK)
1942 "in_offset `%s' invalid", l);
1948 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
1949 if (ms->flags & MAGIC_CHECK)
1951 "missing ')' in indirect offset");
1957 #ifdef ENABLE_CONDITIONALS
1958 m->cond = get_cond(l, &l);
1959 if (check_cond(ms, m->cond, cont_level) == -1)
1970 * Try it as a keyword type prefixed by "u"; match what
1971 * follows the "u". If that fails, try it as an SUS
1974 m->type = get_type(type_tbl, l + 1, &l);
1975 if (m->type == FILE_INVALID) {
1977 * Not a keyword type; parse it as an SUS type,
1978 * 'u' possibly followed by a number or C/S/L.
1980 m->type = get_standard_integer_type(l, &l);
1982 /* It's unsigned. */
1983 if (m->type != FILE_INVALID)
1984 m->flag |= UNSIGNED;
1987 * Try it as a keyword type. If that fails, try it as
1988 * an SUS integer type if it begins with "d" or as an
1989 * SUS string type if it begins with "s". In any case,
1990 * it's not unsigned.
1992 m->type = get_type(type_tbl, l, &l);
1993 if (m->type == FILE_INVALID) {
1995 * Not a keyword type; parse it as an SUS type,
1996 * either 'd' possibly followed by a number or
1997 * C/S/L, or just 's'.
2000 m->type = get_standard_integer_type(l, &l);
2001 else if (*l == 's' && !isalpha((unsigned char)l[1])) {
2002 m->type = FILE_STRING;
2008 if (m->type == FILE_INVALID) {
2009 /* Not found - try it as a special keyword. */
2010 m->type = get_type(special_tbl, l, &l);
2013 if (m->type == FILE_INVALID) {
2014 if (ms->flags & MAGIC_CHECK)
2015 file_magwarn(ms, "type `%s' invalid", l);
2019 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
2020 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
2024 if (!IS_STRING(m->type))
2025 m->mask_op |= FILE_OPINVERSE;
2026 else if (ms->flags & MAGIC_CHECK)
2027 file_magwarn(ms, "'~' invalid for string types");
2031 m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
2032 if ((op = get_op(*l)) != -1) {
2033 if (IS_STRING(m->type)) {
2036 if (op != FILE_OPDIVIDE) {
2037 if (ms->flags & MAGIC_CHECK)
2039 "invalid string/indirect op: "
2044 if (m->type == FILE_INDIRECT)
2045 r = parse_indirect_modifier(ms, m, &l);
2047 r = parse_string_modifier(ms, m, &l);
2051 parse_op_modifier(ms, m, &l, op);
2055 * We used to set mask to all 1's here, instead let's just not do
2056 * anything if mask = 0 (unless you have a better idea)
2066 if (ms->flags & MAGIC_CHECK) {
2067 file_magwarn(ms, "%c= not supported",
2074 /* Old-style anding: "0 byte &0x80 dynamically linked" */
2081 /* HP compat: ignore &= etc. */
2090 m->reln = '='; /* the default relation */
2091 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
2092 isspace((unsigned char)l[1])) || !l[1])) {
2099 * Grab the value part, except for an 'x' reln.
2101 if (m->reln != 'x' && getvalue(ms, m, &l, action))
2105 * TODO finish this macro and start using it!
2106 * #define offsetcheck {if (offset > HOWMANY-1)
2107 * magwarn("offset too big"); }
2111 * Now get last part - the description
2117 } else if ((l[0] == '\\') && (l[1] == 'b')) {
2122 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
2124 if (i == sizeof(m->desc)) {
2125 m->desc[sizeof(m->desc) - 1] = '\0';
2126 if (ms->flags & MAGIC_CHECK)
2127 file_magwarn(ms, "description `%s' truncated", m->desc);
2131 * We only do this check while compiling, or if any of the magic
2132 * files were not compiled.
2134 if (ms->flags & MAGIC_CHECK) {
2135 if (check_format(ms, m) == -1)
2138 #ifndef COMPILE_ONLY
2139 if (action == FILE_CHECK) {
2143 m->mimetype[0] = '\0'; /* initialise MIME type to none */
2148 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
2152 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
2154 const char *l = line;
2156 unsigned long factor;
2157 struct magic *m = &me->mp[0];
2159 if (m->factor_op != FILE_FACTOR_OP_NONE) {
2161 "Current entry already has a strength type: %c %d",
2162 m->factor_op, m->factor);
2165 if (m->type == FILE_NAME) {
2166 file_magwarn(ms, "%s: Strength setting is not supported in "
2167 "\"name\" magic entries", m->value.s);
2172 case FILE_FACTOR_OP_NONE:
2173 case FILE_FACTOR_OP_PLUS:
2174 case FILE_FACTOR_OP_MINUS:
2175 case FILE_FACTOR_OP_TIMES:
2176 case FILE_FACTOR_OP_DIV:
2177 m->factor_op = *l++;
2180 file_magwarn(ms, "Unknown factor op `%c'", *l);
2184 factor = strtoul(l, &el, 0);
2186 file_magwarn(ms, "Too large factor `%lu'", factor);
2189 if (*el && !isspace((unsigned char)*el)) {
2190 file_magwarn(ms, "Bad factor `%s'", l);
2193 m->factor = (uint8_t)factor;
2194 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
2195 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
2196 m->factor_op, m->factor);
2201 m->factor_op = FILE_FACTOR_OP_NONE;
2207 goodchar(unsigned char x, const char *extra)
2209 return (isascii(x) && isalnum(x)) || strchr(extra, x);
2213 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
2214 off_t off, size_t len, const char *name, const char *extra, int nt)
2217 const char *l = line;
2218 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
2219 char *buf = CAST(char *, CAST(void *, m)) + off;
2221 if (buf[0] != '\0') {
2222 len = nt ? strlen(buf) : len;
2223 file_magwarn(ms, "Current entry already has a %s type "
2224 "`%.*s', new type `%s'", name, (int)len, buf, l);
2228 if (*m->desc == '\0') {
2229 file_magwarn(ms, "Current entry does not yet have a "
2230 "description for adding a %s type", name);
2235 for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
2238 if (i == len && *l) {
2240 buf[len - 1] = '\0';
2241 if (ms->flags & MAGIC_CHECK)
2242 file_magwarn(ms, "%s type `%s' truncated %"
2243 SIZE_T_FORMAT "u", name, line, i);
2245 if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
2246 file_magwarn(ms, "%s type `%s' has bad char '%c'",
2255 file_magerror(ms, "Bad magic entry '%s'", line);
2260 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
2264 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
2266 struct magic *m = &me->mp[0];
2268 return parse_extra(ms, me, line,
2269 CAST(off_t, offsetof(struct magic, apple)),
2270 sizeof(m->apple), "APPLE", "!+-./", 0);
2274 * Parse a comma-separated list of extensions
2277 parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line)
2279 struct magic *m = &me->mp[0];
2281 return parse_extra(ms, me, line,
2282 CAST(off_t, offsetof(struct magic, ext)),
2283 sizeof(m->ext), "EXTENSION", ",!+-/", 0);
2287 * parse a MIME annotation line from magic file, put into magic[index - 1]
2291 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
2293 struct magic *m = &me->mp[0];
2295 return parse_extra(ms, me, line,
2296 CAST(off_t, offsetof(struct magic, mimetype)),
2297 sizeof(m->mimetype), "MIME", "+-/.", 1);
2301 check_format_type(const char *ptr, int type)
2305 /* Missing format string; bad */
2309 switch (file_formats[type]) {
2342 while (isdigit((unsigned char)*ptr)) ptr++;
2345 while (isdigit((unsigned char)*ptr)) ptr++;
2354 #ifdef STRICT_FORMAT /* "long" formats are int formats for us */
2355 /* so don't accept the 'l' modifier */
2364 return h != 0 ? -1 : 0;
2370 * Don't accept h and hh modifiers. They make writing
2371 * magic entries more complicated, for very little benefit
2397 return h != 0 ? -1 : 0;
2403 return h != 2 ? -1 : 0;
2410 #ifdef STRICT_FORMAT
2411 return h != 0 ? -1 : 0;
2419 case FILE_FMT_FLOAT:
2420 case FILE_FMT_DOUBLE:
2425 while (isdigit((unsigned char)*ptr)) ptr++;
2428 while (isdigit((unsigned char)*ptr)) ptr++;
2447 while (isdigit((unsigned char )*ptr))
2451 while (isdigit((unsigned char )*ptr))
2463 /* internal error */
2471 * Check that the optional printf format in description matches
2472 * the type of the magic.
2475 check_format(struct magic_set *ms, struct magic *m)
2479 for (ptr = m->desc; *ptr; ptr++)
2483 /* No format string; ok */
2487 assert(file_nformats == file_nnames);
2489 if (m->type >= file_nformats) {
2490 file_magwarn(ms, "Internal error inconsistency between "
2491 "m->type and format strings");
2494 if (file_formats[m->type] == FILE_FMT_NONE) {
2495 file_magwarn(ms, "No format string for `%s' with description "
2496 "`%s'", m->desc, file_names[m->type]);
2501 if (check_format_type(ptr, m->type) == -1) {
2503 * TODO: this error message is unhelpful if the format
2504 * string is not one character long
2506 file_magwarn(ms, "Printf format `%c' is not valid for type "
2507 "`%s' in description `%s'", *ptr ? *ptr : '?',
2508 file_names[m->type], m->desc);
2512 for (; *ptr; ptr++) {
2515 "Too many format strings (should have at most one) "
2516 "for `%s' with description `%s'",
2517 file_names[m->type], m->desc);
2525 * Read a numeric value from a pointer, into the value union of a magic
2526 * pointer, according to the magic type. Update the string pointer to point
2527 * just after the number read. Return 0 for success, non-zero for failure.
2530 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
2533 case FILE_BESTRING16:
2534 case FILE_LESTRING16:
2541 *p = getstr(ms, m, *p, action == FILE_COMPILE);
2543 if (ms->flags & MAGIC_CHECK)
2544 file_magwarn(ms, "cannot get string from `%s'",
2548 if (m->type == FILE_REGEX) {
2550 int rc = file_regcomp(&rx, m->value.s, REG_EXTENDED);
2552 if (ms->flags & MAGIC_CHECK)
2553 file_regerror(&rx, rc, ms);
2562 if (m->reln != 'x') {
2566 m->value.f = strtof(*p, &ep);
2568 m->value.f = (float)strtod(*p, &ep);
2577 if (m->reln != 'x') {
2580 m->value.d = strtod(*p, &ep);
2586 if (m->reln != 'x') {
2589 m->value.q = file_signextend(ms, m,
2590 (uint64_t)strtoull(*p, &ep, 0));
2601 * Convert a string containing C character escapes. Stop at an unescaped
2603 * Copy the converted version to "m->value.s", and the length in m->vallen.
2604 * Return updated scan pointer as function result. Warn if set.
2606 private const char *
2607 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
2609 const char *origs = s;
2610 char *p = m->value.s;
2611 size_t plen = sizeof(m->value.s);
2613 char *pmax = p + plen - 1;
2617 while ((c = *s++) != '\0') {
2618 if (isspace((unsigned char) c))
2621 file_error(ms, 0, "string too long: `%s'", origs);
2629 file_magwarn(ms, "incomplete escape");
2636 "escaped tab found, use \\t instead");
2637 warn = 0; /* already did */
2642 if (isprint((unsigned char)c)) {
2643 /* Allow escaping of
2645 if (strchr("<>&^=!", c) == NULL
2646 && (m->type != FILE_REGEX ||
2647 strchr("[]().*?^$|{}", c)
2649 file_magwarn(ms, "no "
2655 "unknown escape sequence: "
2660 /* space, perhaps force people to use \040? */
2664 * Other things people escape, but shouldn't need to,
2665 * so we disallow them
2678 /* and baskslash itself */
2711 /* \ and up to 3 octal digits */
2721 c = *s++; /* try for 2 */
2722 if (c >= '0' && c <= '7') {
2723 val = (val << 3) | (c - '0');
2724 c = *s++; /* try for 3 */
2725 if (c >= '0' && c <= '7')
2726 val = (val << 3) | (c-'0');
2735 /* \x and up to 2 hex digits */
2737 val = 'x'; /* Default if no digits */
2738 c = hextoint(*s++); /* Get next char */
2743 val = (val << 4) + c;
2757 m->vallen = CAST(unsigned char, (p - origp));
2758 if (m->type == FILE_PSTRING)
2759 m->vallen += (unsigned char)file_pstring_length_size(m);
2764 /* Single hex char to int; -1 if not a hex char. */
2768 if (!isascii((unsigned char) c))
2770 if (isdigit((unsigned char) c))
2772 if ((c >= 'a') && (c <= 'f'))
2773 return c + 10 - 'a';
2774 if (( c>= 'A') && (c <= 'F'))
2775 return c + 10 - 'A';
2781 * Print a string containing C character escapes.
2784 file_showstr(FILE *fp, const char *s, size_t len)
2799 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
2800 (void) fputc(c, fp);
2802 (void) fputc('\\', fp);
2805 (void) fputc('a', fp);
2809 (void) fputc('b', fp);
2813 (void) fputc('f', fp);
2817 (void) fputc('n', fp);
2821 (void) fputc('r', fp);
2825 (void) fputc('t', fp);
2829 (void) fputc('v', fp);
2833 (void) fprintf(fp, "%.3o", c & 0377);
2841 * eatsize(): Eat the size spec from a number [eg. 10UL]
2844 eatsize(const char **p)
2848 if (LOWCASE(*l) == 'u')
2851 switch (LOWCASE(*l)) {
2852 case 'l': /* long */
2853 case 's': /* short */
2854 case 'h': /* short */
2855 case 'b': /* char/byte */
2856 case 'c': /* char/byte */
2867 * handle a buffer containing a compiled file.
2869 private struct magic_map *
2870 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
2872 struct magic_map *map;
2874 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2875 file_oomem(ms, sizeof(*map));
2880 map->type = MAP_TYPE_USER;
2881 if (check_buffer(ms, map, "buffer") != 0) {
2882 apprentice_unmap(map);
2889 * handle a compiled file.
2892 private struct magic_map *
2893 apprentice_map(struct magic_set *ms, const char *fn)
2897 char *dbname = NULL;
2898 struct magic_map *map;
2901 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2902 file_oomem(ms, sizeof(*map));
2906 dbname = mkdbname(ms, fn, 0);
2910 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2913 if (fstat(fd, &st) == -1) {
2914 file_error(ms, errno, "cannot stat `%s'", dbname);
2917 if (st.st_size < 8 || st.st_size > MAXMAGIC_SIZE) {
2918 file_error(ms, 0, "file `%s' is too %s", dbname,
2919 st.st_size < 8 ? "small" : "large");
2923 map->len = (size_t)st.st_size;
2925 if ((map->p = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2926 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2927 file_error(ms, errno, "cannot map `%s'", dbname);
2930 map->type = MAP_TYPE_MMAP;
2932 if ((map->p = CAST(void *, malloc(map->len))) == NULL) {
2933 file_oomem(ms, map->len);
2936 if (read(fd, map->p, map->len) != (ssize_t)map->len) {
2940 map->type = MAP_TYPE_MALLOC;
2946 if (check_buffer(ms, map, dbname) != 0)
2955 apprentice_unmap(map);
2961 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
2964 uint32_t entries, nentries;
2966 int i, needsbyteswap;
2968 ptr = CAST(uint32_t *, map->p);
2969 if (*ptr != MAGICNO) {
2970 if (swap4(*ptr) != MAGICNO) {
2971 file_error(ms, 0, "bad magic in `%s'", dbname);
2978 version = swap4(ptr[1]);
2981 if (version != VERSIONNO) {
2982 file_error(ms, 0, "File %s supports only version %d magic "
2983 "files. `%s' is version %d", VERSION,
2984 VERSIONNO, dbname, version);
2987 entries = (uint32_t)(map->len / sizeof(struct magic));
2988 if ((entries * sizeof(struct magic)) != map->len) {
2989 file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
2990 "a multiple of %" SIZE_T_FORMAT "u",
2991 dbname, map->len, sizeof(struct magic));
2994 map->magic[0] = CAST(struct magic *, map->p) + 1;
2996 for (i = 0; i < MAGIC_SETS; i++) {
2998 map->nmagic[i] = swap4(ptr[i + 2]);
3000 map->nmagic[i] = ptr[i + 2];
3001 if (i != MAGIC_SETS - 1)
3002 map->magic[i + 1] = map->magic[i] + map->nmagic[i];
3003 nentries += map->nmagic[i];
3005 if (entries != nentries + 1) {
3006 file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
3007 dbname, entries, nentries + 1);
3011 for (i = 0; i < MAGIC_SETS; i++)
3012 byteswap(map->magic[i], map->nmagic[i]);
3017 * handle an mmaped file.
3020 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
3022 static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
3023 static const size_t m = sizeof(**map->magic);
3031 uint32_t h[2 + MAGIC_SETS];
3034 dbname = mkdbname(ms, fn, 1);
3039 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1)
3041 file_error(ms, errno, "cannot open `%s'", dbname);
3044 memset(&hdr, 0, sizeof(hdr));
3046 hdr.h[1] = VERSIONNO;
3047 memcpy(hdr.h + 2, map->nmagic, nm);
3049 if (write(fd, &hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
3050 file_error(ms, errno, "error writing `%s'", dbname);
3054 for (i = 0; i < MAGIC_SETS; i++) {
3055 len = m * map->nmagic[i];
3056 if (write(fd, map->magic[i], len) != (ssize_t)len) {
3057 file_error(ms, errno, "error writing `%s'", dbname);
3070 private const char ext[] = ".mgc";
3075 mkdbname(struct magic_set *ms, const char *fn, int strip)
3081 if ((p = strrchr(fn, '/')) != NULL)
3085 for (q = fn; *q; q++)
3088 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
3092 /* Did not find .mgc, restore q */
3098 /* Compatibility with old code that looked in .mime */
3099 if (ms->flags & MAGIC_MIME) {
3100 if (asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext) < 0)
3102 if (access(buf, R_OK) != -1) {
3103 ms->flags &= MAGIC_MIME_TYPE;
3108 if (asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext) < 0)
3111 /* Compatibility with old code that looked in .mime */
3112 if (strstr(p, ".mime") != NULL)
3113 ms->flags &= MAGIC_MIME_TYPE;
3118 * Byteswap an mmap'ed file if needed
3121 byteswap(struct magic *magic, uint32_t nmagic)
3124 for (i = 0; i < nmagic; i++)
3135 uint8_t *s = (uint8_t *)(void *)&sv;
3136 uint8_t *d = (uint8_t *)(void *)&rv;
3149 uint8_t *s = (uint8_t *)(void *)&sv;
3150 uint8_t *d = (uint8_t *)(void *)&rv;
3165 uint8_t *s = (uint8_t *)(void *)&sv;
3166 uint8_t *d = (uint8_t *)(void *)&rv;
3190 * byteswap a single magic entry
3193 bs1(struct magic *m)
3195 m->cont_level = swap2(m->cont_level);
3196 m->offset = swap4((uint32_t)m->offset);
3197 m->in_offset = swap4((uint32_t)m->in_offset);
3198 m->lineno = swap4((uint32_t)m->lineno);
3199 if (IS_STRING(m->type)) {
3200 m->str_range = swap4(m->str_range);
3201 m->str_flags = swap4(m->str_flags);
3204 m->value.q = swap8(m->value.q);
3205 m->num_mask = swap8(m->num_mask);
3210 file_pstring_length_size(const struct magic *m)
3212 switch (m->str_flags & PSTRING_LEN) {
3222 abort(); /* Impossible */
3227 file_pstring_get_length(const struct magic *m, const char *ss)
3230 const unsigned char *s = (const unsigned char *)ss;
3232 switch (m->str_flags & PSTRING_LEN) {
3237 len = (s[1] << 8) | s[0];
3240 len = (s[0] << 8) | s[1];
3243 len = (s[3] << 24) | (s[2] << 16) | (s[1] << 8) | s[0];
3246 len = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
3249 abort(); /* Impossible */
3252 if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
3253 len -= file_pstring_length_size(m);
3259 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
3262 struct mlist *mlist, *ml;
3264 mlist = ms->mlist[1];
3266 for (ml = mlist->next; ml != mlist; ml = ml->next) {
3267 struct magic *ma = ml->magic;
3268 uint32_t nma = ml->nmagic;
3269 for (i = 0; i < nma; i++) {
3270 if (ma[i].type != FILE_NAME)
3272 if (strcmp(ma[i].value.s, name) == 0) {
3274 for (j = i + 1; j < nma; j++)
3275 if (ma[j].cont_level == 0)