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.
34 #include "patchlevel.h"
44 #include <sys/param.h>
48 #include <sys/types.h>
52 FILE_RCSID("@(#)$File: apprentice.c,v 1.140 2008/07/20 04:02:15 christos Exp $")
55 #define EATAB {while (isascii((unsigned char) *l) && \
56 isspace((unsigned char) *l)) ++l;}
57 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
58 tolower((unsigned char) (l)) : (l))
60 * Work around a bug in headers on Digital Unix.
61 * At least confirmed for: OSF1 V4.0 878
63 #if defined(__osf__) && defined(__DECC)
70 #define MAP_FAILED (void *) -1
78 #define MAXPATHLEN 1024
87 int file_formats[FILE_NAMES_SIZE];
88 const size_t file_nformats = FILE_NAMES_SIZE;
89 const char *file_names[FILE_NAMES_SIZE];
90 const size_t file_nnames = FILE_NAMES_SIZE;
92 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
93 private int hextoint(int);
94 private const char *getstr(struct magic_set *, const char *, char *, int,
96 private int parse(struct magic_set *, struct magic_entry **, uint32_t *,
97 const char *, size_t, int);
98 private void eatsize(const char **);
99 private int apprentice_1(struct magic_set *, const char *, int, struct mlist *);
100 private size_t apprentice_magic_strength(const struct magic *);
101 private int apprentice_sort(const void *, const void *);
102 private int apprentice_load(struct magic_set *, struct magic **, uint32_t *,
104 private void byteswap(struct magic *, uint32_t);
105 private void bs1(struct magic *);
106 private uint16_t swap2(uint16_t);
107 private uint32_t swap4(uint32_t);
108 private uint64_t swap8(uint64_t);
109 private void mkdbname(const char *, char **, int);
110 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
112 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
114 private int check_format_type(const char *, int);
115 private int check_format(struct magic_set *, struct magic *);
116 private int get_op(char);
117 private int parse_mime(struct magic_set *, struct magic_entry *, const char *);
118 private int parse_strength(struct magic_set *, struct magic_entry *,
122 private size_t maxmagic = 0;
123 private size_t magicsize = sizeof(struct magic);
125 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
130 int (*fun)(struct magic_set *, struct magic_entry *, const char *);
132 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
134 DECLARE_FIELD(strength),
141 int main(int, char *[]);
144 main(int argc, char *argv[])
147 struct magic_set *ms;
150 if ((progname = strrchr(argv[0], '/')) != NULL)
156 (void)fprintf(stderr, "Usage: %s file\n", progname);
160 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
161 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
164 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
166 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
170 #endif /* COMPILE_ONLY */
172 static const struct type_tbl_s {
178 # define XX(s) s, (sizeof(s) - 1)
179 # define XX_NULL "", 0
180 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
181 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
182 { XX("default"), FILE_DEFAULT, FILE_FMT_STR },
183 { XX("long"), FILE_LONG, FILE_FMT_NUM },
184 { XX("string"), FILE_STRING, FILE_FMT_STR },
185 { XX("date"), FILE_DATE, FILE_FMT_STR },
186 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
187 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
188 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
189 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
190 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
191 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
192 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
193 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
194 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
195 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
196 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
197 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
198 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
199 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
200 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
201 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
202 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
203 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
204 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
205 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
206 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
207 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
208 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
209 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
210 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
211 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
212 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT },
213 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT },
214 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT },
215 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE },
216 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE },
217 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE },
218 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
224 get_type(const char *l, const char **t)
226 const struct type_tbl_s *p;
228 for (p = type_tbl; p->len; p++) {
229 if (strncmp(l, p->name, p->len) == 0) {
239 init_file_tables(void)
242 const struct type_tbl_s *p;
248 for (p = type_tbl; p->len; p++) {
249 assert(p->type < FILE_NAMES_SIZE);
250 file_names[p->type] = p->name;
251 file_formats[p->type] = p->format;
256 * Handle one file or directory.
259 apprentice_1(struct magic_set *ms, const char *fn, int action,
262 struct magic *magic = NULL;
268 if (magicsize != FILE_MAGICSIZE) {
269 file_error(ms, 0, "magic element size %lu != %lu",
270 (unsigned long)sizeof(*magic),
271 (unsigned long)FILE_MAGICSIZE);
275 if (action == FILE_COMPILE) {
276 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
279 rv = apprentice_compile(ms, &magic, &nmagic, fn);
285 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
286 if (ms->flags & MAGIC_CHECK)
287 file_magwarn(ms, "using regular magic file `%s'", fn);
288 rv = apprentice_load(ms, &magic, &nmagic, fn, action);
296 file_delmagic(magic, mapped, nmagic);
300 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL) {
301 file_delmagic(magic, mapped, nmagic);
302 file_oomem(ms, sizeof(*ml));
310 mlist->prev->next = ml;
311 ml->prev = mlist->prev;
316 #endif /* COMPILE_ONLY */
320 file_delmagic(struct magic *p, int type, size_t entries)
328 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
342 /* const char *fn: list of magic files and directories */
343 protected struct mlist *
344 file_apprentice(struct magic_set *ms, const char *fn, int action)
347 int file_err, errs = -1;
353 fn = getenv("MAGIC");
357 if ((mfn = strdup(fn)) == NULL) {
358 file_oomem(ms, strlen(fn));
363 if ((mlist = CAST(struct mlist *, malloc(sizeof(*mlist)))) == NULL) {
365 file_oomem(ms, sizeof(*mlist));
368 mlist->next = mlist->prev = mlist;
371 p = strchr(fn, PATHSEP);
376 file_err = apprentice_1(ms, fn, action, mlist);
377 errs = MAX(errs, file_err);
384 file_error(ms, 0, "could not find any magic files!");
392 * Get weight of this magic entry, for sorting purposes.
395 apprentice_magic_strength(const struct magic *m)
398 size_t val = 2 * MULT; /* baseline strength */
401 case FILE_DEFAULT: /* make sure this sorts last */
402 if (m->factor_op != FILE_FACTOR_OP_NONE)
425 val += m->vallen * MULT;
428 case FILE_BESTRING16:
429 case FILE_LESTRING16:
430 val += m->vallen * MULT / 2;
435 val += m->vallen * MAX(MULT / m->vallen, 1);
469 (void)fprintf(stderr, "Bad type %d\n", m->type);
474 case 'x': /* matches anything penalize */
475 case '!': /* matches almost anything penalize */
479 case '=': /* Exact match, prefer */
484 case '<': /* comparison match reduce strength */
489 case '&': /* masking bits, we could count them too */
494 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
498 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
501 switch (m->factor_op) {
502 case FILE_FACTOR_OP_NONE:
504 case FILE_FACTOR_OP_PLUS:
507 case FILE_FACTOR_OP_MINUS:
510 case FILE_FACTOR_OP_TIMES:
513 case FILE_FACTOR_OP_DIV:
521 * Magic entries with no description get a bonus because they depend
522 * on subsequent magic entries to print something.
524 if (m->desc[0] == '\0')
530 * Sort callback for sorting entries by "strength" (basically length)
533 apprentice_sort(const void *a, const void *b)
535 const struct magic_entry *ma = CAST(const struct magic_entry *, a);
536 const struct magic_entry *mb = CAST(const struct magic_entry *, b);
537 size_t sa = apprentice_magic_strength(ma->mp);
538 size_t sb = apprentice_magic_strength(mb->mp);
548 set_test_type(struct magic *mstart, struct magic *m)
584 case FILE_BESTRING16:
585 case FILE_LESTRING16:
586 /* binary test, set flag */
587 mstart->flag |= BINTEST;
592 /* binary test if pattern is not text */
593 if (file_looks_utf8(m->value.us, m->vallen, NULL, NULL) <= 0)
594 mstart->flag |= BINTEST;
598 /* can't deduce anything; we shouldn't see this at the
603 /* invalid search type, but no need to complain here */
609 * Load and parse one file.
612 load_1(struct magic_set *ms, int action, const char *fn, int *errs,
613 struct magic_entry **marray, uint32_t *marraycount)
617 FILE *f = fopen(ms->file = fn, "r");
620 file_error(ms, errno, "cannot read magic file `%s'",
624 /* read and parse this file */
625 for (ms->line = 1; fgets(line, sizeof(line), f) != NULL; ms->line++) {
628 if (len == 0) /* null line, garbage, etc */
630 if (line[len - 1] == '\n') {
632 line[len - 1] = '\0'; /* delete newline */
634 if (line[0] == '\0') /* empty, do not parse */
636 if (line[0] == '#') /* comment, do not parse */
638 if (line[0] == '!' && line[1] == ':') {
641 for (i = 0; bang[i].name != NULL; i++) {
642 if (len - 2 > bang[i].len &&
643 memcmp(bang[i].name, line + 2,
647 if (bang[i].name == NULL) {
649 "Unknown !: entry `%s'", line);
653 if (*marraycount == 0) {
655 "No current entry for :!%s type",
660 if ((*bang[i].fun)(ms,
661 &(*marray)[*marraycount - 1],
662 line + bang[i].len + 2) != 0) {
668 if (parse(ms, marray, marraycount, line, lineno,
678 * parse a file or directory of files
679 * const char *fn: name of magic file or directory
682 apprentice_load(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
683 const char *fn, int action)
686 struct magic_entry *marray;
687 uint32_t marraycount, i, mentrycount = 0, starttest;
689 char subfn[MAXPATHLEN];
694 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
697 if ((marray = CAST(struct magic_entry *, calloc(maxmagic,
698 sizeof(*marray)))) == NULL) {
699 file_oomem(ms, maxmagic * sizeof(*marray));
704 /* print silly verbose header for USG compat. */
705 if (action == FILE_CHECK)
706 (void)fprintf(stderr, "%s\n", usg_hdr);
708 /* load directory or file */
709 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) {
712 while ((d = readdir(dir)) != NULL) {
713 snprintf(subfn, sizeof(subfn), "%s/%s",
715 if (stat(subfn, &st) == 0 &&
716 S_ISREG(st.st_mode)) {
717 load_1(ms, action, subfn, &errs,
718 &marray, &marraycount);
725 load_1(ms, action, fn, &errs, &marray, &marraycount);
729 /* Set types of tests */
730 for (i = 0; i < marraycount; ) {
731 if (marray[i].mp->cont_level != 0) {
738 static const char text[] = "text";
739 static const char binary[] = "binary";
740 static const size_t len = sizeof(text);
741 set_test_type(marray[starttest].mp, marray[i].mp);
742 if ((ms->flags & MAGIC_DEBUG) == 0)
744 (void)fprintf(stderr, "%s%s%s: %s\n",
745 marray[i].mp->mimetype,
746 marray[i].mp->mimetype[0] == '\0' ? "" : "; ",
747 marray[i].mp->desc[0] ? marray[i].mp->desc :
749 marray[i].mp->flag & BINTEST ? binary : text);
750 if (marray[i].mp->flag & BINTEST) {
751 char *p = strstr(marray[i].mp->desc, text);
752 if (p && (p == marray[i].mp->desc ||
753 isspace((unsigned char)p[-1])) &&
754 (p + len - marray[i].mp->desc ==
755 MAXstring || (p[len] == '\0' ||
756 isspace((unsigned char)p[len]))))
757 (void)fprintf(stderr, "*** Possible "
758 "binary test for text type\n");
760 } while (++i < marraycount && marray[i].mp->cont_level != 0);
763 qsort(marray, marraycount, sizeof(*marray), apprentice_sort);
766 * Make sure that any level 0 "default" line is last (if one exists).
768 for (i = 0; i < marraycount; i++) {
769 if (marray[i].mp->cont_level == 0 &&
770 marray[i].mp->type == FILE_DEFAULT) {
771 while (++i < marraycount)
772 if (marray[i].mp->cont_level == 0)
774 if (i != marraycount) {
775 ms->line = marray[i].mp->lineno; /* XXX - Ugh! */
777 "level 0 \"default\" did not sort last");
783 for (i = 0; i < marraycount; i++)
784 mentrycount += marray[i].cont_count;
786 slen = sizeof(**magicp) * mentrycount;
787 if ((*magicp = CAST(struct magic *, malloc(slen))) == NULL) {
788 file_oomem(ms, slen);
794 for (i = 0; i < marraycount; i++) {
795 (void)memcpy(*magicp + mentrycount, marray[i].mp,
796 marray[i].cont_count * sizeof(**magicp));
797 mentrycount += marray[i].cont_count;
800 for (i = 0; i < marraycount; i++)
808 *nmagicp = mentrycount;
815 * extend the sign bit if the comparison is to be signed
818 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
820 if (!(m->flag & UNSIGNED)) {
823 * Do not remove the casts below. They are
824 * vital. When later compared with the data,
825 * the sign extension must have happened.
868 case FILE_BESTRING16:
869 case FILE_LESTRING16:
875 if (ms->flags & MAGIC_CHECK)
876 file_magwarn(ms, "cannot happen: m->type=%d\n",
885 string_modifier_check(struct magic_set *ms, struct magic *m)
887 if ((ms->flags & MAGIC_CHECK) == 0)
891 case FILE_BESTRING16:
892 case FILE_LESTRING16:
893 if (m->str_flags != 0) {
895 "no modifiers allowed for 16-bit strings\n");
901 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
903 "'/%c' only allowed on regex and search\n",
904 CHAR_REGEX_OFFSET_START);
909 if (m->str_range == 0) {
911 "missing range; defaulting to %d\n",
912 STRING_DEFAULT_RANGE);
913 m->str_range = STRING_DEFAULT_RANGE;
918 if ((m->str_flags & STRING_COMPACT_BLANK) != 0) {
919 file_magwarn(ms, "'/%c' not allowed on regex\n",
923 if ((m->str_flags & STRING_COMPACT_OPTIONAL_BLANK) != 0) {
924 file_magwarn(ms, "'/%c' not allowed on regex\n",
925 CHAR_COMPACT_OPTIONAL_BLANK);
930 file_magwarn(ms, "coding error: m->type=%d\n",
952 return FILE_OPMULTIPLY;
954 return FILE_OPDIVIDE;
956 return FILE_OPMODULO;
962 #ifdef ENABLE_CONDITIONALS
964 get_cond(const char *l, const char **t)
966 static const struct cond_tbl_s {
971 { "if", 2, COND_IF },
972 { "elif", 4, COND_ELIF },
973 { "else", 4, COND_ELSE },
974 { "", 0, COND_NONE },
976 const struct cond_tbl_s *p;
978 for (p = cond_tbl; p->len; p++) {
979 if (strncmp(l, p->name, p->len) == 0 &&
980 isspace((unsigned char)l[p->len])) {
990 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
993 last_cond = ms->c.li[cont_level].last_cond;
997 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
998 if (ms->flags & MAGIC_CHECK)
999 file_magwarn(ms, "syntax error: `if'");
1002 last_cond = COND_IF;
1006 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1007 if (ms->flags & MAGIC_CHECK)
1008 file_magwarn(ms, "syntax error: `elif'");
1011 last_cond = COND_ELIF;
1015 if (last_cond != COND_IF && last_cond != COND_ELIF) {
1016 if (ms->flags & MAGIC_CHECK)
1017 file_magwarn(ms, "syntax error: `else'");
1020 last_cond = COND_NONE;
1024 last_cond = COND_NONE;
1028 ms->c.li[cont_level].last_cond = last_cond;
1031 #endif /* ENABLE_CONDITIONALS */
1034 * parse one line from magic file, put into magic[index++] if valid
1037 parse(struct magic_set *ms, struct magic_entry **mentryp, uint32_t *nmentryp,
1038 const char *line, size_t lineno, int action)
1040 #ifdef ENABLE_CONDITIONALS
1041 static uint32_t last_cont_level = 0;
1044 struct magic_entry *me;
1046 const char *l = line;
1049 uint32_t cont_level;
1054 ++l; /* step over */
1057 #ifdef ENABLE_CONDITIONALS
1058 if (cont_level == 0 || cont_level > last_cont_level)
1059 if (file_check_mem(ms, cont_level) == -1)
1061 last_cont_level = cont_level;
1064 #define ALLOC_CHUNK (size_t)10
1065 #define ALLOC_INCR (size_t)200
1067 if (cont_level != 0) {
1068 if (*nmentryp == 0) {
1069 file_error(ms, 0, "No current entry for continuation");
1072 me = &(*mentryp)[*nmentryp - 1];
1073 if (me->cont_count == me->max_count) {
1075 size_t cnt = me->max_count + ALLOC_CHUNK;
1076 if ((nm = CAST(struct magic *, realloc(me->mp,
1077 sizeof(*nm) * cnt))) == NULL) {
1078 file_oomem(ms, sizeof(*nm) * cnt);
1082 me->max_count = cnt;
1084 m = &me->mp[me->cont_count++];
1085 (void)memset(m, 0, sizeof(*m));
1086 m->cont_level = cont_level;
1088 if (*nmentryp == maxmagic) {
1089 struct magic_entry *mp;
1091 maxmagic += ALLOC_INCR;
1092 if ((mp = CAST(struct magic_entry *,
1093 realloc(*mentryp, sizeof(*mp) * maxmagic))) ==
1095 file_oomem(ms, sizeof(*mp) * maxmagic);
1098 (void)memset(&mp[*nmentryp], 0, sizeof(*mp) *
1102 me = &(*mentryp)[*nmentryp];
1103 if (me->mp == NULL) {
1104 size_t len = sizeof(*m) * ALLOC_CHUNK;
1105 if ((m = CAST(struct magic *, malloc(len))) == NULL) {
1106 file_oomem(ms, len);
1110 me->max_count = ALLOC_CHUNK;
1113 (void)memset(m, 0, sizeof(*m));
1114 m->factor_op = FILE_FACTOR_OP_NONE;
1120 if (*l == '&') { /* m->cont_level == 0 checked below. */
1121 ++l; /* step over */
1125 ++l; /* step over */
1127 if (m->flag & OFFADD)
1128 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
1130 if (*l == '&') { /* m->cont_level == 0 checked below */
1131 ++l; /* step over */
1135 /* Indirect offsets are not valid at level 0. */
1136 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
1137 if (ms->flags & MAGIC_CHECK)
1138 file_magwarn(ms, "relative offset at level 0");
1140 /* get offset, then skip over it */
1141 m->offset = (uint32_t)strtoul(l, &t, 0);
1143 if (ms->flags & MAGIC_CHECK)
1144 file_magwarn(ms, "offset `%s' invalid", l);
1147 if (m->flag & INDIR) {
1148 m->in_type = FILE_LONG;
1151 * read [.lbs][+-]nnnnn)
1157 m->in_type = FILE_LELONG;
1160 m->in_type = FILE_BELONG;
1163 m->in_type = FILE_MELONG;
1167 m->in_type = FILE_LESHORT;
1171 m->in_type = FILE_BESHORT;
1177 m->in_type = FILE_BYTE;
1182 m->in_type = FILE_LEDOUBLE;
1187 m->in_type = FILE_BEDOUBLE;
1190 if (ms->flags & MAGIC_CHECK)
1192 "indirect offset type `%c' invalid",
1201 m->in_op |= FILE_OPINVERSE;
1204 if ((op = get_op(*l)) != -1) {
1209 m->in_op |= FILE_OPINDIRECT;
1212 if (isdigit((unsigned char)*l) || *l == '-') {
1213 m->in_offset = (int32_t)strtol(l, &t, 0);
1215 if (ms->flags & MAGIC_CHECK)
1217 "in_offset `%s' invalid", l);
1221 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
1222 if (ms->flags & MAGIC_CHECK)
1224 "missing ')' in indirect offset");
1228 #ifdef ENABLE_CONDITIONALS
1229 m->cond = get_cond(l, &l);
1230 if (check_cond(ms, m->cond, cont_level) == -1)
1238 m->flag |= UNSIGNED;
1241 m->type = get_type(l, &l);
1242 if (m->type == FILE_INVALID) {
1243 if (ms->flags & MAGIC_CHECK)
1244 file_magwarn(ms, "type `%s' invalid", l);
1248 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1249 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1253 if (!IS_STRING(m->type))
1254 m->mask_op |= FILE_OPINVERSE;
1255 else if (ms->flags & MAGIC_CHECK)
1256 file_magwarn(ms, "'~' invalid for string types");
1262 if ((op = get_op(*l)) != -1) {
1263 if (!IS_STRING(m->type)) {
1267 val = (uint64_t)strtoull(l, &t, 0);
1269 m->num_mask = file_signextend(ms, m, val);
1272 else if (op == FILE_OPDIVIDE) {
1274 while (!isspace((unsigned char)*++l)) {
1276 case '0': case '1': case '2':
1277 case '3': case '4': case '5':
1278 case '6': case '7': case '8':
1281 (ms->flags & MAGIC_CHECK))
1285 m->str_range = strtoul(l, &t, 0);
1286 if (m->str_range == 0)
1291 case CHAR_COMPACT_BLANK:
1292 m->str_flags |= STRING_COMPACT_BLANK;
1294 case CHAR_COMPACT_OPTIONAL_BLANK:
1296 STRING_COMPACT_OPTIONAL_BLANK;
1298 case CHAR_IGNORE_LOWERCASE:
1299 m->str_flags |= STRING_IGNORE_LOWERCASE;
1301 case CHAR_IGNORE_UPPERCASE:
1302 m->str_flags |= STRING_IGNORE_UPPERCASE;
1304 case CHAR_REGEX_OFFSET_START:
1305 m->str_flags |= REGEX_OFFSET_START;
1308 if (ms->flags & MAGIC_CHECK)
1310 "string extension `%c' invalid",
1314 /* allow multiple '/' for readability */
1316 !isspace((unsigned char)l[2]))
1319 if (string_modifier_check(ms, m) == -1)
1323 if (ms->flags & MAGIC_CHECK)
1324 file_magwarn(ms, "invalid string op: %c", *t);
1329 * We used to set mask to all 1's here, instead let's just not do
1330 * anything if mask = 0 (unless you have a better idea)
1340 if (ms->flags & MAGIC_CHECK) {
1341 file_magwarn(ms, "%c= not supported",
1348 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1355 /* HP compat: ignore &= etc. */
1364 m->reln = '='; /* the default relation */
1365 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
1366 isspace((unsigned char)l[1])) || !l[1])) {
1373 * Grab the value part, except for an 'x' reln.
1375 if (m->reln != 'x' && getvalue(ms, m, &l, action))
1379 * TODO finish this macro and start using it!
1380 * #define offsetcheck {if (offset > HOWMANY-1)
1381 * magwarn("offset too big"); }
1385 * Now get last part - the description
1391 } else if ((l[0] == '\\') && (l[1] == 'b')) {
1396 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
1398 if (i == sizeof(m->desc)) {
1399 m->desc[sizeof(m->desc) - 1] = '\0';
1400 if (ms->flags & MAGIC_CHECK)
1401 file_magwarn(ms, "description `%s' truncated", m->desc);
1405 * We only do this check while compiling, or if any of the magic
1406 * files were not compiled.
1408 if (ms->flags & MAGIC_CHECK) {
1409 if (check_format(ms, m) == -1)
1412 #ifndef COMPILE_ONLY
1413 if (action == FILE_CHECK) {
1417 m->mimetype[0] = '\0'; /* initialise MIME type to none */
1418 if (m->cont_level == 0)
1419 ++(*nmentryp); /* make room for next */
1424 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
1428 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line)
1430 const char *l = line;
1432 unsigned long factor;
1433 struct magic *m = &me->mp[0];
1435 if (m->factor_op != FILE_FACTOR_OP_NONE) {
1437 "Current entry already has a strength type: %c %d",
1438 m->factor_op, m->factor);
1443 case FILE_FACTOR_OP_NONE:
1444 case FILE_FACTOR_OP_PLUS:
1445 case FILE_FACTOR_OP_MINUS:
1446 case FILE_FACTOR_OP_TIMES:
1447 case FILE_FACTOR_OP_DIV:
1448 m->factor_op = *l++;
1451 file_magwarn(ms, "Unknown factor op `%c'", *l);
1455 factor = strtoul(l, &el, 0);
1457 file_magwarn(ms, "Too large factor `%lu'", factor);
1460 if (*el && !isspace((unsigned char)*el)) {
1461 file_magwarn(ms, "Bad factor `%s'", l);
1464 m->factor = (uint8_t)factor;
1465 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) {
1466 file_magwarn(ms, "Cannot have factor op `%c' and factor %u",
1467 m->factor_op, m->factor);
1472 m->factor_op = FILE_FACTOR_OP_NONE;
1478 * parse a MIME annotation line from magic file, put into magic[index - 1]
1482 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line)
1485 const char *l = line;
1486 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1];
1488 if (m->mimetype[0] != '\0') {
1489 file_magwarn(ms, "Current entry already has a MIME type `%s',"
1490 " new type `%s'", m->mimetype, l);
1496 *l && ((isascii((unsigned char)*l) && isalnum((unsigned char)*l))
1497 || strchr("-+/.", *l)) && i < sizeof(m->mimetype);
1498 m->mimetype[i++] = *l++)
1500 if (i == sizeof(m->mimetype)) {
1501 m->desc[sizeof(m->mimetype) - 1] = '\0';
1502 if (ms->flags & MAGIC_CHECK)
1503 file_magwarn(ms, "MIME type `%s' truncated %zu",
1506 m->mimetype[i] = '\0';
1515 check_format_type(const char *ptr, int type)
1519 /* Missing format string; bad */
1532 while (isdigit((unsigned char)*ptr)) ptr++;
1535 while (isdigit((unsigned char)*ptr)) ptr++;
1587 case FILE_FMT_FLOAT:
1588 case FILE_FMT_DOUBLE:
1593 while (isdigit((unsigned char)*ptr)) ptr++;
1596 while (isdigit((unsigned char)*ptr)) ptr++;
1615 while (isdigit((unsigned char )*ptr))
1619 while (isdigit((unsigned char )*ptr))
1631 /* internal error */
1639 * Check that the optional printf format in description matches
1640 * the type of the magic.
1643 check_format(struct magic_set *ms, struct magic *m)
1647 for (ptr = m->desc; *ptr; ptr++)
1651 /* No format string; ok */
1655 assert(file_nformats == file_nnames);
1657 if (m->type >= file_nformats) {
1658 file_magwarn(ms, "Internal error inconsistency between "
1659 "m->type and format strings");
1662 if (file_formats[m->type] == FILE_FMT_NONE) {
1663 file_magwarn(ms, "No format string for `%s' with description "
1664 "`%s'", m->desc, file_names[m->type]);
1669 if (check_format_type(ptr, file_formats[m->type]) == -1) {
1671 * TODO: this error message is unhelpful if the format
1672 * string is not one character long
1674 file_magwarn(ms, "Printf format `%c' is not valid for type "
1675 "`%s' in description `%s'",
1676 ptr && *ptr ? *ptr : '?',
1677 file_names[m->type], m->desc);
1681 for (; *ptr; ptr++) {
1684 "Too many format strings (should have at most one) "
1685 "for `%s' with description `%s'",
1686 file_names[m->type], m->desc);
1694 * Read a numeric value from a pointer, into the value union of a magic
1695 * pointer, according to the magic type. Update the string pointer to point
1696 * just after the number read. Return 0 for success, non-zero for failure.
1699 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
1704 case FILE_BESTRING16:
1705 case FILE_LESTRING16:
1710 *p = getstr(ms, *p, m->value.s, sizeof(m->value.s), &slen, action);
1712 if (ms->flags & MAGIC_CHECK)
1713 file_magwarn(ms, "cannot get string from `%s'",
1718 if (m->type == FILE_PSTRING)
1724 if (m->reln != 'x') {
1727 m->value.f = strtof(*p, &ep);
1729 m->value.f = (float)strtod(*p, &ep);
1737 if (m->reln != 'x') {
1739 m->value.d = strtod(*p, &ep);
1744 if (m->reln != 'x') {
1746 m->value.q = file_signextend(ms, m,
1747 (uint64_t)strtoull(*p, &ep, 0));
1756 * Convert a string containing C character escapes. Stop at an unescaped
1758 * Copy the converted version to "p", returning its length in *slen.
1759 * Return updated scan pointer as function result.
1761 private const char *
1762 getstr(struct magic_set *ms, const char *s, char *p, int plen, int *slen, int action)
1764 const char *origs = s;
1766 char *pmax = p + plen - 1;
1770 while ((c = *s++) != '\0') {
1771 if (isspace((unsigned char) c))
1774 file_error(ms, 0, "string too long: `%s'", origs);
1781 if (action == FILE_COMPILE)
1782 file_magwarn(ms, "incomplete escape");
1786 if (action == FILE_COMPILE) {
1788 "escaped tab found, use \\t instead");
1793 if (action == FILE_COMPILE) {
1794 if (isprint((unsigned char)c))
1796 "no need to escape `%c'", c);
1799 "unknown escape sequence: \\%03o", c);
1802 /* space, perhaps force people to use \040? */
1806 * Other things people escape, but shouldn't need to,
1807 * so we disallow them
1820 /* and baskslash itself */
1853 /* \ and up to 3 octal digits */
1863 c = *s++; /* try for 2 */
1864 if (c >= '0' && c <= '7') {
1865 val = (val << 3) | (c - '0');
1866 c = *s++; /* try for 3 */
1867 if (c >= '0' && c <= '7')
1868 val = (val << 3) | (c-'0');
1877 /* \x and up to 2 hex digits */
1879 val = 'x'; /* Default if no digits */
1880 c = hextoint(*s++); /* Get next char */
1885 val = (val << 4) + c;
1903 /* Single hex char to int; -1 if not a hex char. */
1907 if (!isascii((unsigned char) c))
1909 if (isdigit((unsigned char) c))
1911 if ((c >= 'a') && (c <= 'f'))
1912 return c + 10 - 'a';
1913 if (( c>= 'A') && (c <= 'F'))
1914 return c + 10 - 'A';
1920 * Print a string containing C character escapes.
1923 file_showstr(FILE *fp, const char *s, size_t len)
1937 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
1938 (void) fputc(c, fp);
1940 (void) fputc('\\', fp);
1943 (void) fputc('a', fp);
1947 (void) fputc('b', fp);
1951 (void) fputc('f', fp);
1955 (void) fputc('n', fp);
1959 (void) fputc('r', fp);
1963 (void) fputc('t', fp);
1967 (void) fputc('v', fp);
1971 (void) fprintf(fp, "%.3o", c & 0377);
1979 * eatsize(): Eat the size spec from a number [eg. 10UL]
1982 eatsize(const char **p)
1986 if (LOWCASE(*l) == 'u')
1989 switch (LOWCASE(*l)) {
1990 case 'l': /* long */
1991 case 's': /* short */
1992 case 'h': /* short */
1993 case 'b': /* char/byte */
1994 case 'c': /* char/byte */
2005 * handle a compiled file.
2008 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
2016 char *dbname = NULL;
2019 mkdbname(fn, &dbname, 0);
2023 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
2026 if (fstat(fd, &st) == -1) {
2027 file_error(ms, errno, "cannot stat `%s'", dbname);
2030 if (st.st_size < 8) {
2031 file_error(ms, 0, "file `%s' is too small", dbname);
2036 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
2037 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
2038 file_error(ms, errno, "cannot map `%s'", dbname);
2043 if ((mm = CAST(void *, malloc((size_t)st.st_size))) == NULL) {
2044 file_oomem(ms, (size_t)st.st_size);
2047 if (read(fd, mm, (size_t)st.st_size) != (size_t)st.st_size) {
2053 *magicp = CAST(struct magic *, mm);
2056 ptr = (uint32_t *)(void *)*magicp;
2057 if (*ptr != MAGICNO) {
2058 if (swap4(*ptr) != MAGICNO) {
2059 file_error(ms, 0, "bad magic in `%s'", dbname);
2066 version = swap4(ptr[1]);
2069 if (version != VERSIONNO) {
2070 file_error(ms, 0, "File %d.%d supports only %d version magic "
2071 "files. `%s' is version %d", FILE_VERSION_MAJOR, patchlevel,
2072 VERSIONNO, dbname, version);
2075 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic));
2080 byteswap(*magicp, *nmagicp);
2089 (void)munmap((void *)mm, (size_t)st.st_size);
2102 private const uint32_t ar[] = {
2106 * handle an mmaped file.
2109 apprentice_compile(struct magic_set *ms, struct magic **magicp,
2110 uint32_t *nmagicp, const char *fn)
2116 mkdbname(fn, &dbname, 1);
2121 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1) {
2122 file_error(ms, errno, "cannot open `%s'", dbname);
2126 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
2127 file_error(ms, errno, "error writing `%s'", dbname);
2131 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
2132 != sizeof(struct magic)) {
2133 file_error(ms, errno, "error seeking `%s'", dbname);
2137 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
2138 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
2139 file_error(ms, errno, "error writing `%s'", dbname);
2150 private const char ext[] = ".mgc";
2155 mkdbname(const char *fn, char **buf, int strip)
2159 if ((p = strrchr(fn, '/')) != NULL)
2163 if ((p = strstr(fn, ext)) != NULL && p[sizeof(ext) - 1] == '\0')
2166 (void)asprintf(buf, "%s%s", fn, ext);
2168 if (buf && *buf && strlen(*buf) > MAXPATHLEN) {
2175 * Byteswap an mmap'ed file if needed
2178 byteswap(struct magic *magic, uint32_t nmagic)
2181 for (i = 0; i < nmagic; i++)
2192 uint8_t *s = (uint8_t *)(void *)&sv;
2193 uint8_t *d = (uint8_t *)(void *)&rv;
2206 uint8_t *s = (uint8_t *)(void *)&sv;
2207 uint8_t *d = (uint8_t *)(void *)&rv;
2222 uint8_t *s = (uint8_t *)(void *)&sv;
2223 uint8_t *d = (uint8_t *)(void *)&rv;
2247 * byteswap a single magic entry
2250 bs1(struct magic *m)
2252 m->cont_level = swap2(m->cont_level);
2253 m->offset = swap4((uint32_t)m->offset);
2254 m->in_offset = swap4((uint32_t)m->in_offset);
2255 m->lineno = swap4((uint32_t)m->lineno);
2256 if (IS_STRING(m->type)) {
2257 m->str_range = swap4(m->str_range);
2258 m->str_flags = swap4(m->str_flags);
2261 m->value.q = swap8(m->value.q);
2262 m->num_mask = swap8(m->num_mask);