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.
42 #include <sys/param.h>
48 FILE_RCSID("@(#)$Id: apprentice.c,v 1.82 2004/11/24 18:56:04 christos Exp $")
51 #define EATAB {while (isascii((unsigned char) *l) && \
52 isspace((unsigned char) *l)) ++l;}
53 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
54 tolower((unsigned char) (l)) : (l))
56 * Work around a bug in headers on Digital Unix.
57 * At least confirmed for: OSF1 V4.0 878
59 #if defined(__osf__) && defined(__DECC)
66 #define MAP_FAILED (void *) -1
74 #define MAXPATHLEN 1024
77 #define IS_STRING(t) ((t) == FILE_STRING || (t) == FILE_PSTRING || \
78 (t) == FILE_BESTRING16 || (t) == FILE_LESTRING16)
80 private int getvalue(struct magic_set *ms, struct magic *, char **);
81 private int hextoint(int);
82 private char *getstr(struct magic_set *, char *, char *, int, int *);
83 private int parse(struct magic_set *, struct magic **, uint32_t *, char *, int);
84 private void eatsize(char **);
85 private int apprentice_1(struct magic_set *, const char *, int, struct mlist *);
86 private int apprentice_file(struct magic_set *, struct magic **, uint32_t *,
88 private void byteswap(struct magic *, uint32_t);
89 private void bs1(struct magic *);
90 private uint16_t swap2(uint16_t);
91 private uint32_t swap4(uint32_t);
92 private char *mkdbname(const char *, char *, size_t, int);
93 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
95 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
97 private int check_format(struct magic_set *, struct magic *);
99 private size_t maxmagic = 0;
100 private size_t magicsize = sizeof(struct magic);
104 int main(int, char *[]);
107 main(int argc, char *argv[])
110 struct magic_set *ms;
113 if ((progname = strrchr(argv[0], '/')) != NULL)
119 (void)fprintf(stderr, "Usage: %s file\n", progname);
123 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
124 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
127 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
129 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
133 #endif /* COMPILE_ONLY */
140 apprentice_1(struct magic_set *ms, const char *fn, int action,
143 struct magic *magic = NULL;
149 if (magicsize != FILE_MAGICSIZE) {
150 file_error(ms, 0, "magic element size %lu != %lu",
151 (unsigned long)sizeof(*magic),
152 (unsigned long)FILE_MAGICSIZE);
156 if (action == FILE_COMPILE) {
157 rv = apprentice_file(ms, &magic, &nmagic, fn, action);
160 rv = apprentice_compile(ms, &magic, &nmagic, fn);
165 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
166 if (ms->flags & MAGIC_CHECK)
167 file_magwarn(ms, "using regular magic file `%s'", fn);
168 rv = apprentice_file(ms, &magic, &nmagic, fn, action);
178 if (magic == NULL || nmagic == 0) {
179 file_delmagic(magic, mapped, nmagic);
183 if ((ml = malloc(sizeof(*ml))) == NULL) {
184 file_delmagic(magic, mapped, nmagic);
193 mlist->prev->next = ml;
194 ml->prev = mlist->prev;
199 #endif /* COMPILE_ONLY */
203 file_delmagic(struct magic *p, int type, size_t entries)
210 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
224 /* const char *fn: list of magic files */
225 protected struct mlist *
226 file_apprentice(struct magic_set *ms, const char *fn, int action)
228 char *p, *mfn, *afn = NULL;
229 int file_err, errs = -1;
233 fn = getenv("MAGIC");
237 if ((fn = mfn = strdup(fn)) == NULL) {
242 if ((mlist = malloc(sizeof(*mlist))) == NULL) {
247 mlist->next = mlist->prev = mlist;
250 p = strchr(fn, PATHSEP);
255 if (ms->flags & MAGIC_MIME) {
256 if ((afn = malloc(strlen(fn) + 5 + 1)) == NULL) {
262 (void)strcpy(afn, fn);
263 (void)strcat(afn, ".mime");
266 file_err = apprentice_1(ms, fn, action, mlist);
279 file_error(ms, 0, "could not find any magic files!");
288 * const char *fn: name of magic file
291 apprentice_file(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
292 const char *fn, int action)
294 private const char hdr[] =
295 "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
300 f = fopen(ms->file = fn, "r");
303 file_error(ms, errno, "cannot read magic file `%s'",
309 *magicp = (struct magic *) calloc(maxmagic, sizeof(struct magic));
310 if (*magicp == NULL) {
316 /* print silly verbose header for USG compat. */
317 if (action == FILE_CHECK)
318 (void)fprintf(stderr, "%s\n", hdr);
321 for (ms->line = 1; fgets(line, BUFSIZ, f) != NULL; ms->line++) {
323 if (line[0]=='#') /* comment, do not parse */
326 if (len < 2) /* null line, garbage, etc */
328 line[len - 1] = '\0'; /* delete newline */
329 if (parse(ms, magicp, nmagicp, line, action) != 0)
343 * extend the sign bit if the comparison is to be signed
346 file_signextend(struct magic_set *ms, struct magic *m, uint32_t v)
348 if (!(m->flag & UNSIGNED))
351 * Do not remove the casts below. They are
352 * vital. When later compared with the data,
353 * the sign extension must have happened.
376 case FILE_BESTRING16:
377 case FILE_LESTRING16:
382 if (ms->flags & MAGIC_CHECK)
383 file_magwarn(ms, "cannot happen: m->type=%d\n",
391 * parse one line from magic file, put into magic[index++] if valid
394 parse(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp, char *l,
400 private const char *fops = FILE_OPS;
403 #define ALLOC_INCR 200
404 if (*nmagicp + 1 >= maxmagic){
405 maxmagic += ALLOC_INCR;
406 if ((m = (struct magic *) realloc(*magicp,
407 sizeof(struct magic) * maxmagic)) == NULL) {
414 memset(&(*magicp)[*nmagicp], 0, sizeof(struct magic)
417 m = &(*magicp)[*nmagicp];
426 if (m->cont_level != 0 && *l == '(') {
430 if (m->cont_level != 0 && *l == '&') {
435 /* get offset, then skip over it */
436 m->offset = (uint32_t)strtoul(l, &t, 0);
438 if (ms->flags & MAGIC_CHECK)
439 file_magwarn(ms, "offset `%s' invalid", l);
442 if (m->flag & INDIR) {
443 m->in_type = FILE_LONG;
446 * read [.lbs][+-]nnnnn)
452 m->in_type = FILE_LELONG;
455 m->in_type = FILE_BELONG;
459 m->in_type = FILE_LESHORT;
463 m->in_type = FILE_BESHORT;
469 m->in_type = FILE_BYTE;
472 if (ms->flags & MAGIC_CHECK)
474 "indirect offset type `%c' invalid",
481 m->in_op = FILE_OPINVERSE;
486 m->in_op |= FILE_OPAND;
490 m->in_op |= FILE_OPOR;
494 m->in_op |= FILE_OPXOR;
498 m->in_op |= FILE_OPADD;
502 m->in_op |= FILE_OPMINUS;
506 m->in_op |= FILE_OPMULTIPLY;
510 m->in_op |= FILE_OPDIVIDE;
514 m->in_op |= FILE_OPMODULO;
518 if (isdigit((unsigned char)*l))
519 m->in_offset = (uint32_t)strtoul(l, &t, 0);
523 if (ms->flags & MAGIC_CHECK)
525 "missing ')' in indirect offset");
530 while (isascii((unsigned char)*l) && isdigit((unsigned char)*l))
550 #define NBESTRING16 10
551 #define NLESTRING16 10
558 /* get type, skip it */
559 if (strncmp(l, "char", NBYTE)==0) { /* HP/UX compat */
562 } else if (strncmp(l, "byte", NBYTE)==0) {
565 } else if (strncmp(l, "short", NSHORT)==0) {
566 m->type = FILE_SHORT;
568 } else if (strncmp(l, "long", NLONG)==0) {
571 } else if (strncmp(l, "string", NSTRING)==0) {
572 m->type = FILE_STRING;
574 } else if (strncmp(l, "date", NDATE)==0) {
577 } else if (strncmp(l, "beshort", NBESHORT)==0) {
578 m->type = FILE_BESHORT;
580 } else if (strncmp(l, "belong", NBELONG)==0) {
581 m->type = FILE_BELONG;
583 } else if (strncmp(l, "bedate", NBEDATE)==0) {
584 m->type = FILE_BEDATE;
586 } else if (strncmp(l, "leshort", NLESHORT)==0) {
587 m->type = FILE_LESHORT;
589 } else if (strncmp(l, "lelong", NLELONG)==0) {
590 m->type = FILE_LELONG;
592 } else if (strncmp(l, "ledate", NLEDATE)==0) {
593 m->type = FILE_LEDATE;
595 } else if (strncmp(l, "pstring", NPSTRING)==0) {
596 m->type = FILE_PSTRING;
598 } else if (strncmp(l, "ldate", NLDATE)==0) {
599 m->type = FILE_LDATE;
601 } else if (strncmp(l, "beldate", NBELDATE)==0) {
602 m->type = FILE_BELDATE;
604 } else if (strncmp(l, "leldate", NLELDATE)==0) {
605 m->type = FILE_LELDATE;
607 } else if (strncmp(l, "regex", NREGEX)==0) {
608 m->type = FILE_REGEX;
610 } else if (strncmp(l, "bestring16", NBESTRING16)==0) {
611 m->type = FILE_BESTRING16;
613 } else if (strncmp(l, "lestring16", NLESTRING16)==0) {
614 m->type = FILE_LESTRING16;
617 if (ms->flags & MAGIC_CHECK)
618 file_magwarn(ms, "type `%s' invalid", l);
621 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
622 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
624 if (!IS_STRING(m->type))
625 m->mask_op = FILE_OPINVERSE;
628 if ((t = strchr(fops, *l)) != NULL) {
629 uint32_t op = (uint32_t)(t - fops);
630 if (op != FILE_OPDIVIDE || !IS_STRING(m->type)) {
633 val = (uint32_t)strtoul(l, &l, 0);
634 m->mask = file_signextend(ms, m, val);
638 while (!isspace((unsigned char)*++l)) {
640 case CHAR_IGNORE_LOWERCASE:
641 m->mask |= STRING_IGNORE_LOWERCASE;
643 case CHAR_COMPACT_BLANK:
644 m->mask |= STRING_COMPACT_BLANK;
646 case CHAR_COMPACT_OPTIONAL_BLANK:
648 STRING_COMPACT_OPTIONAL_BLANK;
651 if (ms->flags & MAGIC_CHECK)
653 "string extension `%c' invalid",
661 * We used to set mask to all 1's here, instead let's just not do
662 * anything if mask = 0 (unless you have a better idea)
669 /* Old-style anding: "0 byte &0x80 dynamically linked" */
676 /* HP compat: ignore &= etc. */
681 if (!IS_STRING(m->type)) {
688 if (*l == 'x' && isascii((unsigned char)l[1]) &&
689 isspace((unsigned char)l[1])) {
692 goto GetDesc; /* Bill The Cat */
699 if (getvalue(ms, m, &l))
702 * TODO finish this macro and start using it!
703 * #define offsetcheck {if (offset > HOWMANY-1)
704 * magwarn("offset too big"); }
708 * now get last part - the description
715 } else if ((l[0] == '\\') && (l[1] == 'b')) {
721 while ((m->desc[i++] = *l++) != '\0' && i < MAXDESC)
724 if (ms->flags & MAGIC_CHECK) {
725 if (!check_format(ms, m))
729 if (action == FILE_CHECK) {
733 ++(*nmagicp); /* make room for next */
738 * Check that the optional printf format in description matches
739 * the type of the magic.
742 check_format(struct magic_set *ms, struct magic *m)
744 static const char *formats[] = { FILE_FORMAT_STRING };
745 static const char *names[] = { FILE_FORMAT_NAME };
748 for (ptr = m->desc; *ptr; ptr++)
752 /* No format string; ok */
755 if (m->type >= sizeof(formats)/sizeof(formats[0])) {
756 file_magwarn(ms, "Internal error inconsistency between m->type"
757 " and format strings");
760 if (formats[m->type] == NULL) {
761 file_magwarn(ms, "No format string for `%s' with description "
762 "`%s'", m->desc, names[m->type]);
765 for (; *ptr; ptr++) {
766 if (*ptr == 'l' || *ptr == 'h') {
767 /* XXX: we should really fix this one day */
770 if (islower((unsigned char)*ptr) || *ptr == 'X')
774 /* Missing format string; bad */
775 file_magwarn(ms, "Invalid format `%s' for type `%s'",
776 m->desc, names[m->type]);
779 if (strchr(formats[m->type], *ptr) == NULL) {
780 file_magwarn(ms, "Printf format `%c' is not valid for type `%s'"
781 " in description `%s'",
782 *ptr, names[m->type], m->desc);
789 * Read a numeric value from a pointer, into the value union of a magic
790 * pointer, according to the magic type. Update the string pointer to point
791 * just after the number read. Return 0 for success, non-zero for failure.
794 getvalue(struct magic_set *ms, struct magic *m, char **p)
799 case FILE_BESTRING16:
800 case FILE_LESTRING16:
804 *p = getstr(ms, *p, m->value.s, sizeof(m->value.s), &slen);
806 if (ms->flags & MAGIC_CHECK)
807 file_magwarn(ms, "cannot get string from `%s'",
814 if (m->reln != 'x') {
815 m->value.l = file_signextend(ms, m,
816 (uint32_t)strtoul(*p, p, 0));
824 * Convert a string containing C character escapes. Stop at an unescaped
826 * Copy the converted version to "p", returning its length in *slen.
827 * Return updated scan pointer as function result.
830 getstr(struct magic_set *ms, char *s, char *p, int plen, int *slen)
832 char *origs = s, *origp = p;
833 char *pmax = p + plen - 1;
837 while ((c = *s++) != '\0') {
838 if (isspace((unsigned char) c))
841 file_error(ms, 0, "string too long: `%s'", origs);
878 /* \ and up to 3 octal digits */
888 c = *s++; /* try for 2 */
889 if(c >= '0' && c <= '7') {
890 val = (val<<3) | (c - '0');
891 c = *s++; /* try for 3 */
892 if(c >= '0' && c <= '7')
893 val = (val<<3) | (c-'0');
902 /* \x and up to 2 hex digits */
904 val = 'x'; /* Default if no digits */
905 c = hextoint(*s++); /* Get next char */
910 val = (val << 4) + c;
928 /* Single hex char to int; -1 if not a hex char. */
932 if (!isascii((unsigned char) c))
934 if (isdigit((unsigned char) c))
936 if ((c >= 'a')&&(c <= 'f'))
938 if (( c>= 'A')&&(c <= 'F'))
945 * Print a string containing C character escapes.
948 file_showstr(FILE *fp, const char *s, size_t len)
962 if(c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
965 (void) fputc('\\', fp);
969 (void) fputc('n', fp);
973 (void) fputc('r', fp);
977 (void) fputc('b', fp);
981 (void) fputc('t', fp);
985 (void) fputc('f', fp);
989 (void) fputc('v', fp);
993 (void) fprintf(fp, "%.3o", c & 0377);
1001 * eatsize(): Eat the size spec from a number [eg. 10UL]
1008 if (LOWCASE(*l) == 'u')
1011 switch (LOWCASE(*l)) {
1012 case 'l': /* long */
1013 case 's': /* short */
1014 case 'h': /* short */
1015 case 'b': /* char/byte */
1016 case 'c': /* char/byte */
1027 * handle a compiled file.
1030 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
1038 char buf[MAXPATHLEN];
1039 char *dbname = mkdbname(fn, buf, sizeof(buf), 0);
1045 if ((fd = open(dbname, O_RDONLY)) == -1)
1048 if (fstat(fd, &st) == -1) {
1049 file_error(ms, errno, "cannot stat `%s'", dbname);
1052 if (st.st_size < 16) {
1053 file_error(ms, 0, "file `%s' is too small", dbname);
1058 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
1059 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
1060 file_error(ms, errno, "cannot map `%s'", dbname);
1065 if ((mm = malloc((size_t)st.st_size)) == NULL) {
1069 if (read(fd, mm, (size_t)st.st_size) != (size_t)st.st_size) {
1078 ptr = (uint32_t *)(void *)*magicp;
1079 if (*ptr != MAGICNO) {
1080 if (swap4(*ptr) != MAGICNO) {
1081 file_error(ms, 0, "bad magic in `%s'");
1088 version = swap4(ptr[1]);
1091 if (version != VERSIONNO) {
1092 file_error(ms, 0, "version mismatch (%d != %d) in `%s'",
1093 version, VERSIONNO, dbname);
1096 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic)) - 1;
1099 byteswap(*magicp, *nmagicp);
1107 (void)munmap((void *)mm, (size_t)st.st_size);
1118 private const uint32_t ar[] = {
1122 * handle an mmaped file.
1125 apprentice_compile(struct magic_set *ms, struct magic **magicp,
1126 uint32_t *nmagicp, const char *fn)
1129 char buf[MAXPATHLEN];
1130 char *dbname = mkdbname(fn, buf, sizeof(buf), 1);
1135 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1) {
1136 file_error(ms, errno, "cannot open `%s'", dbname);
1140 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
1141 file_error(ms, errno, "error writing `%s'", dbname);
1145 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
1146 != sizeof(struct magic)) {
1147 file_error(ms, errno, "error seeking `%s'", dbname);
1151 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
1152 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
1153 file_error(ms, errno, "error writing `%s'", dbname);
1161 private const char ext[] = ".mgc";
1166 mkdbname(const char *fn, char *buf, size_t bufsiz, int strip)
1170 if ((p = strrchr(fn, '/')) != NULL)
1174 (void)snprintf(buf, bufsiz, "%s%s", fn, ext);
1179 * Byteswap an mmap'ed file if needed
1182 byteswap(struct magic *magic, uint32_t nmagic)
1185 for (i = 0; i < nmagic; i++)
1196 uint8_t *s = (uint8_t *)(void *)&sv;
1197 uint8_t *d = (uint8_t *)(void *)&rv;
1210 uint8_t *s = (uint8_t *)(void *)&sv;
1211 uint8_t *d = (uint8_t *)(void *)&rv;
1220 * byteswap a single magic entry
1223 bs1(struct magic *m)
1225 m->cont_level = swap2(m->cont_level);
1226 m->offset = swap4((uint32_t)m->offset);
1227 m->in_offset = swap4((uint32_t)m->in_offset);
1228 if (IS_STRING(m->type))
1229 m->value.l = swap4(m->value.l);
1230 m->mask = swap4(m->mask);