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.151 2009/03/18 15:19:23 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 *,
103 private void byteswap(struct magic *, uint32_t);
104 private void bs1(struct magic *);
105 private uint16_t swap2(uint16_t);
106 private uint32_t swap4(uint32_t);
107 private uint64_t swap8(uint64_t);
109 private char *mkdbname(struct magic_set *, const char *, int);
111 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
114 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
116 private int check_format_type(const char *, int);
117 private int check_format(struct magic_set *, struct magic *);
118 private int get_op(char);
119 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
120 private int parse_strength(struct magic_set *, struct magic_entry *, const char *);
121 private int parse_apple(struct magic_set *, struct magic_entry *, const char *);
124 private size_t maxmagic = 0;
125 private size_t magicsize = sizeof(struct magic);
127 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
132 int (*fun)(struct magic_set *, struct magic_entry *, const char *);
134 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
136 DECLARE_FIELD(apple),
137 DECLARE_FIELD(strength),
144 int main(int, char *[]);
147 main(int argc, char *argv[])
150 struct magic_set *ms;
153 if ((progname = strrchr(argv[0], '/')) != NULL)
159 (void)fprintf(stderr, "Usage: %s file\n", progname);
163 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
164 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
167 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
169 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
173 #endif /* COMPILE_ONLY */
175 static const struct type_tbl_s {
181 # define XX(s) s, (sizeof(s) - 1)
182 # define XX_NULL "", 0
183 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
184 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
185 { XX("default"), FILE_DEFAULT, FILE_FMT_STR },
186 { XX("long"), FILE_LONG, FILE_FMT_NUM },
187 { XX("string"), FILE_STRING, FILE_FMT_STR },
188 { XX("date"), FILE_DATE, FILE_FMT_STR },
189 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
190 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
191 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
192 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
193 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
194 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
195 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
196 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
197 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
198 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
199 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
200 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
201 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
202 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
203 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
204 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
205 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
206 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
207 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
208 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
209 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
210 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
211 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
212 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
213 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
214 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
215 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
216 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
217 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
218 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
219 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
220 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
221 { XX("leid3"), FILE_LEID3, FILE_FMT_NUM },
222 { XX("beid3"), FILE_BEID3, FILE_FMT_NUM },
223 { XX("indirect"), FILE_INDIRECT, FILE_FMT_NONE },
224 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
230 get_type(const char *l, const char **t)
232 const struct type_tbl_s *p;
234 for (p = type_tbl; p->len; p++) {
235 if (strncmp(l, p->name, p->len) == 0) {
245 init_file_tables(void)
248 const struct type_tbl_s *p;
254 for (p = type_tbl; p->len; p++) {
255 assert(p->type < FILE_NAMES_SIZE);
256 file_names[p->type] = p->name;
257 file_formats[p->type] = p->format;
262 * Handle one file or directory.
265 apprentice_1(struct magic_set *ms, const char *fn, int action,
268 struct magic *magic = NULL;
278 if (magicsize != FILE_MAGICSIZE) {
279 file_error(ms, 0, "magic element size %lu != %lu",
280 (unsigned long)sizeof(*magic),
281 (unsigned long)FILE_MAGICSIZE);
285 if (action == FILE_COMPILE) {
286 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
289 rv = apprentice_compile(ms, &magic, &nmagic, fn);
295 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
296 if (ms->flags & MAGIC_CHECK)
297 file_magwarn(ms, "using regular magic file `%s'", fn);
298 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
306 file_delmagic(magic, mapped, nmagic);
310 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL) {
311 file_delmagic(magic, mapped, nmagic);
312 file_oomem(ms, sizeof(*ml));
320 mlist->prev->next = ml;
321 ml->prev = mlist->prev;
325 #endif /* COMPILE_ONLY */
330 file_delmagic(struct magic *p, int type, size_t entries)
338 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
356 /* const char *fn: list of magic files and directories */
357 protected struct mlist *
358 file_apprentice(struct magic_set *ms, const char *fn, int action)
361 int file_err, errs = -1;
367 fn = getenv("MAGIC");
371 if ((mfn = strdup(fn)) == NULL) {
372 file_oomem(ms, strlen(fn));
377 if ((mlist = CAST(struct mlist *, malloc(sizeof(*mlist)))) == NULL) {
379 file_oomem(ms, sizeof(*mlist));
382 mlist->next = mlist->prev = mlist;
385 p = strchr(fn, PATHSEP);
390 file_err = apprentice_1(ms, fn, action, mlist);
391 errs = MAX(errs, file_err);
398 file_error(ms, 0, "could not find any magic files!");
406 * Get weight of this magic entry, for sorting purposes.
409 apprentice_magic_strength(const struct magic *m)
412 size_t val = 2 * MULT; /* baseline strength */
415 case FILE_DEFAULT: /* make sure this sorts last */
416 if (m->factor_op != FILE_FACTOR_OP_NONE)
439 val += m->vallen * MULT;
442 case FILE_BESTRING16:
443 case FILE_LESTRING16:
444 val += m->vallen * MULT / 2;
449 val += m->vallen * MAX(MULT / m->vallen, 1);
483 (void)fprintf(stderr, "Bad type %d\n", m->type);
488 case 'x': /* matches anything penalize */
489 case '!': /* matches almost anything penalize */
493 case '=': /* Exact match, prefer */
498 case '<': /* comparison match reduce strength */
503 case '&': /* masking bits, we could count them too */
508 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
512 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
515 switch (m->factor_op) {
516 case FILE_FACTOR_OP_NONE:
518 case FILE_FACTOR_OP_PLUS:
521 case FILE_FACTOR_OP_MINUS:
524 case FILE_FACTOR_OP_TIMES:
527 case FILE_FACTOR_OP_DIV:
535 * Magic entries with no description get a bonus because they depend
536 * on subsequent magic entries to print something.
538 if (m->desc[0] == '\0')
544 * Sort callback for sorting entries by "strength" (basically length)
547 apprentice_sort(const void *a, const void *b)
549 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
550 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
551 size_t sa = apprentice_magic_strength(ma->mp);
552 size_t sb = apprentice_magic_strength(mb->mp);
562 set_test_type(struct magic *mstart, struct magic *m)
598 case FILE_BESTRING16:
599 case FILE_LESTRING16:
600 /* binary test, set flag */
601 mstart->flag |= BINTEST;
606 /* binary test if pattern is not text */
607 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL,
609 mstart->flag |= BINTEST;
613 /* can't deduce anything; we shouldn't see this at the
618 /* invalid search type, but no need to complain here */
624 * Load and parse one file.
627 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
628 struct magic_entry **marray, uint32_t *marraycount)
632 FILE *f = fopen(ms->file = fn, "r");
635 file_error(ms, errno, "cannot read magic file `%s'",
639 /* read and parse this file */
640 for (ms->line = 1; fgets(line, sizeof(line), f) != NULL; ms->line++) {
643 if (len == 0) /* null line, garbage, etc */
645 if (line[len - 1] == '\n') {
647 line[len - 1] = '\0'; /* delete newline */
649 if (line[0] == '\0') /* empty, do not parse */
651 if (line[0] == '#') /* comment, do not parse */
653 if (line[0] == '!' && line[1] == ':') {
656 for (i = 0; bang[i].name != NULL; i++) {
657 if (len - 2 > bang[i].len &&
658 memcmp(bang[i].name, line + 2,
662 if (bang[i].name == NULL) {
664 "Unknown !: entry `%s'", line);
668 if (*marraycount == 0) {
670 "No current entry for :!%s type",
675 if ((*bang[i].fun)(ms,
676 &(*marray)[*marraycount - 1],
677 line + bang[i].len + 2) != 0) {
683 if (parse(ms, marray, marraycount, line, lineno,
693 * parse a file or directory of files
694 * const char *fn: name of magic file or directory
697 apprentice_load(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
698 const char *fn, int action)
701 struct magic_entry *marray;
702 uint32_t marraycount, i, mentrycount = 0, starttest;
704 char subfn[MAXPATHLEN];
709 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
712 if ((marray = CAST(struct magic_entry *, calloc(maxmagic,
713 sizeof(*marray)))) == NULL) {
714 file_oomem(ms, maxmagic * sizeof(*marray));
719 /* print silly verbose header for USG compat. */
720 if (action == FILE_CHECK)
721 (void)fprintf(stderr, "%s\n", usg_hdr);
723 /* load directory or file */
724 /* FIXME: Read file names and sort them to prevent
725 non-determinism. See Debian bug #488562. */
726 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
729 while ((d = readdir(dir)) != NULL) {
730 snprintf(subfn, sizeof(subfn), "%s/%s",
732 if (stat(subfn, &st) == 0 &&
733 S_ISREG(st.st_mode)) {
734 load_1(ms, action, subfn, &errs,
735 &marray, &marraycount);
742 load_1(ms, action, fn, &errs, &marray, &marraycount);
746 /* Set types of tests */
747 for (i = 0; i < marraycount; ) {
748 if (marray[i].mp->cont_level != 0) {
755 static const char text[] = "text";
756 static const char binary[] = "binary";
757 static const size_t len = sizeof(text);
758 set_test_type(marray[starttest].mp, marray[i].mp);
759 if ((ms->flags & MAGIC_DEBUG) == 0)
761 (void)fprintf(stderr, "%s%s%s: %s\n",
762 marray[i].mp->mimetype,
763 marray[i].mp->mimetype[0] == '\0' ? "" : "; ",
764 marray[i].mp->desc[0] ? marray[i].mp->desc :
766 marray[i].mp->flag & BINTEST ? binary : text);
767 if (marray[i].mp->flag & BINTEST) {
768 char *p = strstr(marray[i].mp->desc, text);
769 if (p && (p == marray[i].mp->desc ||
770 isspace((unsigned char)p[-1])) &&
771 (p + len - marray[i].mp->desc ==
772 MAXstring || (p[len] == '\0' ||
773 isspace((unsigned char)p[len]))))
774 (void)fprintf(stderr, "*** Possible "
775 "binary test for text type\n");
777 } while (++i < marraycount && marray[i].mp->cont_level != 0);
780 qsort(marray, marraycount, sizeof(*marray), apprentice_sort);
783 * Make sure that any level 0 "default" line is last (if one exists).
785 for (i = 0; i < marraycount; i++) {
786 if (marray[i].mp->cont_level == 0 &&
787 marray[i].mp->type == FILE_DEFAULT) {
788 while (++i < marraycount)
789 if (marray[i].mp->cont_level == 0)
791 if (i != marraycount) {
792 ms->line = marray[i].mp->lineno; /* XXX - Ugh! */
794 "level 0 \"default\" did not sort last");
800 for (i = 0; i < marraycount; i++)
801 mentrycount += marray[i].cont_count;
803 slen = sizeof(**magicp) * mentrycount;
804 if ((*magicp = CAST(struct magic *, malloc(slen))) == NULL) {
805 file_oomem(ms, slen);
811 for (i = 0; i < marraycount; i++) {
812 (void)memcpy(*magicp + mentrycount, marray[i].mp,
813 marray[i].cont_count * sizeof(**magicp));
814 mentrycount += marray[i].cont_count;
817 for (i = 0; i < marraycount; i++)
825 *nmagicp = mentrycount;
832 * extend the sign bit if the comparison is to be signed
835 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
837 if (!(m->flag & UNSIGNED)) {
840 * Do not remove the casts below. They are
841 * vital. When later compared with the data,
842 * the sign extension must have happened.
885 case FILE_BESTRING16:
886 case FILE_LESTRING16:
893 if (ms->flags & MAGIC_CHECK)
894 file_magwarn(ms, "cannot happen: m->type=%d\n",
903 string_modifier_check(struct magic_set *ms, struct magic *m)
905 if ((ms->flags & MAGIC_CHECK) == 0)
909 case FILE_BESTRING16:
910 case FILE_LESTRING16:
911 if (m->str_flags != 0) {
913 "no modifiers allowed for 16-bit strings\n");
919 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
921 "'/%c' only allowed on regex and search\n",
922 CHAR_REGEX_OFFSET_START);
927 if (m->str_range == 0) {
929 "missing range; defaulting to %d\n",
930 STRING_DEFAULT_RANGE);
931 m->str_range = STRING_DEFAULT_RANGE;
936 if ((m->str_flags & STRING_COMPACT_BLANK) != 0) {
937 file_magwarn(ms, "'/%c' not allowed on regex\n",
941 if ((m->str_flags & STRING_COMPACT_OPTIONAL_BLANK) != 0) {
942 file_magwarn(ms, "'/%c' not allowed on regex\n",
943 CHAR_COMPACT_OPTIONAL_BLANK);
948 file_magwarn(ms, "coding error: m->type=%d\n",
970 return FILE_OPMULTIPLY;
972 return FILE_OPDIVIDE;
974 return FILE_OPMODULO;
980 #ifdef ENABLE_CONDITIONALS
982 get_cond(const char *l, const char **t)
984 static const struct cond_tbl_s {
989 { "if", 2, COND_IF },
990 { "elif", 4, COND_ELIF },
991 { "else", 4, COND_ELSE },
992 { "", 0, COND_NONE },
994 const struct cond_tbl_s *p;
996 for (p = cond_tbl; p->len; p++) {
997 if (strncmp(l, p->name, p->len) == 0 &&
998 isspace((unsigned char)l[p->len])) {
1008 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
1011 last_cond = ms->c.li[cont_level].last_cond;
1015 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
1016 if (ms->flags & MAGIC_CHECK)
1017 file_magwarn(ms, "syntax error: `if'");
1020 last_cond = COND_IF;
1024 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1025 if (ms->flags & MAGIC_CHECK)
1026 file_magwarn(ms, "syntax error: `elif'");
1029 last_cond = COND_ELIF;
1033 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1034 if (ms->flags & MAGIC_CHECK)
1035 file_magwarn(ms, "syntax error: `else'");
1038 last_cond = COND_NONE;
1042 last_cond = COND_NONE;
1046 ms->c.li[cont_level].last_cond = last_cond;
1049 #endif /* ENABLE_CONDITIONALS */
1052 * parse one line from magic file, put into magic[index++] if valid
1055 parse(struct magic_set *ms, struct magic_entry **mentryp, uint32_t *nmentryp,
1056 const char *line, size_t lineno, int action)
1058 #ifdef ENABLE_CONDITIONALS
1059 static uint32_t last_cont_level = 0;
1062 struct magic_entry *me;
1064 const char *l = line;
1067 uint32_t cont_level;
1072 ++l; /* step over */
1075 #ifdef ENABLE_CONDITIONALS
1076 if (cont_level == 0 || cont_level > last_cont_level)
1077 if (file_check_mem(ms, cont_level) == -1)
1079 last_cont_level = cont_level;
1082 #define ALLOC_CHUNK (size_t)10
1083 #define ALLOC_INCR (size_t)200
1085 if (cont_level != 0) {
1086 if (*nmentryp == 0) {
1087 file_error(ms, 0, "No current entry for continuation");
1090 me = &(*mentryp)[*nmentryp - 1];
1091 if (me->cont_count == me->max_count) {
1093 size_t cnt = me->max_count + ALLOC_CHUNK;
1094 if ((nm = CAST(struct magic *, realloc(me->mp,
1095 sizeof(*nm) * cnt))) == NULL) {
1096 file_oomem(ms, sizeof(*nm) * cnt);
1100 me->max_count = cnt;
1102 m = &me->mp[me->cont_count++];
1103 (void)memset(m, 0, sizeof(*m));
1104 m->cont_level = cont_level;
1106 if (*nmentryp == maxmagic) {
1107 struct magic_entry *mp;
1109 maxmagic += ALLOC_INCR;
1110 if ((mp = CAST(struct magic_entry *,
1111 realloc(*mentryp, sizeof(*mp) * maxmagic))) ==
1113 file_oomem(ms, sizeof(*mp) * maxmagic);
1116 (void)memset(&mp[*nmentryp], 0, sizeof(*mp) *
1120 me = &(*mentryp)[*nmentryp];
1121 if (me->mp == NULL) {
1122 size_t len = sizeof(*m) * ALLOC_CHUNK;
1123 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1124 file_oomem(ms, len);
1128 me->max_count = ALLOC_CHUNK;
1131 (void)memset(m, 0, sizeof(*m));
1132 m->factor_op = FILE_FACTOR_OP_NONE;
1138 if (*l == '&') { /* m->cont_level == 0 checked below. */
1139 ++l; /* step over */
1143 ++l; /* step over */
1145 if (m->flag & OFFADD)
1146 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1148 if (*l == '&') { /* m->cont_level == 0 checked below */
1149 ++l; /* step over */
1153 /* Indirect offsets are not valid at level 0. */
1154 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
1155 if (ms->flags & MAGIC_CHECK)
1156 file_magwarn(ms, "relative offset at level 0");
1158 /* get offset, then skip over it */
1159 m->offset = (uint32_t)strtoul(l, &t, 0);
1161 if (ms->flags & MAGIC_CHECK)
1162 file_magwarn(ms, "offset `%s' invalid", l);
1165 if (m->flag & INDIR) {
1166 m->in_type = FILE_LONG;
1169 * read [.lbs][+-]nnnnn)
1175 m->in_type = FILE_LELONG;
1178 m->in_type = FILE_BELONG;
1181 m->in_type = FILE_MELONG;
1185 m->in_type = FILE_LESHORT;
1189 m->in_type = FILE_BESHORT;
1195 m->in_type = FILE_BYTE;
1200 m->in_type = FILE_LEDOUBLE;
1205 m->in_type = FILE_BEDOUBLE;
1208 m->in_type = FILE_LEID3;
1211 m->in_type = FILE_BEID3;
1214 if (ms->flags & MAGIC_CHECK)
1216 "indirect offset type `%c' invalid",
1225 m->in_op |= FILE_OPINVERSE;
1228 if ((op = get_op(*l)) != -1) {
1233 m->in_op |= FILE_OPINDIRECT;
1236 if (isdigit((unsigned char)*l) || *l == '-') {
1237 m->in_offset = (int32_t)strtol(l, &t, 0);
1239 if (ms->flags & MAGIC_CHECK)
1241 "in_offset `%s' invalid", l);
1245 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
1246 if (ms->flags & MAGIC_CHECK)
1248 "missing ')' in indirect offset");
1252 #ifdef ENABLE_CONDITIONALS
1253 m->cond = get_cond(l, &l);
1254 if (check_cond(ms, m->cond, cont_level) == -1)
1262 m->flag |= UNSIGNED;
1265 m->type = get_type(l, &l);
1266 if (m->type == FILE_INVALID) {
1267 if (ms->flags & MAGIC_CHECK)
1268 file_magwarn(ms, "type `%s' invalid", l);
1272 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1273 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1277 if (!IS_STRING(m->type))
1278 m->mask_op |= FILE_OPINVERSE;
1279 else if (ms->flags & MAGIC_CHECK)
1280 file_magwarn(ms, "'~' invalid for string types");
1286 if ((op = get_op(*l)) != -1) {
1287 if (!IS_STRING(m->type)) {
1291 val = (uint64_t)strtoull(l, &t, 0);
1293 m->num_mask = file_signextend(ms, m, val);
1296 else if (op == FILE_OPDIVIDE) {
1298 while (!isspace((unsigned char)*++l)) {
1300 case '0': case '1': case '2':
1301 case '3': case '4': case '5':
1302 case '6': case '7': case '8':
1305 (ms->flags & MAGIC_CHECK))
1309 m->str_range = strtoul(l, &t, 0);
1310 if (m->str_range == 0)
1315 case CHAR_COMPACT_BLANK:
1316 m->str_flags |= STRING_COMPACT_BLANK;
1318 case CHAR_COMPACT_OPTIONAL_BLANK:
1320 STRING_COMPACT_OPTIONAL_BLANK;
1322 case CHAR_IGNORE_LOWERCASE:
1323 m->str_flags |= STRING_IGNORE_LOWERCASE;
1325 case CHAR_IGNORE_UPPERCASE:
1326 m->str_flags |= STRING_IGNORE_UPPERCASE;
1328 case CHAR_REGEX_OFFSET_START:
1329 m->str_flags |= REGEX_OFFSET_START;
1332 if (ms->flags & MAGIC_CHECK)
1334 "string extension `%c' invalid",
1338 /* allow multiple '/' for readability */
1340 !isspace((unsigned char)l[2]))
1343 if (string_modifier_check(ms, m) == -1)
1347 if (ms->flags & MAGIC_CHECK)
1348 file_magwarn(ms, "invalid string op: %c", *t);
1353 * We used to set mask to all 1's here, instead let's just not do
1354 * anything if mask = 0 (unless you have a better idea)
1364 if (ms->flags & MAGIC_CHECK) {
1365 file_magwarn(ms, "%c= not supported",
1372 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1379 /* HP compat: ignore &= etc. */
1388 m->reln = '='; /* the default relation */
1389 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
1390 isspace((unsigned char)l[1])) || !l[1])) {
1397 * Grab the value part, except for an 'x' reln.
1399 if (m->reln != 'x' && getvalue(ms, m, &l, action))
1403 * TODO finish this macro and start using it!
1404 * #define offsetcheck {if (offset > HOWMANY-1)
1405 * magwarn("offset too big"); }
1409 * Now get last part - the description
1415 } else if ((l[0] == '\\') && (l[1] == 'b')) {
1420 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
1422 if (i == sizeof(m->desc)) {
1423 m->desc[sizeof(m->desc) - 1] = '\0';
1424 if (ms->flags & MAGIC_CHECK)
1425 file_magwarn(ms, "description `%s' truncated", m->desc);
1429 * We only do this check while compiling, or if any of the magic
1430 * files were not compiled.
1432 if (ms->flags & MAGIC_CHECK) {
1433 if (check_format(ms, m) == -1)
1436 #ifndef COMPILE_ONLY
1437 if (action == FILE_CHECK) {
1441 m->mimetype[0] = '\0'; /* initialise MIME type to none */
1442 if (m->cont_level == 0)
1443 ++(*nmentryp); /* make room for next */
1448 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
1452 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
1454 const char *l = line;
1456 unsigned long factor;
1457 struct magic *m = &me->mp[0];
1459 if (m->factor_op != FILE_FACTOR_OP_NONE) {
1461 "Current entry already has a strength type: %c %d",
1462 m->factor_op, m->factor);
1467 case FILE_FACTOR_OP_NONE:
1468 case FILE_FACTOR_OP_PLUS:
1469 case FILE_FACTOR_OP_MINUS:
1470 case FILE_FACTOR_OP_TIMES:
1471 case FILE_FACTOR_OP_DIV:
1472 m->factor_op = *l++;
1475 file_magwarn(ms, "Unknown factor op `%c'", *l);
1479 factor = strtoul(l, &el, 0);
1481 file_magwarn(ms, "Too large factor `%lu'", factor);
1484 if (*el && !isspace((unsigned char)*el)) {
1485 file_magwarn(ms, "Bad factor `%s'", l);
1488 m->factor = (uint8_t)factor;
1489 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
1490 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
1491 m->factor_op, m->factor);
1496 m->factor_op = FILE_FACTOR_OP_NONE;
1502 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into magic[index - 1]
1505 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line)
1508 const char *l = line;
1509 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1511 if (m->apple[0] != '\0') {
1512 file_magwarn(ms, "Current entry already has a APPLE type `%.8s',"
1513 " new type `%s'", m->mimetype, l);
1518 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1519 || strchr("-+/.", *l)) && i < sizeof(m->apple); m->apple[i++] = *l++)
1521 if (i == sizeof(m->apple) && *l) {
1522 if (ms->flags & MAGIC_CHECK)
1523 file_magwarn(ms, "APPLE type `%s' truncated %zu",
1534 * parse a MIME annotation line from magic file, put into magic[index - 1]
1538 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
1541 const char *l = line;
1542 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1544 if (m->mimetype[0] != '\0') {
1545 file_magwarn(ms, "Current entry already has a MIME type `%s',"
1546 " new type `%s'", m->mimetype, l);
1551 for (i = 0; *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1552 || strchr("-+/.", *l)) && i < sizeof(m->mimetype); m->mimetype[i++] = *l++)
1554 if (i == sizeof(m->mimetype)) {
1555 m->desc[sizeof(m->mimetype) - 1] = '\0';
1556 if (ms->flags & MAGIC_CHECK)
1557 file_magwarn(ms, "MIME type `%s' truncated %zu",
1560 m->mimetype[i] = '\0';
1569 check_format_type(const char *ptr, int type)
1573 /* Missing format string; bad */
1586 while (isdigit((unsigned char)*ptr)) ptr++;
1589 while (isdigit((unsigned char)*ptr)) ptr++;
1641 case FILE_FMT_FLOAT:
1642 case FILE_FMT_DOUBLE:
1647 while (isdigit((unsigned char)*ptr)) ptr++;
1650 while (isdigit((unsigned char)*ptr)) ptr++;
1669 while (isdigit((unsigned char )*ptr))
1673 while (isdigit((unsigned char )*ptr))
1685 /* internal error */
1693 * Check that the optional printf format in description matches
1694 * the type of the magic.
1697 check_format(struct magic_set *ms, struct magic *m)
1701 for (ptr = m->desc; *ptr; ptr++)
1705 /* No format string; ok */
1709 assert(file_nformats == file_nnames);
1711 if (m->type >= file_nformats) {
1712 file_magwarn(ms, "Internal error inconsistency between "
1713 "m->type and format strings");
1716 if (file_formats[m->type] == FILE_FMT_NONE) {
1717 file_magwarn(ms, "No format string for `%s' with description "
1718 "`%s'", m->desc, file_names[m->type]);
1723 if (check_format_type(ptr, file_formats[m->type]) == -1) {
1725 * TODO: this error message is unhelpful if the format
1726 * string is not one character long
1728 file_magwarn(ms, "Printf format `%c' is not valid for type "
1729 "`%s' in description `%s'", *ptr ? *ptr : '?',
1730 file_names[m->type], m->desc);
1734 for (; *ptr; ptr++) {
1737 "Too many format strings (should have at most one) "
1738 "for `%s' with description `%s'",
1739 file_names[m->type], m->desc);
1747 * Read a numeric value from a pointer, into the value union of a magic
1748 * pointer, according to the magic type. Update the string pointer to point
1749 * just after the number read. Return 0 for success, non-zero for failure.
1752 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
1755 case FILE_BESTRING16:
1756 case FILE_LESTRING16:
1761 *p = getstr(ms, m, *p, action == FILE_COMPILE);
1763 if (ms->flags & MAGIC_CHECK)
1764 file_magwarn(ms, "cannot get string from `%s'",
1772 if (m->reln != 'x') {
1775 m->value.f = strtof(*p, &ep);
1777 m->value.f = (float)strtod(*p, &ep);
1785 if (m->reln != 'x') {
1787 m->value.d = strtod(*p, &ep);
1792 if (m->reln != 'x') {
1794 m->value.q = file_signextend(ms, m,
1795 (uint64_t)strtoull(*p, &ep, 0));
1804 * Convert a string containing C character escapes. Stop at an unescaped
1806 * Copy the converted version to "m->value.s", and the length in m->vallen.
1807 * Return updated scan pointer as function result. Warn if set.
1809 private const char *
1810 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn)
1812 const char *origs = s;
1813 char *p = m->value.s;
1814 size_t plen = sizeof(m->value.s);
1816 char *pmax = p + plen - 1;
1820 while ((c = *s++) != '\0') {
1821 if (isspace((unsigned char) c))
1824 file_error(ms, 0, "string too long: `%s'", origs);
1832 file_magwarn(ms, "incomplete escape");
1838 "escaped tab found, use \\t instead");
1839 warn = 0; /* already did */
1844 if (isprint((unsigned char)c)) {
1845 /* Allow escaping of
1847 if (strchr("<>&^=!", c)
1849 file_magwarn(ms, "no "
1855 "unknown escape sequence: "
1860 /* space, perhaps force people to use \040? */
1864 * Other things people escape, but shouldn't need to,
1865 * so we disallow them
1878 /* and baskslash itself */
1911 /* \ and up to 3 octal digits */
1921 c = *s++; /* try for 2 */
1922 if (c >= '0' && c <= '7') {
1923 val = (val << 3) | (c - '0');
1924 c = *s++; /* try for 3 */
1925 if (c >= '0' && c <= '7')
1926 val = (val << 3) | (c-'0');
1935 /* \x and up to 2 hex digits */
1937 val = 'x'; /* Default if no digits */
1938 c = hextoint(*s++); /* Get next char */
1943 val = (val << 4) + c;
1956 m->vallen = p - origp;
1957 if (m->type == FILE_PSTRING)
1963 /* Single hex char to int; -1 if not a hex char. */
1967 if (!isascii((unsigned char) c))
1969 if (isdigit((unsigned char) c))
1971 if ((c >= 'a') && (c <= 'f'))
1972 return c + 10 - 'a';
1973 if (( c>= 'A') && (c <= 'F'))
1974 return c + 10 - 'A';
1980 * Print a string containing C character escapes.
1983 file_showstr(FILE *fp, const char *s, size_t len)
1997 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
1998 (void) fputc(c, fp);
2000 (void) fputc('\\', fp);
2003 (void) fputc('a', fp);
2007 (void) fputc('b', fp);
2011 (void) fputc('f', fp);
2015 (void) fputc('n', fp);
2019 (void) fputc('r', fp);
2023 (void) fputc('t', fp);
2027 (void) fputc('v', fp);
2031 (void) fprintf(fp, "%.3o", c & 0377);
2039 * eatsize(): Eat the size spec from a number [eg. 10UL]
2042 eatsize(const char **p)
2046 if (LOWCASE(*l) == 'u')
2049 switch (LOWCASE(*l)) {
2050 case 'l': /* long */
2051 case 's': /* short */
2052 case 'h': /* short */
2053 case 'b': /* char/byte */
2054 case 'c': /* char/byte */
2064 #ifndef COMPILE_ONLY
2066 * handle a compiled file.
2069 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
2077 char *dbname = NULL;
2080 dbname = mkdbname(ms, fn, 0);
2084 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2087 if (fstat(fd, &st) == -1) {
2088 file_error(ms, errno, "cannot stat `%s'", dbname);
2091 if (st.st_size < 8) {
2092 file_error(ms, 0, "file `%s' is too small", dbname);
2097 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2098 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2099 file_error(ms, errno, "cannot map `%s'", dbname);
2104 if ((mm = CAST(void *, malloc((size_t)st.st_size))) == NULL) {
2105 file_oomem(ms, (size_t)st.st_size);
2108 if (read(fd, mm, (size_t)st.st_size) != (ssize_t)st.st_size) {
2114 *magicp = CAST(struct magic *, mm);
2117 ptr = (uint32_t *)(void *)*magicp;
2118 if (*ptr != MAGICNO) {
2119 if (swap4(*ptr) != MAGICNO) {
2120 file_error(ms, 0, "bad magic in `%s'", dbname);
2127 version = swap4(ptr[1]);
2130 if (version != VERSIONNO) {
2131 file_error(ms, 0, "File %d.%d supports only version %d magic "
2132 "files. `%s' is version %d", FILE_VERSION_MAJOR, patchlevel,
2133 VERSIONNO, dbname, version);
2136 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic));
2141 byteswap(*magicp, *nmagicp);
2150 (void)munmap((void *)mm, (size_t)st.st_size);
2162 #endif /* COMPILE_ONLY */
2164 private const uint32_t ar[] = {
2168 * handle an mmaped file.
2171 apprentice_compile(struct magic_set *ms, struct magic **magicp,
2172 uint32_t *nmagicp, const char *fn)
2178 dbname = mkdbname(ms, fn, 1);
2183 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1) {
2184 file_error(ms, errno, "cannot open `%s'", dbname);
2188 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
2189 file_error(ms, errno, "error writing `%s'", dbname);
2193 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
2194 != sizeof(struct magic)) {
2195 file_error(ms, errno, "error seeking `%s'", dbname);
2199 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
2200 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
2201 file_error(ms, errno, "error writing `%s'", dbname);
2212 private const char ext[] = ".mgc";
2217 mkdbname(struct magic_set *ms, const char *fn, int strip)
2223 if ((p = strrchr(fn, '/')) != NULL)
2227 for (q = fn; *q; q++)
2230 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--)
2234 /* Did not find .mgc, restore q */
2240 /* Compatibility with old code that looked in .mime */
2241 if (ms->flags & MAGIC_MIME) {
2242 asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext);
2243 if (access(buf, R_OK) != -1) {
2244 ms->flags &= MAGIC_MIME_TYPE;
2249 asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext);
2251 /* Compatibility with old code that looked in .mime */
2252 if (strstr(p, ".mime") != NULL)
2253 ms->flags &= MAGIC_MIME_TYPE;
2257 #ifndef COMPILE_ONLY
2259 * Byteswap an mmap'ed file if needed
2262 byteswap(struct magic *magic, uint32_t nmagic)
2265 for (i = 0; i < nmagic; i++)
2276 uint8_t *s = (uint8_t *)(void *)&sv;
2277 uint8_t *d = (uint8_t *)(void *)&rv;
2290 uint8_t *s = (uint8_t *)(void *)&sv;
2291 uint8_t *d = (uint8_t *)(void *)&rv;
2306 uint8_t *s = (uint8_t *)(void *)&sv;
2307 uint8_t *d = (uint8_t *)(void *)&rv;
2331 * byteswap a single magic entry
2334 bs1(struct magic *m)
2336 m->cont_level = swap2(m->cont_level);
2337 m->offset = swap4((uint32_t)m->offset);
2338 m->in_offset = swap4((uint32_t)m->in_offset);
2339 m->lineno = swap4((uint32_t)m->lineno);
2340 if (IS_STRING(m->type)) {
2341 m->str_range = swap4(m->str_range);
2342 m->str_flags = swap4(m->str_flags);
2345 m->value.q = swap8(m->value.q);
2346 m->num_mask = swap8(m->num_mask);
2349 #endif /* COMPILE_ONLY */