2 * Copyright (c) Ian F. Darwin 1986-1995.
3 * Software written by Ian F. Darwin and others;
4 * maintained 1995-present by Christos Zoulas and others.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice immediately at the beginning of the file, without modification,
11 * this list of conditions, and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * apprentice - make one pass through /etc/magic, learning its secrets.
35 FILE_RCSID("@(#)$File: apprentice.c,v 1.158 2009/10/19 13:10:20 christos Exp $")
39 #include "patchlevel.h"
53 #define EATAB {while (isascii((unsigned char) *l) && \
54 isspace((unsigned char) *l)) ++l;}
55 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
56 tolower((unsigned char) (l)) : (l))
58 * Work around a bug in headers on Digital Unix.
59 * At least confirmed for: OSF1 V4.0 878
61 #if defined(__osf__) && defined(__DECC)
68 #define MAP_FAILED (void *) -1
76 #define MAXPATHLEN 1024
85 int file_formats[FILE_NAMES_SIZE];
86 const size_t file_nformats = FILE_NAMES_SIZE;
87 const char *file_names[FILE_NAMES_SIZE];
88 const size_t file_nnames = FILE_NAMES_SIZE;
90 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
91 private int hextoint(int);
92 private const char *getstr(struct magic_set *, struct magic *, const char *,
94 private int parse(struct magic_set *, struct magic_entry **, uint32_t *,
95 const char *, size_t, int);
96 private void eatsize(const char **);
97 private int apprentice_1(struct magic_set *, const char *, int, struct mlist *);
98 private size_t apprentice_magic_strength(const struct magic *);
99 private int apprentice_sort(const void *, const void *);
100 private int apprentice_load(struct magic_set *, struct magic **, uint32_t *,
102 private void byteswap(struct magic *, uint32_t);
103 private void bs1(struct magic *);
104 private uint16_t swap2(uint16_t);
105 private uint32_t swap4(uint32_t);
106 private uint64_t swap8(uint64_t);
107 private char *mkdbname(struct magic_set *, const char *, int);
108 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
110 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
112 private int check_format_type(const char *, int);
113 private int check_format(struct magic_set *, struct magic *);
114 private int get_op(char);
115 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
116 private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
117 private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
120 private size_t maxmagic = 0;
121 private size_t magicsize = sizeof(struct magic);
123 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
128 int (*fun)(struct magic_set *, struct magic_entry *, const char *);
130 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
132 DECLARE_FIELD(apple),
133 DECLARE_FIELD(strength),
140 int main(int, char *[]);
143 main(int argc, char *argv[])
146 struct magic_set *ms;
149 if ((progname = strrchr(argv[0], '/')) != NULL)
155 (void)fprintf(stderr, "Usage: %s file\n", progname);
159 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
160 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
163 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
165 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
169 #endif /* COMPILE_ONLY */
171 static const struct type_tbl_s {
177 # define XX(s) s, (sizeof(s) - 1)
178 # define XX_NULL "", 0
179 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
180 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
181 { XX("default"), FILE_DEFAULT, FILE_FMT_STR },
182 { XX("long"), FILE_LONG, FILE_FMT_NUM },
183 { XX("string"), FILE_STRING, FILE_FMT_STR },
184 { XX("date"), FILE_DATE, FILE_FMT_STR },
185 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
186 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
187 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
188 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
189 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
190 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
191 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
192 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
193 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
194 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
195 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
196 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
197 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
198 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
199 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
200 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
201 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
202 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
203 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
204 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
205 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
206 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
207 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
208 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
209 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
210 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
211 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
212 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
213 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
214 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
215 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
216 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
217 { XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
218 { XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
219 { XX("indirect"), FILE_INDIRECT, FILE_FMT_NONE },
220 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
226 get_type(const char *l, const char **t)
228 const struct type_tbl_s *p;
230 for (p = type_tbl; p->len; p++) {
231 if (strncmp(l, p->name, p->len) == 0) {
241 init_file_tables(void)
244 const struct type_tbl_s *p;
250 for (p = type_tbl; p->len; p++) {
251 assert(p->type < FILE_NAMES_SIZE);
252 file_names[p->type] = p->name;
253 file_formats[p->type] = p->format;
258 * Handle one file or directory.
261 apprentice_1(struct magic_set *ms, const char *fn, int action,
264 struct magic *magic = NULL;
270 if (magicsize != FILE_MAGICSIZE) {
271 file_error(ms, 0, "magic element size %lu != %lu",
272 (unsigned long)sizeof(*magic),
273 (unsigned long)FILE_MAGICSIZE);
277 if (action == FILE_COMPILE) {
278 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
281 rv = apprentice_compile(ms, &magic, &nmagic, fn);
287 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
288 if (ms->flags & MAGIC_CHECK)
289 file_magwarn(ms, "using regular magic file `%s'", fn);
290 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
298 file_delmagic(magic, mapped, nmagic);
302 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL) {
303 file_delmagic(magic, mapped, nmagic);
304 file_oomem(ms, sizeof(*ml));
312 mlist->prev->next = ml;
313 ml->prev = mlist->prev;
318 #endif /* COMPILE_ONLY */
322 file_delmagic(struct magic *p, int type, size_t entries)
330 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
348 /* const char *fn: list of magic files and directories */
349 protected struct mlist *
350 file_apprentice(struct magic_set *ms, const char *fn, int action)
353 int file_err, errs = -1;
356 if ((fn = magic_getpath(fn, action)) == NULL)
361 if ((mfn = strdup(fn)) == NULL) {
362 file_oomem(ms, strlen(fn));
367 if ((mlist = CAST(struct mlist *, malloc(sizeof(*mlist)))) == NULL) {
369 file_oomem(ms, sizeof(*mlist));
372 mlist->next = mlist->prev = mlist;
375 p = strchr(fn, PATHSEP);
380 file_err = apprentice_1(ms, fn, action, mlist);
381 errs = MAX(errs, file_err);
388 file_error(ms, 0, "could not find any magic files!");
396 * Get weight of this magic entry, for sorting purposes.
399 apprentice_magic_strength(const struct magic *m)
402 size_t val = 2 * MULT; /* baseline strength */
405 case FILE_DEFAULT: /* make sure this sorts last */
406 if (m->factor_op != FILE_FACTOR_OP_NONE)
429 val += m->vallen * MULT;
432 case FILE_BESTRING16:
433 case FILE_LESTRING16:
434 val += m->vallen * MULT / 2;
439 val += m->vallen * MAX(MULT / m->vallen, 1);
473 (void)fprintf(stderr, "Bad type %d\n", m->type);
478 case 'x': /* matches anything penalize */
479 case '!': /* matches almost anything penalize */
483 case '=': /* Exact match, prefer */
488 case '<': /* comparison match reduce strength */
493 case '&': /* masking bits, we could count them too */
498 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
502 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
505 switch (m->factor_op) {
506 case FILE_FACTOR_OP_NONE:
508 case FILE_FACTOR_OP_PLUS:
511 case FILE_FACTOR_OP_MINUS:
514 case FILE_FACTOR_OP_TIMES:
517 case FILE_FACTOR_OP_DIV:
525 * Magic entries with no description get a bonus because they depend
526 * on subsequent magic entries to print something.
528 if (m->desc[0] == '\0')
534 * Sort callback for sorting entries by "strength" (basically length)
537 apprentice_sort(const void *a, const void *b)
539 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
540 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
541 size_t sa = apprentice_magic_strength(ma->mp);
542 size_t sb = apprentice_magic_strength(mb->mp);
552 set_test_type(struct magic *mstart, struct magic *m)
588 case FILE_BESTRING16:
589 case FILE_LESTRING16:
590 /* binary test, set flag */
591 mstart->flag |= BINTEST;
595 /* Check for override */
596 if (mstart->str_flags & STRING_BINTEST)
597 mstart->flag |= BINTEST;
598 if (mstart->str_flags & STRING_TEXTTEST)
599 mstart->flag |= TEXTTEST;
601 if (mstart->flag & (TEXTTEST|BINTEST))
604 /* binary test if pattern is not text */
605 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
607 mstart->flag |= BINTEST;
609 mstart->flag |= TEXTTEST;
612 /* can't deduce anything; we shouldn't see this at the
617 /* invalid search type, but no need to complain here */
623 * Load and parse one file.
626 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
627 struct magic_entry **marray, uint32_t *marraycount)
631 FILE *f = fopen(ms->file = fn, "r");
634 file_error(ms, errno, "cannot read magic file `%s'",
638 /* read and parse this file */
640 fgets(line, CAST(int, sizeof(line)), f) != NULL;
644 if (len == 0) /* null line, garbage, etc */
646 if (line[len - 1] == '\n') {
648 line[len - 1] = '\0'; /* delete newline */
650 if (line[0] == '\0') /* empty, do not parse */
652 if (line[0] == '#') /* comment, do not parse */
654 if (line[0] == '!' && line[1] == ':') {
657 for (i = 0; bang[i].name != NULL; i++) {
658 if (len - 2 > bang[i].len &&
659 memcmp(bang[i].name, line + 2,
663 if (bang[i].name == NULL) {
665 "Unknown !: entry `%s'", line);
669 if (*marraycount == 0) {
671 "No current entry for :!%s type",
676 if ((*bang[i].fun)(ms,
677 &(*marray)[*marraycount - 1],
678 line + bang[i].len + 2) != 0) {
684 if (parse(ms, marray, marraycount, line, lineno,
694 * parse a file or directory of files
695 * const char *fn: name of magic file or directory
698 cmpstrp(const void *p1, const void *p2)
700 return strcmp(*(char *const *)p1, *(char *const *)p2);
704 apprentice_load(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
705 const char *fn, int action)
708 struct magic_entry *marray;
709 uint32_t marraycount, i, mentrycount = 0, starttest;
710 size_t slen, files = 0, maxfiles = 0;
711 char subfn[MAXPATHLEN], **filearr = NULL, *mfn;
716 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
719 if ((marray = CAST(struct magic_entry *, calloc(maxmagic,
720 sizeof(*marray)))) == NULL) {
721 file_oomem(ms, maxmagic * sizeof(*marray));
726 /* print silly verbose header for USG compat. */
727 if (action == FILE_CHECK)
728 (void)fprintf(stderr, "%s\n", usg_hdr);
730 /* load directory or file */
731 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
737 while ((d = readdir(dir)) != NULL) {
738 (void)snprintf(subfn, sizeof(subfn), "%s/%s",
740 if (stat(subfn, &st) == -1 || !S_ISREG(st.st_mode))
742 if ((mfn = strdup(subfn)) == NULL) {
743 file_oomem(ms, strlen(subfn));
747 if (files >= maxfiles) {
749 maxfiles = (maxfiles + 1) * 2;
750 mlen = maxfiles * sizeof(*filearr);
751 if ((filearr = CAST(char **,
752 realloc(filearr, mlen))) == NULL) {
753 file_oomem(ms, mlen);
758 filearr[files++] = mfn;
761 qsort(filearr, files, sizeof(*filearr), cmpstrp);
762 for (i = 0; i < files; i++) {
763 load_1(ms, action, filearr[i], &errs, &marray,
769 load_1(ms, action, fn, &errs, &marray, &marraycount);
773 /* Set types of tests */
774 for (i = 0; i < marraycount; ) {
775 if (marray[i].mp->cont_level != 0) {
782 static const char text[] = "text";
783 static const char binary[] = "binary";
784 static const size_t len = sizeof(text);
785 set_test_type(marray[starttest].mp, marray[i].mp);
786 if ((ms->flags & MAGIC_DEBUG) == 0)
788 (void)fprintf(stderr, "%s%s%s: %s\n",
789 marray[i].mp->mimetype,
790 marray[i].mp->mimetype[0] == '\0' ? "" : "; ",
791 marray[i].mp->desc[0] ? marray[i].mp->desc :
793 marray[i].mp->flag & BINTEST ? binary : text);
794 if (marray[i].mp->flag & BINTEST) {
795 char *p = strstr(marray[i].mp->desc, text);
796 if (p && (p == marray[i].mp->desc ||
797 isspace((unsigned char)p[-1])) &&
798 (p + len - marray[i].mp->desc ==
799 MAXstring || (p[len] == '\0' ||
800 isspace((unsigned char)p[len]))))
801 (void)fprintf(stderr, "*** Possible "
802 "binary test for text type\n");
804 } while (++i < marraycount && marray[i].mp->cont_level != 0);
807 qsort(marray, marraycount, sizeof(*marray), apprentice_sort);
810 * Make sure that any level 0 "default" line is last (if one exists).
812 for (i = 0; i < marraycount; i++) {
813 if (marray[i].mp->cont_level == 0 &&
814 marray[i].mp->type == FILE_DEFAULT) {
815 while (++i < marraycount)
816 if (marray[i].mp->cont_level == 0)
818 if (i != marraycount) {
819 ms->line = marray[i].mp->lineno; /* XXX - Ugh! */
821 "level 0 \"default\" did not sort last");
827 for (i = 0; i < marraycount; i++)
828 mentrycount += marray[i].cont_count;
830 slen = sizeof(**magicp) * mentrycount;
831 if ((*magicp = CAST(struct magic *, malloc(slen))) == NULL) {
832 file_oomem(ms, slen);
838 for (i = 0; i < marraycount; i++) {
839 (void)memcpy(*magicp + mentrycount, marray[i].mp,
840 marray[i].cont_count * sizeof(**magicp));
841 mentrycount += marray[i].cont_count;
844 for (i = 0; i < marraycount; i++)
852 *nmagicp = mentrycount;
859 * extend the sign bit if the comparison is to be signed
862 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
864 if (!(m->flag & UNSIGNED)) {
867 * Do not remove the casts below. They are
868 * vital. When later compared with the data,
869 * the sign extension must have happened.
912 case FILE_BESTRING16:
913 case FILE_LESTRING16:
920 if (ms->flags & MAGIC_CHECK)
921 file_magwarn(ms, "cannot happen: m->type=%d\n",
930 string_modifier_check(struct magic_set *ms, struct magic *m)
932 if ((ms->flags & MAGIC_CHECK) == 0)
936 case FILE_BESTRING16:
937 case FILE_LESTRING16:
938 if (m->str_flags != 0) {
940 "no modifiers allowed for 16-bit strings\n");
946 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
948 "'/%c' only allowed on regex and search\n",
949 CHAR_REGEX_OFFSET_START);
954 if (m->str_range == 0) {
956 "missing range; defaulting to %d\n",
957 STRING_DEFAULT_RANGE);
958 m->str_range = STRING_DEFAULT_RANGE;
963 if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) {
964 file_magwarn(ms, "'/%c' not allowed on regex\n",
965 CHAR_COMPACT_WHITESPACE);
968 if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) {
969 file_magwarn(ms, "'/%c' not allowed on regex\n",
970 CHAR_COMPACT_OPTIONAL_WHITESPACE);
975 file_magwarn(ms, "coding error: m->type=%d\n",
997 return FILE_OPMULTIPLY;
999 return FILE_OPDIVIDE;
1001 return FILE_OPMODULO;
1007 #ifdef ENABLE_CONDITIONALS
1009 get_cond(const char *l, const char **t)
1011 static const struct cond_tbl_s {
1016 { "if", 2, COND_IF },
1017 { "elif", 4, COND_ELIF },
1018 { "else", 4, COND_ELSE },
1019 { "", 0, COND_NONE },
1021 const struct cond_tbl_s *p;
1023 for (p = cond_tbl; p->len; p++) {
1024 if (strncmp(l, p->name, p->len) == 0 &&
1025 isspace((unsigned char)l[p->len])) {
1035 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1038 last_cond = ms->c.li[cont_level].last_cond;
1042 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1043 if (ms->flags & MAGIC_CHECK)
1044 file_magwarn(ms, "syntax error: `if'");
1047 last_cond = COND_IF;
1051 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1052 if (ms->flags & MAGIC_CHECK)
1053 file_magwarn(ms, "syntax error: `elif'");
1056 last_cond = COND_ELIF;
1060 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1061 if (ms->flags & MAGIC_CHECK)
1062 file_magwarn(ms, "syntax error: `else'");
1065 last_cond = COND_NONE;
1069 last_cond = COND_NONE;
1073 ms->c.li[cont_level].last_cond = last_cond;
1076 #endif /* ENABLE_CONDITIONALS */
1079 * parse one line from magic file, put into magic[index++] if valid
1082 parse(struct magic_set *ms, struct magic_entry **mentryp, uint32_t *nmentryp,
1083 const char *line, size_t lineno, int action)
1085 #ifdef ENABLE_CONDITIONALS
1086 static uint32_t last_cont_level = 0;
1089 struct magic_entry *me;
1091 const char *l = line;
1094 uint32_t cont_level;
1099 ++l; /* step over */
1102 #ifdef ENABLE_CONDITIONALS
1103 if (cont_level == 0 || cont_level > last_cont_level)
1104 if (file_check_mem(ms, cont_level) == -1)
1106 last_cont_level = cont_level;
1109 #define ALLOC_CHUNK (size_t)10
1110 #define ALLOC_INCR (size_t)200
1112 if (cont_level != 0) {
1113 if (*nmentryp == 0) {
1114 file_error(ms, 0, "No current entry for continuation");
1117 me = &(*mentryp)[*nmentryp - 1];
1118 if (me->cont_count == me->max_count) {
1120 size_t cnt = me->max_count + ALLOC_CHUNK;
1121 if ((nm = CAST(struct magic *, realloc(me->mp,
1122 sizeof(*nm) * cnt))) == NULL) {
1123 file_oomem(ms, sizeof(*nm) * cnt);
1127 me->max_count = CAST(uint32_t, cnt);
1129 m = &me->mp[me->cont_count++];
1130 (void)memset(m, 0, sizeof(*m));
1131 m->cont_level = cont_level;
1133 if (*nmentryp == maxmagic) {
1134 struct magic_entry *mp;
1136 maxmagic += ALLOC_INCR;
1137 if ((mp = CAST(struct magic_entry *,
1138 realloc(*mentryp, sizeof(*mp) * maxmagic))) ==
1140 file_oomem(ms, sizeof(*mp) * maxmagic);
1143 (void)memset(&mp[*nmentryp], 0, sizeof(*mp) *
1147 me = &(*mentryp)[*nmentryp];
1148 if (me->mp == NULL) {
1149 size_t len = sizeof(*m) * ALLOC_CHUNK;
1150 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1151 file_oomem(ms, len);
1155 me->max_count = ALLOC_CHUNK;
1158 (void)memset(m, 0, sizeof(*m));
1159 m->factor_op = FILE_FACTOR_OP_NONE;
1163 m->lineno = CAST(uint32_t, lineno);
1165 if (*l == '&') { /* m->cont_level == 0 checked below. */
1166 ++l; /* step over */
1170 ++l; /* step over */
1172 if (m->flag & OFFADD)
1173 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1175 if (*l == '&') { /* m->cont_level == 0 checked below */
1176 ++l; /* step over */
1180 /* Indirect offsets are not valid at level 0. */
1181 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
1182 if (ms->flags & MAGIC_CHECK)
1183 file_magwarn(ms, "relative offset at level 0");
1185 /* get offset, then skip over it */
1186 m->offset = (uint32_t)strtoul(l, &t, 0);
1188 if (ms->flags & MAGIC_CHECK)
1189 file_magwarn(ms, "offset `%s' invalid", l);
1192 if (m->flag & INDIR) {
1193 m->in_type = FILE_LONG;
1196 * read [.lbs][+-]nnnnn)
1202 m->in_type = FILE_LELONG;
1205 m->in_type = FILE_BELONG;
1208 m->in_type = FILE_MELONG;
1212 m->in_type = FILE_LESHORT;
1216 m->in_type = FILE_BESHORT;
1222 m->in_type = FILE_BYTE;
1227 m->in_type = FILE_LEDOUBLE;
1232 m->in_type = FILE_BEDOUBLE;
1235 m->in_type = FILE_LEID3;
1238 m->in_type = FILE_BEID3;
1241 if (ms->flags & MAGIC_CHECK)
1243 "indirect offset type `%c' invalid",
1252 m->in_op |= FILE_OPINVERSE;
1255 if ((op = get_op(*l)) != -1) {
1260 m->in_op |= FILE_OPINDIRECT;
1263 if (isdigit((unsigned char)*l) || *l == '-') {
1264 m->in_offset = (int32_t)strtol(l, &t, 0);
1266 if (ms->flags & MAGIC_CHECK)
1268 "in_offset `%s' invalid", l);
1272 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
1273 if (ms->flags & MAGIC_CHECK)
1275 "missing ')' in indirect offset");
1279 #ifdef ENABLE_CONDITIONALS
1280 m->cond = get_cond(l, &l);
1281 if (check_cond(ms, m->cond, cont_level) == -1)
1289 m->flag |= UNSIGNED;
1292 m->type = get_type(l, &l);
1293 if (m->type == FILE_INVALID) {
1294 if (ms->flags & MAGIC_CHECK)
1295 file_magwarn(ms, "type `%s' invalid", l);
1299 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1300 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1304 if (!IS_STRING(m->type))
1305 m->mask_op |= FILE_OPINVERSE;
1306 else if (ms->flags & MAGIC_CHECK)
1307 file_magwarn(ms, "'~' invalid for string types");
1313 if ((op = get_op(*l)) != -1) {
1314 if (!IS_STRING(m->type)) {
1318 val = (uint64_t)strtoull(l, &t, 0);
1320 m->num_mask = file_signextend(ms, m, val);
1323 else if (op == FILE_OPDIVIDE) {
1325 while (!isspace((unsigned char)*++l)) {
1327 case '0': case '1': case '2':
1328 case '3': case '4': case '5':
1329 case '6': case '7': case '8':
1332 (ms->flags & MAGIC_CHECK))
1336 m->str_range = CAST(uint32_t,
1338 if (m->str_range == 0)
1343 case CHAR_COMPACT_WHITESPACE:
1344 m->str_flags |= STRING_COMPACT_WHITESPACE;
1346 case CHAR_COMPACT_OPTIONAL_WHITESPACE:
1348 STRING_COMPACT_OPTIONAL_WHITESPACE;
1350 case CHAR_IGNORE_LOWERCASE:
1351 m->str_flags |= STRING_IGNORE_LOWERCASE;
1353 case CHAR_IGNORE_UPPERCASE:
1354 m->str_flags |= STRING_IGNORE_UPPERCASE;
1356 case CHAR_REGEX_OFFSET_START:
1357 m->str_flags |= REGEX_OFFSET_START;
1360 m->str_flags |= STRING_BINTEST;
1363 m->str_flags |= STRING_TEXTTEST;
1366 if (ms->flags & MAGIC_CHECK)
1368 "string extension `%c' invalid",
1372 /* allow multiple '/' for readability */
1374 !isspace((unsigned char)l[2]))
1377 if (string_modifier_check(ms, m) == -1)
1381 if (ms->flags & MAGIC_CHECK)
1382 file_magwarn(ms, "invalid string op: %c", *t);
1387 * We used to set mask to all 1's here, instead let's just not do
1388 * anything if mask = 0 (unless you have a better idea)
1398 if (ms->flags & MAGIC_CHECK) {
1399 file_magwarn(ms, "%c= not supported",
1406 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1413 /* HP compat: ignore &= etc. */
1422 m->reln = '='; /* the default relation */
1423 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
1424 isspace((unsigned char)l[1])) || !l[1])) {
1431 * Grab the value part, except for an 'x' reln.
1433 if (m->reln != 'x' && getvalue(ms, m, &l, action))
1437 * TODO finish this macro and start using it!
1438 * #define offsetcheck {if (offset > HOWMANY-1)
1439 * magwarn("offset too big"); }
1443 * Now get last part - the description
1449 } else if ((l[0] == '\\') && (l[1] == 'b')) {
1454 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
1456 if (i == sizeof(m->desc)) {
1457 m->desc[sizeof(m->desc) - 1] = '\0';
1458 if (ms->flags & MAGIC_CHECK)
1459 file_magwarn(ms, "description `%s' truncated", m->desc);
1463 * We only do this check while compiling, or if any of the magic
1464 * files were not compiled.
1466 if (ms->flags & MAGIC_CHECK) {
1467 if (check_format(ms, m) == -1)
1470 #ifndef COMPILE_ONLY
1471 if (action == FILE_CHECK) {
1475 m->mimetype[0] = '\0'; /* initialise MIME type to none */
1476 if (m->cont_level == 0)
1477 ++(*nmentryp); /* make room for next */
1482 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
1486 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
1488 const char *l = line;
1490 unsigned long factor;
1491 struct magic *m = &me->mp[0];
1493 if (m->factor_op != FILE_FACTOR_OP_NONE) {
1495 "Current entry already has a strength type: %c %d",
1496 m->factor_op, m->factor);
1501 case FILE_FACTOR_OP_NONE:
1502 case FILE_FACTOR_OP_PLUS:
1503 case FILE_FACTOR_OP_MINUS:
1504 case FILE_FACTOR_OP_TIMES:
1505 case FILE_FACTOR_OP_DIV:
1506 m->factor_op = *l++;
1509 file_magwarn(ms, "Unknown factor op `%c'", *l);
1513 factor = strtoul(l, &el, 0);
1515 file_magwarn(ms, "Too large factor `%lu'", factor);
1518 if (*el && !isspace((unsigned char)*el)) {
1519 file_magwarn(ms, "Bad factor `%s'", l);
1522 m->factor = (uint8_t)factor;
1523 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
1524 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
1525 m->factor_op, m->factor);
1530 m->factor_op = FILE_FACTOR_OP_NONE;
1536 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into magic[index - 1]
1539 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
1542 const char *l = line;
1543 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1545 if (m->apple[0] != '\0') {
1546 file_magwarn(ms, "Current entry already has a APPLE type `%.8s',"
1547 " new type `%s'", m->mimetype, l);
1552 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1553 || strchr("-+/.", *l)) && i < sizeof(m->apple); m->apple[i++] = *l++)
1555 if (i == sizeof(m->apple) && *l) {
1556 /* We don't need to NUL terminate here, printing handles it */
1557 if (ms->flags & MAGIC_CHECK)
1558 file_magwarn(ms, "APPLE type `%s' truncated %zu",
1569 * parse a MIME annotation line from magic file, put into magic[index - 1]
1573 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
1576 const char *l = line;
1577 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1579 if (m->mimetype[0] != '\0') {
1580 file_magwarn(ms, "Current entry already has a MIME type `%s',"
1581 " new type `%s'", m->mimetype, l);
1586 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1587 || strchr("-+/.", *l)) && i < sizeof(m->mimetype); m->mimetype[i++] = *l++)
1589 if (i == sizeof(m->mimetype)) {
1590 m->mimetype[sizeof(m->mimetype) - 1] = '\0';
1591 if (ms->flags & MAGIC_CHECK)
1592 file_magwarn(ms, "MIME type `%s' truncated %zu",
1595 m->mimetype[i] = '\0';
1604 check_format_type(const char *ptr, int type)
1608 /* Missing format string; bad */
1621 while (isdigit((unsigned char)*ptr)) ptr++;
1624 while (isdigit((unsigned char)*ptr)) ptr++;
1676 case FILE_FMT_FLOAT:
1677 case FILE_FMT_DOUBLE:
1682 while (isdigit((unsigned char)*ptr)) ptr++;
1685 while (isdigit((unsigned char)*ptr)) ptr++;
1704 while (isdigit((unsigned char )*ptr))
1708 while (isdigit((unsigned char )*ptr))
1720 /* internal error */
1728 * Check that the optional printf format in description matches
1729 * the type of the magic.
1732 check_format(struct magic_set *ms, struct magic *m)
1736 for (ptr = m->desc; *ptr; ptr++)
1740 /* No format string; ok */
1744 assert(file_nformats == file_nnames);
1746 if (m->type >= file_nformats) {
1747 file_magwarn(ms, "Internal error inconsistency between "
1748 "m->type and format strings");
1751 if (file_formats[m->type] == FILE_FMT_NONE) {
1752 file_magwarn(ms, "No format string for `%s' with description "
1753 "`%s'", m->desc, file_names[m->type]);
1758 if (check_format_type(ptr, file_formats[m->type]) == -1) {
1760 * TODO: this error message is unhelpful if the format
1761 * string is not one character long
1763 file_magwarn(ms, "Printf format `%c' is not valid for type "
1764 "`%s' in description `%s'", *ptr ? *ptr : '?',
1765 file_names[m->type], m->desc);
1769 for (; *ptr; ptr++) {
1772 "Too many format strings (should have at most one) "
1773 "for `%s' with description `%s'",
1774 file_names[m->type], m->desc);
1782 * Read a numeric value from a pointer, into the value union of a magic
1783 * pointer, according to the magic type. Update the string pointer to point
1784 * just after the number read. Return 0 for success, non-zero for failure.
1787 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
1790 case FILE_BESTRING16:
1791 case FILE_LESTRING16:
1796 *p = getstr(ms, m, *p, action == FILE_COMPILE);
1798 if (ms->flags & MAGIC_CHECK)
1799 file_magwarn(ms, "cannot get string from `%s'",
1807 if (m->reln != 'x') {
1810 m->value.f = strtof(*p, &ep);
1812 m->value.f = (float)strtod(*p, &ep);
1820 if (m->reln != 'x') {
1822 m->value.d = strtod(*p, &ep);
1827 if (m->reln != 'x') {
1829 m->value.q = file_signextend(ms, m,
1830 (uint64_t)strtoull(*p, &ep, 0));
1839 * Convert a string containing C character escapes. Stop at an unescaped
1841 * Copy the converted version to "m->value.s", and the length in m->vallen.
1842 * Return updated scan pointer as function result. Warn if set.
1844 private const char *
1845 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
1847 const char *origs = s;
1848 char *p = m->value.s;
1849 size_t plen = sizeof(m->value.s);
1851 char *pmax = p + plen - 1;
1855 while ((c = *s++) != '\0') {
1856 if (isspace((unsigned char) c))
1859 file_error(ms, 0, "string too long: `%s'", origs);
1867 file_magwarn(ms, "incomplete escape");
1873 "escaped tab found, use \\t instead");
1874 warn = 0; /* already did */
1879 if (isprint((unsigned char)c)) {
1880 /* Allow escaping of
1882 if (strchr("<>&^=!", c)
1884 file_magwarn(ms, "no "
1890 "unknown escape sequence: "
1895 /* space, perhaps force people to use \040? */
1899 * Other things people escape, but shouldn't need to,
1900 * so we disallow them
1913 /* and baskslash itself */
1946 /* \ and up to 3 octal digits */
1956 c = *s++; /* try for 2 */
1957 if (c >= '0' && c <= '7') {
1958 val = (val << 3) | (c - '0');
1959 c = *s++; /* try for 3 */
1960 if (c >= '0' && c <= '7')
1961 val = (val << 3) | (c-'0');
1970 /* \x and up to 2 hex digits */
1972 val = 'x'; /* Default if no digits */
1973 c = hextoint(*s++); /* Get next char */
1978 val = (val << 4) + c;
1991 m->vallen = CAST(unsigned char, (p - origp));
1992 if (m->type == FILE_PSTRING)
1998 /* Single hex char to int; -1 if not a hex char. */
2002 if (!isascii((unsigned char) c))
2004 if (isdigit((unsigned char) c))
2006 if ((c >= 'a') && (c <= 'f'))
2007 return c + 10 - 'a';
2008 if (( c>= 'A') && (c <= 'F'))
2009 return c + 10 - 'A';
2015 * Print a string containing C character escapes.
2018 file_showstr(FILE *fp, const char *s, size_t len)
2033 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
2034 (void) fputc(c, fp);
2036 (void) fputc('\\', fp);
2039 (void) fputc('a', fp);
2043 (void) fputc('b', fp);
2047 (void) fputc('f', fp);
2051 (void) fputc('n', fp);
2055 (void) fputc('r', fp);
2059 (void) fputc('t', fp);
2063 (void) fputc('v', fp);
2067 (void) fprintf(fp, "%.3o", c & 0377);
2075 * eatsize(): Eat the size spec from a number [eg. 10UL]
2078 eatsize(const char **p)
2082 if (LOWCASE(*l) == 'u')
2085 switch (LOWCASE(*l)) {
2086 case 'l': /* long */
2087 case 's': /* short */
2088 case 'h': /* short */
2089 case 'b': /* char/byte */
2090 case 'c': /* char/byte */
2101 * handle a compiled file.
2104 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
2112 char *dbname = NULL;
2115 dbname = mkdbname(ms, fn, 0);
2119 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2122 if (fstat(fd, &st) == -1) {
2123 file_error(ms, errno, "cannot stat `%s'", dbname);
2126 if (st.st_size < 8) {
2127 file_error(ms, 0, "file `%s' is too small", dbname);
2132 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2133 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2134 file_error(ms, errno, "cannot map `%s'", dbname);
2139 if ((mm = CAST(void *, malloc((size_t)st.st_size))) == NULL) {
2140 file_oomem(ms, (size_t)st.st_size);
2143 if (read(fd, mm, (size_t)st.st_size) != (ssize_t)st.st_size) {
2149 *magicp = CAST(struct magic *, mm);
2152 ptr = (uint32_t *)(void *)*magicp;
2153 if (*ptr != MAGICNO) {
2154 if (swap4(*ptr) != MAGICNO) {
2155 file_error(ms, 0, "bad magic in `%s'", dbname);
2162 version = swap4(ptr[1]);
2165 if (version != VERSIONNO) {
2166 file_error(ms, 0, "File %d.%d supports only version %d magic "
2167 "files. `%s' is version %d", FILE_VERSION_MAJOR, patchlevel,
2168 VERSIONNO, dbname, version);
2171 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic));
2176 byteswap(*magicp, *nmagicp);
2185 (void)munmap((void *)mm, (size_t)st.st_size);
2198 private const uint32_t ar[] = {
2202 * handle an mmaped file.
2205 apprentice_compile(struct magic_set *ms, struct magic **magicp,
2206 uint32_t *nmagicp, const char *fn)
2212 dbname = mkdbname(ms, fn, 1);
2217 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1) {
2218 file_error(ms, errno, "cannot open `%s'", dbname);
2222 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
2223 file_error(ms, errno, "error writing `%s'", dbname);
2227 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
2228 != sizeof(struct magic)) {
2229 file_error(ms, errno, "error seeking `%s'", dbname);
2233 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
2234 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
2235 file_error(ms, errno, "error writing `%s'", dbname);
2246 private const char ext[] = ".mgc";
2251 mkdbname(struct magic_set *ms, const char *fn, int strip)
2257 if ((p = strrchr(fn, '/')) != NULL)
2261 for (q = fn; *q; q++)
2264 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
2268 /* Did not find .mgc, restore q */
2274 /* Compatibility with old code that looked in .mime */
2275 if (ms->flags & MAGIC_MIME) {
2276 asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext);
2277 if (access(buf, R_OK) != -1) {
2278 ms->flags &= MAGIC_MIME_TYPE;
2283 asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext);
2285 /* Compatibility with old code that looked in .mime */
2286 if (strstr(p, ".mime") != NULL)
2287 ms->flags &= MAGIC_MIME_TYPE;
2292 * Byteswap an mmap'ed file if needed
2295 byteswap(struct magic *magic, uint32_t nmagic)
2298 for (i = 0; i < nmagic; i++)
2309 uint8_t *s = (uint8_t *)(void *)&sv;
2310 uint8_t *d = (uint8_t *)(void *)&rv;
2323 uint8_t *s = (uint8_t *)(void *)&sv;
2324 uint8_t *d = (uint8_t *)(void *)&rv;
2339 uint8_t *s = (uint8_t *)(void *)&sv;
2340 uint8_t *d = (uint8_t *)(void *)&rv;
2364 * byteswap a single magic entry
2367 bs1(struct magic *m)
2369 m->cont_level = swap2(m->cont_level);
2370 m->offset = swap4((uint32_t)m->offset);
2371 m->in_offset = swap4((uint32_t)m->in_offset);
2372 m->lineno = swap4((uint32_t)m->lineno);
2373 if (IS_STRING(m->type)) {
2374 m->str_range = swap4(m->str_range);
2375 m->str_flags = swap4(m->str_flags);
2378 m->value.q = swap8(m->value.q);
2379 m->num_mask = swap8(m->num_mask);