2 * Copyright (c) Ian F. Darwin 1986-1995.
3 * Software written by Ian F. Darwin and others;
4 * maintained 1995-present by Christos Zoulas and others.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice immediately at the beginning of the file, without modification,
11 * this list of conditions, and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
20 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * apprentice - make one pass through /etc/magic, learning its secrets.
35 FILE_RCSID("@(#)$File: apprentice.c,v 1.151 2009/03/18 15:19:23 christos Exp $")
39 #include "patchlevel.h"
53 #define EATAB {while (isascii((unsigned char) *l) && \
54 isspace((unsigned char) *l)) ++l;}
55 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
56 tolower((unsigned char) (l)) : (l))
58 * Work around a bug in headers on Digital Unix.
59 * At least confirmed for: OSF1 V4.0 878
61 #if defined(__osf__) && defined(__DECC)
68 #define MAP_FAILED (void *) -1
76 #define MAXPATHLEN 1024
85 int file_formats
[FILE_NAMES_SIZE
];
86 const size_t file_nformats
= FILE_NAMES_SIZE
;
87 const char *file_names
[FILE_NAMES_SIZE
];
88 const size_t file_nnames
= FILE_NAMES_SIZE
;
90 private int getvalue(struct magic_set
*ms
, struct magic
*, const char **, int);
91 private int hextoint(int);
92 private const char *getstr(struct magic_set
*, struct magic
*, const char *,
94 private int parse(struct magic_set
*, struct magic_entry
**, uint32_t *,
95 const char *, size_t, int);
96 private void eatsize(const char **);
97 private int apprentice_1(struct magic_set
*, const char *, int, struct mlist
*);
98 private size_t apprentice_magic_strength(const struct magic
*);
99 private int apprentice_sort(const void *, const void *);
100 private int apprentice_load(struct magic_set
*, struct magic
**, uint32_t *,
102 private void byteswap(struct magic
*, uint32_t);
103 private void bs1(struct magic
*);
104 private uint16_t swap2(uint16_t);
105 private uint32_t swap4(uint32_t);
106 private uint64_t swap8(uint64_t);
107 private char *mkdbname(struct magic_set
*, const char *, int);
108 private int apprentice_map(struct magic_set
*, struct magic
**, uint32_t *,
110 private int apprentice_compile(struct magic_set
*, struct magic
**, uint32_t *,
112 private int check_format_type(const char *, int);
113 private int check_format(struct magic_set
*, struct magic
*);
114 private int get_op(char);
115 private int parse_mime(struct magic_set
*, struct magic_entry
*, const char *);
116 private int parse_strength(struct magic_set
*, struct magic_entry
*, const char *);
117 private int parse_apple(struct magic_set
*, struct magic_entry
*, const char *);
120 private size_t maxmagic
= 0;
121 private size_t magicsize
= sizeof(struct magic
);
123 private const char usg_hdr
[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
128 int (*fun
)(struct magic_set
*, struct magic_entry
*, const char *);
130 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
132 DECLARE_FIELD(apple
),
133 DECLARE_FIELD(strength
),
140 int main(int, char *[]);
143 main(int argc
, char *argv
[])
146 struct magic_set
*ms
;
149 if ((progname
= strrchr(argv
[0], '/')) != NULL
)
155 (void)fprintf(stderr
, "Usage: %s file\n", progname
);
159 if ((ms
= magic_open(MAGIC_CHECK
)) == NULL
) {
160 (void)fprintf(stderr
, "%s: %s\n", progname
, strerror(errno
));
163 ret
= magic_compile(ms
, argv
[1]) == -1 ? 1 : 0;
165 (void)fprintf(stderr
, "%s: %s\n", progname
, magic_error(ms
));
169 #endif /* COMPILE_ONLY */
171 static const struct type_tbl_s
{
177 # define XX(s) s, (sizeof(s) - 1)
178 # define XX_NULL "", 0
179 { XX("byte"), FILE_BYTE
, FILE_FMT_NUM
},
180 { XX("short"), FILE_SHORT
, FILE_FMT_NUM
},
181 { XX("default"), FILE_DEFAULT
, FILE_FMT_STR
},
182 { XX("long"), FILE_LONG
, FILE_FMT_NUM
},
183 { XX("string"), FILE_STRING
, FILE_FMT_STR
},
184 { XX("date"), FILE_DATE
, FILE_FMT_STR
},
185 { XX("beshort"), FILE_BESHORT
, FILE_FMT_NUM
},
186 { XX("belong"), FILE_BELONG
, FILE_FMT_NUM
},
187 { XX("bedate"), FILE_BEDATE
, FILE_FMT_STR
},
188 { XX("leshort"), FILE_LESHORT
, FILE_FMT_NUM
},
189 { XX("lelong"), FILE_LELONG
, FILE_FMT_NUM
},
190 { XX("ledate"), FILE_LEDATE
, FILE_FMT_STR
},
191 { XX("pstring"), FILE_PSTRING
, FILE_FMT_STR
},
192 { XX("ldate"), FILE_LDATE
, FILE_FMT_STR
},
193 { XX("beldate"), FILE_BELDATE
, FILE_FMT_STR
},
194 { XX("leldate"), FILE_LELDATE
, FILE_FMT_STR
},
195 { XX("regex"), FILE_REGEX
, FILE_FMT_STR
},
196 { XX("bestring16"), FILE_BESTRING16
, FILE_FMT_STR
},
197 { XX("lestring16"), FILE_LESTRING16
, FILE_FMT_STR
},
198 { XX("search"), FILE_SEARCH
, FILE_FMT_STR
},
199 { XX("medate"), FILE_MEDATE
, FILE_FMT_STR
},
200 { XX("meldate"), FILE_MELDATE
, FILE_FMT_STR
},
201 { XX("melong"), FILE_MELONG
, FILE_FMT_NUM
},
202 { XX("quad"), FILE_QUAD
, FILE_FMT_QUAD
},
203 { XX("lequad"), FILE_LEQUAD
, FILE_FMT_QUAD
},
204 { XX("bequad"), FILE_BEQUAD
, FILE_FMT_QUAD
},
205 { XX("qdate"), FILE_QDATE
, FILE_FMT_STR
},
206 { XX("leqdate"), FILE_LEQDATE
, FILE_FMT_STR
},
207 { XX("beqdate"), FILE_BEQDATE
, FILE_FMT_STR
},
208 { XX("qldate"), FILE_QLDATE
, FILE_FMT_STR
},
209 { XX("leqldate"), FILE_LEQLDATE
, FILE_FMT_STR
},
210 { XX("beqldate"), FILE_BEQLDATE
, FILE_FMT_STR
},
211 { XX("float"), FILE_FLOAT
, FILE_FMT_FLOAT
},
212 { XX("befloat"), FILE_BEFLOAT
, FILE_FMT_FLOAT
},
213 { XX("lefloat"), FILE_LEFLOAT
, FILE_FMT_FLOAT
},
214 { XX("double"), FILE_DOUBLE
, FILE_FMT_DOUBLE
},
215 { XX("bedouble"), FILE_BEDOUBLE
, FILE_FMT_DOUBLE
},
216 { XX("ledouble"), FILE_LEDOUBLE
, FILE_FMT_DOUBLE
},
217 { XX("leid3"), FILE_LEID3
, FILE_FMT_NUM
},
218 { XX("beid3"), FILE_BEID3
, FILE_FMT_NUM
},
219 { XX("indirect"), FILE_INDIRECT
, FILE_FMT_NONE
},
220 { XX_NULL
, FILE_INVALID
, FILE_FMT_NONE
},
226 get_type(const char *l
, const char **t
)
228 const struct type_tbl_s
*p
;
230 for (p
= type_tbl
; p
->len
; p
++) {
231 if (strncmp(l
, p
->name
, p
->len
) == 0) {
241 init_file_tables(void)
244 const struct type_tbl_s
*p
;
250 for (p
= type_tbl
; p
->len
; p
++) {
251 assert(p
->type
< FILE_NAMES_SIZE
);
252 file_names
[p
->type
] = p
->name
;
253 file_formats
[p
->type
] = p
->format
;
258 * Handle one file or directory.
261 apprentice_1(struct magic_set
*ms
, const char *fn
, int action
,
264 struct magic
*magic
= NULL
;
270 if (magicsize
!= FILE_MAGICSIZE
) {
271 file_error(ms
, 0, "magic element size %lu != %lu",
272 (unsigned long)sizeof(*magic
),
273 (unsigned long)FILE_MAGICSIZE
);
277 if (action
== FILE_COMPILE
) {
278 rv
= apprentice_load(ms
, &magic
, &nmagic
, fn
, action
);
281 rv
= apprentice_compile(ms
, &magic
, &nmagic
, fn
);
287 if ((rv
= apprentice_map(ms
, &magic
, &nmagic
, fn
)) == -1) {
288 if (ms
->flags
& MAGIC_CHECK
)
289 file_magwarn(ms
, "using regular magic file `%s'", fn
);
290 rv
= apprentice_load(ms
, &magic
, &nmagic
, fn
, action
);
298 file_delmagic(magic
, mapped
, nmagic
);
302 if ((ml
= CAST(struct mlist
*, malloc(sizeof(*ml
)))) == NULL
) {
303 file_delmagic(magic
, mapped
, nmagic
);
304 file_oomem(ms
, sizeof(*ml
));
312 mlist
->prev
->next
= ml
;
313 ml
->prev
= mlist
->prev
;
318 #endif /* COMPILE_ONLY */
322 file_delmagic(struct magic
*p
, int type
, size_t entries
)
330 (void)munmap((void *)p
, sizeof(*p
) * (entries
+ 1));
348 /* const char *fn: list of magic files and directories */
349 protected struct mlist
*
350 file_apprentice(struct magic_set
*ms
, const char *fn
, int action
)
353 int file_err
, errs
= -1;
359 fn
= getenv("MAGIC");
363 if ((mfn
= strdup(fn
)) == NULL
) {
364 file_oomem(ms
, strlen(fn
));
369 if ((mlist
= CAST(struct mlist
*, malloc(sizeof(*mlist
)))) == NULL
) {
371 file_oomem(ms
, sizeof(*mlist
));
374 mlist
->next
= mlist
->prev
= mlist
;
377 p
= strchr(fn
, PATHSEP
);
382 file_err
= apprentice_1(ms
, fn
, action
, mlist
);
383 errs
= MAX(errs
, file_err
);
390 file_error(ms
, 0, "could not find any magic files!");
398 * Get weight of this magic entry, for sorting purposes.
401 apprentice_magic_strength(const struct magic
*m
)
404 size_t val
= 2 * MULT
; /* baseline strength */
407 case FILE_DEFAULT
: /* make sure this sorts last */
408 if (m
->factor_op
!= FILE_FACTOR_OP_NONE
)
431 val
+= m
->vallen
* MULT
;
434 case FILE_BESTRING16
:
435 case FILE_LESTRING16
:
436 val
+= m
->vallen
* MULT
/ 2;
441 val
+= m
->vallen
* MAX(MULT
/ m
->vallen
, 1);
475 (void)fprintf(stderr
, "Bad type %d\n", m
->type
);
480 case 'x': /* matches anything penalize */
481 case '!': /* matches almost anything penalize */
485 case '=': /* Exact match, prefer */
490 case '<': /* comparison match reduce strength */
495 case '&': /* masking bits, we could count them too */
500 (void)fprintf(stderr
, "Bad relation %c\n", m
->reln
);
504 if (val
== 0) /* ensure we only return 0 for FILE_DEFAULT */
507 switch (m
->factor_op
) {
508 case FILE_FACTOR_OP_NONE
:
510 case FILE_FACTOR_OP_PLUS
:
513 case FILE_FACTOR_OP_MINUS
:
516 case FILE_FACTOR_OP_TIMES
:
519 case FILE_FACTOR_OP_DIV
:
527 * Magic entries with no description get a bonus because they depend
528 * on subsequent magic entries to print something.
530 if (m
->desc
[0] == '\0')
536 * Sort callback for sorting entries by "strength" (basically length)
539 apprentice_sort(const void *a
, const void *b
)
541 const struct magic_entry
*ma
= CAST(const struct magic_entry
*, a
);
542 const struct magic_entry
*mb
= CAST(const struct magic_entry
*, b
);
543 size_t sa
= apprentice_magic_strength(ma
->mp
);
544 size_t sb
= apprentice_magic_strength(mb
->mp
);
554 set_test_type(struct magic
*mstart
, struct magic
*m
)
590 case FILE_BESTRING16
:
591 case FILE_LESTRING16
:
592 /* binary test, set flag */
593 mstart
->flag
|= BINTEST
;
598 /* binary test if pattern is not text */
599 if (file_looks_utf8(m
->value
.us
, (size_t)m
->vallen
, NULL
,
601 mstart
->flag
|= BINTEST
;
605 /* can't deduce anything; we shouldn't see this at the
610 /* invalid search type, but no need to complain here */
616 * Load and parse one file.
619 load_1(struct magic_set
*ms
, int action
, const char *fn
, int *errs
,
620 struct magic_entry
**marray
, uint32_t *marraycount
)
624 FILE *f
= fopen(ms
->file
= fn
, "r");
627 file_error(ms
, errno
, "cannot read magic file `%s'",
631 /* read and parse this file */
632 for (ms
->line
= 1; fgets(line
, sizeof(line
), f
) != NULL
; ms
->line
++) {
635 if (len
== 0) /* null line, garbage, etc */
637 if (line
[len
- 1] == '\n') {
639 line
[len
- 1] = '\0'; /* delete newline */
641 if (line
[0] == '\0') /* empty, do not parse */
643 if (line
[0] == '#') /* comment, do not parse */
645 if (line
[0] == '!' && line
[1] == ':') {
648 for (i
= 0; bang
[i
].name
!= NULL
; i
++) {
649 if (len
- 2 > bang
[i
].len
&&
650 memcmp(bang
[i
].name
, line
+ 2,
654 if (bang
[i
].name
== NULL
) {
656 "Unknown !: entry `%s'", line
);
660 if (*marraycount
== 0) {
662 "No current entry for :!%s type",
667 if ((*bang
[i
].fun
)(ms
,
668 &(*marray
)[*marraycount
- 1],
669 line
+ bang
[i
].len
+ 2) != 0) {
675 if (parse(ms
, marray
, marraycount
, line
, lineno
,
685 * parse a file or directory of files
686 * const char *fn: name of magic file or directory
689 apprentice_load(struct magic_set
*ms
, struct magic
**magicp
, uint32_t *nmagicp
,
690 const char *fn
, int action
)
693 struct magic_entry
*marray
;
694 uint32_t marraycount
, i
, mentrycount
= 0, starttest
;
696 char subfn
[MAXPATHLEN
];
701 ms
->flags
|= MAGIC_CHECK
; /* Enable checks for parsed files */
704 if ((marray
= CAST(struct magic_entry
*, calloc(maxmagic
,
705 sizeof(*marray
)))) == NULL
) {
706 file_oomem(ms
, maxmagic
* sizeof(*marray
));
711 /* print silly verbose header for USG compat. */
712 if (action
== FILE_CHECK
)
713 (void)fprintf(stderr
, "%s\n", usg_hdr
);
715 /* load directory or file */
716 /* FIXME: Read file names and sort them to prevent
717 non-determinism. See Debian bug #488562. */
718 if (stat(fn
, &st
) == 0 && S_ISDIR(st
.st_mode
)) {
721 while ((d
= readdir(dir
)) != NULL
) {
722 snprintf(subfn
, sizeof(subfn
), "%s/%s",
724 if (stat(subfn
, &st
) == 0 &&
725 S_ISREG(st
.st_mode
)) {
726 load_1(ms
, action
, subfn
, &errs
,
727 &marray
, &marraycount
);
734 load_1(ms
, action
, fn
, &errs
, &marray
, &marraycount
);
738 /* Set types of tests */
739 for (i
= 0; i
< marraycount
; ) {
740 if (marray
[i
].mp
->cont_level
!= 0) {
747 static const char text
[] = "text";
748 static const char binary
[] = "binary";
749 static const size_t len
= sizeof(text
);
750 set_test_type(marray
[starttest
].mp
, marray
[i
].mp
);
751 if ((ms
->flags
& MAGIC_DEBUG
) == 0)
753 (void)fprintf(stderr
, "%s%s%s: %s\n",
754 marray
[i
].mp
->mimetype
,
755 marray
[i
].mp
->mimetype
[0] == '\0' ? "" : "; ",
756 marray
[i
].mp
->desc
[0] ? marray
[i
].mp
->desc
:
758 marray
[i
].mp
->flag
& BINTEST
? binary
: text
);
759 if (marray
[i
].mp
->flag
& BINTEST
) {
760 char *p
= strstr(marray
[i
].mp
->desc
, text
);
761 if (p
&& (p
== marray
[i
].mp
->desc
||
762 isspace((unsigned char)p
[-1])) &&
763 (p
+ len
- marray
[i
].mp
->desc
==
764 MAXstring
|| (p
[len
] == '\0' ||
765 isspace((unsigned char)p
[len
]))))
766 (void)fprintf(stderr
, "*** Possible "
767 "binary test for text type\n");
769 } while (++i
< marraycount
&& marray
[i
].mp
->cont_level
!= 0);
772 qsort(marray
, marraycount
, sizeof(*marray
), apprentice_sort
);
775 * Make sure that any level 0 "default" line is last (if one exists).
777 for (i
= 0; i
< marraycount
; i
++) {
778 if (marray
[i
].mp
->cont_level
== 0 &&
779 marray
[i
].mp
->type
== FILE_DEFAULT
) {
780 while (++i
< marraycount
)
781 if (marray
[i
].mp
->cont_level
== 0)
783 if (i
!= marraycount
) {
784 ms
->line
= marray
[i
].mp
->lineno
; /* XXX - Ugh! */
786 "level 0 \"default\" did not sort last");
792 for (i
= 0; i
< marraycount
; i
++)
793 mentrycount
+= marray
[i
].cont_count
;
795 slen
= sizeof(**magicp
) * mentrycount
;
796 if ((*magicp
= CAST(struct magic
*, malloc(slen
))) == NULL
) {
797 file_oomem(ms
, slen
);
803 for (i
= 0; i
< marraycount
; i
++) {
804 (void)memcpy(*magicp
+ mentrycount
, marray
[i
].mp
,
805 marray
[i
].cont_count
* sizeof(**magicp
));
806 mentrycount
+= marray
[i
].cont_count
;
809 for (i
= 0; i
< marraycount
; i
++)
817 *nmagicp
= mentrycount
;
824 * extend the sign bit if the comparison is to be signed
827 file_signextend(struct magic_set
*ms
, struct magic
*m
, uint64_t v
)
829 if (!(m
->flag
& UNSIGNED
)) {
832 * Do not remove the casts below. They are
833 * vital. When later compared with the data,
834 * the sign extension must have happened.
877 case FILE_BESTRING16
:
878 case FILE_LESTRING16
:
885 if (ms
->flags
& MAGIC_CHECK
)
886 file_magwarn(ms
, "cannot happen: m->type=%d\n",
895 string_modifier_check(struct magic_set
*ms
, struct magic
*m
)
897 if ((ms
->flags
& MAGIC_CHECK
) == 0)
901 case FILE_BESTRING16
:
902 case FILE_LESTRING16
:
903 if (m
->str_flags
!= 0) {
905 "no modifiers allowed for 16-bit strings\n");
911 if ((m
->str_flags
& REGEX_OFFSET_START
) != 0) {
913 "'/%c' only allowed on regex and search\n",
914 CHAR_REGEX_OFFSET_START
);
919 if (m
->str_range
== 0) {
921 "missing range; defaulting to %d\n",
922 STRING_DEFAULT_RANGE
);
923 m
->str_range
= STRING_DEFAULT_RANGE
;
928 if ((m
->str_flags
& STRING_COMPACT_BLANK
) != 0) {
929 file_magwarn(ms
, "'/%c' not allowed on regex\n",
933 if ((m
->str_flags
& STRING_COMPACT_OPTIONAL_BLANK
) != 0) {
934 file_magwarn(ms
, "'/%c' not allowed on regex\n",
935 CHAR_COMPACT_OPTIONAL_BLANK
);
940 file_magwarn(ms
, "coding error: m->type=%d\n",
962 return FILE_OPMULTIPLY
;
964 return FILE_OPDIVIDE
;
966 return FILE_OPMODULO
;
972 #ifdef ENABLE_CONDITIONALS
974 get_cond(const char *l
, const char **t
)
976 static const struct cond_tbl_s
{
981 { "if", 2, COND_IF
},
982 { "elif", 4, COND_ELIF
},
983 { "else", 4, COND_ELSE
},
984 { "", 0, COND_NONE
},
986 const struct cond_tbl_s
*p
;
988 for (p
= cond_tbl
; p
->len
; p
++) {
989 if (strncmp(l
, p
->name
, p
->len
) == 0 &&
990 isspace((unsigned char)l
[p
->len
])) {
1000 check_cond(struct magic_set
*ms
, int cond
, uint32_t cont_level
)
1003 last_cond
= ms
->c
.li
[cont_level
].last_cond
;
1007 if (last_cond
!= COND_NONE
&& last_cond
!= COND_ELIF
) {
1008 if (ms
->flags
& MAGIC_CHECK
)
1009 file_magwarn(ms
, "syntax error: `if'");
1012 last_cond
= COND_IF
;
1016 if (last_cond
!= COND_IF
&& last_cond
!= COND_ELIF
) {
1017 if (ms
->flags
& MAGIC_CHECK
)
1018 file_magwarn(ms
, "syntax error: `elif'");
1021 last_cond
= COND_ELIF
;
1025 if (last_cond
!= COND_IF
&& last_cond
!= COND_ELIF
) {
1026 if (ms
->flags
& MAGIC_CHECK
)
1027 file_magwarn(ms
, "syntax error: `else'");
1030 last_cond
= COND_NONE
;
1034 last_cond
= COND_NONE
;
1038 ms
->c
.li
[cont_level
].last_cond
= last_cond
;
1041 #endif /* ENABLE_CONDITIONALS */
1044 * parse one line from magic file, put into magic[index++] if valid
1047 parse(struct magic_set
*ms
, struct magic_entry
**mentryp
, uint32_t *nmentryp
,
1048 const char *line
, size_t lineno
, int action
)
1050 #ifdef ENABLE_CONDITIONALS
1051 static uint32_t last_cont_level
= 0;
1054 struct magic_entry
*me
;
1056 const char *l
= line
;
1059 uint32_t cont_level
;
1064 ++l
; /* step over */
1067 #ifdef ENABLE_CONDITIONALS
1068 if (cont_level
== 0 || cont_level
> last_cont_level
)
1069 if (file_check_mem(ms
, cont_level
) == -1)
1071 last_cont_level
= cont_level
;
1074 #define ALLOC_CHUNK (size_t)10
1075 #define ALLOC_INCR (size_t)200
1077 if (cont_level
!= 0) {
1078 if (*nmentryp
== 0) {
1079 file_error(ms
, 0, "No current entry for continuation");
1082 me
= &(*mentryp
)[*nmentryp
- 1];
1083 if (me
->cont_count
== me
->max_count
) {
1085 size_t cnt
= me
->max_count
+ ALLOC_CHUNK
;
1086 if ((nm
= CAST(struct magic
*, realloc(me
->mp
,
1087 sizeof(*nm
) * cnt
))) == NULL
) {
1088 file_oomem(ms
, sizeof(*nm
) * cnt
);
1092 me
->max_count
= cnt
;
1094 m
= &me
->mp
[me
->cont_count
++];
1095 (void)memset(m
, 0, sizeof(*m
));
1096 m
->cont_level
= cont_level
;
1098 if (*nmentryp
== maxmagic
) {
1099 struct magic_entry
*mp
;
1101 maxmagic
+= ALLOC_INCR
;
1102 if ((mp
= CAST(struct magic_entry
*,
1103 realloc(*mentryp
, sizeof(*mp
) * maxmagic
))) ==
1105 file_oomem(ms
, sizeof(*mp
) * maxmagic
);
1108 (void)memset(&mp
[*nmentryp
], 0, sizeof(*mp
) *
1112 me
= &(*mentryp
)[*nmentryp
];
1113 if (me
->mp
== NULL
) {
1114 size_t len
= sizeof(*m
) * ALLOC_CHUNK
;
1115 if ((m
= CAST(struct magic
*, malloc(len
))) == NULL
) {
1116 file_oomem(ms
, len
);
1120 me
->max_count
= ALLOC_CHUNK
;
1123 (void)memset(m
, 0, sizeof(*m
));
1124 m
->factor_op
= FILE_FACTOR_OP_NONE
;
1130 if (*l
== '&') { /* m->cont_level == 0 checked below. */
1131 ++l
; /* step over */
1135 ++l
; /* step over */
1137 if (m
->flag
& OFFADD
)
1138 m
->flag
= (m
->flag
& ~OFFADD
) | INDIROFFADD
;
1140 if (*l
== '&') { /* m->cont_level == 0 checked below */
1141 ++l
; /* step over */
1145 /* Indirect offsets are not valid at level 0. */
1146 if (m
->cont_level
== 0 && (m
->flag
& (OFFADD
| INDIROFFADD
)))
1147 if (ms
->flags
& MAGIC_CHECK
)
1148 file_magwarn(ms
, "relative offset at level 0");
1150 /* get offset, then skip over it */
1151 m
->offset
= (uint32_t)strtoul(l
, &t
, 0);
1153 if (ms
->flags
& MAGIC_CHECK
)
1154 file_magwarn(ms
, "offset `%s' invalid", l
);
1157 if (m
->flag
& INDIR
) {
1158 m
->in_type
= FILE_LONG
;
1161 * read [.lbs][+-]nnnnn)
1167 m
->in_type
= FILE_LELONG
;
1170 m
->in_type
= FILE_BELONG
;
1173 m
->in_type
= FILE_MELONG
;
1177 m
->in_type
= FILE_LESHORT
;
1181 m
->in_type
= FILE_BESHORT
;
1187 m
->in_type
= FILE_BYTE
;
1192 m
->in_type
= FILE_LEDOUBLE
;
1197 m
->in_type
= FILE_BEDOUBLE
;
1200 m
->in_type
= FILE_LEID3
;
1203 m
->in_type
= FILE_BEID3
;
1206 if (ms
->flags
& MAGIC_CHECK
)
1208 "indirect offset type `%c' invalid",
1217 m
->in_op
|= FILE_OPINVERSE
;
1220 if ((op
= get_op(*l
)) != -1) {
1225 m
->in_op
|= FILE_OPINDIRECT
;
1228 if (isdigit((unsigned char)*l
) || *l
== '-') {
1229 m
->in_offset
= (int32_t)strtol(l
, &t
, 0);
1231 if (ms
->flags
& MAGIC_CHECK
)
1233 "in_offset `%s' invalid", l
);
1237 ((m
->in_op
& FILE_OPINDIRECT
) && *l
++ != ')'))
1238 if (ms
->flags
& MAGIC_CHECK
)
1240 "missing ')' in indirect offset");
1244 #ifdef ENABLE_CONDITIONALS
1245 m
->cond
= get_cond(l
, &l
);
1246 if (check_cond(ms
, m
->cond
, cont_level
) == -1)
1254 m
->flag
|= UNSIGNED
;
1257 m
->type
= get_type(l
, &l
);
1258 if (m
->type
== FILE_INVALID
) {
1259 if (ms
->flags
& MAGIC_CHECK
)
1260 file_magwarn(ms
, "type `%s' invalid", l
);
1264 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1265 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1269 if (!IS_STRING(m
->type
))
1270 m
->mask_op
|= FILE_OPINVERSE
;
1271 else if (ms
->flags
& MAGIC_CHECK
)
1272 file_magwarn(ms
, "'~' invalid for string types");
1278 if ((op
= get_op(*l
)) != -1) {
1279 if (!IS_STRING(m
->type
)) {
1283 val
= (uint64_t)strtoull(l
, &t
, 0);
1285 m
->num_mask
= file_signextend(ms
, m
, val
);
1288 else if (op
== FILE_OPDIVIDE
) {
1290 while (!isspace((unsigned char)*++l
)) {
1292 case '0': case '1': case '2':
1293 case '3': case '4': case '5':
1294 case '6': case '7': case '8':
1297 (ms
->flags
& MAGIC_CHECK
))
1301 m
->str_range
= strtoul(l
, &t
, 0);
1302 if (m
->str_range
== 0)
1307 case CHAR_COMPACT_BLANK
:
1308 m
->str_flags
|= STRING_COMPACT_BLANK
;
1310 case CHAR_COMPACT_OPTIONAL_BLANK
:
1312 STRING_COMPACT_OPTIONAL_BLANK
;
1314 case CHAR_IGNORE_LOWERCASE
:
1315 m
->str_flags
|= STRING_IGNORE_LOWERCASE
;
1317 case CHAR_IGNORE_UPPERCASE
:
1318 m
->str_flags
|= STRING_IGNORE_UPPERCASE
;
1320 case CHAR_REGEX_OFFSET_START
:
1321 m
->str_flags
|= REGEX_OFFSET_START
;
1324 if (ms
->flags
& MAGIC_CHECK
)
1326 "string extension `%c' invalid",
1330 /* allow multiple '/' for readability */
1332 !isspace((unsigned char)l
[2]))
1335 if (string_modifier_check(ms
, m
) == -1)
1339 if (ms
->flags
& MAGIC_CHECK
)
1340 file_magwarn(ms
, "invalid string op: %c", *t
);
1345 * We used to set mask to all 1's here, instead let's just not do
1346 * anything if mask = 0 (unless you have a better idea)
1356 if (ms
->flags
& MAGIC_CHECK
) {
1357 file_magwarn(ms
, "%c= not supported",
1364 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1371 /* HP compat: ignore &= etc. */
1380 m
->reln
= '='; /* the default relation */
1381 if (*l
== 'x' && ((isascii((unsigned char)l
[1]) &&
1382 isspace((unsigned char)l
[1])) || !l
[1])) {
1389 * Grab the value part, except for an 'x' reln.
1391 if (m
->reln
!= 'x' && getvalue(ms
, m
, &l
, action
))
1395 * TODO finish this macro and start using it!
1396 * #define offsetcheck {if (offset > HOWMANY-1)
1397 * magwarn("offset too big"); }
1401 * Now get last part - the description
1407 } else if ((l
[0] == '\\') && (l
[1] == 'b')) {
1412 for (i
= 0; (m
->desc
[i
++] = *l
++) != '\0' && i
< sizeof(m
->desc
); )
1414 if (i
== sizeof(m
->desc
)) {
1415 m
->desc
[sizeof(m
->desc
) - 1] = '\0';
1416 if (ms
->flags
& MAGIC_CHECK
)
1417 file_magwarn(ms
, "description `%s' truncated", m
->desc
);
1421 * We only do this check while compiling, or if any of the magic
1422 * files were not compiled.
1424 if (ms
->flags
& MAGIC_CHECK
) {
1425 if (check_format(ms
, m
) == -1)
1428 #ifndef COMPILE_ONLY
1429 if (action
== FILE_CHECK
) {
1433 m
->mimetype
[0] = '\0'; /* initialise MIME type to none */
1434 if (m
->cont_level
== 0)
1435 ++(*nmentryp
); /* make room for next */
1440 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
1444 parse_strength(struct magic_set
*ms
, struct magic_entry
*me
, const char *line
)
1446 const char *l
= line
;
1448 unsigned long factor
;
1449 struct magic
*m
= &me
->mp
[0];
1451 if (m
->factor_op
!= FILE_FACTOR_OP_NONE
) {
1453 "Current entry already has a strength type: %c %d",
1454 m
->factor_op
, m
->factor
);
1459 case FILE_FACTOR_OP_NONE
:
1460 case FILE_FACTOR_OP_PLUS
:
1461 case FILE_FACTOR_OP_MINUS
:
1462 case FILE_FACTOR_OP_TIMES
:
1463 case FILE_FACTOR_OP_DIV
:
1464 m
->factor_op
= *l
++;
1467 file_magwarn(ms
, "Unknown factor op `%c'", *l
);
1471 factor
= strtoul(l
, &el
, 0);
1473 file_magwarn(ms
, "Too large factor `%lu'", factor
);
1476 if (*el
&& !isspace((unsigned char)*el
)) {
1477 file_magwarn(ms
, "Bad factor `%s'", l
);
1480 m
->factor
= (uint8_t)factor
;
1481 if (m
->factor
== 0 && m
->factor_op
== FILE_FACTOR_OP_DIV
) {
1482 file_magwarn(ms
, "Cannot have factor op `%c' and factor %u",
1483 m
->factor_op
, m
->factor
);
1488 m
->factor_op
= FILE_FACTOR_OP_NONE
;
1494 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into magic[index - 1]
1497 parse_apple(struct magic_set
*ms
, struct magic_entry
*me
, const char *line
)
1500 const char *l
= line
;
1501 struct magic
*m
= &me
->mp
[me
->cont_count
== 0 ? 0 : me
->cont_count
- 1];
1503 if (m
->apple
[0] != '\0') {
1504 file_magwarn(ms
, "Current entry already has a APPLE type `%.8s',"
1505 " new type `%s'", m
->mimetype
, l
);
1510 for (i
= 0; *l
&& ((isascii((unsigned char)*l
) && isalnum((unsigned char)*l
))
1511 || strchr("-+/.", *l
)) && i
< sizeof(m
->apple
); m
->apple
[i
++] = *l
++)
1513 if (i
== sizeof(m
->apple
) && *l
) {
1514 if (ms
->flags
& MAGIC_CHECK
)
1515 file_magwarn(ms
, "APPLE type `%s' truncated %zu",
1526 * parse a MIME annotation line from magic file, put into magic[index - 1]
1530 parse_mime(struct magic_set
*ms
, struct magic_entry
*me
, const char *line
)
1533 const char *l
= line
;
1534 struct magic
*m
= &me
->mp
[me
->cont_count
== 0 ? 0 : me
->cont_count
- 1];
1536 if (m
->mimetype
[0] != '\0') {
1537 file_magwarn(ms
, "Current entry already has a MIME type `%s',"
1538 " new type `%s'", m
->mimetype
, l
);
1543 for (i
= 0; *l
&& ((isascii((unsigned char)*l
) && isalnum((unsigned char)*l
))
1544 || strchr("-+/.", *l
)) && i
< sizeof(m
->mimetype
); m
->mimetype
[i
++] = *l
++)
1546 if (i
== sizeof(m
->mimetype
)) {
1547 m
->desc
[sizeof(m
->mimetype
) - 1] = '\0';
1548 if (ms
->flags
& MAGIC_CHECK
)
1549 file_magwarn(ms
, "MIME type `%s' truncated %zu",
1552 m
->mimetype
[i
] = '\0';
1561 check_format_type(const char *ptr
, int type
)
1565 /* Missing format string; bad */
1578 while (isdigit((unsigned char)*ptr
)) ptr
++;
1581 while (isdigit((unsigned char)*ptr
)) ptr
++;
1633 case FILE_FMT_FLOAT
:
1634 case FILE_FMT_DOUBLE
:
1639 while (isdigit((unsigned char)*ptr
)) ptr
++;
1642 while (isdigit((unsigned char)*ptr
)) ptr
++;
1661 while (isdigit((unsigned char )*ptr
))
1665 while (isdigit((unsigned char )*ptr
))
1677 /* internal error */
1685 * Check that the optional printf format in description matches
1686 * the type of the magic.
1689 check_format(struct magic_set
*ms
, struct magic
*m
)
1693 for (ptr
= m
->desc
; *ptr
; ptr
++)
1697 /* No format string; ok */
1701 assert(file_nformats
== file_nnames
);
1703 if (m
->type
>= file_nformats
) {
1704 file_magwarn(ms
, "Internal error inconsistency between "
1705 "m->type and format strings");
1708 if (file_formats
[m
->type
] == FILE_FMT_NONE
) {
1709 file_magwarn(ms
, "No format string for `%s' with description "
1710 "`%s'", m
->desc
, file_names
[m
->type
]);
1715 if (check_format_type(ptr
, file_formats
[m
->type
]) == -1) {
1717 * TODO: this error message is unhelpful if the format
1718 * string is not one character long
1720 file_magwarn(ms
, "Printf format `%c' is not valid for type "
1721 "`%s' in description `%s'", *ptr
? *ptr
: '?',
1722 file_names
[m
->type
], m
->desc
);
1726 for (; *ptr
; ptr
++) {
1729 "Too many format strings (should have at most one) "
1730 "for `%s' with description `%s'",
1731 file_names
[m
->type
], m
->desc
);
1739 * Read a numeric value from a pointer, into the value union of a magic
1740 * pointer, according to the magic type. Update the string pointer to point
1741 * just after the number read. Return 0 for success, non-zero for failure.
1744 getvalue(struct magic_set
*ms
, struct magic
*m
, const char **p
, int action
)
1747 case FILE_BESTRING16
:
1748 case FILE_LESTRING16
:
1753 *p
= getstr(ms
, m
, *p
, action
== FILE_COMPILE
);
1755 if (ms
->flags
& MAGIC_CHECK
)
1756 file_magwarn(ms
, "cannot get string from `%s'",
1764 if (m
->reln
!= 'x') {
1767 m
->value
.f
= strtof(*p
, &ep
);
1769 m
->value
.f
= (float)strtod(*p
, &ep
);
1777 if (m
->reln
!= 'x') {
1779 m
->value
.d
= strtod(*p
, &ep
);
1784 if (m
->reln
!= 'x') {
1786 m
->value
.q
= file_signextend(ms
, m
,
1787 (uint64_t)strtoull(*p
, &ep
, 0));
1796 * Convert a string containing C character escapes. Stop at an unescaped
1798 * Copy the converted version to "m->value.s", and the length in m->vallen.
1799 * Return updated scan pointer as function result. Warn if set.
1801 private const char *
1802 getstr(struct magic_set
*ms
, struct magic
*m
, const char *s
, int warn
)
1804 const char *origs
= s
;
1805 char *p
= m
->value
.s
;
1806 size_t plen
= sizeof(m
->value
.s
);
1808 char *pmax
= p
+ plen
- 1;
1812 while ((c
= *s
++) != '\0') {
1813 if (isspace((unsigned char) c
))
1816 file_error(ms
, 0, "string too long: `%s'", origs
);
1824 file_magwarn(ms
, "incomplete escape");
1830 "escaped tab found, use \\t instead");
1831 warn
= 0; /* already did */
1836 if (isprint((unsigned char)c
)) {
1837 /* Allow escaping of
1839 if (strchr("<>&^=!", c
)
1841 file_magwarn(ms
, "no "
1847 "unknown escape sequence: "
1852 /* space, perhaps force people to use \040? */
1856 * Other things people escape, but shouldn't need to,
1857 * so we disallow them
1870 /* and baskslash itself */
1903 /* \ and up to 3 octal digits */
1913 c
= *s
++; /* try for 2 */
1914 if (c
>= '0' && c
<= '7') {
1915 val
= (val
<< 3) | (c
- '0');
1916 c
= *s
++; /* try for 3 */
1917 if (c
>= '0' && c
<= '7')
1918 val
= (val
<< 3) | (c
-'0');
1927 /* \x and up to 2 hex digits */
1929 val
= 'x'; /* Default if no digits */
1930 c
= hextoint(*s
++); /* Get next char */
1935 val
= (val
<< 4) + c
;
1948 m
->vallen
= p
- origp
;
1949 if (m
->type
== FILE_PSTRING
)
1955 /* Single hex char to int; -1 if not a hex char. */
1959 if (!isascii((unsigned char) c
))
1961 if (isdigit((unsigned char) c
))
1963 if ((c
>= 'a') && (c
<= 'f'))
1964 return c
+ 10 - 'a';
1965 if (( c
>= 'A') && (c
<= 'F'))
1966 return c
+ 10 - 'A';
1972 * Print a string containing C character escapes.
1975 file_showstr(FILE *fp
, const char *s
, size_t len
)
1989 if (c
>= 040 && c
<= 0176) /* TODO isprint && !iscntrl */
1990 (void) fputc(c
, fp
);
1992 (void) fputc('\\', fp
);
1995 (void) fputc('a', fp
);
1999 (void) fputc('b', fp
);
2003 (void) fputc('f', fp
);
2007 (void) fputc('n', fp
);
2011 (void) fputc('r', fp
);
2015 (void) fputc('t', fp
);
2019 (void) fputc('v', fp
);
2023 (void) fprintf(fp
, "%.3o", c
& 0377);
2031 * eatsize(): Eat the size spec from a number [eg. 10UL]
2034 eatsize(const char **p
)
2038 if (LOWCASE(*l
) == 'u')
2041 switch (LOWCASE(*l
)) {
2042 case 'l': /* long */
2043 case 's': /* short */
2044 case 'h': /* short */
2045 case 'b': /* char/byte */
2046 case 'c': /* char/byte */
2057 * handle a compiled file.
2060 apprentice_map(struct magic_set
*ms
, struct magic
**magicp
, uint32_t *nmagicp
,
2068 char *dbname
= NULL
;
2071 dbname
= mkdbname(ms
, fn
, 0);
2075 if ((fd
= open(dbname
, O_RDONLY
|O_BINARY
)) == -1)
2078 if (fstat(fd
, &st
) == -1) {
2079 file_error(ms
, errno
, "cannot stat `%s'", dbname
);
2082 if (st
.st_size
< 8) {
2083 file_error(ms
, 0, "file `%s' is too small", dbname
);
2088 if ((mm
= mmap(0, (size_t)st
.st_size
, PROT_READ
|PROT_WRITE
,
2089 MAP_PRIVATE
|MAP_FILE
, fd
, (off_t
)0)) == MAP_FAILED
) {
2090 file_error(ms
, errno
, "cannot map `%s'", dbname
);
2095 if ((mm
= CAST(void *, malloc((size_t)st
.st_size
))) == NULL
) {
2096 file_oomem(ms
, (size_t)st
.st_size
);
2099 if (read(fd
, mm
, (size_t)st
.st_size
) != (ssize_t
)st
.st_size
) {
2105 *magicp
= CAST(struct magic
*, mm
);
2108 ptr
= (uint32_t *)(void *)*magicp
;
2109 if (*ptr
!= MAGICNO
) {
2110 if (swap4(*ptr
) != MAGICNO
) {
2111 file_error(ms
, 0, "bad magic in `%s'", dbname
);
2118 version
= swap4(ptr
[1]);
2121 if (version
!= VERSIONNO
) {
2122 file_error(ms
, 0, "File %d.%d supports only version %d magic "
2123 "files. `%s' is version %d", FILE_VERSION_MAJOR
, patchlevel
,
2124 VERSIONNO
, dbname
, version
);
2127 *nmagicp
= (uint32_t)(st
.st_size
/ sizeof(struct magic
));
2132 byteswap(*magicp
, *nmagicp
);
2141 (void)munmap((void *)mm
, (size_t)st
.st_size
);
2154 private const uint32_t ar
[] = {
2158 * handle an mmaped file.
2161 apprentice_compile(struct magic_set
*ms
, struct magic
**magicp
,
2162 uint32_t *nmagicp
, const char *fn
)
2168 dbname
= mkdbname(ms
, fn
, 1);
2173 if ((fd
= open(dbname
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_BINARY
, 0644)) == -1) {
2174 file_error(ms
, errno
, "cannot open `%s'", dbname
);
2178 if (write(fd
, ar
, sizeof(ar
)) != (ssize_t
)sizeof(ar
)) {
2179 file_error(ms
, errno
, "error writing `%s'", dbname
);
2183 if (lseek(fd
, (off_t
)sizeof(struct magic
), SEEK_SET
)
2184 != sizeof(struct magic
)) {
2185 file_error(ms
, errno
, "error seeking `%s'", dbname
);
2189 if (write(fd
, *magicp
, (sizeof(struct magic
) * *nmagicp
))
2190 != (ssize_t
)(sizeof(struct magic
) * *nmagicp
)) {
2191 file_error(ms
, errno
, "error writing `%s'", dbname
);
2202 private const char ext
[] = ".mgc";
2207 mkdbname(struct magic_set
*ms
, const char *fn
, int strip
)
2213 if ((p
= strrchr(fn
, '/')) != NULL
)
2217 for (q
= fn
; *q
; q
++)
2220 for (p
= ext
+ sizeof(ext
) - 1; p
>= ext
&& q
>= fn
; p
--, q
--)
2224 /* Did not find .mgc, restore q */
2230 /* Compatibility with old code that looked in .mime */
2231 if (ms
->flags
& MAGIC_MIME
) {
2232 asprintf(&buf
, "%.*s.mime%s", (int)(q
- fn
), fn
, ext
);
2233 if (access(buf
, R_OK
) != -1) {
2234 ms
->flags
&= MAGIC_MIME_TYPE
;
2239 asprintf(&buf
, "%.*s%s", (int)(q
- fn
), fn
, ext
);
2241 /* Compatibility with old code that looked in .mime */
2242 if (strstr(p
, ".mime") != NULL
)
2243 ms
->flags
&= MAGIC_MIME_TYPE
;
2248 * Byteswap an mmap'ed file if needed
2251 byteswap(struct magic
*magic
, uint32_t nmagic
)
2254 for (i
= 0; i
< nmagic
; i
++)
2265 uint8_t *s
= (uint8_t *)(void *)&sv
;
2266 uint8_t *d
= (uint8_t *)(void *)&rv
;
2279 uint8_t *s
= (uint8_t *)(void *)&sv
;
2280 uint8_t *d
= (uint8_t *)(void *)&rv
;
2295 uint8_t *s
= (uint8_t *)(void *)&sv
;
2296 uint8_t *d
= (uint8_t *)(void *)&rv
;
2320 * byteswap a single magic entry
2323 bs1(struct magic
*m
)
2325 m
->cont_level
= swap2(m
->cont_level
);
2326 m
->offset
= swap4((uint32_t)m
->offset
);
2327 m
->in_offset
= swap4((uint32_t)m
->in_offset
);
2328 m
->lineno
= swap4((uint32_t)m
->lineno
);
2329 if (IS_STRING(m
->type
)) {
2330 m
->str_range
= swap4(m
->str_range
);
2331 m
->str_flags
= swap4(m
->str_flags
);
2334 m
->value
.q
= swap8(m
->value
.q
);
2335 m
->num_mask
= swap8(m
->num_mask
);