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.
43 #include <sys/param.h>
49 FILE_RCSID("@(#)$File: apprentice.c,v 1.105 2007/05/16 20:51:40 christos Exp $")
52 #define EATAB {while (isascii((unsigned char) *l) && \
53 isspace((unsigned char) *l)) ++l;}
54 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
55 tolower((unsigned char) (l)) : (l))
57 * Work around a bug in headers on Digital Unix.
58 * At least confirmed for: OSF1 V4.0 878
60 #if defined(__osf__) && defined(__DECC)
67 #define MAP_FAILED (void *) -1
75 #define MAXPATHLEN 1024
84 int file_formats[FILE_NAMES_SIZE];
85 const size_t file_nformats = FILE_NAMES_SIZE;
86 const char *file_names[FILE_NAMES_SIZE];
87 const size_t file_nnames = FILE_NAMES_SIZE;
89 private int getvalue(struct magic_set *ms, struct magic *, const char **, int);
90 private int hextoint(int);
91 private const char *getstr(struct magic_set *, const char *, char *, int,
93 private int parse(struct magic_set *, struct magic_entry **, uint32_t *,
94 const char *, size_t, int);
95 private void eatsize(const char **);
96 private int apprentice_1(struct magic_set *, const char *, int, struct mlist *);
97 private size_t apprentice_magic_strength(const struct magic *);
98 private int apprentice_sort(const void *, const void *);
99 private int apprentice_file(struct magic_set *, struct magic **, uint32_t *,
101 private void byteswap(struct magic *, uint32_t);
102 private void bs1(struct magic *);
103 private uint16_t swap2(uint16_t);
104 private uint32_t swap4(uint32_t);
105 private uint64_t swap8(uint64_t);
106 private char *mkdbname(const char *, char *, size_t, int);
107 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
109 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
111 private int check_format_type(const char *, int);
112 private int check_format(struct magic_set *, struct magic *);
114 private size_t maxmagic = 0;
115 private size_t magicsize = sizeof(struct magic);
120 int main(int, char *[]);
123 main(int argc, char *argv[])
126 struct magic_set *ms;
129 if ((progname = strrchr(argv[0], '/')) != NULL)
135 (void)fprintf(stderr, "Usage: %s file\n", progname);
139 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
140 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
143 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
145 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
149 #endif /* COMPILE_ONLY */
151 static const struct type_tbl_s {
157 # define XX(s) s, (sizeof(s) - 1)
158 # define XX_NULL NULL, 0
159 { XX("byte"), FILE_BYTE, FILE_FMT_NUM },
160 { XX("short"), FILE_SHORT, FILE_FMT_NUM },
161 { XX("default"), FILE_DEFAULT, FILE_FMT_STR },
162 { XX("long"), FILE_LONG, FILE_FMT_NUM },
163 { XX("string"), FILE_STRING, FILE_FMT_STR },
164 { XX("date"), FILE_DATE, FILE_FMT_STR },
165 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM },
166 { XX("belong"), FILE_BELONG, FILE_FMT_NUM },
167 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR },
168 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM },
169 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM },
170 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR },
171 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR },
172 { XX("ldate"), FILE_LDATE, FILE_FMT_STR },
173 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR },
174 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR },
175 { XX("regex"), FILE_REGEX, FILE_FMT_STR },
176 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR },
177 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR },
178 { XX("search"), FILE_SEARCH, FILE_FMT_STR },
179 { XX("medate"), FILE_MEDATE, FILE_FMT_STR },
180 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR },
181 { XX("melong"), FILE_MELONG, FILE_FMT_NUM },
182 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD },
183 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD },
184 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD },
185 { XX("qdate"), FILE_QDATE, FILE_FMT_STR },
186 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR },
187 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR },
188 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR },
189 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR },
190 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR },
191 { XX_NULL, FILE_INVALID, FILE_FMT_NONE },
197 get_type(const char *l, const char **t)
199 const struct type_tbl_s *p;
201 for (p = type_tbl; p->name; p++) {
202 if (strncmp(l, p->name, p->len) == 0) {
212 init_file_tables(void)
215 const struct type_tbl_s *p;
221 for (p = type_tbl; p->name; p++) {
222 assert(p->type < FILE_NAMES_SIZE);
223 file_names[p->type] = p->name;
224 file_formats[p->type] = p->format;
232 apprentice_1(struct magic_set *ms, const char *fn, int action,
235 struct magic *magic = NULL;
241 if (magicsize != FILE_MAGICSIZE) {
242 file_error(ms, 0, "magic element size %lu != %lu",
243 (unsigned long)sizeof(*magic),
244 (unsigned long)FILE_MAGICSIZE);
248 if (action == FILE_COMPILE) {
249 rv = apprentice_file(ms, &magic, &nmagic, fn, action);
252 rv = apprentice_compile(ms, &magic, &nmagic, fn);
258 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
259 if (ms->flags & MAGIC_CHECK)
260 file_magwarn(ms, "using regular magic file `%s'", fn);
261 rv = apprentice_file(ms, &magic, &nmagic, fn, action);
269 if (magic == NULL || nmagic == 0) {
270 file_delmagic(magic, mapped, nmagic);
274 if ((ml = malloc(sizeof(*ml))) == NULL) {
275 file_delmagic(magic, mapped, nmagic);
276 file_oomem(ms, sizeof(*ml));
284 mlist->prev->next = ml;
285 ml->prev = mlist->prev;
290 #endif /* COMPILE_ONLY */
294 file_delmagic(struct magic *p, int type, size_t entries)
301 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
314 /* const char *fn: list of magic files */
315 protected struct mlist *
316 file_apprentice(struct magic_set *ms, const char *fn, int action)
318 char *p, *mfn, *afn = NULL;
319 int file_err, errs = -1;
321 static const char mime[] = ".mime";
326 fn = getenv("MAGIC");
330 if ((mfn = strdup(fn)) == NULL) {
331 file_oomem(ms, strlen(fn));
336 if ((mlist = malloc(sizeof(*mlist))) == NULL) {
338 file_oomem(ms, sizeof(*mlist));
341 mlist->next = mlist->prev = mlist;
344 p = strchr(fn, PATHSEP);
349 if (ms->flags & MAGIC_MIME) {
350 size_t len = strlen(fn) + sizeof(mime);
351 if ((afn = malloc(len)) == NULL) {
357 (void)strcpy(afn, fn);
358 (void)strcat(afn, mime);
361 file_err = apprentice_1(ms, fn, action, mlist);
374 file_error(ms, 0, "could not find any magic files!");
382 * Get weight of this magic entry, for sorting purposes.
385 apprentice_magic_strength(const struct magic *m)
388 size_t val = 2 * MULT; /* baseline strength */
391 case FILE_DEFAULT: /* make sure this sorts last */
413 val += m->vallen * MULT;
416 case FILE_BESTRING16:
417 case FILE_LESTRING16:
418 val += m->vallen * MULT / 2;
451 (void)fprintf(stderr, "Bad type %d\n", m->type);
456 case 'x': /* matches anything penalize */
461 case '=': /* Exact match, prefer */
466 case '<': /* comparison match reduce strength */
471 case '&': /* masking bits, we could count them too */
476 (void)fprintf(stderr, "Bad relation %c\n", m->reln);
480 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */
487 * Sort callback for sorting entries by "strength" (basically length)
490 apprentice_sort(const void *a, const void *b)
492 const struct magic_entry *ma = a;
493 const struct magic_entry *mb = b;
494 size_t sa = apprentice_magic_strength(ma->mp);
495 size_t sb = apprentice_magic_strength(mb->mp);
506 * const char *fn: name of magic file
509 apprentice_file(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
510 const char *fn, int action)
512 private const char hdr[] =
513 "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
517 struct magic_entry *marray;
518 uint32_t marraycount, i, mentrycount = 0;
521 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */
523 f = fopen(ms->file = fn, "r");
526 file_error(ms, errno, "cannot read magic file `%s'",
532 if ((marray = calloc(maxmagic, sizeof(*marray))) == NULL) {
534 file_oomem(ms, maxmagic * sizeof(*marray));
539 /* print silly verbose header for USG compat. */
540 if (action == FILE_CHECK)
541 (void)fprintf(stderr, "%s\n", hdr);
543 /* read and parse this file */
544 for (ms->line = 1; fgets(line, BUFSIZ, f) != NULL; ms->line++) {
547 if (len == 0) /* null line, garbage, etc */
549 if (line[len - 1] == '\n') {
551 line[len - 1] = '\0'; /* delete newline */
553 if (line[0] == '\0') /* empty, do not parse */
555 if (line[0] == '#') /* comment, do not parse */
557 if (parse(ms, &marray, &marraycount, line, lineno, action) != 0)
566 qsort(marray, marraycount, sizeof(*marray), apprentice_sort);
568 * Make sure that any level 0 "default" line is last (if one exists).
570 for (i = 0; i < marraycount; i++) {
571 if (marray[i].mp->cont_level == 0 &&
572 marray[i].mp->type == FILE_DEFAULT) {
573 while (++i < marraycount)
574 if (marray[i].mp->cont_level == 0)
576 if (i != marraycount) {
577 ms->line = marray[i].mp->lineno; /* XXX - Ugh! */
579 "level 0 \"default\" did not sort last");
586 for (i = 0; i < marraycount; i++)
587 mentrycount += marray[i].cont_count;
589 if ((*magicp = malloc(sizeof(**magicp) * mentrycount)) == NULL) {
590 file_oomem(ms, sizeof(**magicp) * mentrycount);
596 for (i = 0; i < marraycount; i++) {
597 (void)memcpy(*magicp + mentrycount, marray[i].mp,
598 marray[i].cont_count * sizeof(**magicp));
599 mentrycount += marray[i].cont_count;
602 for (i = 0; i < marraycount; i++)
610 *nmagicp = mentrycount;
617 * extend the sign bit if the comparison is to be signed
620 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v)
622 if (!(m->flag & UNSIGNED)) {
625 * Do not remove the casts below. They are
626 * vital. When later compared with the data,
627 * the sign extension must have happened.
664 case FILE_BESTRING16:
665 case FILE_LESTRING16:
671 if (ms->flags & MAGIC_CHECK)
672 file_magwarn(ms, "cannot happen: m->type=%d\n",
681 string_modifier_check(struct magic_set *ms, struct magic const *m)
683 if ((ms->flags & MAGIC_CHECK) == 0)
687 case FILE_BESTRING16:
688 case FILE_LESTRING16:
689 if (m->str_flags != 0) {
690 file_magwarn(ms, "no modifiers allowed for 16-bit strings\n");
696 if ((m->str_flags & REGEX_OFFSET_START) != 0) {
697 file_magwarn(ms, "'/%c' only allowed on regex and search\n",
698 CHAR_REGEX_OFFSET_START);
705 if ((m->str_flags & STRING_COMPACT_BLANK) != 0) {
706 file_magwarn(ms, "'/%c' not allowed on regex\n",
710 if ((m->str_flags & STRING_COMPACT_OPTIONAL_BLANK) != 0) {
711 file_magwarn(ms, "'/%c' not allowed on regex\n",
712 CHAR_COMPACT_OPTIONAL_BLANK);
717 file_magwarn(ms, "coding error: m->type=%d\n",
739 return FILE_OPMULTIPLY;
741 return FILE_OPDIVIDE;
743 return FILE_OPMODULO;
749 #ifdef ENABLE_CONDITIONALS
751 get_cond(const char *l, const char **t)
753 static struct cond_tbl_s {
758 { "if", 2, COND_IF },
759 { "elif", 4, COND_ELIF },
760 { "else", 4, COND_ELSE },
761 { NULL, 0, COND_NONE },
763 struct cond_tbl_s *p;
765 for (p = cond_tbl; p->name; p++) {
766 if (strncmp(l, p->name, p->len) == 0 &&
767 isspace((unsigned char)l[p->len])) {
777 check_cond(struct magic_set *ms, int cond, uint32_t cont_level)
780 last_cond = ms->c.li[cont_level].last_cond;
784 if (last_cond != COND_NONE && last_cond != COND_ELIF) {
785 if (ms->flags & MAGIC_CHECK)
786 file_magwarn(ms, "syntax error: `if'");
793 if (last_cond != COND_IF && last_cond != COND_ELIF) {
794 if (ms->flags & MAGIC_CHECK)
795 file_magwarn(ms, "syntax error: `elif'");
798 last_cond = COND_ELIF;
802 if (last_cond != COND_IF && last_cond != COND_ELIF) {
803 if (ms->flags & MAGIC_CHECK)
804 file_magwarn(ms, "syntax error: `else'");
807 last_cond = COND_NONE;
811 last_cond = COND_NONE;
815 ms->c.li[cont_level].last_cond = last_cond;
818 #endif /* ENABLE_CONDITIONALS */
821 * parse one line from magic file, put into magic[index++] if valid
824 parse(struct magic_set *ms, struct magic_entry **mentryp, uint32_t *nmentryp,
825 const char *line, size_t lineno, int action)
827 #ifdef ENABLE_CONDITIONALS
828 static uint32_t last_cont_level = 0;
831 struct magic_entry *me;
833 const char *l = line;
844 #ifdef ENABLE_CONDITIONALS
845 if (cont_level == 0 || cont_level > last_cont_level)
846 if (file_check_mem(ms, cont_level) == -1)
848 last_cont_level = cont_level;
851 #define ALLOC_CHUNK (size_t)10
852 #define ALLOC_INCR (size_t)200
854 if (cont_level != 0) {
855 if (*nmentryp == 0) {
856 file_error(ms, 0, "No current entry for continuation");
859 me = &(*mentryp)[*nmentryp - 1];
860 if (me->cont_count == me->max_count) {
862 size_t cnt = me->max_count + ALLOC_CHUNK;
863 if ((nm = realloc(me->mp, sizeof(*nm) * cnt)) == NULL) {
864 file_oomem(ms, sizeof(*nm) * cnt);
870 m = &me->mp[me->cont_count++];
871 (void)memset(m, 0, sizeof(*m));
872 m->cont_level = cont_level;
874 if (*nmentryp == maxmagic) {
875 struct magic_entry *mp;
877 maxmagic += ALLOC_INCR;
878 if ((mp = realloc(*mentryp, sizeof(*mp) * maxmagic)) ==
880 file_oomem(ms, sizeof(*mp) * maxmagic);
883 (void)memset(&mp[*nmentryp], 0, sizeof(*mp) *
887 me = &(*mentryp)[*nmentryp];
888 if (me->mp == NULL) {
889 if ((m = malloc(sizeof(*m) * ALLOC_CHUNK)) == NULL) {
890 file_oomem(ms, sizeof(*m) * ALLOC_CHUNK);
894 me->max_count = ALLOC_CHUNK;
897 (void)memset(m, 0, sizeof(*m));
903 if (*l == '&') { /* m->cont_level == 0 checked below. */
910 if (m->flag & OFFADD)
911 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
913 if (*l == '&') { /* m->cont_level == 0 checked below */
918 /* Indirect offsets are not valid at level 0. */
919 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD)))
920 if (ms->flags & MAGIC_CHECK)
921 file_magwarn(ms, "relative offset at level 0");
923 /* get offset, then skip over it */
924 m->offset = (uint32_t)strtoul(l, &t, 0);
926 if (ms->flags & MAGIC_CHECK)
927 file_magwarn(ms, "offset `%s' invalid", l);
930 if (m->flag & INDIR) {
931 m->in_type = FILE_LONG;
934 * read [.lbs][+-]nnnnn)
940 m->in_type = FILE_LELONG;
943 m->in_type = FILE_BELONG;
946 m->in_type = FILE_MELONG;
950 m->in_type = FILE_LESHORT;
954 m->in_type = FILE_BESHORT;
960 m->in_type = FILE_BYTE;
963 if (ms->flags & MAGIC_CHECK)
965 "indirect offset type `%c' invalid",
974 m->in_op |= FILE_OPINVERSE;
977 if ((op = get_op(*l)) != -1) {
982 m->in_op |= FILE_OPINDIRECT;
985 if (isdigit((unsigned char)*l) || *l == '-') {
986 m->in_offset = (int32_t)strtol(l, &t, 0);
988 if (ms->flags & MAGIC_CHECK)
990 "in_offset `%s' invalid", l);
994 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')'))
995 if (ms->flags & MAGIC_CHECK)
997 "missing ')' in indirect offset");
1001 #ifdef ENABLE_CONDITIONALS
1002 m->cond = get_cond(l, &l);
1003 if (check_cond(ms, m->cond, cont_level) == -1)
1011 m->flag |= UNSIGNED;
1014 m->type = get_type(l, &l);
1015 if (m->type == FILE_INVALID) {
1016 if (ms->flags & MAGIC_CHECK)
1017 file_magwarn(ms, "type `%s' invalid", l);
1021 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1022 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1026 if (!IS_STRING(m->type))
1027 m->mask_op |= FILE_OPINVERSE;
1028 else if (ms->flags & MAGIC_CHECK)
1029 file_magwarn(ms, "'~' invalid for string types");
1035 if ((op = get_op(*l)) != -1) {
1036 if (!IS_STRING(m->type)) {
1040 val = (uint64_t)strtoull(l, &t, 0);
1042 m->num_mask = file_signextend(ms, m, val);
1045 else if (op == FILE_OPDIVIDE) {
1047 while (!isspace((unsigned char)*++l)) {
1049 /* for portability avoid "case '0' ... '9':" */
1050 case '0': case '1': case '2':
1051 case '3': case '4': case '5':
1052 case '6': case '7': case '8':
1054 if (have_count && ms->flags & MAGIC_CHECK)
1058 m->str_count = strtoul(l, &t, 0);
1062 case CHAR_COMPACT_BLANK:
1063 m->str_flags |= STRING_COMPACT_BLANK;
1065 case CHAR_COMPACT_OPTIONAL_BLANK:
1067 STRING_COMPACT_OPTIONAL_BLANK;
1069 case CHAR_IGNORE_LOWERCASE:
1070 m->str_flags |= STRING_IGNORE_LOWERCASE;
1072 case CHAR_IGNORE_UPPERCASE:
1073 m->str_flags |= STRING_IGNORE_UPPERCASE;
1075 case CHAR_REGEX_OFFSET_START:
1076 m->str_flags |= REGEX_OFFSET_START;
1079 if (ms->flags & MAGIC_CHECK)
1081 "string extension `%c' invalid",
1085 /* allow multiple '/' for readability */
1086 if (l[1] == '/' && !isspace((unsigned char)l[2]))
1089 if (string_modifier_check(ms, m) == -1)
1093 if (ms->flags & MAGIC_CHECK)
1094 file_magwarn(ms, "invalid string op: %c", *t);
1099 * We used to set mask to all 1's here, instead let's just not do
1100 * anything if mask = 0 (unless you have a better idea)
1107 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1114 /* HP compat: ignore &= etc. */
1123 m->reln = '='; /* the default relation */
1124 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
1125 isspace((unsigned char)l[1])) || !l[1])) {
1132 * Grab the value part, except for an 'x' reln.
1134 if (m->reln != 'x' && getvalue(ms, m, &l, action))
1138 * TODO finish this macro and start using it!
1139 * #define offsetcheck {if (offset > HOWMANY-1)
1140 * magwarn("offset too big"); }
1144 * Now get last part - the description
1150 } else if ((l[0] == '\\') && (l[1] == 'b')) {
1156 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); )
1158 if (i == sizeof(m->desc)) {
1159 m->desc[sizeof(m->desc) - 1] = '\0';
1160 if (ms->flags & MAGIC_CHECK)
1161 file_magwarn(ms, "description `%s' truncated", m->desc);
1165 * We only do this check while compiling, or if any of the magic
1166 * files were not compiled.
1168 if (ms->flags & MAGIC_CHECK) {
1169 if (check_format(ms, m) == -1)
1172 #ifndef COMPILE_ONLY
1173 if (action == FILE_CHECK) {
1177 if (m->cont_level == 0)
1178 ++(*nmentryp); /* make room for next */
1183 check_format_type(const char *ptr, int type)
1187 /* Missing format string; bad */
1200 while (isdigit((unsigned char)*ptr)) ptr++;
1203 while (isdigit((unsigned char)*ptr)) ptr++;
1258 while (isdigit((unsigned char )*ptr))
1262 while (isdigit((unsigned char )*ptr))
1274 /* internal error */
1282 * Check that the optional printf format in description matches
1283 * the type of the magic.
1286 check_format(struct magic_set *ms, struct magic *m)
1290 for (ptr = m->desc; *ptr; ptr++)
1294 /* No format string; ok */
1298 assert(file_nformats == file_nnames);
1300 if (m->type >= file_nformats) {
1301 file_error(ms, 0, "Internal error inconsistency between "
1302 "m->type and format strings");
1305 if (file_formats[m->type] == FILE_FMT_NONE) {
1306 file_error(ms, 0, "No format string for `%s' with description "
1307 "`%s'", m->desc, file_names[m->type]);
1312 if (check_format_type(ptr, file_formats[m->type]) == -1) {
1314 * TODO: this error message is unhelpful if the format
1315 * string is not one character long
1317 file_error(ms, 0, "Printf format `%c' is not valid for type "
1318 " `%s' in description `%s'", *ptr,
1319 file_names[m->type], m->desc);
1323 for (; *ptr; ptr++) {
1326 "Too many format strings (should have at most one) "
1327 "for `%s' with description `%s'",
1328 file_names[m->type], m->desc);
1336 * Read a numeric value from a pointer, into the value union of a magic
1337 * pointer, according to the magic type. Update the string pointer to point
1338 * just after the number read. Return 0 for success, non-zero for failure.
1341 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action)
1346 case FILE_BESTRING16:
1347 case FILE_LESTRING16:
1352 *p = getstr(ms, *p, m->value.s, sizeof(m->value.s), &slen, action);
1354 if (ms->flags & MAGIC_CHECK)
1355 file_magwarn(ms, "cannot get string from `%s'",
1362 if (m->reln != 'x') {
1364 m->value.q = file_signextend(ms, m,
1365 (uint64_t)strtoull(*p, &ep, 0));
1374 * Convert a string containing C character escapes. Stop at an unescaped
1376 * Copy the converted version to "p", returning its length in *slen.
1377 * Return updated scan pointer as function result.
1379 private const char *
1380 getstr(struct magic_set *ms, const char *s, char *p, int plen, int *slen, int action)
1382 const char *origs = s;
1384 char *pmax = p + plen - 1;
1388 while ((c = *s++) != '\0') {
1389 if (isspace((unsigned char) c))
1392 file_error(ms, 0, "string too long: `%s'", origs);
1399 if (action == FILE_COMPILE)
1400 file_magwarn(ms, "incomplete escape");
1404 if (action == FILE_COMPILE) {
1406 "escaped tab found, use \\t instead");
1411 if (action == FILE_COMPILE) {
1412 if (isprint((unsigned char)c))
1414 "no need to escape `%c'", c);
1417 "unknown escape sequence: \\%03o", c);
1420 /* space, perhaps force people to use \040? */
1424 * Other things people escape, but shouldn't need to,
1425 * so we disallow them
1438 /* and baskslash itself */
1471 /* \ and up to 3 octal digits */
1481 c = *s++; /* try for 2 */
1482 if (c >= '0' && c <= '7') {
1483 val = (val << 3) | (c - '0');
1484 c = *s++; /* try for 3 */
1485 if (c >= '0' && c <= '7')
1486 val = (val << 3) | (c-'0');
1495 /* \x and up to 2 hex digits */
1497 val = 'x'; /* Default if no digits */
1498 c = hextoint(*s++); /* Get next char */
1503 val = (val << 4) + c;
1521 /* Single hex char to int; -1 if not a hex char. */
1525 if (!isascii((unsigned char) c))
1527 if (isdigit((unsigned char) c))
1529 if ((c >= 'a') && (c <= 'f'))
1530 return c + 10 - 'a';
1531 if (( c>= 'A') && (c <= 'F'))
1532 return c + 10 - 'A';
1538 * Print a string containing C character escapes.
1541 file_showstr(FILE *fp, const char *s, size_t len)
1555 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
1556 (void) fputc(c, fp);
1558 (void) fputc('\\', fp);
1561 (void) fputc('a', fp);
1565 (void) fputc('b', fp);
1569 (void) fputc('f', fp);
1573 (void) fputc('n', fp);
1577 (void) fputc('r', fp);
1581 (void) fputc('t', fp);
1585 (void) fputc('v', fp);
1589 (void) fprintf(fp, "%.3o", c & 0377);
1597 * eatsize(): Eat the size spec from a number [eg. 10UL]
1600 eatsize(const char **p)
1604 if (LOWCASE(*l) == 'u')
1607 switch (LOWCASE(*l)) {
1608 case 'l': /* long */
1609 case 's': /* short */
1610 case 'h': /* short */
1611 case 'b': /* char/byte */
1612 case 'c': /* char/byte */
1623 * handle a compiled file.
1626 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
1634 char buf[MAXPATHLEN];
1635 char *dbname = mkdbname(fn, buf, sizeof(buf), 0);
1641 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1)
1644 if (fstat(fd, &st) == -1) {
1645 file_error(ms, errno, "cannot stat `%s'", dbname);
1648 if (st.st_size < 16) {
1649 file_error(ms, 0, "file `%s' is too small", dbname);
1654 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
1655 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
1656 file_error(ms, errno, "cannot map `%s'", dbname);
1661 if ((mm = malloc((size_t)st.st_size)) == NULL) {
1662 file_oomem(ms, (size_t)st.st_size);
1665 if (read(fd, mm, (size_t)st.st_size) != (size_t)st.st_size) {
1674 ptr = (uint32_t *)(void *)*magicp;
1675 if (*ptr != MAGICNO) {
1676 if (swap4(*ptr) != MAGICNO) {
1677 file_error(ms, 0, "bad magic in `%s'");
1684 version = swap4(ptr[1]);
1687 if (version != VERSIONNO) {
1688 file_error(ms, 0, "version mismatch (%d != %d) in `%s'",
1689 version, VERSIONNO, dbname);
1692 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic)) - 1;
1695 byteswap(*magicp, *nmagicp);
1703 (void)munmap((void *)mm, (size_t)st.st_size);
1714 private const uint32_t ar[] = {
1718 * handle an mmaped file.
1721 apprentice_compile(struct magic_set *ms, struct magic **magicp,
1722 uint32_t *nmagicp, const char *fn)
1725 char buf[MAXPATHLEN];
1726 char *dbname = mkdbname(fn, buf, sizeof(buf), 1);
1731 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1) {
1732 file_error(ms, errno, "cannot open `%s'", dbname);
1736 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
1737 file_error(ms, errno, "error writing `%s'", dbname);
1741 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
1742 != sizeof(struct magic)) {
1743 file_error(ms, errno, "error seeking `%s'", dbname);
1747 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
1748 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
1749 file_error(ms, errno, "error writing `%s'", dbname);
1757 private const char ext[] = ".mgc";
1762 mkdbname(const char *fn, char *buf, size_t bufsiz, int strip)
1766 if ((p = strrchr(fn, '/')) != NULL)
1770 (void)snprintf(buf, bufsiz, "%s%s", fn, ext);
1775 * Byteswap an mmap'ed file if needed
1778 byteswap(struct magic *magic, uint32_t nmagic)
1781 for (i = 0; i < nmagic; i++)
1792 uint8_t *s = (uint8_t *)(void *)&sv;
1793 uint8_t *d = (uint8_t *)(void *)&rv;
1806 uint8_t *s = (uint8_t *)(void *)&sv;
1807 uint8_t *d = (uint8_t *)(void *)&rv;
1822 uint8_t *s = (uint8_t *)(void *)&sv;
1823 uint8_t *d = (uint8_t *)(void *)&rv;
1836 * byteswap a single magic entry
1839 bs1(struct magic *m)
1841 m->cont_level = swap2(m->cont_level);
1842 m->offset = swap4((uint32_t)m->offset);
1843 m->in_offset = swap4((uint32_t)m->in_offset);
1844 m->lineno = swap4((uint32_t)m->lineno);
1845 if (IS_STRING(m->type)) {
1846 m->str_count = swap4(m->str_count);
1847 m->str_flags = swap4(m->str_flags);
1850 m->value.q = swap8(m->value.q);
1851 m->num_mask = swap8(m->num_mask);