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.84 2005/03/25 18:03:18 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_PLAINSTRING(t) ((t) == FILE_STRING || (t) == FILE_PSTRING || \
78 (t) == FILE_BESTRING16 || (t) == FILE_LESTRING16)
80 #define IS_STRING(t) (IS_PLAINSTRING(t) || (t) == FILE_REGEX || \
83 private int getvalue(struct magic_set *ms, struct magic *, char **);
84 private int hextoint(int);
85 private char *getstr(struct magic_set *, char *, char *, int, int *);
86 private int parse(struct magic_set *, struct magic **, uint32_t *, char *, int);
87 private void eatsize(char **);
88 private int apprentice_1(struct magic_set *, const char *, int, struct mlist *);
89 private int apprentice_file(struct magic_set *, struct magic **, uint32_t *,
91 private void byteswap(struct magic *, uint32_t);
92 private void bs1(struct magic *);
93 private uint16_t swap2(uint16_t);
94 private uint32_t swap4(uint32_t);
95 private char *mkdbname(const char *, char *, size_t, int);
96 private int apprentice_map(struct magic_set *, struct magic **, uint32_t *,
98 private int apprentice_compile(struct magic_set *, struct magic **, uint32_t *,
100 private int check_format(struct magic_set *, struct magic *);
102 private size_t maxmagic = 0;
103 private size_t magicsize = sizeof(struct magic);
107 int main(int, char *[]);
110 main(int argc, char *argv[])
113 struct magic_set *ms;
116 if ((progname = strrchr(argv[0], '/')) != NULL)
122 (void)fprintf(stderr, "Usage: %s file\n", progname);
126 if ((ms = magic_open(MAGIC_CHECK)) == NULL) {
127 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
130 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0;
132 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms));
136 #endif /* COMPILE_ONLY */
143 apprentice_1(struct magic_set *ms, const char *fn, int action,
146 struct magic *magic = NULL;
152 if (magicsize != FILE_MAGICSIZE) {
153 file_error(ms, 0, "magic element size %lu != %lu",
154 (unsigned long)sizeof(*magic),
155 (unsigned long)FILE_MAGICSIZE);
159 if (action == FILE_COMPILE) {
160 rv = apprentice_file(ms, &magic, &nmagic, fn, action);
163 rv = apprentice_compile(ms, &magic, &nmagic, fn);
168 if ((rv = apprentice_map(ms, &magic, &nmagic, fn)) == -1) {
169 if (ms->flags & MAGIC_CHECK)
170 file_magwarn(ms, "using regular magic file `%s'", fn);
171 rv = apprentice_file(ms, &magic, &nmagic, fn, action);
181 if (magic == NULL || nmagic == 0) {
182 file_delmagic(magic, mapped, nmagic);
186 if ((ml = malloc(sizeof(*ml))) == NULL) {
187 file_delmagic(magic, mapped, nmagic);
196 mlist->prev->next = ml;
197 ml->prev = mlist->prev;
202 #endif /* COMPILE_ONLY */
206 file_delmagic(struct magic *p, int type, size_t entries)
213 (void)munmap((void *)p, sizeof(*p) * (entries + 1));
227 /* const char *fn: list of magic files */
228 protected struct mlist *
229 file_apprentice(struct magic_set *ms, const char *fn, int action)
231 char *p, *mfn, *afn = NULL;
232 int file_err, errs = -1;
236 fn = getenv("MAGIC");
240 if ((fn = mfn = strdup(fn)) == NULL) {
245 if ((mlist = malloc(sizeof(*mlist))) == NULL) {
250 mlist->next = mlist->prev = mlist;
253 p = strchr(fn, PATHSEP);
258 if (ms->flags & MAGIC_MIME) {
259 if ((afn = malloc(strlen(fn) + 5 + 1)) == NULL) {
265 (void)strcpy(afn, fn);
266 (void)strcat(afn, ".mime");
269 file_err = apprentice_1(ms, fn, action, mlist);
282 file_error(ms, 0, "could not find any magic files!");
291 * const char *fn: name of magic file
294 apprentice_file(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
295 const char *fn, int action)
297 private const char hdr[] =
298 "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
303 f = fopen(ms->file = fn, "r");
306 file_error(ms, errno, "cannot read magic file `%s'",
312 *magicp = (struct magic *) calloc(maxmagic, sizeof(struct magic));
313 if (*magicp == NULL) {
319 /* print silly verbose header for USG compat. */
320 if (action == FILE_CHECK)
321 (void)fprintf(stderr, "%s\n", hdr);
324 for (ms->line = 1; fgets(line, BUFSIZ, f) != NULL; ms->line++) {
326 if (line[0]=='#') /* comment, do not parse */
329 if (len < 2) /* null line, garbage, etc */
331 line[len - 1] = '\0'; /* delete newline */
332 if (parse(ms, magicp, nmagicp, line, action) != 0)
346 * extend the sign bit if the comparison is to be signed
349 file_signextend(struct magic_set *ms, struct magic *m, uint32_t v)
351 if (!(m->flag & UNSIGNED))
354 * Do not remove the casts below. They are
355 * vital. When later compared with the data,
356 * the sign extension must have happened.
379 case FILE_BESTRING16:
380 case FILE_LESTRING16:
385 if (ms->flags & MAGIC_CHECK)
386 file_magwarn(ms, "cannot happen: m->type=%d\n",
394 * parse one line from magic file, put into magic[index++] if valid
397 parse(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp, char *l,
403 private const char *fops = FILE_OPS;
406 #define ALLOC_INCR 200
407 if (*nmagicp + 1 >= maxmagic){
408 maxmagic += ALLOC_INCR;
409 if ((m = (struct magic *) realloc(*magicp,
410 sizeof(struct magic) * maxmagic)) == NULL) {
417 memset(&(*magicp)[*nmagicp], 0, sizeof(struct magic)
420 m = &(*magicp)[*nmagicp];
429 if (m->cont_level != 0 && *l == '&') {
433 if (m->cont_level != 0 && *l == '(') {
436 if (m->flag & OFFADD)
437 m->flag = (m->flag & ~OFFADD) | INDIROFFADD;
439 if (m->cont_level != 0 && *l == '&') {
444 /* get offset, then skip over it */
445 m->offset = (uint32_t)strtoul(l, &t, 0);
447 if (ms->flags & MAGIC_CHECK)
448 file_magwarn(ms, "offset `%s' invalid", l);
451 if (m->flag & INDIR) {
452 m->in_type = FILE_LONG;
455 * read [.lbs][+-]nnnnn)
461 m->in_type = FILE_LELONG;
464 m->in_type = FILE_BELONG;
468 m->in_type = FILE_LESHORT;
472 m->in_type = FILE_BESHORT;
478 m->in_type = FILE_BYTE;
481 if (ms->flags & MAGIC_CHECK)
483 "indirect offset type `%c' invalid",
490 m->in_op |= FILE_OPINVERSE;
495 m->in_op |= FILE_OPAND;
499 m->in_op |= FILE_OPOR;
503 m->in_op |= FILE_OPXOR;
507 m->in_op |= FILE_OPADD;
511 m->in_op |= FILE_OPMINUS;
515 m->in_op |= FILE_OPMULTIPLY;
519 m->in_op |= FILE_OPDIVIDE;
523 m->in_op |= FILE_OPMODULO;
528 m->in_op |= FILE_OPINDIRECT;
531 if (isdigit((unsigned char)*l) || *l == '-')
532 m->in_offset = (int32_t)strtol(l, &t, 0);
536 ((m->in_op & FILE_OPINDIRECT) && *t++ != ')'))
537 if (ms->flags & MAGIC_CHECK)
539 "missing ')' in indirect offset");
544 while (isascii((unsigned char)*l) && isdigit((unsigned char)*l))
564 #define NBESTRING16 10
565 #define NLESTRING16 10
573 /* get type, skip it */
574 if (strncmp(l, "char", NBYTE)==0) { /* HP/UX compat */
577 } else if (strncmp(l, "byte", NBYTE)==0) {
580 } else if (strncmp(l, "short", NSHORT)==0) {
581 m->type = FILE_SHORT;
583 } else if (strncmp(l, "long", NLONG)==0) {
586 } else if (strncmp(l, "string", NSTRING)==0) {
587 m->type = FILE_STRING;
589 } else if (strncmp(l, "date", NDATE)==0) {
592 } else if (strncmp(l, "beshort", NBESHORT)==0) {
593 m->type = FILE_BESHORT;
595 } else if (strncmp(l, "belong", NBELONG)==0) {
596 m->type = FILE_BELONG;
598 } else if (strncmp(l, "bedate", NBEDATE)==0) {
599 m->type = FILE_BEDATE;
601 } else if (strncmp(l, "leshort", NLESHORT)==0) {
602 m->type = FILE_LESHORT;
604 } else if (strncmp(l, "lelong", NLELONG)==0) {
605 m->type = FILE_LELONG;
607 } else if (strncmp(l, "ledate", NLEDATE)==0) {
608 m->type = FILE_LEDATE;
610 } else if (strncmp(l, "pstring", NPSTRING)==0) {
611 m->type = FILE_PSTRING;
613 } else if (strncmp(l, "ldate", NLDATE)==0) {
614 m->type = FILE_LDATE;
616 } else if (strncmp(l, "beldate", NBELDATE)==0) {
617 m->type = FILE_BELDATE;
619 } else if (strncmp(l, "leldate", NLELDATE)==0) {
620 m->type = FILE_LELDATE;
622 } else if (strncmp(l, "regex", NREGEX)==0) {
623 m->type = FILE_REGEX;
625 } else if (strncmp(l, "bestring16", NBESTRING16)==0) {
626 m->type = FILE_BESTRING16;
628 } else if (strncmp(l, "lestring16", NLESTRING16)==0) {
629 m->type = FILE_LESTRING16;
631 } else if (strncmp(l, "search", NSEARCH)==0) {
632 m->type = FILE_SEARCH;
635 if (ms->flags & MAGIC_CHECK)
636 file_magwarn(ms, "type `%s' invalid", l);
639 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
640 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
642 if (!IS_STRING(m->type))
643 m->mask_op |= FILE_OPINVERSE;
646 if ((t = strchr(fops, *l)) != NULL) {
647 uint32_t op = (uint32_t)(t - fops);
648 if (op != FILE_OPDIVIDE || !IS_PLAINSTRING(m->type)) {
651 val = (uint32_t)strtoul(l, &l, 0);
652 m->mask = file_signextend(ms, m, val);
656 while (!isspace((unsigned char)*++l)) {
658 case CHAR_IGNORE_LOWERCASE:
659 m->mask |= STRING_IGNORE_LOWERCASE;
661 case CHAR_COMPACT_BLANK:
662 m->mask |= STRING_COMPACT_BLANK;
664 case CHAR_COMPACT_OPTIONAL_BLANK:
666 STRING_COMPACT_OPTIONAL_BLANK;
669 if (ms->flags & MAGIC_CHECK)
671 "string extension `%c' invalid",
680 * We used to set mask to all 1's here, instead let's just not do
681 * anything if mask = 0 (unless you have a better idea)
688 /* Old-style anding: "0 byte &0x80 dynamically linked" */
695 /* HP compat: ignore &= etc. */
704 if (*l == 'x' && ((isascii((unsigned char)l[1]) &&
705 isspace((unsigned char)l[1])) || !l[1])) {
708 goto GetDesc; /* Bill The Cat */
715 if (getvalue(ms, m, &l))
718 * TODO finish this macro and start using it!
719 * #define offsetcheck {if (offset > HOWMANY-1)
720 * magwarn("offset too big"); }
724 * now get last part - the description
731 } else if ((l[0] == '\\') && (l[1] == 'b')) {
737 while ((m->desc[i++] = *l++) != '\0' && i < MAXDESC)
740 if (ms->flags & MAGIC_CHECK) {
741 if (!check_format(ms, m))
745 if (action == FILE_CHECK) {
749 ++(*nmagicp); /* make room for next */
754 * Check that the optional printf format in description matches
755 * the type of the magic.
758 check_format(struct magic_set *ms, struct magic *m)
760 static const char *formats[] = { FILE_FORMAT_STRING };
761 static const char *names[] = { FILE_FORMAT_NAME };
764 for (ptr = m->desc; *ptr; ptr++)
768 /* No format string; ok */
771 if (m->type >= sizeof(formats)/sizeof(formats[0])) {
772 file_magwarn(ms, "Internal error inconsistency between m->type"
773 " and format strings");
776 if (formats[m->type] == NULL) {
777 file_magwarn(ms, "No format string for `%s' with description "
778 "`%s'", m->desc, names[m->type]);
781 for (; *ptr; ptr++) {
782 if (*ptr == 'l' || *ptr == 'h') {
783 /* XXX: we should really fix this one day */
786 if (islower((unsigned char)*ptr) || *ptr == 'X')
790 /* Missing format string; bad */
791 file_magwarn(ms, "Invalid format `%s' for type `%s'",
792 m->desc, names[m->type]);
795 if (strchr(formats[m->type], *ptr) == NULL) {
796 file_magwarn(ms, "Printf format `%c' is not valid for type `%s'"
797 " in description `%s'",
798 *ptr, names[m->type], m->desc);
805 * Read a numeric value from a pointer, into the value union of a magic
806 * pointer, according to the magic type. Update the string pointer to point
807 * just after the number read. Return 0 for success, non-zero for failure.
810 getvalue(struct magic_set *ms, struct magic *m, char **p)
815 case FILE_BESTRING16:
816 case FILE_LESTRING16:
821 *p = getstr(ms, *p, m->value.s, sizeof(m->value.s), &slen);
823 if (ms->flags & MAGIC_CHECK)
824 file_magwarn(ms, "cannot get string from `%s'",
831 if (m->reln != 'x') {
832 m->value.l = file_signextend(ms, m,
833 (uint32_t)strtoul(*p, p, 0));
841 * Convert a string containing C character escapes. Stop at an unescaped
843 * Copy the converted version to "p", returning its length in *slen.
844 * Return updated scan pointer as function result.
847 getstr(struct magic_set *ms, char *s, char *p, int plen, int *slen)
849 char *origs = s, *origp = p;
850 char *pmax = p + plen - 1;
854 while ((c = *s++) != '\0') {
855 if (isspace((unsigned char) c))
858 file_error(ms, 0, "string too long: `%s'", origs);
895 /* \ and up to 3 octal digits */
905 c = *s++; /* try for 2 */
906 if(c >= '0' && c <= '7') {
907 val = (val<<3) | (c - '0');
908 c = *s++; /* try for 3 */
909 if(c >= '0' && c <= '7')
910 val = (val<<3) | (c-'0');
919 /* \x and up to 2 hex digits */
921 val = 'x'; /* Default if no digits */
922 c = hextoint(*s++); /* Get next char */
927 val = (val << 4) + c;
945 /* Single hex char to int; -1 if not a hex char. */
949 if (!isascii((unsigned char) c))
951 if (isdigit((unsigned char) c))
953 if ((c >= 'a')&&(c <= 'f'))
955 if (( c>= 'A')&&(c <= 'F'))
962 * Print a string containing C character escapes.
965 file_showstr(FILE *fp, const char *s, size_t len)
979 if(c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */
982 (void) fputc('\\', fp);
986 (void) fputc('n', fp);
990 (void) fputc('r', fp);
994 (void) fputc('b', fp);
998 (void) fputc('t', fp);
1002 (void) fputc('f', fp);
1006 (void) fputc('v', fp);
1010 (void) fprintf(fp, "%.3o", c & 0377);
1018 * eatsize(): Eat the size spec from a number [eg. 10UL]
1025 if (LOWCASE(*l) == 'u')
1028 switch (LOWCASE(*l)) {
1029 case 'l': /* long */
1030 case 's': /* short */
1031 case 'h': /* short */
1032 case 'b': /* char/byte */
1033 case 'c': /* char/byte */
1044 * handle a compiled file.
1047 apprentice_map(struct magic_set *ms, struct magic **magicp, uint32_t *nmagicp,
1055 char buf[MAXPATHLEN];
1056 char *dbname = mkdbname(fn, buf, sizeof(buf), 0);
1062 if ((fd = open(dbname, O_RDONLY)) == -1)
1065 if (fstat(fd, &st) == -1) {
1066 file_error(ms, errno, "cannot stat `%s'", dbname);
1069 if (st.st_size < 16) {
1070 file_error(ms, 0, "file `%s' is too small", dbname);
1075 if ((mm = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE,
1076 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) {
1077 file_error(ms, errno, "cannot map `%s'", dbname);
1082 if ((mm = malloc((size_t)st.st_size)) == NULL) {
1086 if (read(fd, mm, (size_t)st.st_size) != (size_t)st.st_size) {
1095 ptr = (uint32_t *)(void *)*magicp;
1096 if (*ptr != MAGICNO) {
1097 if (swap4(*ptr) != MAGICNO) {
1098 file_error(ms, 0, "bad magic in `%s'");
1105 version = swap4(ptr[1]);
1108 if (version != VERSIONNO) {
1109 file_error(ms, 0, "version mismatch (%d != %d) in `%s'",
1110 version, VERSIONNO, dbname);
1113 *nmagicp = (uint32_t)(st.st_size / sizeof(struct magic)) - 1;
1116 byteswap(*magicp, *nmagicp);
1124 (void)munmap((void *)mm, (size_t)st.st_size);
1135 private const uint32_t ar[] = {
1139 * handle an mmaped file.
1142 apprentice_compile(struct magic_set *ms, struct magic **magicp,
1143 uint32_t *nmagicp, const char *fn)
1146 char buf[MAXPATHLEN];
1147 char *dbname = mkdbname(fn, buf, sizeof(buf), 1);
1152 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC, 0644)) == -1) {
1153 file_error(ms, errno, "cannot open `%s'", dbname);
1157 if (write(fd, ar, sizeof(ar)) != (ssize_t)sizeof(ar)) {
1158 file_error(ms, errno, "error writing `%s'", dbname);
1162 if (lseek(fd, (off_t)sizeof(struct magic), SEEK_SET)
1163 != sizeof(struct magic)) {
1164 file_error(ms, errno, "error seeking `%s'", dbname);
1168 if (write(fd, *magicp, (sizeof(struct magic) * *nmagicp))
1169 != (ssize_t)(sizeof(struct magic) * *nmagicp)) {
1170 file_error(ms, errno, "error writing `%s'", dbname);
1178 private const char ext[] = ".mgc";
1183 mkdbname(const char *fn, char *buf, size_t bufsiz, int strip)
1187 if ((p = strrchr(fn, '/')) != NULL)
1191 (void)snprintf(buf, bufsiz, "%s%s", fn, ext);
1196 * Byteswap an mmap'ed file if needed
1199 byteswap(struct magic *magic, uint32_t nmagic)
1202 for (i = 0; i < nmagic; i++)
1213 uint8_t *s = (uint8_t *)(void *)&sv;
1214 uint8_t *d = (uint8_t *)(void *)&rv;
1227 uint8_t *s = (uint8_t *)(void *)&sv;
1228 uint8_t *d = (uint8_t *)(void *)&rv;
1237 * byteswap a single magic entry
1240 bs1(struct magic *m)
1242 m->cont_level = swap2(m->cont_level);
1243 m->offset = swap4((uint32_t)m->offset);
1244 m->in_offset = swap4((uint32_t)m->in_offset);
1245 if (!IS_STRING(m->type))
1246 m->value.l = swap4(m->value.l);
1247 m->mask = swap4(m->mask);