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.229 2015/01/01 17:07:34 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 *);
154 private size_t magicsize = sizeof(struct magic);
156 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
161 int (*fun)(struct magic_set *, struct magic_entry *, const char *);
163 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
165 DECLARE_FIELD(apple),
166 DECLARE_FIELD(strength),
173 int main(int, char *[]);
176 main(int argc, char *argv[])
179 struct magic_set *ms;
182 if ((progname = strrchr(argv[0], '/')) != NULL)
188 (void)fprintf(stderr, "Usage: %s file\n", progname);
192 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
193 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
196 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
198 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
202 #endif /* COMPILE_ONLY */
212 * XXX - the actual Single UNIX Specification says that "long" means "long",
213 * as in the C data type, but we treat it as meaning "4-byte integer".
214 * Given that the OS X version of file 5.04 did the same, I guess that passes
215 * the actual test; having "long" be dependent on how big a "long" is on
216 * the machine running "file" is silly.
218 static const struct type_tbl_s type_tbl[] = {
219 # define XX(s) s, (sizeof(s) - 1)
220 # define XX_NULL "", 0
221 { XX("invalid"), FILE_INVALID, FILE_FMT_NONE },
222 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
223 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
224 { XX("default"), FILE_DEFAULT, FILE_FMT_NONE },
225 { XX("long"), FILE_LONG, FILE_FMT_NUM },
226 { XX("string"), FILE_STRING, FILE_FMT_STR },
227 { XX("date"), FILE_DATE, FILE_FMT_STR },
228 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
229 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
230 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
231 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
232 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
233 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
234 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
235 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
236 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
237 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
238 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
239 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
240 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
241 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
242 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
243 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
244 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
245 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
246 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
247 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
248 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
249 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
250 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
251 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
252 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
253 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
254 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
255 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
256 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
257 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
258 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
259 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
260 { XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
261 { XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
262 { XX("indirect"), FILE_INDIRECT, FILE_FMT_NUM },
263 { XX("qwdate"), FILE_QWDATE, FILE_FMT_STR },
264 { XX("leqwdate"), FILE_LEQWDATE, FILE_FMT_STR },
265 { XX("beqwdate"), FILE_BEQWDATE, FILE_FMT_STR },
266 { XX("name"), FILE_NAME, FILE_FMT_NONE },
267 { XX("use"), FILE_USE, FILE_FMT_NONE },
268 { XX("clear"), FILE_CLEAR, FILE_FMT_NONE },
269 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
273 * These are not types, and cannot be preceded by "u" to make them
276 static const struct type_tbl_s special_tbl[] = {
277 { XX("name"), FILE_NAME, FILE_FMT_STR },
278 { XX("use"), FILE_USE, FILE_FMT_STR },
279 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
285 get_type(const struct type_tbl_s *tbl, const char *l, const char **t)
287 const struct type_tbl_s *p;
289 for (p = tbl; p->len; p++) {
290 if (strncmp(l, p->name, p->len) == 0) {
300 get_standard_integer_type(const char *l, const char **t)
304 if (isalpha((unsigned char)l[1])) {
317 * "dI", "dL", "uI", and "uL".
319 * XXX - the actual Single UNIX Specification says
320 * that "L" means "long", as in the C data type,
321 * but we treat it as meaning "4-byte integer".
322 * Given that the OS X version of file 5.04 did
323 * the same, I guess that passes the actual SUS
324 * validation suite; having "dL" be dependent on
325 * how big a "long" is on the machine running
335 /* "d{anything else}", "u{anything else}" */
339 } else if (isdigit((unsigned char)l[1])) {
341 * "d{num}" and "u{num}"; we only support {num} values
342 * of 1, 2, 4, and 8 - the Single UNIX Specification
343 * doesn't say anything about whether arbitrary
344 * values should be supported, but both the Solaris 10
345 * and OS X Mountain Lion versions of file passed the
346 * Single UNIX Specification validation suite, and
347 * neither of them support values bigger than 8 or
348 * non-power-of-2 values.
350 if (isdigit((unsigned char)l[2])) {
351 /* Multi-digit, so > 9 */
368 /* XXX - what about 3, 5, 6, or 7? */
374 * "d" or "u" by itself.
385 init_file_tables(void)
388 const struct type_tbl_s *p;
394 for (p = type_tbl; p->len; p++) {
395 assert(p->type < FILE_NAMES_SIZE);
396 file_names[p->type] = p->name;
397 file_formats[p->type] = p->format;
399 assert(p - type_tbl == FILE_NAMES_SIZE);
403 add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx)
407 mlp->map = idx == 0 ? map : NULL;
408 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL)
412 ml->magic = map->magic[idx];
413 ml->nmagic = map->nmagic[idx];
415 mlp->prev->next = ml;
416 ml->prev = mlp->prev;
423 * Handle one file or directory.
426 apprentice_1(struct magic_set *ms, const char *fn, int action)
428 struct magic_map *map;
434 if (magicsize != FILE_MAGICSIZE) {
435 file_error(ms, 0, "magic element size %lu != %lu",
436 (unsigned long)sizeof(*map->magic[0]),
437 (unsigned long)FILE_MAGICSIZE);
441 if (action == FILE_COMPILE) {
442 map = apprentice_load(ms, fn, action);
445 return apprentice_compile(ms, map, fn);
449 map = apprentice_map(ms, fn);
451 if (ms->flags & MAGIC_CHECK)
452 file_magwarn(ms, "using regular magic file `%s'", fn);
453 map = apprentice_load(ms, fn, action);
458 for (i = 0; i < MAGIC_SETS; i++) {
459 if (add_mlist(ms->mlist[i], map, i) == -1) {
460 file_oomem(ms, sizeof(*ml));
465 if (action == FILE_LIST) {
466 for (i = 0; i < MAGIC_SETS; i++) {
467 printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n",
469 apprentice_list(ms->mlist[i], BINTEST);
470 printf("Text patterns:\n");
471 apprentice_list(ms->mlist[i], TEXTTEST);
476 for (i = 0; i < MAGIC_SETS; i++) {
477 mlist_free(ms->mlist[i]);
483 #endif /* COMPILE_ONLY */
487 file_ms_free(struct magic_set *ms)
492 for (i = 0; i < MAGIC_SETS; i++)
493 mlist_free(ms->mlist[i]);
500 protected struct magic_set *
501 file_ms_alloc(int flags)
503 struct magic_set *ms;
506 if ((ms = CAST(struct magic_set *, calloc((size_t)1,
507 sizeof(struct magic_set)))) == NULL)
510 if (magic_setflags(ms, flags) == -1) {
515 ms->o.buf = ms->o.pbuf = NULL;
516 len = (ms->c.len = 10) * sizeof(*ms->c.li);
518 if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL)
523 for (i = 0; i < MAGIC_SETS; i++)
525 ms->file = "unknown";
527 ms->indir_max = FILE_INDIR_MAX;
528 ms->name_max = FILE_NAME_MAX;
529 ms->elf_shnum_max = FILE_ELF_SHNUM_MAX;
530 ms->elf_phnum_max = FILE_ELF_PHNUM_MAX;
531 ms->elf_notes_max = FILE_ELF_NOTES_MAX;
539 apprentice_unmap(struct magic_map *map)
548 (void)munmap(map->p, map->len);
551 case MAP_TYPE_MALLOC:
562 private struct mlist *
566 if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) {
569 mlist->next = mlist->prev = mlist;
574 mlist_free(struct mlist *mlist)
576 struct mlist *ml, *next;
582 for (ml = mlist->next; (next = ml->next) != NULL; ml = next) {
584 apprentice_unmap(ml->map);
592 /* void **bufs: an array of compiled magic files */
594 buffer_apprentice(struct magic_set *ms, struct magic **bufs,
595 size_t *sizes, size_t nbufs)
599 struct magic_map *map;
604 if (ms->mlist[0] != NULL)
609 for (i = 0; i < MAGIC_SETS; i++) {
610 mlist_free(ms->mlist[i]);
611 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
612 file_oomem(ms, sizeof(*ms->mlist[i]));
617 for (i = 0; i < nbufs; i++) {
618 map = apprentice_buf(ms, bufs[i], sizes[i]);
622 for (j = 0; j < MAGIC_SETS; j++) {
623 if (add_mlist(ms->mlist[j], map, j) == -1) {
624 file_oomem(ms, sizeof(*ml));
632 for (i = 0; i < MAGIC_SETS; i++) {
633 mlist_free(ms->mlist[i]);
640 /* const char *fn: list of magic files and directories */
642 file_apprentice(struct magic_set *ms, const char *fn, int action)
645 int file_err, errs = -1;
648 if (ms->mlist[0] != NULL)
651 if ((fn = magic_getpath(fn, action)) == NULL)
656 if ((mfn = strdup(fn)) == NULL) {
657 file_oomem(ms, strlen(fn));
661 for (i = 0; i < MAGIC_SETS; i++) {
662 mlist_free(ms->mlist[i]);
663 if ((ms->mlist[i] = mlist_alloc()) == NULL) {
664 file_oomem(ms, sizeof(*ms->mlist[i]));
666 mlist_free(ms->mlist[i]);
676 p = strchr(fn, PATHSEP);
681 file_err = apprentice_1(ms, fn, action);
682 errs = MAX(errs, file_err);
689 for (i = 0; i < MAGIC_SETS; i++) {
690 mlist_free(ms->mlist[i]);
693 file_error(ms, 0, "could not find any valid magic files!");
699 * Always leave the database loaded
701 if (action == FILE_LOAD)
704 for (i = 0; i < MAGIC_SETS; i++) {
705 mlist_free(ms->mlist[i]);
717 file_error(ms, 0, "Invalid action %d", action);
723 * Compute the real length of a magic expression, for the purposes
724 * of determining how "strong" a magic expression is (approximating
725 * how specific its matches are):
726 * - magic characters count 0 unless escaped.
727 * - [] expressions count 1
728 * - {} expressions count 0
729 * - regular characters or escaped magic characters count 1
730 * - 0 length expressions count as one
733 nonmagic(const char *str)
738 for (p = str; *p; p++)
740 case '\\': /* Escaped anything counts 1 */
745 case '?': /* Magic characters count 0 */
752 case '[': /* Bracketed expressions count 1 the ']' */
753 while (*p && *p != ']')
757 case '{': /* Braced expressions count 0 */
758 while (*p && *p != '}')
763 default: /* Anything else counts 1 */
768 return rv == 0 ? 1 : rv; /* Return at least 1 */
772 * Get weight of this magic entry, for sorting purposes.
775 apprentice_magic_strength(const struct magic *m)
778 size_t v, val = 2 * MULT; /* baseline strength */
781 case FILE_DEFAULT: /* make sure this sorts last */
782 if (m->factor_op != FILE_FACTOR_OP_NONE)
805 val += m->vallen * MULT;
808 case FILE_BESTRING16:
809 case FILE_LESTRING16:
810 val += m->vallen * MULT / 2;
814 val += m->vallen * MAX(MULT / m->vallen, 1);
818 v = nonmagic(m->value.s);
819 val += v * MAX(MULT / v, 1);
860 (void)fprintf(stderr, "Bad type %d\n", m->type);
865 case 'x': /* matches anything penalize */
866 case '!': /* matches almost anything penalize */
870 case '=': /* Exact match, prefer */
875 case '<': /* comparison match reduce strength */
880 case '&': /* masking bits, we could count them too */
885 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
889 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
892 switch (m->factor_op) {
893 case FILE_FACTOR_OP_NONE:
895 case FILE_FACTOR_OP_PLUS:
898 case FILE_FACTOR_OP_MINUS:
901 case FILE_FACTOR_OP_TIMES:
904 case FILE_FACTOR_OP_DIV:
912 * Magic entries with no description get a bonus because they depend
913 * on subsequent magic entries to print something.
915 if (m->desc[0] == '\0')
921 * Sort callback for sorting entries by "strength" (basically length)
924 apprentice_sort(const void *a, const void *b)
926 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
927 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
928 size_t sa = apprentice_magic_strength(ma->mp);
929 size_t sb = apprentice_magic_strength(mb->mp);
939 * Shows sorted patterns list in the order which is used for the matching
942 apprentice_list(struct mlist *mlist, int mode)
944 uint32_t magindex = 0;
946 for (ml = mlist->next; ml != mlist; ml = ml->next) {
947 for (magindex = 0; magindex < ml->nmagic; magindex++) {
948 struct magic *m = &ml->magic[magindex];
949 if ((m->flag & mode) != mode) {
951 while (magindex + 1 < ml->nmagic &&
952 ml->magic[magindex + 1].cont_level != 0)
954 continue; /* Skip to next top-level test*/
958 * Try to iterate over the tree until we find item with
959 * description/mimetype.
961 while (magindex + 1 < ml->nmagic &&
962 ml->magic[magindex + 1].cont_level != 0 &&
963 *ml->magic[magindex].desc == '\0' &&
964 *ml->magic[magindex].mimetype == '\0')
967 printf("Strength = %3" SIZE_T_FORMAT "u : %s [%s]\n",
968 apprentice_magic_strength(m),
969 ml->magic[magindex].desc,
970 ml->magic[magindex].mimetype);
976 set_test_type(struct magic *mstart, struct magic *m)
1013 mstart->flag |= BINTEST;
1017 case FILE_BESTRING16:
1018 case FILE_LESTRING16:
1019 /* Allow text overrides */
1020 if (mstart->str_flags & STRING_TEXTTEST)
1021 mstart->flag |= TEXTTEST;
1023 mstart->flag |= BINTEST;
1027 /* Check for override */
1028 if (mstart->str_flags & STRING_BINTEST)
1029 mstart->flag |= BINTEST;
1030 if (mstart->str_flags & STRING_TEXTTEST)
1031 mstart->flag |= TEXTTEST;
1033 if (mstart->flag & (TEXTTEST|BINTEST))
1036 /* binary test if pattern is not text */
1037 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
1039 mstart->flag |= BINTEST;
1041 mstart->flag |= TEXTTEST;
1044 /* can't deduce anything; we shouldn't see this at the
1049 /* invalid search type, but no need to complain here */
1055 addentry(struct magic_set *ms, struct magic_entry *me,
1056 struct magic_entry_set *mset)
1058 size_t i = me->mp->type == FILE_NAME ? 1 : 0;
1059 if (mset[i].count == mset[i].max) {
1060 struct magic_entry *mp;
1062 mset[i].max += ALLOC_INCR;
1063 if ((mp = CAST(struct magic_entry *,
1064 realloc(mset[i].me, sizeof(*mp) * mset[i].max))) ==
1066 file_oomem(ms, sizeof(*mp) * mset[i].max);
1069 (void)memset(&mp[mset[i].count], 0, sizeof(*mp) *
1073 mset[i].me[mset[i].count++] = *me;
1074 memset(me, 0, sizeof(*me));
1079 * Load and parse one file.
1082 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
1083 struct magic_entry_set *mset)
1085 size_t lineno = 0, llen = 0;
1088 struct magic_entry me;
1090 FILE *f = fopen(ms->file = fn, "r");
1092 if (errno != ENOENT)
1093 file_error(ms, errno, "cannot read magic file `%s'",
1099 memset(&me, 0, sizeof(me));
1100 /* read and parse this file */
1101 for (ms->line = 1; (len = getline(&line, &llen, f)) != -1;
1103 if (len == 0) /* null line, garbage, etc */
1105 if (line[len - 1] == '\n') {
1107 line[len - 1] = '\0'; /* delete newline */
1110 case '\0': /* empty, do not parse */
1111 case '#': /* comment, do not parse */
1114 if (line[1] == ':') {
1117 for (i = 0; bang[i].name != NULL; i++) {
1118 if ((size_t)(len - 2) > bang[i].len &&
1119 memcmp(bang[i].name, line + 2,
1123 if (bang[i].name == NULL) {
1125 "Unknown !: entry `%s'", line);
1129 if (me.mp == NULL) {
1131 "No current entry for :!%s type",
1136 if ((*bang[i].fun)(ms, &me,
1137 line + bang[i].len + 2) != 0) {
1146 switch (parse(ms, &me, line, lineno, action)) {
1150 (void)addentry(ms, &me, mset);
1159 (void)addentry(ms, &me, mset);
1165 * parse a file or directory of files
1166 * const char *fn: name of magic file or directory
1169 cmpstrp(const void *p1, const void *p2)
1171 return strcmp(*(char *const *)p1, *(char *const *)p2);
1176 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1179 static const char text[] = "text";
1180 static const char binary[] = "binary";
1181 static const size_t len = sizeof(text);
1183 uint32_t i = starttest;
1186 set_test_type(me[starttest].mp, me[i].mp);
1187 if ((ms->flags & MAGIC_DEBUG) == 0)
1189 (void)fprintf(stderr, "%s%s%s: %s\n",
1191 me[i].mp->mimetype[0] == '\0' ? "" : "; ",
1192 me[i].mp->desc[0] ? me[i].mp->desc : "(no description)",
1193 me[i].mp->flag & BINTEST ? binary : text);
1194 if (me[i].mp->flag & BINTEST) {
1195 char *p = strstr(me[i].mp->desc, text);
1196 if (p && (p == me[i].mp->desc ||
1197 isspace((unsigned char)p[-1])) &&
1198 (p + len - me[i].mp->desc == MAXstring
1199 || (p[len] == '\0' ||
1200 isspace((unsigned char)p[len]))))
1201 (void)fprintf(stderr, "*** Possible "
1202 "binary test for text type\n");
1204 } while (++i < nme && me[i].mp->cont_level != 0);
1209 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme)
1212 for (i = 0; i < nme; i++) {
1213 if (me[i].mp->cont_level == 0 &&
1214 me[i].mp->type == FILE_DEFAULT) {
1216 if (me[i].mp->cont_level == 0)
1220 ms->line = me[i].mp->lineno;
1222 "level 0 \"default\" did not sort last");
1230 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme,
1231 struct magic **ma, uint32_t *nma)
1233 uint32_t i, mentrycount = 0;
1236 for (i = 0; i < nme; i++)
1237 mentrycount += me[i].cont_count;
1239 slen = sizeof(**ma) * mentrycount;
1240 if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) {
1241 file_oomem(ms, slen);
1246 for (i = 0; i < nme; i++) {
1247 (void)memcpy(*ma + mentrycount, me[i].mp,
1248 me[i].cont_count * sizeof(**ma));
1249 mentrycount += me[i].cont_count;
1256 magic_entry_free(struct magic_entry *me, uint32_t nme)
1261 for (i = 0; i < nme; i++)
1266 private struct magic_map *
1267 apprentice_load(struct magic_set *ms, const char *fn, int action)
1271 size_t files = 0, maxfiles = 0;
1272 char **filearr = NULL, *mfn;
1274 struct magic_map *map;
1275 struct magic_entry_set mset[MAGIC_SETS];
1279 memset(mset, 0, sizeof(mset));
1280 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
1283 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL)
1285 file_oomem(ms, sizeof(*map));
1289 /* print silly verbose header for USG compat. */
1290 if (action == FILE_CHECK)
1291 (void)fprintf(stderr, "%s\n", usg_hdr);
1293 /* load directory or file */
1294 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
1300 while ((d = readdir(dir)) != NULL) {
1301 if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) {
1303 strlen(fn) + strlen(d->d_name) + 2);
1308 if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) {
1312 if (files >= maxfiles) {
1314 maxfiles = (maxfiles + 1) * 2;
1315 mlen = maxfiles * sizeof(*filearr);
1316 if ((filearr = CAST(char **,
1317 realloc(filearr, mlen))) == NULL) {
1318 file_oomem(ms, mlen);
1325 filearr[files++] = mfn;
1328 qsort(filearr, files, sizeof(*filearr), cmpstrp);
1329 for (i = 0; i < files; i++) {
1330 load_1(ms, action, filearr[i], &errs, mset);
1335 load_1(ms, action, fn, &errs, mset);
1339 for (j = 0; j < MAGIC_SETS; j++) {
1340 /* Set types of tests */
1341 for (i = 0; i < mset[j].count; ) {
1342 if (mset[j].me[i].mp->cont_level != 0) {
1346 i = set_text_binary(ms, mset[j].me, mset[j].count, i);
1348 qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me),
1352 * Make sure that any level 0 "default" line is last
1355 set_last_default(ms, mset[j].me, mset[j].count);
1357 /* coalesce per file arrays into a single one */
1358 if (coalesce_entries(ms, mset[j].me, mset[j].count,
1359 &map->magic[j], &map->nmagic[j]) == -1) {
1366 for (j = 0; j < MAGIC_SETS; j++)
1367 magic_entry_free(mset[j].me, mset[j].count);
1370 apprentice_unmap(map);
1377 * extend the sign bit if the comparison is to be signed
1380 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
1382 if (!(m->flag & UNSIGNED)) {
1385 * Do not remove the casts below. They are
1386 * vital. When later compared with the data,
1387 * the sign extension must have happened.
1390 v = (signed char) v;
1433 case FILE_BESTRING16:
1434 case FILE_LESTRING16:
1444 if (ms->flags & MAGIC_CHECK)
1445 file_magwarn(ms, "cannot happen: m->type=%d\n",
1454 string_modifier_check(struct magic_set *ms, struct magic *m)
1456 if ((ms->flags & MAGIC_CHECK) == 0)
1459 if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) &&
1460 (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) {
1462 "'/BHhLl' modifiers are only allowed for pascal strings\n");
1466 case FILE_BESTRING16:
1467 case FILE_LESTRING16:
1468 if (m->str_flags != 0) {
1470 "no modifiers allowed for 16-bit strings\n");
1476 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
1478 "'/%c' only allowed on regex and search\n",
1479 CHAR_REGEX_OFFSET_START);
1484 if (m->str_range == 0) {
1486 "missing range; defaulting to %d\n",
1487 STRING_DEFAULT_RANGE);
1488 m->str_range = STRING_DEFAULT_RANGE;
1493 if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
1494 file_magwarn(ms, "'/%c' not allowed on regex\n",
1495 CHAR_COMPACT_WHITESPACE);
1498 if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
1499 file_magwarn(ms, "'/%c' not allowed on regex\n",
1500 CHAR_COMPACT_OPTIONAL_WHITESPACE);
1505 file_magwarn(ms, "coding error: m->type=%d\n",
1525 return FILE_OPMINUS;
1527 return FILE_OPMULTIPLY;
1529 return FILE_OPDIVIDE;
1531 return FILE_OPMODULO;
1537 #ifdef ENABLE_CONDITIONALS
1539 get_cond(const char *l, const char **t)
1541 static const struct cond_tbl_s {
1546 { "if", 2, COND_IF },
1547 { "elif", 4, COND_ELIF },
1548 { "else", 4, COND_ELSE },
1549 { "", 0, COND_NONE },
1551 const struct cond_tbl_s *p;
1553 for (p = cond_tbl; p->len; p++) {
1554 if (strncmp(l, p->name, p->len) == 0 &&
1555 isspace((unsigned char)l[p->len])) {
1565 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1568 last_cond = ms->c.li[cont_level].last_cond;
1572 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1573 if (ms->flags & MAGIC_CHECK)
1574 file_magwarn(ms, "syntax error: `if'");
1577 last_cond = COND_IF;
1581 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1582 if (ms->flags & MAGIC_CHECK)
1583 file_magwarn(ms, "syntax error: `elif'");
1586 last_cond = COND_ELIF;
1590 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1591 if (ms->flags & MAGIC_CHECK)
1592 file_magwarn(ms, "syntax error: `else'");
1595 last_cond = COND_NONE;
1599 last_cond = COND_NONE;
1603 ms->c.li[cont_level].last_cond = last_cond;
1606 #endif /* ENABLE_CONDITIONALS */
1609 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1611 const char *l = *lp;
1613 while (!isspace((unsigned char)*++l))
1615 case CHAR_INDIRECT_RELATIVE:
1616 m->str_flags |= INDIRECT_RELATIVE;
1619 if (ms->flags & MAGIC_CHECK)
1620 file_magwarn(ms, "indirect modifier `%c' "
1630 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp,
1633 const char *l = *lp;
1639 val = (uint64_t)strtoull(l, &t, 0);
1641 m->num_mask = file_signextend(ms, m, val);
1647 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp)
1649 const char *l = *lp;
1653 while (!isspace((unsigned char)*++l)) {
1655 case '0': case '1': case '2':
1656 case '3': case '4': case '5':
1657 case '6': case '7': case '8':
1659 if (have_range && (ms->flags & MAGIC_CHECK))
1660 file_magwarn(ms, "multiple ranges");
1662 m->str_range = CAST(uint32_t, strtoul(l, &t, 0));
1663 if (m->str_range == 0)
1664 file_magwarn(ms, "zero range");
1667 case CHAR_COMPACT_WHITESPACE:
1668 m->str_flags |= STRING_COMPACT_WHITESPACE;
1670 case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1671 m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE;
1673 case CHAR_IGNORE_LOWERCASE:
1674 m->str_flags |= STRING_IGNORE_LOWERCASE;
1676 case CHAR_IGNORE_UPPERCASE:
1677 m->str_flags |= STRING_IGNORE_UPPERCASE;
1679 case CHAR_REGEX_OFFSET_START:
1680 m->str_flags |= REGEX_OFFSET_START;
1683 m->str_flags |= STRING_BINTEST;
1686 m->str_flags |= STRING_TEXTTEST;
1689 m->str_flags |= STRING_TRIM;
1691 case CHAR_PSTRING_1_LE:
1692 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a)
1693 if (m->type != FILE_PSTRING)
1695 SET_LENGTH(PSTRING_1_LE);
1697 case CHAR_PSTRING_2_BE:
1698 if (m->type != FILE_PSTRING)
1700 SET_LENGTH(PSTRING_2_BE);
1702 case CHAR_PSTRING_2_LE:
1703 if (m->type != FILE_PSTRING)
1705 SET_LENGTH(PSTRING_2_LE);
1707 case CHAR_PSTRING_4_BE:
1708 if (m->type != FILE_PSTRING)
1710 SET_LENGTH(PSTRING_4_BE);
1712 case CHAR_PSTRING_4_LE:
1720 SET_LENGTH(PSTRING_4_LE);
1722 case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF:
1723 if (m->type != FILE_PSTRING)
1725 m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF;
1729 if (ms->flags & MAGIC_CHECK)
1730 file_magwarn(ms, "string modifier `%c' "
1734 /* allow multiple '/' for readability */
1735 if (l[1] == '/' && !isspace((unsigned char)l[2]))
1738 if (string_modifier_check(ms, m) == -1)
1748 * parse one line from magic file, put into magic[index++] if valid
1751 parse(struct magic_set *ms, struct magic_entry *me, const char *line,
1752 size_t lineno, int action)
1754 #ifdef ENABLE_CONDITIONALS
1755 static uint32_t last_cont_level = 0;
1759 const char *l = line;
1762 uint32_t cont_level;
1771 ++l; /* step over */
1774 #ifdef ENABLE_CONDITIONALS
1775 if (cont_level == 0 || cont_level > last_cont_level)
1776 if (file_check_mem(ms, cont_level) == -1)
1778 last_cont_level = cont_level;
1780 if (cont_level != 0) {
1781 if (me->mp == NULL) {
1782 file_magerror(ms, "No current entry for continuation");
1785 if (me->cont_count == 0) {
1786 file_magerror(ms, "Continuations present with 0 count");
1789 m = &me->mp[me->cont_count - 1];
1790 diff = (int32_t)cont_level - (int32_t)m->cont_level;
1792 file_magwarn(ms, "New continuation level %u is more "
1793 "than one larger than current level %u", cont_level,
1795 if (me->cont_count == me->max_count) {
1797 size_t cnt = me->max_count + ALLOC_CHUNK;
1798 if ((nm = CAST(struct magic *, realloc(me->mp,
1799 sizeof(*nm) * cnt))) == NULL) {
1800 file_oomem(ms, sizeof(*nm) * cnt);
1804 me->max_count = CAST(uint32_t, cnt);
1806 m = &me->mp[me->cont_count++];
1807 (void)memset(m, 0, sizeof(*m));
1808 m->cont_level = cont_level;
1810 static const size_t len = sizeof(*m) * ALLOC_CHUNK;
1813 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1814 file_oomem(ms, len);
1818 me->max_count = ALLOC_CHUNK;
1819 (void)memset(m, 0, sizeof(*m));
1820 m->factor_op = FILE_FACTOR_OP_NONE;
1824 m->lineno = CAST(uint32_t, lineno);
1826 if (*l == '&') { /* m->cont_level == 0 checked below. */
1827 ++l; /* step over */
1831 ++l; /* step over */
1833 if (m->flag & OFFADD)
1834 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1836 if (*l == '&') { /* m->cont_level == 0 checked below */
1837 ++l; /* step over */
1841 /* Indirect offsets are not valid at level 0. */
1842 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
1843 if (ms->flags & MAGIC_CHECK)
1844 file_magwarn(ms, "relative offset at level 0");
1846 /* get offset, then skip over it */
1847 m->offset = (uint32_t)strtoul(l, &t, 0);
1849 if (ms->flags & MAGIC_CHECK)
1850 file_magwarn(ms, "offset `%s' invalid", l);
1853 if (m->flag & INDIR) {
1854 m->in_type = FILE_LONG;
1857 * read [.lbs][+-]nnnnn)
1863 m->in_type = FILE_LELONG;
1866 m->in_type = FILE_BELONG;
1869 m->in_type = FILE_MELONG;
1873 m->in_type = FILE_LESHORT;
1877 m->in_type = FILE_BESHORT;
1883 m->in_type = FILE_BYTE;
1888 m->in_type = FILE_LEDOUBLE;
1893 m->in_type = FILE_BEDOUBLE;
1896 m->in_type = FILE_LEID3;
1899 m->in_type = FILE_BEID3;
1902 if (ms->flags & MAGIC_CHECK)
1904 "indirect offset type `%c' invalid",
1913 m->in_op |= FILE_OPINVERSE;
1916 if ((op = get_op(*l)) != -1) {
1921 m->in_op |= FILE_OPINDIRECT;
1924 if (isdigit((unsigned char)*l) || *l == '-') {
1925 m->in_offset = (int32_t)strtol(l, &t, 0);
1927 if (ms->flags & MAGIC_CHECK)
1929 "in_offset `%s' invalid", l);
1933 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
1934 if (ms->flags & MAGIC_CHECK)
1936 "missing ')' in indirect offset");
1940 #ifdef ENABLE_CONDITIONALS
1941 m->cond = get_cond(l, &l);
1942 if (check_cond(ms, m->cond, cont_level) == -1)
1953 * Try it as a keyword type prefixed by "u"; match what
1954 * follows the "u". If that fails, try it as an SUS
1957 m->type = get_type(type_tbl, l + 1, &l);
1958 if (m->type == FILE_INVALID) {
1960 * Not a keyword type; parse it as an SUS type,
1961 * 'u' possibly followed by a number or C/S/L.
1963 m->type = get_standard_integer_type(l, &l);
1965 /* It's unsigned. */
1966 if (m->type != FILE_INVALID)
1967 m->flag |= UNSIGNED;
1970 * Try it as a keyword type. If that fails, try it as
1971 * an SUS integer type if it begins with "d" or as an
1972 * SUS string type if it begins with "s". In any case,
1973 * it's not unsigned.
1975 m->type = get_type(type_tbl, l, &l);
1976 if (m->type == FILE_INVALID) {
1978 * Not a keyword type; parse it as an SUS type,
1979 * either 'd' possibly followed by a number or
1980 * C/S/L, or just 's'.
1983 m->type = get_standard_integer_type(l, &l);
1984 else if (*l == 's' && !isalpha((unsigned char)l[1])) {
1985 m->type = FILE_STRING;
1991 if (m->type == FILE_INVALID) {
1992 /* Not found - try it as a special keyword. */
1993 m->type = get_type(special_tbl, l, &l);
1996 if (m->type == FILE_INVALID) {
1997 if (ms->flags & MAGIC_CHECK)
1998 file_magwarn(ms, "type `%s' invalid", l);
2002 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
2003 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
2007 if (!IS_STRING(m->type))
2008 m->mask_op |= FILE_OPINVERSE;
2009 else if (ms->flags & MAGIC_CHECK)
2010 file_magwarn(ms, "'~' invalid for string types");
2014 m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0;
2015 if ((op = get_op(*l)) != -1) {
2016 if (IS_STRING(m->type)) {
2019 if (op != FILE_OPDIVIDE) {
2020 if (ms->flags & MAGIC_CHECK)
2022 "invalid string/indirect op: "
2027 if (m->type == FILE_INDIRECT)
2028 r = parse_indirect_modifier(ms, m, &l);
2030 r = parse_string_modifier(ms, m, &l);
2034 parse_op_modifier(ms, m, &l, op);
2038 * We used to set mask to all 1's here, instead let's just not do
2039 * anything if mask = 0 (unless you have a better idea)
2049 if (ms->flags & MAGIC_CHECK) {
2050 file_magwarn(ms, "%c= not supported",
2057 /* Old-style anding: "0 byte &0x80 dynamically linked" */
2064 /* HP compat: ignore &= etc. */
2073 m->reln = '='; /* the default relation */
2074 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
2075 isspace((unsigned char)l[1])) || !l[1])) {
2082 * Grab the value part, except for an 'x' reln.
2084 if (m->reln != 'x' && getvalue(ms, m, &l, action))
2088 * TODO finish this macro and start using it!
2089 * #define offsetcheck {if (offset > HOWMANY-1)
2090 * magwarn("offset too big"); }
2094 * Now get last part - the description
2100 } else if ((l[0] == '\\') && (l[1] == 'b')) {
2105 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
2107 if (i == sizeof(m->desc)) {
2108 m->desc[sizeof(m->desc) - 1] = '\0';
2109 if (ms->flags & MAGIC_CHECK)
2110 file_magwarn(ms, "description `%s' truncated", m->desc);
2114 * We only do this check while compiling, or if any of the magic
2115 * files were not compiled.
2117 if (ms->flags & MAGIC_CHECK) {
2118 if (check_format(ms, m) == -1)
2121 #ifndef COMPILE_ONLY
2122 if (action == FILE_CHECK) {
2126 m->mimetype[0] = '\0'; /* initialise MIME type to none */
2131 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
2135 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
2137 const char *l = line;
2139 unsigned long factor;
2140 struct magic *m = &me->mp[0];
2142 if (m->factor_op != FILE_FACTOR_OP_NONE) {
2144 "Current entry already has a strength type: %c %d",
2145 m->factor_op, m->factor);
2148 if (m->type == FILE_NAME) {
2149 file_magwarn(ms, "%s: Strength setting is not supported in "
2150 "\"name\" magic entries", m->value.s);
2155 case FILE_FACTOR_OP_NONE:
2156 case FILE_FACTOR_OP_PLUS:
2157 case FILE_FACTOR_OP_MINUS:
2158 case FILE_FACTOR_OP_TIMES:
2159 case FILE_FACTOR_OP_DIV:
2160 m->factor_op = *l++;
2163 file_magwarn(ms, "Unknown factor op `%c'", *l);
2167 factor = strtoul(l, &el, 0);
2169 file_magwarn(ms, "Too large factor `%lu'", factor);
2172 if (*el && !isspace((unsigned char)*el)) {
2173 file_magwarn(ms, "Bad factor `%s'", l);
2176 m->factor = (uint8_t)factor;
2177 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
2178 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
2179 m->factor_op, m->factor);
2184 m->factor_op = FILE_FACTOR_OP_NONE;
2190 goodchar(unsigned char x, const char *extra)
2192 return (isascii(x) && isalnum(x)) || strchr(extra, x);
2196 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line,
2197 off_t off, size_t len, const char *name, const char *extra, int nt)
2200 const char *l = line;
2201 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
2202 char *buf = (char *)m + off;
2204 if (buf[0] != '\0') {
2205 len = nt ? strlen(buf) : len;
2206 file_magwarn(ms, "Current entry already has a %s type "
2207 "`%.*s', new type `%s'", name, (int)len, buf, l);
2211 if (*m->desc == '\0') {
2212 file_magwarn(ms, "Current entry does not yet have a "
2213 "description for adding a %s type", name);
2218 for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++)
2221 if (i == len && *l) {
2223 buf[len - 1] = '\0';
2224 if (ms->flags & MAGIC_CHECK)
2225 file_magwarn(ms, "%s type `%s' truncated %"
2226 SIZE_T_FORMAT "u", name, line, i);
2228 if (!isspace((unsigned char)*l) && !goodchar(*l, extra))
2229 file_magwarn(ms, "%s type `%s' has bad char '%c'",
2238 file_magerror(ms, "Bad magic entry '%s'", line);
2243 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into
2247 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
2249 struct magic *m = &me->mp[0];
2251 return parse_extra(ms, me, line, offsetof(struct magic, apple),
2252 sizeof(m->apple), "APPLE", "!+-./", 0);
2256 * parse a MIME annotation line from magic file, put into magic[index - 1]
2260 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
2262 struct magic *m = &me->mp[0];
2264 return parse_extra(ms, me, line, offsetof(struct magic, mimetype),
2265 sizeof(m->mimetype), "MIME", "+-/.", 1);
2269 check_format_type(const char *ptr, int type)
2273 /* Missing format string; bad */
2277 switch (file_formats[type]) {
2310 while (isdigit((unsigned char)*ptr)) ptr++;
2313 while (isdigit((unsigned char)*ptr)) ptr++;
2322 #ifdef STRICT_FORMAT /* "long" formats are int formats for us */
2323 /* so don't accept the 'l' modifier */
2332 return h != 0 ? -1 : 0;
2338 * Don't accept h and hh modifiers. They make writing
2339 * magic entries more complicated, for very little benefit
2365 return h != 0 ? -1 : 0;
2371 return h != 2 ? -1 : 0;
2378 #ifdef STRICT_FORMAT
2379 return h != 0 ? -1 : 0;
2387 case FILE_FMT_FLOAT:
2388 case FILE_FMT_DOUBLE:
2393 while (isdigit((unsigned char)*ptr)) ptr++;
2396 while (isdigit((unsigned char)*ptr)) ptr++;
2415 while (isdigit((unsigned char )*ptr))
2419 while (isdigit((unsigned char )*ptr))
2431 /* internal error */
2439 * Check that the optional printf format in description matches
2440 * the type of the magic.
2443 check_format(struct magic_set *ms, struct magic *m)
2447 for (ptr = m->desc; *ptr; ptr++)
2451 /* No format string; ok */
2455 assert(file_nformats == file_nnames);
2457 if (m->type >= file_nformats) {
2458 file_magwarn(ms, "Internal error inconsistency between "
2459 "m->type and format strings");
2462 if (file_formats[m->type] == FILE_FMT_NONE) {
2463 file_magwarn(ms, "No format string for `%s' with description "
2464 "`%s'", m->desc, file_names[m->type]);
2469 if (check_format_type(ptr, m->type) == -1) {
2471 * TODO: this error message is unhelpful if the format
2472 * string is not one character long
2474 file_magwarn(ms, "Printf format `%c' is not valid for type "
2475 "`%s' in description `%s'", *ptr ? *ptr : '?',
2476 file_names[m->type], m->desc);
2480 for (; *ptr; ptr++) {
2483 "Too many format strings (should have at most one) "
2484 "for `%s' with description `%s'",
2485 file_names[m->type], m->desc);
2493 * Read a numeric value from a pointer, into the value union of a magic
2494 * pointer, according to the magic type. Update the string pointer to point
2495 * just after the number read. Return 0 for success, non-zero for failure.
2498 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
2501 case FILE_BESTRING16:
2502 case FILE_LESTRING16:
2509 *p = getstr(ms, m, *p, action == FILE_COMPILE);
2511 if (ms->flags & MAGIC_CHECK)
2512 file_magwarn(ms, "cannot get string from `%s'",
2516 if (m->type == FILE_REGEX) {
2518 int rc = file_regcomp(&rx, m->value.s, REG_EXTENDED);
2520 if (ms->flags & MAGIC_CHECK)
2521 file_regerror(&rx, rc, ms);
2530 if (m->reln != 'x') {
2533 m->value.f = strtof(*p, &ep);
2535 m->value.f = (float)strtod(*p, &ep);
2543 if (m->reln != 'x') {
2545 m->value.d = strtod(*p, &ep);
2550 if (m->reln != 'x') {
2552 m->value.q = file_signextend(ms, m,
2553 (uint64_t)strtoull(*p, &ep, 0));
2562 * Convert a string containing C character escapes. Stop at an unescaped
2564 * Copy the converted version to "m->value.s", and the length in m->vallen.
2565 * Return updated scan pointer as function result. Warn if set.
2567 private const char *
2568 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
2570 const char *origs = s;
2571 char *p = m->value.s;
2572 size_t plen = sizeof(m->value.s);
2574 char *pmax = p + plen - 1;
2578 while ((c = *s++) != '\0') {
2579 if (isspace((unsigned char) c))
2582 file_error(ms, 0, "string too long: `%s'", origs);
2590 file_magwarn(ms, "incomplete escape");
2596 "escaped tab found, use \\t instead");
2597 warn = 0; /* already did */
2602 if (isprint((unsigned char)c)) {
2603 /* Allow escaping of
2605 if (strchr("<>&^=!", c) == NULL
2606 && (m->type != FILE_REGEX ||
2607 strchr("[]().*?^$|{}", c)
2609 file_magwarn(ms, "no "
2615 "unknown escape sequence: "
2620 /* space, perhaps force people to use \040? */
2624 * Other things people escape, but shouldn't need to,
2625 * so we disallow them
2638 /* and baskslash itself */
2671 /* \ and up to 3 octal digits */
2681 c = *s++; /* try for 2 */
2682 if (c >= '0' && c <= '7') {
2683 val = (val << 3) | (c - '0');
2684 c = *s++; /* try for 3 */
2685 if (c >= '0' && c <= '7')
2686 val = (val << 3) | (c-'0');
2695 /* \x and up to 2 hex digits */
2697 val = 'x'; /* Default if no digits */
2698 c = hextoint(*s++); /* Get next char */
2703 val = (val << 4) + c;
2716 m->vallen = CAST(unsigned char, (p - origp));
2717 if (m->type == FILE_PSTRING)
2718 m->vallen += (unsigned char)file_pstring_length_size(m);
2723 /* Single hex char to int; -1 if not a hex char. */
2727 if (!isascii((unsigned char) c))
2729 if (isdigit((unsigned char) c))
2731 if ((c >= 'a') && (c <= 'f'))
2732 return c + 10 - 'a';
2733 if (( c>= 'A') && (c <= 'F'))
2734 return c + 10 - 'A';
2740 * Print a string containing C character escapes.
2743 file_showstr(FILE *fp, const char *s, size_t len)
2758 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
2759 (void) fputc(c, fp);
2761 (void) fputc('\\', fp);
2764 (void) fputc('a', fp);
2768 (void) fputc('b', fp);
2772 (void) fputc('f', fp);
2776 (void) fputc('n', fp);
2780 (void) fputc('r', fp);
2784 (void) fputc('t', fp);
2788 (void) fputc('v', fp);
2792 (void) fprintf(fp, "%.3o", c & 0377);
2800 * eatsize(): Eat the size spec from a number [eg. 10UL]
2803 eatsize(const char **p)
2807 if (LOWCASE(*l) == 'u')
2810 switch (LOWCASE(*l)) {
2811 case 'l': /* long */
2812 case 's': /* short */
2813 case 'h': /* short */
2814 case 'b': /* char/byte */
2815 case 'c': /* char/byte */
2826 * handle a buffer containing a compiled file.
2828 private struct magic_map *
2829 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len)
2831 struct magic_map *map;
2833 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2834 file_oomem(ms, sizeof(*map));
2839 map->type = MAP_TYPE_USER;
2840 if (check_buffer(ms, map, "buffer") != 0) {
2841 apprentice_unmap(map);
2848 * handle a compiled file.
2851 private struct magic_map *
2852 apprentice_map(struct magic_set *ms, const char *fn)
2856 char *dbname = NULL;
2857 struct magic_map *map;
2860 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) {
2861 file_oomem(ms, sizeof(*map));
2865 dbname = mkdbname(ms, fn, 0);
2869 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2872 if (fstat(fd, &st) == -1) {
2873 file_error(ms, errno, "cannot stat `%s'", dbname);
2876 if (st.st_size < 8 || st.st_size > MAXMAGIC_SIZE) {
2877 file_error(ms, 0, "file `%s' is too %s", dbname,
2878 st.st_size < 8 ? "small" : "large");
2882 map->len = (size_t)st.st_size;
2884 if ((map->p = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2885 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2886 file_error(ms, errno, "cannot map `%s'", dbname);
2889 map->type = MAP_TYPE_MMAP;
2891 if ((map->p = CAST(void *, malloc(map->len))) == NULL) {
2892 file_oomem(ms, map->len);
2895 if (read(fd, map->p, map->len) != (ssize_t)map->len) {
2899 map->type = MAP_TYPE_MALLOC;
2905 if (check_buffer(ms, map, dbname) != 0)
2914 apprentice_unmap(map);
2920 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname)
2923 uint32_t entries, nentries;
2925 int i, needsbyteswap;
2927 ptr = CAST(uint32_t *, map->p);
2928 if (*ptr != MAGICNO) {
2929 if (swap4(*ptr) != MAGICNO) {
2930 file_error(ms, 0, "bad magic in `%s'", dbname);
2937 version = swap4(ptr[1]);
2940 if (version != VERSIONNO) {
2941 file_error(ms, 0, "File %s supports only version %d magic "
2942 "files. `%s' is version %d", VERSION,
2943 VERSIONNO, dbname, version);
2946 entries = (uint32_t)(map->len / sizeof(struct magic));
2947 if ((entries * sizeof(struct magic)) != map->len) {
2948 file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not "
2949 "a multiple of %" SIZE_T_FORMAT "u",
2950 dbname, map->len, sizeof(struct magic));
2953 map->magic[0] = CAST(struct magic *, map->p) + 1;
2955 for (i = 0; i < MAGIC_SETS; i++) {
2957 map->nmagic[i] = swap4(ptr[i + 2]);
2959 map->nmagic[i] = ptr[i + 2];
2960 if (i != MAGIC_SETS - 1)
2961 map->magic[i + 1] = map->magic[i] + map->nmagic[i];
2962 nentries += map->nmagic[i];
2964 if (entries != nentries + 1) {
2965 file_error(ms, 0, "Inconsistent entries in `%s' %u != %u",
2966 dbname, entries, nentries + 1);
2970 for (i = 0; i < MAGIC_SETS; i++)
2971 byteswap(map->magic[i], map->nmagic[i]);
2976 * handle an mmaped file.
2979 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn)
2981 static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS;
2982 static const size_t m = sizeof(**map->magic);
2990 uint32_t h[2 + MAGIC_SETS];
2993 dbname = mkdbname(ms, fn, 1);
2998 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1)
3000 file_error(ms, errno, "cannot open `%s'", dbname);
3003 memset(&hdr, 0, sizeof(hdr));
3005 hdr.h[1] = VERSIONNO;
3006 memcpy(hdr.h + 2, map->nmagic, nm);
3008 if (write(fd, &hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) {
3009 file_error(ms, errno, "error writing `%s'", dbname);
3013 for (i = 0; i < MAGIC_SETS; i++) {
3014 len = m * map->nmagic[i];
3015 if (write(fd, map->magic[i], len) != (ssize_t)len) {
3016 file_error(ms, errno, "error writing `%s'", dbname);
3029 private const char ext[] = ".mgc";
3034 mkdbname(struct magic_set *ms, const char *fn, int strip)
3040 if ((p = strrchr(fn, '/')) != NULL)
3044 for (q = fn; *q; q++)
3047 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
3051 /* Did not find .mgc, restore q */
3057 /* Compatibility with old code that looked in .mime */
3058 if (ms->flags & MAGIC_MIME) {
3059 if (asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext) < 0)
3061 if (access(buf, R_OK) != -1) {
3062 ms->flags &= MAGIC_MIME_TYPE;
3067 if (asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext) < 0)
3070 /* Compatibility with old code that looked in .mime */
3071 if (strstr(p, ".mime") != NULL)
3072 ms->flags &= MAGIC_MIME_TYPE;
3077 * Byteswap an mmap'ed file if needed
3080 byteswap(struct magic *magic, uint32_t nmagic)
3083 for (i = 0; i < nmagic; i++)
3094 uint8_t *s = (uint8_t *)(void *)&sv;
3095 uint8_t *d = (uint8_t *)(void *)&rv;
3108 uint8_t *s = (uint8_t *)(void *)&sv;
3109 uint8_t *d = (uint8_t *)(void *)&rv;
3124 uint8_t *s = (uint8_t *)(void *)&sv;
3125 uint8_t *d = (uint8_t *)(void *)&rv;
3149 * byteswap a single magic entry
3152 bs1(struct magic *m)
3154 m->cont_level = swap2(m->cont_level);
3155 m->offset = swap4((uint32_t)m->offset);
3156 m->in_offset = swap4((uint32_t)m->in_offset);
3157 m->lineno = swap4((uint32_t)m->lineno);
3158 if (IS_STRING(m->type)) {
3159 m->str_range = swap4(m->str_range);
3160 m->str_flags = swap4(m->str_flags);
3163 m->value.q = swap8(m->value.q);
3164 m->num_mask = swap8(m->num_mask);
3169 file_pstring_length_size(const struct magic *m)
3171 switch (m->str_flags & PSTRING_LEN) {
3181 abort(); /* Impossible */
3186 file_pstring_get_length(const struct magic *m, const char *s)
3190 switch (m->str_flags & PSTRING_LEN) {
3195 len = (s[1] << 8) | s[0];
3198 len = (s[0] << 8) | s[1];
3201 len = (s[3] << 24) | (s[2] << 16) | (s[1] << 8) | s[0];
3204 len = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
3207 abort(); /* Impossible */
3210 if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF)
3211 len -= file_pstring_length_size(m);
3217 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v)
3220 struct mlist *mlist, *ml;
3222 mlist = ms->mlist[1];
3224 for (ml = mlist->next; ml != mlist; ml = ml->next) {
3225 struct magic *ma = ml->magic;
3226 uint32_t nma = ml->nmagic;
3227 for (i = 0; i < nma; i++) {
3228 if (ma[i].type != FILE_NAME)
3230 if (strcmp(ma[i].value.s, name) == 0) {
3232 for (j = i + 1; j < nma; j++)
3233 if (ma[j].cont_level == 0)