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.248 2016/03/31 17:51:12 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)
411 mlp->map = idx == 0 ? map : NULL;
412 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == 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);
455 if (ms->flags & MAGIC_CHECK)
456 file_magwarn(ms, "using regular magic file `%s'", fn);
457 map = apprentice_load(ms, fn, action);
462 for (i = 0; i < MAGIC_SETS; i++) {
463 if (add_mlist(ms->mlist[i], map, i) == -1) {
464 file_oomem(ms, sizeof(*ml));
469 if (action == FILE_LIST) {
470 for (i = 0; i < MAGIC_SETS; i++) {
471 printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
473 apprentice_list(ms->mlist[i], BINTEST);
474 printf("Text patterns:\n");
475 apprentice_list(ms->mlist[i], TEXTTEST);
480 for (i = 0; i < MAGIC_SETS; i++) {
481 mlist_free(ms->mlist[i]);
487 #endif /* COMPILE_ONLY */
491 file_ms_free(struct magic_set *ms)
496 for (i = 0; i < MAGIC_SETS; i++)
497 mlist_free(ms->mlist[i]);
504 protected struct magic_set *
505 file_ms_alloc(int flags)
507 struct magic_set *ms;
510 if ((ms = CAST(struct magic_set *, calloc((size_t)1,
511 sizeof(struct magic_set)))) == NULL)
514 if (magic_setflags(ms, flags) == -1) {
519 ms->o.buf = ms->o.pbuf = NULL;
520 len = (ms->c.len = 10) * sizeof(*ms->c.li);
522 if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
527 for (i = 0; i < MAGIC_SETS; i++)
529 ms->file = "unknown";
531 ms->indir_max = FILE_INDIR_MAX;
532 ms->name_max = FILE_NAME_MAX;
533 ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
534 ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
535 ms->elf_notes_max = FILE_ELF_NOTES_MAX;
536 ms->regex_max = FILE_REGEX_MAX;
537 ms->bytes_max = FILE_BYTES_MAX;
545 apprentice_unmap(struct magic_map *map)
554 case MAP_TYPE_MALLOC:
555 for (i = 0; i < MAGIC_SETS; i++) {
556 if ((char *)map->magic[i] >= (char *)map->p &&
557 (char *)map->magic[i] < (char *)map->p + map->len)
565 if (map->p && map->p != MAP_FAILED)
566 (void)munmap(map->p, map->len);
575 private struct mlist *
579 if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
582 mlist->next = mlist->prev = mlist;
587 mlist_free(struct mlist *mlist)
589 struct mlist *ml, *next;
595 for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
597 apprentice_unmap(ml->map);
605 /* void **bufs: an array of compiled magic files */
607 buffer_apprentice(struct magic_set *ms, struct magic **bufs,
608 size_t *sizes, size_t nbufs)
612 struct magic_map *map;
617 if (ms->mlist[0] != NULL)
622 for (i = 0; i < MAGIC_SETS; i++) {
623 mlist_free(ms->mlist[i]);
624 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
625 file_oomem(ms, sizeof(*ms->mlist[i]));
630 for (i = 0; i < nbufs; i++) {
631 map = apprentice_buf(ms, bufs[i], sizes[i]);
635 for (j = 0; j < MAGIC_SETS; j++) {
636 if (add_mlist(ms->mlist[j], map, j) == -1) {
637 file_oomem(ms, sizeof(*ml));
645 for (i = 0; i < MAGIC_SETS; i++) {
646 mlist_free(ms->mlist[i]);
653 /* const char *fn: list of magic files and directories */
655 file_apprentice(struct magic_set *ms, const char *fn, int action)
658 int file_err, errs = -1;
661 if (ms->mlist[0] != NULL)
664 if ((fn = magic_getpath(fn, action)) == NULL)
669 if ((mfn = strdup(fn)) == NULL) {
670 file_oomem(ms, strlen(fn));
674 for (i = 0; i < MAGIC_SETS; i++) {
675 mlist_free(ms->mlist[i]);
676 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
677 file_oomem(ms, sizeof(*ms->mlist[i]));
679 mlist_free(ms->mlist[i]);
689 p = strchr(fn, PATHSEP);
694 file_err = apprentice_1(ms, fn, action);
695 errs = MAX(errs, file_err);
702 for (i = 0; i < MAGIC_SETS; i++) {
703 mlist_free(ms->mlist[i]);
706 file_error(ms, 0, "could not find any valid magic files!");
712 * Always leave the database loaded
714 if (action == FILE_LOAD)
717 for (i = 0; i < MAGIC_SETS; i++) {
718 mlist_free(ms->mlist[i]);
730 file_error(ms, 0, "Invalid action %d", action);
736 * Compute the real length of a magic expression, for the purposes
737 * of determining how "strong" a magic expression is (approximating
738 * how specific its matches are):
739 * - magic characters count 0 unless escaped.
740 * - [] expressions count 1
741 * - {} expressions count 0
742 * - regular characters or escaped magic characters count 1
743 * - 0 length expressions count as one
746 nonmagic(const char *str)
751 for (p = str; *p; p++)
753 case '\\': /* Escaped anything counts 1 */
758 case '?': /* Magic characters count 0 */
765 case '[': /* Bracketed expressions count 1 the ']' */
766 while (*p && *p != ']')
770 case '{': /* Braced expressions count 0 */
771 while (*p && *p != '}')
776 default: /* Anything else counts 1 */
781 return rv == 0 ? 1 : rv; /* Return at least 1 */
785 * Get weight of this magic entry, for sorting purposes.
788 apprentice_magic_strength(const struct magic *m)
791 size_t v, val = 2 * MULT; /* baseline strength */
794 case FILE_DEFAULT: /* make sure this sorts last */
795 if (m->factor_op != FILE_FACTOR_OP_NONE)
818 val += m->vallen * MULT;
821 case FILE_BESTRING16:
822 case FILE_LESTRING16:
823 val += m->vallen * MULT / 2;
827 val += m->vallen * MAX(MULT / m->vallen, 1);
831 v = nonmagic(m->value.s);
832 val += v * MAX(MULT / v, 1);
877 (void)fprintf(stderr, "Bad type %d\n", m->type);
882 case 'x': /* matches anything penalize */
883 case '!': /* matches almost anything penalize */
887 case '=': /* Exact match, prefer */
892 case '<': /* comparison match reduce strength */
897 case '&': /* masking bits, we could count them too */
902 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
906 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
909 switch (m->factor_op) {
910 case FILE_FACTOR_OP_NONE:
912 case FILE_FACTOR_OP_PLUS:
915 case FILE_FACTOR_OP_MINUS:
918 case FILE_FACTOR_OP_TIMES:
921 case FILE_FACTOR_OP_DIV:
929 * Magic entries with no description get a bonus because they depend
930 * on subsequent magic entries to print something.
932 if (m->desc[0] == '\0')
938 * Sort callback for sorting entries by "strength" (basically length)
941 apprentice_sort(const void *a, const void *b)
943 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
944 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
945 size_t sa = apprentice_magic_strength(ma->mp);
946 size_t sb = apprentice_magic_strength(mb->mp);
956 * Shows sorted patterns list in the order which is used for the matching
959 apprentice_list(struct mlist *mlist, int mode)
961 uint32_t magindex = 0;
963 for (ml = mlist->next; ml != mlist; ml = ml->next) {
964 for (magindex = 0; magindex < ml->nmagic; magindex++) {
965 struct magic *m = &ml->magic[magindex];
966 if ((m->flag & mode) != mode) {
968 while (magindex + 1 < ml->nmagic &&
969 ml->magic[magindex + 1].cont_level != 0)
971 continue; /* Skip to next top-level test*/
975 * Try to iterate over the tree until we find item with
976 * description/mimetype.
978 while (magindex + 1 < ml->nmagic &&
979 ml->magic[magindex + 1].cont_level != 0 &&
980 *ml->magic[magindex].desc == '\0' &&
981 *ml->magic[magindex].mimetype == '\0')
984 printf("Strength = %3" SIZE_T_FORMAT "u@%u: %s [%s]\n",
985 apprentice_magic_strength(m),
986 ml->magic[magindex].lineno,
987 ml->magic[magindex].desc,
988 ml->magic[magindex].mimetype);
994 set_test_type(struct magic *mstart, struct magic *m)
1032 mstart->flag |= BINTEST;
1036 case FILE_BESTRING16:
1037 case FILE_LESTRING16:
1038 /* Allow text overrides */
1039 if (mstart->str_flags & STRING_TEXTTEST)
1040 mstart->flag |= TEXTTEST;
1042 mstart->flag |= BINTEST;
1046 /* Check for override */
1047 if (mstart->str_flags & STRING_BINTEST)
1048 mstart->flag |= BINTEST;
1049 if (mstart->str_flags & STRING_TEXTTEST)
1050 mstart->flag |= TEXTTEST;
1052 if (mstart->flag & (TEXTTEST|BINTEST))
1055 /* binary test if pattern is not text */
1056 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
1058 mstart->flag |= BINTEST;
1060 mstart->flag |= TEXTTEST;
1063 /* can't deduce anything; we shouldn't see this at the
1068 /* invalid search type, but no need to complain here */
1074 addentry(struct magic_set *ms, struct magic_entry *me,
1075 struct magic_entry_set *mset)
1077 size_t i = me->mp->type == FILE_NAME ? 1 : 0;
1078 if (mset[i].count == mset[i].max) {
1079 struct magic_entry *mp;
1081 mset[i].max += ALLOC_INCR;
1082 if ((mp = CAST(struct magic_entry *,
1083 realloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
1085 file_oomem(ms, sizeof(*mp) * mset[i].max);
1088 (void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
1092 mset[i].me[mset[i].count++] = *me;
1093 memset(me, 0, sizeof(*me));
1098 * Load and parse one file.
1101 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
1102 struct magic_entry_set *mset)
1104 size_t lineno = 0, llen = 0;
1107 struct magic_entry me;
1109 FILE *f = fopen(ms->file = fn, "r");
1111 if (errno != ENOENT)
1112 file_error(ms, errno, "cannot read magic file `%s'",
1118 memset(&me, 0, sizeof(me));
1119 /* read and parse this file */
1120 for (ms->line = 1; (len = getline(&line, &llen, f)) != -1;
1122 if (len == 0) /* null line, garbage, etc */
1124 if (line[len - 1] == '\n') {
1126 line[len - 1] = '\0'; /* delete newline */
1129 case '\0': /* empty, do not parse */
1130 case '#': /* comment, do not parse */
1133 if (line[1] == ':') {
1136 for (i = 0; bang[i].name != NULL; i++) {
1137 if ((size_t)(len - 2) > bang[i].len &&
1138 memcmp(bang[i].name, line + 2,
1142 if (bang[i].name == NULL) {
1144 "Unknown !: entry `%s'", line);
1148 if (me.mp == NULL) {
1150 "No current entry for :!%s type",
1155 if ((*bang[i].fun)(ms, &me,
1156 line + bang[i].len + 2) != 0) {
1165 switch (parse(ms, &me, line, lineno, action)) {
1169 (void)addentry(ms, &me, mset);
1178 (void)addentry(ms, &me, mset);
1184 * parse a file or directory of files
1185 * const char *fn: name of magic file or directory
1188 cmpstrp(const void *p1, const void *p2)
1190 return strcmp(*(char *const *)p1, *(char *const *)p2);
1195 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1198 static const char text[] = "text";
1199 static const char binary[] = "binary";
1200 static const size_t len = sizeof(text);
1202 uint32_t i = starttest;
1205 set_test_type(me[starttest].mp, me[i].mp);
1206 if ((ms->flags & MAGIC_DEBUG) == 0)
1208 (void)fprintf(stderr, "%s%s%s: %s\n",
1210 me[i].mp->mimetype[0] == '\0' ? "" : "; ",
1211 me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
1212 me[i].mp->flag & BINTEST ? binary : text);
1213 if (me[i].mp->flag & BINTEST) {
1214 char *p = strstr(me[i].mp->desc, text);
1215 if (p && (p == me[i].mp->desc ||
1216 isspace((unsigned char)p[-1])) &&
1217 (p + len - me[i].mp->desc == MAXstring
1218 || (p[len] == '\0' ||
1219 isspace((unsigned char)p[len]))))
1220 (void)fprintf(stderr, "*** Possible "
1221 "binary test for text type\n");
1223 } while (++i < nme && me[i].mp->cont_level != 0);
1228 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
1231 for (i = 0; i < nme; i++) {
1232 if (me[i].mp->cont_level == 0 &&
1233 me[i].mp->type == FILE_DEFAULT) {
1235 if (me[i].mp->cont_level == 0)
1239 ms->line = me[i].mp->lineno;
1241 "level 0 \"default\" did not sort last");
1249 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1250 struct magic **ma, uint32_t *nma)
1252 uint32_t i, mentrycount = 0;
1255 for (i = 0; i < nme; i++)
1256 mentrycount += me[i].cont_count;
1258 slen = sizeof(**ma) * mentrycount;
1259 if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) {
1260 file_oomem(ms, slen);
1265 for (i = 0; i < nme; i++) {
1266 (void)memcpy(*ma + mentrycount, me[i].mp,
1267 me[i].cont_count * sizeof(**ma));
1268 mentrycount += me[i].cont_count;
1275 magic_entry_free(struct magic_entry *me, uint32_t nme)
1280 for (i = 0; i < nme; i++)
1285 private struct magic_map *
1286 apprentice_load(struct magic_set *ms, const char *fn, int action)
1290 size_t files = 0, maxfiles = 0;
1291 char **filearr = NULL, *mfn;
1293 struct magic_map *map;
1294 struct magic_entry_set mset[MAGIC_SETS];
1298 memset(mset, 0, sizeof(mset));
1299 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
1302 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL)
1304 file_oomem(ms, sizeof(*map));
1307 map->type = MAP_TYPE_MALLOC;
1309 /* print silly verbose header for USG compat. */
1310 if (action == FILE_CHECK)
1311 (void)fprintf(stderr, "%s\n", usg_hdr);
1313 /* load directory or file */
1314 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
1320 while ((d = readdir(dir)) != NULL) {
1321 if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) {
1323 strlen(fn) + strlen(d->d_name) + 2);
1328 if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
1332 if (files >= maxfiles) {
1334 maxfiles = (maxfiles + 1) * 2;
1335 mlen = maxfiles * sizeof(*filearr);
1336 if ((filearr = CAST(char **,
1337 realloc(filearr, mlen))) == NULL) {
1338 file_oomem(ms, mlen);
1345 filearr[files++] = mfn;
1348 qsort(filearr, files, sizeof(*filearr), cmpstrp);
1349 for (i = 0; i < files; i++) {
1350 load_1(ms, action, filearr[i], &errs, mset);
1355 load_1(ms, action, fn, &errs, mset);
1359 for (j = 0; j < MAGIC_SETS; j++) {
1360 /* Set types of tests */
1361 for (i = 0; i < mset[j].count; ) {
1362 if (mset[j].me[i].mp->cont_level != 0) {
1366 i = set_text_binary(ms, mset[j].me, mset[j].count, i);
1369 qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
1373 * Make sure that any level 0 "default" line is last
1376 set_last_default(ms, mset[j].me, mset[j].count);
1378 /* coalesce per file arrays into a single one */
1379 if (coalesce_entries(ms, mset[j].me, mset[j].count,
1380 &map->magic[j], &map->nmagic[j]) == -1) {
1387 for (j = 0; j < MAGIC_SETS; j++)
1388 magic_entry_free(mset[j].me, mset[j].count);
1391 apprentice_unmap(map);
1398 * extend the sign bit if the comparison is to be signed
1401 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
1403 if (!(m->flag & UNSIGNED)) {
1406 * Do not remove the casts below. They are
1407 * vital. When later compared with the data,
1408 * the sign extension must have happened.
1411 v = (signed char) v;
1454 case FILE_BESTRING16:
1455 case FILE_LESTRING16:
1466 if (ms->flags & MAGIC_CHECK)
1467 file_magwarn(ms, "cannot happen: m->type=%d\n",
1476 string_modifier_check(struct magic_set *ms, struct magic *m)
1478 if ((ms->flags & MAGIC_CHECK) == 0)
1481 if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
1482 (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
1484 "'/BHhLl' modifiers are only allowed for pascal strings\n");
1488 case FILE_BESTRING16:
1489 case FILE_LESTRING16:
1490 if (m->str_flags != 0) {
1492 "no modifiers allowed for 16-bit strings\n");
1498 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
1500 "'/%c' only allowed on regex and search\n",
1501 CHAR_REGEX_OFFSET_START);
1506 if (m->str_range == 0) {
1508 "missing range; defaulting to %d\n",
1509 STRING_DEFAULT_RANGE);
1510 m->str_range = STRING_DEFAULT_RANGE;
1515 if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
1516 file_magwarn(ms, "'/%c' not allowed on regex\n",
1517 CHAR_COMPACT_WHITESPACE);
1520 if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
1521 file_magwarn(ms, "'/%c' not allowed on regex\n",
1522 CHAR_COMPACT_OPTIONAL_WHITESPACE);
1527 file_magwarn(ms, "coding error: m->type=%d\n",
1547 return FILE_OPMINUS;
1549 return FILE_OPMULTIPLY;
1551 return FILE_OPDIVIDE;
1553 return FILE_OPMODULO;
1559 #ifdef ENABLE_CONDITIONALS
1561 get_cond(const char *l, const char **t)
1563 static const struct cond_tbl_s {
1568 { "if", 2, COND_IF },
1569 { "elif", 4, COND_ELIF },
1570 { "else", 4, COND_ELSE },
1571 { "", 0, COND_NONE },
1573 const struct cond_tbl_s *p;
1575 for (p = cond_tbl; p->len; p++) {
1576 if (strncmp(l, p->name, p->len) == 0 &&
1577 isspace((unsigned char)l[p->len])) {
1587 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1590 last_cond = ms->c.li[cont_level].last_cond;
1594 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1595 if (ms->flags & MAGIC_CHECK)
1596 file_magwarn(ms, "syntax error: `if'");
1599 last_cond = COND_IF;
1603 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1604 if (ms->flags & MAGIC_CHECK)
1605 file_magwarn(ms, "syntax error: `elif'");
1608 last_cond = COND_ELIF;
1612 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1613 if (ms->flags & MAGIC_CHECK)
1614 file_magwarn(ms, "syntax error: `else'");
1617 last_cond = COND_NONE;
1621 last_cond = COND_NONE;
1625 ms->c.li[cont_level].last_cond = last_cond;
1628 #endif /* ENABLE_CONDITIONALS */
1631 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1633 const char *l = *lp;
1635 while (!isspace((unsigned char)*++l))
1637 case CHAR_INDIRECT_RELATIVE:
1638 m->str_flags |= INDIRECT_RELATIVE;
1641 if (ms->flags & MAGIC_CHECK)
1642 file_magwarn(ms, "indirect modifier `%c' "
1652 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
1655 const char *l = *lp;
1661 val = (uint64_t)strtoull(l, &t, 0);
1663 m->num_mask = file_signextend(ms, m, val);
1669 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1671 const char *l = *lp;
1675 while (!isspace((unsigned char)*++l)) {
1677 case '0': case '1': case '2':
1678 case '3': case '4': case '5':
1679 case '6': case '7': case '8':
1681 if (have_range && (ms->flags & MAGIC_CHECK))
1682 file_magwarn(ms, "multiple ranges");
1684 m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
1685 if (m->str_range == 0)
1686 file_magwarn(ms, "zero range");
1689 case CHAR_COMPACT_WHITESPACE:
1690 m->str_flags |= STRING_COMPACT_WHITESPACE;
1692 case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1693 m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
1695 case CHAR_IGNORE_LOWERCASE:
1696 m->str_flags |= STRING_IGNORE_LOWERCASE;
1698 case CHAR_IGNORE_UPPERCASE:
1699 m->str_flags |= STRING_IGNORE_UPPERCASE;
1701 case CHAR_REGEX_OFFSET_START:
1702 m->str_flags |= REGEX_OFFSET_START;
1705 m->str_flags |= STRING_BINTEST;
1708 m->str_flags |= STRING_TEXTTEST;
1711 m->str_flags |= STRING_TRIM;
1713 case CHAR_PSTRING_1_LE:
1714 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
1715 if (m->type != FILE_PSTRING)
1717 SET_LENGTH(PSTRING_1_LE);
1719 case CHAR_PSTRING_2_BE:
1720 if (m->type != FILE_PSTRING)
1722 SET_LENGTH(PSTRING_2_BE);
1724 case CHAR_PSTRING_2_LE:
1725 if (m->type != FILE_PSTRING)
1727 SET_LENGTH(PSTRING_2_LE);
1729 case CHAR_PSTRING_4_BE:
1730 if (m->type != FILE_PSTRING)
1732 SET_LENGTH(PSTRING_4_BE);
1734 case CHAR_PSTRING_4_LE:
1742 SET_LENGTH(PSTRING_4_LE);
1744 case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
1745 if (m->type != FILE_PSTRING)
1747 m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
1751 if (ms->flags & MAGIC_CHECK)
1752 file_magwarn(ms, "string modifier `%c' "
1756 /* allow multiple '/' for readability */
1757 if (l[1] == '/' && !isspace((unsigned char)l[2]))
1760 if (string_modifier_check(ms, m) == -1)
1770 * parse one line from magic file, put into magic[index++] if valid
1773 parse(struct magic_set *ms, struct magic_entry *me, const char *line,
1774 size_t lineno, int action)
1776 #ifdef ENABLE_CONDITIONALS
1777 static uint32_t last_cont_level = 0;
1781 const char *l = line;
1784 uint32_t cont_level;
1793 ++l; /* step over */
1796 #ifdef ENABLE_CONDITIONALS
1797 if (cont_level == 0 || cont_level > last_cont_level)
1798 if (file_check_mem(ms, cont_level) == -1)
1800 last_cont_level = cont_level;
1802 if (cont_level != 0) {
1803 if (me->mp == NULL) {
1804 file_magerror(ms, "No current entry for continuation");
1807 if (me->cont_count == 0) {
1808 file_magerror(ms, "Continuations present with 0 count");
1811 m = &me->mp[me->cont_count - 1];
1812 diff = (int32_t)cont_level - (int32_t)m->cont_level;
1814 file_magwarn(ms, "New continuation level %u is more "
1815 "than one larger than current level %u", cont_level,
1817 if (me->cont_count == me->max_count) {
1819 size_t cnt = me->max_count + ALLOC_CHUNK;
1820 if ((nm = CAST(struct magic *, realloc(me->mp,
1821 sizeof(*nm) * cnt))) == NULL) {
1822 file_oomem(ms, sizeof(*nm) * cnt);
1826 me->max_count = CAST(uint32_t, cnt);
1828 m = &me->mp[me->cont_count++];
1829 (void)memset(m, 0, sizeof(*m));
1830 m->cont_level = cont_level;
1832 static const size_t len = sizeof(*m) * ALLOC_CHUNK;
1835 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1836 file_oomem(ms, len);
1840 me->max_count = ALLOC_CHUNK;
1841 (void)memset(m, 0, sizeof(*m));
1842 m->factor_op = FILE_FACTOR_OP_NONE;
1846 m->lineno = CAST(uint32_t, lineno);
1848 if (*l == '&') { /* m->cont_level == 0 checked below. */
1849 ++l; /* step over */
1853 ++l; /* step over */
1855 if (m->flag & OFFADD)
1856 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1858 if (*l == '&') { /* m->cont_level == 0 checked below */
1859 ++l; /* step over */
1863 /* Indirect offsets are not valid at level 0. */
1864 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) {
1865 if (ms->flags & MAGIC_CHECK)
1866 file_magwarn(ms, "relative offset at level 0");
1870 /* get offset, then skip over it */
1871 m->offset = (uint32_t)strtoul(l, &t, 0);
1873 if (ms->flags & MAGIC_CHECK)
1874 file_magwarn(ms, "offset `%s' invalid", l);
1879 if (m->flag & INDIR) {
1880 m->in_type = FILE_LONG;
1883 * read [.lbs][+-]nnnnn)
1889 m->in_type = FILE_LELONG;
1892 m->in_type = FILE_BELONG;
1895 m->in_type = FILE_MELONG;
1899 m->in_type = FILE_LESHORT;
1903 m->in_type = FILE_BESHORT;
1909 m->in_type = FILE_BYTE;
1914 m->in_type = FILE_LEDOUBLE;
1919 m->in_type = FILE_BEDOUBLE;
1922 m->in_type = FILE_LEID3;
1925 m->in_type = FILE_BEID3;
1928 if (ms->flags & MAGIC_CHECK)
1930 "indirect offset type `%c' invalid",
1939 m->in_op |= FILE_OPINVERSE;
1942 if ((op = get_op(*l)) != -1) {
1947 m->in_op |= FILE_OPINDIRECT;
1950 if (isdigit((unsigned char)*l) || *l == '-') {
1951 m->in_offset = (int32_t)strtol(l, &t, 0);
1953 if (ms->flags & MAGIC_CHECK)
1955 "in_offset `%s' invalid", l);
1961 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) {
1962 if (ms->flags & MAGIC_CHECK)
1964 "missing ')' in indirect offset");
1970 #ifdef ENABLE_CONDITIONALS
1971 m->cond = get_cond(l, &l);
1972 if (check_cond(ms, m->cond, cont_level) == -1)
1983 * Try it as a keyword type prefixed by "u"; match what
1984 * follows the "u". If that fails, try it as an SUS
1987 m->type = get_type(type_tbl, l + 1, &l);
1988 if (m->type == FILE_INVALID) {
1990 * Not a keyword type; parse it as an SUS type,
1991 * 'u' possibly followed by a number or C/S/L.
1993 m->type = get_standard_integer_type(l, &l);
1995 /* It's unsigned. */
1996 if (m->type != FILE_INVALID)
1997 m->flag |= UNSIGNED;
2000 * Try it as a keyword type. If that fails, try it as
2001 * an SUS integer type if it begins with "d" or as an
2002 * SUS string type if it begins with "s". In any case,
2003 * it's not unsigned.
2005 m->type = get_type(type_tbl, l, &l);
2006 if (m->type == FILE_INVALID) {
2008 * Not a keyword type; parse it as an SUS type,
2009 * either 'd' possibly followed by a number or
2010 * C/S/L, or just 's'.
2013 m->type = get_standard_integer_type(l, &l);
2014 else if (*l == 's' && !isalpha((unsigned char)l[1])) {
2015 m->type = FILE_STRING;
2021 if (m->type == FILE_INVALID) {
2022 /* Not found - try it as a special keyword. */
2023 m->type = get_type(special_tbl, l, &l);
2026 if (m->type == FILE_INVALID) {
2027 if (ms->flags & MAGIC_CHECK)
2028 file_magwarn(ms, "type `%s' invalid", l);
2032 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
2033 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
2037 if (!IS_STRING(m->type))
2038 m->mask_op |= FILE_OPINVERSE;
2039 else if (ms->flags & MAGIC_CHECK)
2040 file_magwarn(ms, "'~' invalid for string types");
2044 m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
2045 if ((op = get_op(*l)) != -1) {
2046 if (IS_STRING(m->type)) {
2049 if (op != FILE_OPDIVIDE) {
2050 if (ms->flags & MAGIC_CHECK)
2052 "invalid string/indirect op: "
2057 if (m->type == FILE_INDIRECT)
2058 r = parse_indirect_modifier(ms, m, &l);
2060 r = parse_string_modifier(ms, m, &l);
2064 parse_op_modifier(ms, m, &l, op);
2068 * We used to set mask to all 1's here, instead let's just not do
2069 * anything if mask = 0 (unless you have a better idea)
2079 if (ms->flags & MAGIC_CHECK) {
2080 file_magwarn(ms, "%c= not supported",
2087 /* Old-style anding: "0 byte &0x80 dynamically linked" */
2094 /* HP compat: ignore &= etc. */
2103 m->reln = '='; /* the default relation */
2104 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
2105 isspace((unsigned char)l[1])) || !l[1])) {
2112 * Grab the value part, except for an 'x' reln.
2114 if (m->reln != 'x' && getvalue(ms, m, &l, action))
2118 * TODO finish this macro and start using it!
2119 * #define offsetcheck {if (offset > ms->bytes_max -1)
2120 * magwarn("offset too big"); }
2124 * Now get last part - the description
2130 } else if ((l[0] == '\\') && (l[1] == 'b')) {
2135 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
2137 if (i == sizeof(m->desc)) {
2138 m->desc[sizeof(m->desc) - 1] = '\0';
2139 if (ms->flags & MAGIC_CHECK)
2140 file_magwarn(ms, "description `%s' truncated", m->desc);
2144 * We only do this check while compiling, or if any of the magic
2145 * files were not compiled.
2147 if (ms->flags & MAGIC_CHECK) {
2148 if (check_format(ms, m) == -1)
2151 #ifndef COMPILE_ONLY
2152 if (action == FILE_CHECK) {
2156 m->mimetype[0] = '\0'; /* initialise MIME type to none */
2161 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
2165 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
2167 const char *l = line;
2169 unsigned long factor;
2170 struct magic *m = &me->mp[0];
2172 if (m->factor_op != FILE_FACTOR_OP_NONE) {
2174 "Current entry already has a strength type: %c %d",
2175 m->factor_op, m->factor);
2178 if (m->type == FILE_NAME) {
2179 file_magwarn(ms, "%s: Strength setting is not supported in "
2180 "\"name\" magic entries", m->value.s);
2185 case FILE_FACTOR_OP_NONE:
2186 case FILE_FACTOR_OP_PLUS:
2187 case FILE_FACTOR_OP_MINUS:
2188 case FILE_FACTOR_OP_TIMES:
2189 case FILE_FACTOR_OP_DIV:
2190 m->factor_op = *l++;
2193 file_magwarn(ms, "Unknown factor op `%c'", *l);
2197 factor = strtoul(l, &el, 0);
2199 file_magwarn(ms, "Too large factor `%lu'", factor);
2202 if (*el && !isspace((unsigned char)*el)) {
2203 file_magwarn(ms, "Bad factor `%s'", l);
2206 m->factor = (uint8_t)factor;
2207 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
2208 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
2209 m->factor_op, m->factor);
2214 m->factor_op = FILE_FACTOR_OP_NONE;
2220 goodchar(unsigned char x, const char *extra)
2222 return (isascii(x) && isalnum(x)) || strchr(extra, x);
2226 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
2227 off_t off, size_t len, const char *name, const char *extra, int nt)
2230 const char *l = line;
2231 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
2232 char *buf = CAST(char *, CAST(void *, m)) + off;
2234 if (buf[0] != '\0') {
2235 len = nt ? strlen(buf) : len;
2236 file_magwarn(ms, "Current entry already has a %s type "
2237 "`%.*s', new type `%s'", name, (int)len, buf, l);
2241 if (*m->desc == '\0') {
2242 file_magwarn(ms, "Current entry does not yet have a "
2243 "description for adding a %s type", name);
2248 for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
2251 if (i == len && *l) {
2253 buf[len - 1] = '\0';
2254 if (ms->flags & MAGIC_CHECK)
2255 file_magwarn(ms, "%s type `%s' truncated %"
2256 SIZE_T_FORMAT "u", name, line, i);
2258 if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
2259 file_magwarn(ms, "%s type `%s' has bad char '%c'",
2268 file_magerror(ms, "Bad magic entry '%s'", line);
2273 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
2277 parse_apple(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, apple)),
2283 sizeof(m->apple), "APPLE", "!+-./?", 0);
2287 * Parse a comma-separated list of extensions
2290 parse_ext(struct magic_set *ms, struct magic_entry *me, const char *line)
2292 struct magic *m = &me->mp[0];
2294 return parse_extra(ms, me, line,
2295 CAST(off_t, offsetof(struct magic, ext)),
2296 sizeof(m->ext), "EXTENSION", ",!+-/", 0);
2300 * parse a MIME annotation line from magic file, put into magic[index - 1]
2304 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
2306 struct magic *m = &me->mp[0];
2308 return parse_extra(ms, me, line,
2309 CAST(off_t, offsetof(struct magic, mimetype)),
2310 sizeof(m->mimetype), "MIME", "+-/.", 1);
2314 check_format_type(const char *ptr, int type, const char **estr)
2319 /* Missing format string; bad */
2320 *estr = "missing format spec";
2324 switch (file_formats[type]) {
2357 #define CHECKLEN() do { \
2358 for (len = cnt = 0; isdigit((unsigned char)*ptr); ptr++, cnt++) \
2359 len = len * 10 + (*ptr - '0'); \
2360 if (cnt > 5 || len > 1024) \
2362 } while (/*CONSTCOND*/0)
2376 #ifdef STRICT_FORMAT /* "long" formats are int formats for us */
2377 /* so don't accept the 'l' modifier */
2394 * Don't accept h and hh modifiers. They make writing
2395 * magic entries more complicated, for very little benefit
2438 #ifdef STRICT_FORMAT
2449 case FILE_FMT_FLOAT:
2450 case FILE_FMT_DOUBLE:
2476 while (isdigit((unsigned char )*ptr))
2480 while (isdigit((unsigned char )*ptr))
2492 /* internal error */
2496 *estr = "not valid";
2503 * Check that the optional printf format in description matches
2504 * the type of the magic.
2507 check_format(struct magic_set *ms, struct magic *m)
2512 for (ptr = m->desc; *ptr; ptr++)
2516 /* No format string; ok */
2520 assert(file_nformats == file_nnames);
2522 if (m->type >= file_nformats) {
2523 file_magwarn(ms, "Internal error inconsistency between "
2524 "m->type and format strings");
2527 if (file_formats[m->type] == FILE_FMT_NONE) {
2528 file_magwarn(ms, "No format string for `%s' with description "
2529 "`%s'", m->desc, file_names[m->type]);
2534 if (check_format_type(ptr, m->type, &estr) == -1) {
2536 * TODO: this error message is unhelpful if the format
2537 * string is not one character long
2539 file_magwarn(ms, "Printf format is %s for type "
2540 "`%s' in description `%s'", estr,
2541 file_names[m->type], m->desc);
2545 for (; *ptr; ptr++) {
2548 "Too many format strings (should have at most one) "
2549 "for `%s' with description `%s'",
2550 file_names[m->type], m->desc);
2558 * Read a numeric value from a pointer, into the value union of a magic
2559 * pointer, according to the magic type. Update the string pointer to point
2560 * just after the number read. Return 0 for success, non-zero for failure.
2563 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
2566 case FILE_BESTRING16:
2567 case FILE_LESTRING16:
2575 *p = getstr(ms, m, *p, action == FILE_COMPILE);
2577 if (ms->flags & MAGIC_CHECK)
2578 file_magwarn(ms, "cannot get string from `%s'",
2582 if (m->type == FILE_REGEX) {
2584 int rc = file_regcomp(&rx, m->value.s, REG_EXTENDED);
2586 if (ms->flags & MAGIC_CHECK)
2587 file_regerror(&rx, rc, ms);
2596 if (m->reln != 'x') {
2600 m->value.f = strtof(*p, &ep);
2602 m->value.f = (float)strtod(*p, &ep);
2611 if (m->reln != 'x') {
2614 m->value.d = strtod(*p, &ep);
2620 if (m->reln != 'x') {
2623 m->value.q = file_signextend(ms, m,
2624 (uint64_t)strtoull(*p, &ep, 0));
2635 * Convert a string containing C character escapes. Stop at an unescaped
2637 * Copy the converted version to "m->value.s", and the length in m->vallen.
2638 * Return updated scan pointer as function result. Warn if set.
2640 private const char *
2641 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
2643 const char *origs = s;
2644 char *p = m->value.s;
2645 size_t plen = sizeof(m->value.s);
2647 char *pmax = p + plen - 1;
2651 while ((c = *s++) != '\0') {
2652 if (isspace((unsigned char) c))
2655 file_error(ms, 0, "string too long: `%s'", origs);
2663 file_magwarn(ms, "incomplete escape");
2670 "escaped tab found, use \\t instead");
2671 warn = 0; /* already did */
2676 if (isprint((unsigned char)c)) {
2677 /* Allow escaping of
2679 if (strchr("<>&^=!", c) == NULL
2680 && (m->type != FILE_REGEX ||
2681 strchr("[]().*?^$|{}", c)
2683 file_magwarn(ms, "no "
2689 "unknown escape sequence: "
2694 /* space, perhaps force people to use \040? */
2698 * Other things people escape, but shouldn't need to,
2699 * so we disallow them
2712 /* and baskslash itself */
2745 /* \ and up to 3 octal digits */
2755 c = *s++; /* try for 2 */
2756 if (c >= '0' && c <= '7') {
2757 val = (val << 3) | (c - '0');
2758 c = *s++; /* try for 3 */
2759 if (c >= '0' && c <= '7')
2760 val = (val << 3) | (c-'0');
2769 /* \x and up to 2 hex digits */
2771 val = 'x'; /* Default if no digits */
2772 c = hextoint(*s++); /* Get next char */
2777 val = (val << 4) + c;
2791 m->vallen = CAST(unsigned char, (p - origp));
2792 if (m->type == FILE_PSTRING)
2793 m->vallen += (unsigned char)file_pstring_length_size(m);
2798 /* Single hex char to int; -1 if not a hex char. */
2802 if (!isascii((unsigned char) c))
2804 if (isdigit((unsigned char) c))
2806 if ((c >= 'a') && (c <= 'f'))
2807 return c + 10 - 'a';
2808 if (( c>= 'A') && (c <= 'F'))
2809 return c + 10 - 'A';
2815 * Print a string containing C character escapes.
2818 file_showstr(FILE *fp, const char *s, size_t len)
2833 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
2834 (void) fputc(c, fp);
2836 (void) fputc('\\', fp);
2839 (void) fputc('a', fp);
2843 (void) fputc('b', fp);
2847 (void) fputc('f', fp);
2851 (void) fputc('n', fp);
2855 (void) fputc('r', fp);
2859 (void) fputc('t', fp);
2863 (void) fputc('v', fp);
2867 (void) fprintf(fp, "%.3o", c & 0377);
2875 * eatsize(): Eat the size spec from a number [eg. 10UL]
2878 eatsize(const char **p)
2882 if (LOWCASE(*l) == 'u')
2885 switch (LOWCASE(*l)) {
2886 case 'l': /* long */
2887 case 's': /* short */
2888 case 'h': /* short */
2889 case 'b': /* char/byte */
2890 case 'c': /* char/byte */
2901 * handle a buffer containing a compiled file.
2903 private struct magic_map *
2904 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
2906 struct magic_map *map;
2908 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2909 file_oomem(ms, sizeof(*map));
2914 map->type = MAP_TYPE_USER;
2915 if (check_buffer(ms, map, "buffer") != 0) {
2916 apprentice_unmap(map);
2923 * handle a compiled file.
2926 private struct magic_map *
2927 apprentice_map(struct magic_set *ms, const char *fn)
2931 char *dbname = NULL;
2932 struct magic_map *map;
2935 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2936 file_oomem(ms, sizeof(*map));
2939 map->type = MAP_TYPE_USER; /* unspecified */
2941 dbname = mkdbname(ms, fn, 0);
2945 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2948 if (fstat(fd, &st) == -1) {
2949 file_error(ms, errno, "cannot stat `%s'", dbname);
2952 if (st.st_size < 8 || st.st_size > MAXMAGIC_SIZE) {
2953 file_error(ms, 0, "file `%s' is too %s", dbname,
2954 st.st_size < 8 ? "small" : "large");
2958 map->len = (size_t)st.st_size;
2960 map->type = MAP_TYPE_MMAP;
2961 if ((map->p = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2962 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2963 file_error(ms, errno, "cannot map `%s'", dbname);
2967 map->type = MAP_TYPE_MALLOC;
2968 if ((map->p = CAST(void *, malloc(map->len))) == NULL) {
2969 file_oomem(ms, map->len);
2972 if (read(fd, map->p, map->len) != (ssize_t)map->len) {
2981 if (check_buffer(ms, map, dbname) != 0)
2984 if (mprotect(map->p, (size_t)st.st_size, PROT_READ) == -1) {
2985 file_error(ms, errno, "cannot mprotect `%s'", dbname);
2996 apprentice_unmap(map);
3002 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
3005 uint32_t entries, nentries;
3007 int i, needsbyteswap;
3009 ptr = CAST(uint32_t *, map->p);
3010 if (*ptr != MAGICNO) {
3011 if (swap4(*ptr) != MAGICNO) {
3012 file_error(ms, 0, "bad magic in `%s'", dbname);
3019 version = swap4(ptr[1]);
3022 if (version != VERSIONNO) {
3023 file_error(ms, 0, "File %s supports only version %d magic "
3024 "files. `%s' is version %d", VERSION,
3025 VERSIONNO, dbname, version);
3028 entries = (uint32_t)(map->len / sizeof(struct magic));
3029 if ((entries * sizeof(struct magic)) != map->len) {
3030 file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
3031 "a multiple of %" SIZE_T_FORMAT "u",
3032 dbname, map->len, sizeof(struct magic));
3035 map->magic[0] = CAST(struct magic *, map->p) + 1;
3037 for (i = 0; i < MAGIC_SETS; i++) {
3039 map->nmagic[i] = swap4(ptr[i + 2]);
3041 map->nmagic[i] = ptr[i + 2];
3042 if (i != MAGIC_SETS - 1)
3043 map->magic[i + 1] = map->magic[i] + map->nmagic[i];
3044 nentries += map->nmagic[i];
3046 if (entries != nentries + 1) {
3047 file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
3048 dbname, entries, nentries + 1);
3052 for (i = 0; i < MAGIC_SETS; i++)
3053 byteswap(map->magic[i], map->nmagic[i]);
3058 * handle an mmaped file.
3061 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
3063 static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
3064 static const size_t m = sizeof(**map->magic);
3072 uint32_t h[2 + MAGIC_SETS];
3075 dbname = mkdbname(ms, fn, 1);
3080 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1)
3082 file_error(ms, errno, "cannot open `%s'", dbname);
3085 memset(&hdr, 0, sizeof(hdr));
3087 hdr.h[1] = VERSIONNO;
3088 memcpy(hdr.h + 2, map->nmagic, nm);
3090 if (write(fd, &hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
3091 file_error(ms, errno, "error writing `%s'", dbname);
3095 for (i = 0; i < MAGIC_SETS; i++) {
3096 len = m * map->nmagic[i];
3097 if (write(fd, map->magic[i], len) != (ssize_t)len) {
3098 file_error(ms, errno, "error writing `%s'", dbname);
3111 private const char ext[] = ".mgc";
3116 mkdbname(struct magic_set *ms, const char *fn, int strip)
3122 if ((p = strrchr(fn, '/')) != NULL)
3126 for (q = fn; *q; q++)
3129 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
3133 /* Did not find .mgc, restore q */
3139 /* Compatibility with old code that looked in .mime */
3140 if (ms->flags & MAGIC_MIME) {
3141 if (asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext) < 0)
3143 if (access(buf, R_OK) != -1) {
3144 ms->flags &= MAGIC_MIME_TYPE;
3149 if (asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext) < 0)
3152 /* Compatibility with old code that looked in .mime */
3153 if (strstr(p, ".mime") != NULL)
3154 ms->flags &= MAGIC_MIME_TYPE;
3159 * Byteswap an mmap'ed file if needed
3162 byteswap(struct magic *magic, uint32_t nmagic)
3165 for (i = 0; i < nmagic; i++)
3176 uint8_t *s = (uint8_t *)(void *)&sv;
3177 uint8_t *d = (uint8_t *)(void *)&rv;
3190 uint8_t *s = (uint8_t *)(void *)&sv;
3191 uint8_t *d = (uint8_t *)(void *)&rv;
3206 uint8_t *s = (uint8_t *)(void *)&sv;
3207 uint8_t *d = (uint8_t *)(void *)&rv;
3231 * byteswap a single magic entry
3234 bs1(struct magic *m)
3236 m->cont_level = swap2(m->cont_level);
3237 m->offset = swap4((uint32_t)m->offset);
3238 m->in_offset = swap4((uint32_t)m->in_offset);
3239 m->lineno = swap4((uint32_t)m->lineno);
3240 if (IS_STRING(m->type)) {
3241 m->str_range = swap4(m->str_range);
3242 m->str_flags = swap4(m->str_flags);
3245 m->value.q = swap8(m->value.q);
3246 m->num_mask = swap8(m->num_mask);
3251 file_pstring_length_size(const struct magic *m)
3253 switch (m->str_flags & PSTRING_LEN) {
3263 abort(); /* Impossible */
3268 file_pstring_get_length(const struct magic *m, const char *ss)
3271 const unsigned char *s = (const unsigned char *)ss;
3273 switch (m->str_flags & PSTRING_LEN) {
3278 len = (s[1] << 8) | s[0];
3281 len = (s[0] << 8) | s[1];
3284 len = (s[3] << 24) | (s[2] << 16) | (s[1] << 8) | s[0];
3287 len = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
3290 abort(); /* Impossible */
3293 if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
3294 len -= file_pstring_length_size(m);
3300 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
3303 struct mlist *mlist, *ml;
3305 mlist = ms->mlist[1];
3307 for (ml = mlist->next; ml != mlist; ml = ml->next) {
3308 struct magic *ma = ml->magic;
3309 uint32_t nma = ml->nmagic;
3310 for (i = 0; i < nma; i++) {
3311 if (ma[i].type != FILE_NAME)
3313 if (strcmp(ma[i].value.s, name) == 0) {
3315 for (j = i + 1; j < nma; j++)
3316 if (ma[j].cont_level == 0)