1 /* $NetBSD: apprentice.c,v 1.1.1.1 2009/05/08 16:35:05 christos Exp $ */
4 * Copyright (c) Ian F. Darwin 1986-1995.
5 * Software written by Ian F. Darwin and others;
6 * maintained 1995-present by Christos Zoulas and others.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice immediately at the beginning of the file, without modification,
13 * this list of conditions, and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * apprentice - make one pass through /etc/magic, learning its secrets.
38 FILE_RCSID("@(#)$File: apprentice.c,v 1.151 2009/03/18 15:19:23 christos Exp $")
40 __RCSID("$NetBSD: apprentice.c,v 1.1.1.1 2009/05/08 16:35:05 christos Exp $");
45 #include "patchlevel.h"
59 #define EATAB {while (isascii((unsigned char) *l) && \
60 isspace((unsigned char) *l)) ++l;}
61 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \
62 tolower((unsigned char) (l)) : (l))
64 * Work around a bug in headers on Digital Unix.
65 * At least confirmed for: OSF1 V4.0 878
67 #if defined(__osf__) && defined(__DECC)
74 #define MAP_FAILED (void *) -1
82 #define MAXPATHLEN 1024
91 int file_formats
[FILE_NAMES_SIZE
];
92 const size_t file_nformats
= FILE_NAMES_SIZE
;
93 const char *file_names
[FILE_NAMES_SIZE
];
94 const size_t file_nnames
= FILE_NAMES_SIZE
;
96 private int getvalue(struct magic_set
*ms
, struct magic
*, const char **, int);
97 private int hextoint(int);
98 private const char *getstr(struct magic_set
*, struct magic
*, const char *,
100 private int parse(struct magic_set
*, struct magic_entry
**, uint32_t *,
101 const char *, size_t, int);
102 private void eatsize(const char **);
103 private int apprentice_1(struct magic_set
*, const char *, int, struct mlist
*);
104 private size_t apprentice_magic_strength(const struct magic
*);
105 private int apprentice_sort(const void *, const void *);
106 private int apprentice_load(struct magic_set
*, struct magic
**, uint32_t *,
108 private void byteswap(struct magic
*, uint32_t);
109 private void bs1(struct magic
*);
110 private uint16_t swap2(uint16_t);
111 private uint32_t swap4(uint32_t);
112 private uint64_t swap8(uint64_t);
113 private char *mkdbname(struct magic_set
*, const char *, int);
114 private int apprentice_map(struct magic_set
*, struct magic
**, uint32_t *,
116 private int apprentice_compile(struct magic_set
*, struct magic
**, uint32_t *,
118 private int check_format_type(const char *, int);
119 private int check_format(struct magic_set
*, struct magic
*);
120 private int get_op(char);
121 private int parse_mime(struct magic_set
*, struct magic_entry
*, const char *);
122 private int parse_strength(struct magic_set
*, struct magic_entry
*, const char *);
123 private int parse_apple(struct magic_set
*, struct magic_entry
*, const char *);
126 private size_t maxmagic
= 0;
127 private size_t magicsize
= sizeof(struct magic
);
129 private const char usg_hdr
[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc";
134 int (*fun
)(struct magic_set
*, struct magic_entry
*, const char *);
136 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name }
138 DECLARE_FIELD(apple
),
139 DECLARE_FIELD(strength
),
146 int main(int, char *[]);
149 main(int argc
, char *argv
[])
152 struct magic_set
*ms
;
155 if ((progname
= strrchr(argv
[0], '/')) != NULL
)
161 (void)fprintf(stderr
, "Usage: %s file\n", progname
);
165 if ((ms
= magic_open(MAGIC_CHECK
)) == NULL
) {
166 (void)fprintf(stderr
, "%s: %s\n", progname
, strerror(errno
));
169 ret
= magic_compile(ms
, argv
[1]) == -1 ? 1 : 0;
171 (void)fprintf(stderr
, "%s: %s\n", progname
, magic_error(ms
));
175 #endif /* COMPILE_ONLY */
177 static const struct type_tbl_s
{
183 # define XX(s) s, (sizeof(s) - 1)
184 # define XX_NULL "", 0
185 { XX("byte"), FILE_BYTE
, FILE_FMT_NUM
},
186 { XX("short"), FILE_SHORT
, FILE_FMT_NUM
},
187 { XX("default"), FILE_DEFAULT
, FILE_FMT_STR
},
188 { XX("long"), FILE_LONG
, FILE_FMT_NUM
},
189 { XX("string"), FILE_STRING
, FILE_FMT_STR
},
190 { XX("date"), FILE_DATE
, FILE_FMT_STR
},
191 { XX("beshort"), FILE_BESHORT
, FILE_FMT_NUM
},
192 { XX("belong"), FILE_BELONG
, FILE_FMT_NUM
},
193 { XX("bedate"), FILE_BEDATE
, FILE_FMT_STR
},
194 { XX("leshort"), FILE_LESHORT
, FILE_FMT_NUM
},
195 { XX("lelong"), FILE_LELONG
, FILE_FMT_NUM
},
196 { XX("ledate"), FILE_LEDATE
, FILE_FMT_STR
},
197 { XX("pstring"), FILE_PSTRING
, FILE_FMT_STR
},
198 { XX("ldate"), FILE_LDATE
, FILE_FMT_STR
},
199 { XX("beldate"), FILE_BELDATE
, FILE_FMT_STR
},
200 { XX("leldate"), FILE_LELDATE
, FILE_FMT_STR
},
201 { XX("regex"), FILE_REGEX
, FILE_FMT_STR
},
202 { XX("bestring16"), FILE_BESTRING16
, FILE_FMT_STR
},
203 { XX("lestring16"), FILE_LESTRING16
, FILE_FMT_STR
},
204 { XX("search"), FILE_SEARCH
, FILE_FMT_STR
},
205 { XX("medate"), FILE_MEDATE
, FILE_FMT_STR
},
206 { XX("meldate"), FILE_MELDATE
, FILE_FMT_STR
},
207 { XX("melong"), FILE_MELONG
, FILE_FMT_NUM
},
208 { XX("quad"), FILE_QUAD
, FILE_FMT_QUAD
},
209 { XX("lequad"), FILE_LEQUAD
, FILE_FMT_QUAD
},
210 { XX("bequad"), FILE_BEQUAD
, FILE_FMT_QUAD
},
211 { XX("qdate"), FILE_QDATE
, FILE_FMT_STR
},
212 { XX("leqdate"), FILE_LEQDATE
, FILE_FMT_STR
},
213 { XX("beqdate"), FILE_BEQDATE
, FILE_FMT_STR
},
214 { XX("qldate"), FILE_QLDATE
, FILE_FMT_STR
},
215 { XX("leqldate"), FILE_LEQLDATE
, FILE_FMT_STR
},
216 { XX("beqldate"), FILE_BEQLDATE
, FILE_FMT_STR
},
217 { XX("float"), FILE_FLOAT
, FILE_FMT_FLOAT
},
218 { XX("befloat"), FILE_BEFLOAT
, FILE_FMT_FLOAT
},
219 { XX("lefloat"), FILE_LEFLOAT
, FILE_FMT_FLOAT
},
220 { XX("double"), FILE_DOUBLE
, FILE_FMT_DOUBLE
},
221 { XX("bedouble"), FILE_BEDOUBLE
, FILE_FMT_DOUBLE
},
222 { XX("ledouble"), FILE_LEDOUBLE
, FILE_FMT_DOUBLE
},
223 { XX("leid3"), FILE_LEID3
, FILE_FMT_NUM
},
224 { XX("beid3"), FILE_BEID3
, FILE_FMT_NUM
},
225 { XX("indirect"), FILE_INDIRECT
, FILE_FMT_NONE
},
226 { XX_NULL
, FILE_INVALID
, FILE_FMT_NONE
},
232 get_type(const char *l
, const char **t
)
234 const struct type_tbl_s
*p
;
236 for (p
= type_tbl
; p
->len
; p
++) {
237 if (strncmp(l
, p
->name
, p
->len
) == 0) {
247 init_file_tables(void)
250 const struct type_tbl_s
*p
;
256 for (p
= type_tbl
; p
->len
; p
++) {
257 assert(p
->type
< FILE_NAMES_SIZE
);
258 file_names
[p
->type
] = p
->name
;
259 file_formats
[p
->type
] = p
->format
;
264 * Handle one file or directory.
267 apprentice_1(struct magic_set
*ms
, const char *fn
, int action
,
270 struct magic
*magic
= NULL
;
276 if (magicsize
!= FILE_MAGICSIZE
) {
277 file_error(ms
, 0, "magic element size %lu != %lu",
278 (unsigned long)sizeof(*magic
),
279 (unsigned long)FILE_MAGICSIZE
);
283 if (action
== FILE_COMPILE
) {
284 rv
= apprentice_load(ms
, &magic
, &nmagic
, fn
, action
);
287 rv
= apprentice_compile(ms
, &magic
, &nmagic
, fn
);
293 if ((rv
= apprentice_map(ms
, &magic
, &nmagic
, fn
)) == -1) {
294 if (ms
->flags
& MAGIC_CHECK
)
295 file_magwarn(ms
, "using regular magic file `%s'", fn
);
296 rv
= apprentice_load(ms
, &magic
, &nmagic
, fn
, action
);
304 file_delmagic(magic
, mapped
, nmagic
);
308 if ((ml
= CAST(struct mlist
*, malloc(sizeof(*ml
)))) == NULL
) {
309 file_delmagic(magic
, mapped
, nmagic
);
310 file_oomem(ms
, sizeof(*ml
));
318 mlist
->prev
->next
= ml
;
319 ml
->prev
= mlist
->prev
;
324 #endif /* COMPILE_ONLY */
328 file_delmagic(struct magic
*p
, int type
, size_t entries
)
336 (void)munmap((void *)p
, sizeof(*p
) * (entries
+ 1));
354 /* const char *fn: list of magic files and directories */
355 protected struct mlist
*
356 file_apprentice(struct magic_set
*ms
, const char *fn
, int action
)
359 int file_err
, errs
= -1;
365 fn
= getenv("MAGIC");
369 if ((mfn
= strdup(fn
)) == NULL
) {
370 file_oomem(ms
, strlen(fn
));
375 if ((mlist
= CAST(struct mlist
*, malloc(sizeof(*mlist
)))) == NULL
) {
377 file_oomem(ms
, sizeof(*mlist
));
380 mlist
->next
= mlist
->prev
= mlist
;
383 p
= strchr(fn
, PATHSEP
);
388 file_err
= apprentice_1(ms
, fn
, action
, mlist
);
389 errs
= MAX(errs
, file_err
);
396 file_error(ms
, 0, "could not find any magic files!");
404 * Get weight of this magic entry, for sorting purposes.
407 apprentice_magic_strength(const struct magic
*m
)
410 size_t val
= 2 * MULT
; /* baseline strength */
413 case FILE_DEFAULT
: /* make sure this sorts last */
414 if (m
->factor_op
!= FILE_FACTOR_OP_NONE
)
437 val
+= m
->vallen
* MULT
;
440 case FILE_BESTRING16
:
441 case FILE_LESTRING16
:
442 val
+= m
->vallen
* MULT
/ 2;
447 val
+= m
->vallen
* MAX(MULT
/ m
->vallen
, 1);
481 (void)fprintf(stderr
, "Bad type %d\n", m
->type
);
486 case 'x': /* matches anything penalize */
487 case '!': /* matches almost anything penalize */
491 case '=': /* Exact match, prefer */
496 case '<': /* comparison match reduce strength */
501 case '&': /* masking bits, we could count them too */
506 (void)fprintf(stderr
, "Bad relation %c\n", m
->reln
);
510 if (val
== 0) /* ensure we only return 0 for FILE_DEFAULT */
513 switch (m
->factor_op
) {
514 case FILE_FACTOR_OP_NONE
:
516 case FILE_FACTOR_OP_PLUS
:
519 case FILE_FACTOR_OP_MINUS
:
522 case FILE_FACTOR_OP_TIMES
:
525 case FILE_FACTOR_OP_DIV
:
533 * Magic entries with no description get a bonus because they depend
534 * on subsequent magic entries to print something.
536 if (m
->desc
[0] == '\0')
542 * Sort callback for sorting entries by "strength" (basically length)
545 apprentice_sort(const void *a
, const void *b
)
547 const struct magic_entry
*ma
= CAST(const struct magic_entry
*, a
);
548 const struct magic_entry
*mb
= CAST(const struct magic_entry
*, b
);
549 size_t sa
= apprentice_magic_strength(ma
->mp
);
550 size_t sb
= apprentice_magic_strength(mb
->mp
);
560 set_test_type(struct magic
*mstart
, struct magic
*m
)
596 case FILE_BESTRING16
:
597 case FILE_LESTRING16
:
598 /* binary test, set flag */
599 mstart
->flag
|= BINTEST
;
603 /* binary test if pattern is not text */
604 if (file_looks_utf8(m
->value
.us
, (size_t)m
->vallen
, NULL
,
606 mstart
->flag
|= BINTEST
;
609 /* can't deduce anything; we shouldn't see this at the
614 /* invalid search type, but no need to complain here */
620 * Load and parse one file.
623 load_1(struct magic_set
*ms
, int action
, const char *fn
, int *errs
,
624 struct magic_entry
**marray
, uint32_t *marraycount
)
628 FILE *f
= fopen(ms
->file
= fn
, "r");
631 file_error(ms
, errno
, "cannot read magic file `%s'",
635 /* read and parse this file */
637 fgets(line
, CAST(int, sizeof(line
)), f
) != NULL
;
641 if (len
== 0) /* null line, garbage, etc */
643 if (line
[len
- 1] == '\n') {
645 line
[len
- 1] = '\0'; /* delete newline */
647 if (line
[0] == '\0') /* empty, do not parse */
649 if (line
[0] == '#') /* comment, do not parse */
651 if (line
[0] == '!' && line
[1] == ':') {
654 for (i
= 0; bang
[i
].name
!= NULL
; i
++) {
655 if (len
- 2 > bang
[i
].len
&&
656 memcmp(bang
[i
].name
, line
+ 2,
660 if (bang
[i
].name
== NULL
) {
662 "Unknown !: entry `%s'", line
);
666 if (*marraycount
== 0) {
668 "No current entry for :!%s type",
673 if ((*bang
[i
].fun
)(ms
,
674 &(*marray
)[*marraycount
- 1],
675 line
+ bang
[i
].len
+ 2) != 0) {
681 if (parse(ms
, marray
, marraycount
, line
, lineno
,
691 * parse a file or directory of files
692 * const char *fn: name of magic file or directory
695 apprentice_load(struct magic_set
*ms
, struct magic
**magicp
, uint32_t *nmagicp
,
696 const char *fn
, int action
)
699 struct magic_entry
*marray
;
700 uint32_t marraycount
, i
, mentrycount
= 0, starttest
;
702 char subfn
[MAXPATHLEN
];
707 ms
->flags
|= MAGIC_CHECK
; /* Enable checks for parsed files */
710 if ((marray
= CAST(struct magic_entry
*, calloc(maxmagic
,
711 sizeof(*marray
)))) == NULL
) {
712 file_oomem(ms
, maxmagic
* sizeof(*marray
));
717 /* print silly verbose header for USG compat. */
718 if (action
== FILE_CHECK
)
719 (void)fprintf(stderr
, "%s\n", usg_hdr
);
721 /* load directory or file */
722 /* FIXME: Read file names and sort them to prevent
723 non-determinism. See Debian bug #488562. */
724 if (stat(fn
, &st
) == 0 && S_ISDIR(st
.st_mode
)) {
727 while ((d
= readdir(dir
)) != NULL
) {
728 snprintf(subfn
, sizeof(subfn
), "%s/%s",
730 if (stat(subfn
, &st
) == 0 &&
731 S_ISREG(st
.st_mode
)) {
732 load_1(ms
, action
, subfn
, &errs
,
733 &marray
, &marraycount
);
740 load_1(ms
, action
, fn
, &errs
, &marray
, &marraycount
);
744 /* Set types of tests */
745 for (i
= 0; i
< marraycount
; ) {
746 if (marray
[i
].mp
->cont_level
!= 0) {
753 static const char text
[] = "text";
754 static const char binary
[] = "binary";
755 static const size_t len
= sizeof(text
);
756 set_test_type(marray
[starttest
].mp
, marray
[i
].mp
);
757 if ((ms
->flags
& MAGIC_DEBUG
) == 0)
759 (void)fprintf(stderr
, "%s%s%s: %s\n",
760 marray
[i
].mp
->mimetype
,
761 marray
[i
].mp
->mimetype
[0] == '\0' ? "" : "; ",
762 marray
[i
].mp
->desc
[0] ? marray
[i
].mp
->desc
:
764 marray
[i
].mp
->flag
& BINTEST
? binary
: text
);
765 if (marray
[i
].mp
->flag
& BINTEST
) {
766 char *p
= strstr(marray
[i
].mp
->desc
, text
);
767 if (p
&& (p
== marray
[i
].mp
->desc
||
768 isspace((unsigned char)p
[-1])) &&
769 (p
+ len
- marray
[i
].mp
->desc
==
770 MAXstring
|| (p
[len
] == '\0' ||
771 isspace((unsigned char)p
[len
]))))
772 (void)fprintf(stderr
, "*** Possible "
773 "binary test for text type\n");
775 } while (++i
< marraycount
&& marray
[i
].mp
->cont_level
!= 0);
778 qsort(marray
, marraycount
, sizeof(*marray
), apprentice_sort
);
781 * Make sure that any level 0 "default" line is last (if one exists).
783 for (i
= 0; i
< marraycount
; i
++) {
784 if (marray
[i
].mp
->cont_level
== 0 &&
785 marray
[i
].mp
->type
== FILE_DEFAULT
) {
786 while (++i
< marraycount
)
787 if (marray
[i
].mp
->cont_level
== 0)
789 if (i
!= marraycount
) {
790 ms
->line
= marray
[i
].mp
->lineno
; /* XXX - Ugh! */
792 "level 0 \"default\" did not sort last");
798 for (i
= 0; i
< marraycount
; i
++)
799 mentrycount
+= marray
[i
].cont_count
;
801 slen
= sizeof(**magicp
) * mentrycount
;
802 if ((*magicp
= CAST(struct magic
*, malloc(slen
))) == NULL
) {
803 file_oomem(ms
, slen
);
809 for (i
= 0; i
< marraycount
; i
++) {
810 (void)memcpy(*magicp
+ mentrycount
, marray
[i
].mp
,
811 marray
[i
].cont_count
* sizeof(**magicp
));
812 mentrycount
+= marray
[i
].cont_count
;
815 for (i
= 0; i
< marraycount
; i
++)
823 *nmagicp
= mentrycount
;
830 * extend the sign bit if the comparison is to be signed
833 file_signextend(struct magic_set
*ms
, struct magic
*m
, uint64_t v
)
835 if (!(m
->flag
& UNSIGNED
)) {
838 * Do not remove the casts below. They are
839 * vital. When later compared with the data,
840 * the sign extension must have happened.
883 case FILE_BESTRING16
:
884 case FILE_LESTRING16
:
891 if (ms
->flags
& MAGIC_CHECK
)
892 file_magwarn(ms
, "cannot happen: m->type=%d\n",
901 string_modifier_check(struct magic_set
*ms
, struct magic
*m
)
903 if ((ms
->flags
& MAGIC_CHECK
) == 0)
907 case FILE_BESTRING16
:
908 case FILE_LESTRING16
:
909 if (m
->str_flags
!= 0) {
911 "no modifiers allowed for 16-bit strings\n");
917 if ((m
->str_flags
& REGEX_OFFSET_START
) != 0) {
919 "'/%c' only allowed on regex and search\n",
920 CHAR_REGEX_OFFSET_START
);
925 if (m
->str_range
== 0) {
927 "missing range; defaulting to %d\n",
928 STRING_DEFAULT_RANGE
);
929 m
->str_range
= STRING_DEFAULT_RANGE
;
934 if ((m
->str_flags
& STRING_COMPACT_BLANK
) != 0) {
935 file_magwarn(ms
, "'/%c' not allowed on regex\n",
939 if ((m
->str_flags
& STRING_COMPACT_OPTIONAL_BLANK
) != 0) {
940 file_magwarn(ms
, "'/%c' not allowed on regex\n",
941 CHAR_COMPACT_OPTIONAL_BLANK
);
946 file_magwarn(ms
, "coding error: m->type=%d\n",
968 return FILE_OPMULTIPLY
;
970 return FILE_OPDIVIDE
;
972 return FILE_OPMODULO
;
978 #ifdef ENABLE_CONDITIONALS
980 get_cond(const char *l
, const char **t
)
982 static const struct cond_tbl_s
{
987 { "if", 2, COND_IF
},
988 { "elif", 4, COND_ELIF
},
989 { "else", 4, COND_ELSE
},
990 { "", 0, COND_NONE
},
992 const struct cond_tbl_s
*p
;
994 for (p
= cond_tbl
; p
->len
; p
++) {
995 if (strncmp(l
, p
->name
, p
->len
) == 0 &&
996 isspace((unsigned char)l
[p
->len
])) {
1006 check_cond(struct magic_set
*ms
, int cond
, uint32_t cont_level
)
1009 last_cond
= ms
->c
.li
[cont_level
].last_cond
;
1013 if (last_cond
!= COND_NONE
&& last_cond
!= COND_ELIF
) {
1014 if (ms
->flags
& MAGIC_CHECK
)
1015 file_magwarn(ms
, "syntax error: `if'");
1018 last_cond
= COND_IF
;
1022 if (last_cond
!= COND_IF
&& last_cond
!= COND_ELIF
) {
1023 if (ms
->flags
& MAGIC_CHECK
)
1024 file_magwarn(ms
, "syntax error: `elif'");
1027 last_cond
= COND_ELIF
;
1031 if (last_cond
!= COND_IF
&& last_cond
!= COND_ELIF
) {
1032 if (ms
->flags
& MAGIC_CHECK
)
1033 file_magwarn(ms
, "syntax error: `else'");
1036 last_cond
= COND_NONE
;
1040 last_cond
= COND_NONE
;
1044 ms
->c
.li
[cont_level
].last_cond
= last_cond
;
1047 #endif /* ENABLE_CONDITIONALS */
1050 * parse one line from magic file, put into magic[index++] if valid
1053 parse(struct magic_set
*ms
, struct magic_entry
**mentryp
, uint32_t *nmentryp
,
1054 const char *line
, size_t lineno
, int action
)
1056 #ifdef ENABLE_CONDITIONALS
1057 static uint32_t last_cont_level
= 0;
1060 struct magic_entry
*me
;
1062 const char *l
= line
;
1065 uint32_t cont_level
;
1070 ++l
; /* step over */
1073 #ifdef ENABLE_CONDITIONALS
1074 if (cont_level
== 0 || cont_level
> last_cont_level
)
1075 if (file_check_mem(ms
, cont_level
) == -1)
1077 last_cont_level
= cont_level
;
1080 #define ALLOC_CHUNK (size_t)10
1081 #define ALLOC_INCR (size_t)200
1083 if (cont_level
!= 0) {
1084 if (*nmentryp
== 0) {
1085 file_error(ms
, 0, "No current entry for continuation");
1088 me
= &(*mentryp
)[*nmentryp
- 1];
1089 if (me
->cont_count
== me
->max_count
) {
1091 size_t cnt
= me
->max_count
+ ALLOC_CHUNK
;
1092 if ((nm
= CAST(struct magic
*, realloc(me
->mp
,
1093 sizeof(*nm
) * cnt
))) == NULL
) {
1094 file_oomem(ms
, sizeof(*nm
) * cnt
);
1098 me
->max_count
= CAST(uint32_t, cnt
);
1100 m
= &me
->mp
[me
->cont_count
++];
1101 (void)memset(m
, 0, sizeof(*m
));
1102 m
->cont_level
= cont_level
;
1104 if (*nmentryp
== maxmagic
) {
1105 struct magic_entry
*mp
;
1107 maxmagic
+= ALLOC_INCR
;
1108 if ((mp
= CAST(struct magic_entry
*,
1109 realloc(*mentryp
, sizeof(*mp
) * maxmagic
))) ==
1111 file_oomem(ms
, sizeof(*mp
) * maxmagic
);
1114 (void)memset(&mp
[*nmentryp
], 0, sizeof(*mp
) *
1118 me
= &(*mentryp
)[*nmentryp
];
1119 if (me
->mp
== NULL
) {
1120 size_t len
= sizeof(*m
) * ALLOC_CHUNK
;
1121 if ((m
= CAST(struct magic
*, malloc(len
))) == NULL
) {
1122 file_oomem(ms
, len
);
1126 me
->max_count
= ALLOC_CHUNK
;
1129 (void)memset(m
, 0, sizeof(*m
));
1130 m
->factor_op
= FILE_FACTOR_OP_NONE
;
1134 m
->lineno
= CAST(uint32_t, lineno
);
1136 if (*l
== '&') { /* m->cont_level == 0 checked below. */
1137 ++l
; /* step over */
1141 ++l
; /* step over */
1143 if (m
->flag
& OFFADD
)
1144 m
->flag
= (m
->flag
& ~OFFADD
) | INDIROFFADD
;
1146 if (*l
== '&') { /* m->cont_level == 0 checked below */
1147 ++l
; /* step over */
1151 /* Indirect offsets are not valid at level 0. */
1152 if (m
->cont_level
== 0 && (m
->flag
& (OFFADD
| INDIROFFADD
)))
1153 if (ms
->flags
& MAGIC_CHECK
)
1154 file_magwarn(ms
, "relative offset at level 0");
1156 /* get offset, then skip over it */
1157 m
->offset
= (uint32_t)strtoul(l
, &t
, 0);
1159 if (ms
->flags
& MAGIC_CHECK
)
1160 file_magwarn(ms
, "offset `%s' invalid", l
);
1163 if (m
->flag
& INDIR
) {
1164 m
->in_type
= FILE_LONG
;
1167 * read [.lbs][+-]nnnnn)
1173 m
->in_type
= FILE_LELONG
;
1176 m
->in_type
= FILE_BELONG
;
1179 m
->in_type
= FILE_MELONG
;
1183 m
->in_type
= FILE_LESHORT
;
1187 m
->in_type
= FILE_BESHORT
;
1193 m
->in_type
= FILE_BYTE
;
1198 m
->in_type
= FILE_LEDOUBLE
;
1203 m
->in_type
= FILE_BEDOUBLE
;
1206 m
->in_type
= FILE_LEID3
;
1209 m
->in_type
= FILE_BEID3
;
1212 if (ms
->flags
& MAGIC_CHECK
)
1214 "indirect offset type `%c' invalid",
1223 m
->in_op
|= FILE_OPINVERSE
;
1226 if ((op
= get_op(*l
)) != -1) {
1231 m
->in_op
|= FILE_OPINDIRECT
;
1234 if (isdigit((unsigned char)*l
) || *l
== '-') {
1235 m
->in_offset
= (int32_t)strtol(l
, &t
, 0);
1237 if (ms
->flags
& MAGIC_CHECK
)
1239 "in_offset `%s' invalid", l
);
1243 ((m
->in_op
& FILE_OPINDIRECT
) && *l
++ != ')'))
1244 if (ms
->flags
& MAGIC_CHECK
)
1246 "missing ')' in indirect offset");
1250 #ifdef ENABLE_CONDITIONALS
1251 m
->cond
= get_cond(l
, &l
);
1252 if (check_cond(ms
, m
->cond
, cont_level
) == -1)
1260 m
->flag
|= UNSIGNED
;
1263 m
->type
= get_type(l
, &l
);
1264 if (m
->type
== FILE_INVALID
) {
1265 if (ms
->flags
& MAGIC_CHECK
)
1266 file_magwarn(ms
, "type `%s' invalid", l
);
1270 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */
1271 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */
1275 if (!IS_STRING(m
->type
))
1276 m
->mask_op
|= FILE_OPINVERSE
;
1277 else if (ms
->flags
& MAGIC_CHECK
)
1278 file_magwarn(ms
, "'~' invalid for string types");
1284 if ((op
= get_op(*l
)) != -1) {
1285 if (!IS_STRING(m
->type
)) {
1289 val
= (uint64_t)strtoull(l
, &t
, 0);
1291 m
->num_mask
= file_signextend(ms
, m
, val
);
1294 else if (op
== FILE_OPDIVIDE
) {
1296 while (!isspace((unsigned char)*++l
)) {
1298 case '0': case '1': case '2':
1299 case '3': case '4': case '5':
1300 case '6': case '7': case '8':
1303 (ms
->flags
& MAGIC_CHECK
))
1307 m
->str_range
= CAST(uint32_t,
1309 if (m
->str_range
== 0)
1314 case CHAR_COMPACT_BLANK
:
1315 m
->str_flags
|= STRING_COMPACT_BLANK
;
1317 case CHAR_COMPACT_OPTIONAL_BLANK
:
1319 STRING_COMPACT_OPTIONAL_BLANK
;
1321 case CHAR_IGNORE_LOWERCASE
:
1322 m
->str_flags
|= STRING_IGNORE_LOWERCASE
;
1324 case CHAR_IGNORE_UPPERCASE
:
1325 m
->str_flags
|= STRING_IGNORE_UPPERCASE
;
1327 case CHAR_REGEX_OFFSET_START
:
1328 m
->str_flags
|= REGEX_OFFSET_START
;
1331 if (ms
->flags
& MAGIC_CHECK
)
1333 "string extension `%c' invalid",
1337 /* allow multiple '/' for readability */
1339 !isspace((unsigned char)l
[2]))
1342 if (string_modifier_check(ms
, m
) == -1)
1346 if (ms
->flags
& MAGIC_CHECK
)
1347 file_magwarn(ms
, "invalid string op: %c", *t
);
1352 * We used to set mask to all 1's here, instead let's just not do
1353 * anything if mask = 0 (unless you have a better idea)
1363 if (ms
->flags
& MAGIC_CHECK
) {
1364 file_magwarn(ms
, "%c= not supported",
1371 /* Old-style anding: "0 byte &0x80 dynamically linked" */
1378 /* HP compat: ignore &= etc. */
1387 m
->reln
= '='; /* the default relation */
1388 if (*l
== 'x' && ((isascii((unsigned char)l
[1]) &&
1389 isspace((unsigned char)l
[1])) || !l
[1])) {
1396 * Grab the value part, except for an 'x' reln.
1398 if (m
->reln
!= 'x' && getvalue(ms
, m
, &l
, action
))
1402 * TODO finish this macro and start using it!
1403 * #define offsetcheck {if (offset > HOWMANY-1)
1404 * magwarn("offset too big"); }
1408 * Now get last part - the description
1414 } else if ((l
[0] == '\\') && (l
[1] == 'b')) {
1419 for (i
= 0; (m
->desc
[i
++] = *l
++) != '\0' && i
< sizeof(m
->desc
); )
1421 if (i
== sizeof(m
->desc
)) {
1422 m
->desc
[sizeof(m
->desc
) - 1] = '\0';
1423 if (ms
->flags
& MAGIC_CHECK
)
1424 file_magwarn(ms
, "description `%s' truncated", m
->desc
);
1428 * We only do this check while compiling, or if any of the magic
1429 * files were not compiled.
1431 if (ms
->flags
& MAGIC_CHECK
) {
1432 if (check_format(ms
, m
) == -1)
1435 #ifndef COMPILE_ONLY
1436 if (action
== FILE_CHECK
) {
1440 m
->mimetype
[0] = '\0'; /* initialise MIME type to none */
1441 if (m
->cont_level
== 0)
1442 ++(*nmentryp
); /* make room for next */
1447 * parse a STRENGTH annotation line from magic file, put into magic[index - 1]
1451 parse_strength(struct magic_set
*ms
, struct magic_entry
*me
, const char *line
)
1453 const char *l
= line
;
1455 unsigned long factor
;
1456 struct magic
*m
= &me
->mp
[0];
1458 if (m
->factor_op
!= FILE_FACTOR_OP_NONE
) {
1460 "Current entry already has a strength type: %c %d",
1461 m
->factor_op
, m
->factor
);
1466 case FILE_FACTOR_OP_NONE
:
1467 case FILE_FACTOR_OP_PLUS
:
1468 case FILE_FACTOR_OP_MINUS
:
1469 case FILE_FACTOR_OP_TIMES
:
1470 case FILE_FACTOR_OP_DIV
:
1471 m
->factor_op
= *l
++;
1474 file_magwarn(ms
, "Unknown factor op `%c'", *l
);
1478 factor
= strtoul(l
, &el
, 0);
1480 file_magwarn(ms
, "Too large factor `%lu'", factor
);
1483 if (*el
&& !isspace((unsigned char)*el
)) {
1484 file_magwarn(ms
, "Bad factor `%s'", l
);
1487 m
->factor
= (uint8_t)factor
;
1488 if (m
->factor
== 0 && m
->factor_op
== FILE_FACTOR_OP_DIV
) {
1489 file_magwarn(ms
, "Cannot have factor op `%c' and factor %u",
1490 m
->factor_op
, m
->factor
);
1495 m
->factor_op
= FILE_FACTOR_OP_NONE
;
1501 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into magic[index - 1]
1504 parse_apple(struct magic_set
*ms
, struct magic_entry
*me
, const char *line
)
1507 const char *l
= line
;
1508 struct magic
*m
= &me
->mp
[me
->cont_count
== 0 ? 0 : me
->cont_count
- 1];
1510 if (m
->apple
[0] != '\0') {
1511 file_magwarn(ms
, "Current entry already has a APPLE type `%.8s',"
1512 " new type `%s'", m
->mimetype
, l
);
1517 for (i
= 0; *l
&& ((isascii((unsigned char)*l
) && isalnum((unsigned char)*l
))
1518 || strchr("-+/.", *l
)) && i
< sizeof(m
->apple
); m
->apple
[i
++] = *l
++)
1520 if (i
== sizeof(m
->apple
) && *l
) {
1521 if (ms
->flags
& MAGIC_CHECK
)
1522 file_magwarn(ms
, "APPLE type `%s' truncated %zu",
1533 * parse a MIME annotation line from magic file, put into magic[index - 1]
1537 parse_mime(struct magic_set
*ms
, struct magic_entry
*me
, const char *line
)
1540 const char *l
= line
;
1541 struct magic
*m
= &me
->mp
[me
->cont_count
== 0 ? 0 : me
->cont_count
- 1];
1543 if (m
->mimetype
[0] != '\0') {
1544 file_magwarn(ms
, "Current entry already has a MIME type `%s',"
1545 " new type `%s'", m
->mimetype
, l
);
1550 for (i
= 0; *l
&& ((isascii((unsigned char)*l
) && isalnum((unsigned char)*l
))
1551 || strchr("-+/.", *l
)) && i
< sizeof(m
->mimetype
); m
->mimetype
[i
++] = *l
++)
1553 if (i
== sizeof(m
->mimetype
)) {
1554 m
->desc
[sizeof(m
->mimetype
) - 1] = '\0';
1555 if (ms
->flags
& MAGIC_CHECK
)
1556 file_magwarn(ms
, "MIME type `%s' truncated %zu",
1559 m
->mimetype
[i
] = '\0';
1568 check_format_type(const char *ptr
, int type
)
1572 /* Missing format string; bad */
1585 while (isdigit((unsigned char)*ptr
)) ptr
++;
1588 while (isdigit((unsigned char)*ptr
)) ptr
++;
1640 case FILE_FMT_FLOAT
:
1641 case FILE_FMT_DOUBLE
:
1646 while (isdigit((unsigned char)*ptr
)) ptr
++;
1649 while (isdigit((unsigned char)*ptr
)) ptr
++;
1668 while (isdigit((unsigned char )*ptr
))
1672 while (isdigit((unsigned char )*ptr
))
1684 /* internal error */
1692 * Check that the optional printf format in description matches
1693 * the type of the magic.
1696 check_format(struct magic_set
*ms
, struct magic
*m
)
1700 for (ptr
= m
->desc
; *ptr
; ptr
++)
1704 /* No format string; ok */
1708 assert(file_nformats
== file_nnames
);
1710 if (m
->type
>= file_nformats
) {
1711 file_magwarn(ms
, "Internal error inconsistency between "
1712 "m->type and format strings");
1715 if (file_formats
[m
->type
] == FILE_FMT_NONE
) {
1716 file_magwarn(ms
, "No format string for `%s' with description "
1717 "`%s'", m
->desc
, file_names
[m
->type
]);
1722 if (check_format_type(ptr
, file_formats
[m
->type
]) == -1) {
1724 * TODO: this error message is unhelpful if the format
1725 * string is not one character long
1727 file_magwarn(ms
, "Printf format `%c' is not valid for type "
1728 "`%s' in description `%s'", *ptr
? *ptr
: '?',
1729 file_names
[m
->type
], m
->desc
);
1733 for (; *ptr
; ptr
++) {
1736 "Too many format strings (should have at most one) "
1737 "for `%s' with description `%s'",
1738 file_names
[m
->type
], m
->desc
);
1746 * Read a numeric value from a pointer, into the value union of a magic
1747 * pointer, according to the magic type. Update the string pointer to point
1748 * just after the number read. Return 0 for success, non-zero for failure.
1751 getvalue(struct magic_set
*ms
, struct magic
*m
, const char **p
, int action
)
1754 case FILE_BESTRING16
:
1755 case FILE_LESTRING16
:
1760 *p
= getstr(ms
, m
, *p
, action
== FILE_COMPILE
);
1762 if (ms
->flags
& MAGIC_CHECK
)
1763 file_magwarn(ms
, "cannot get string from `%s'",
1771 if (m
->reln
!= 'x') {
1774 m
->value
.f
= strtof(*p
, &ep
);
1776 m
->value
.f
= (float)strtod(*p
, &ep
);
1784 if (m
->reln
!= 'x') {
1786 m
->value
.d
= strtod(*p
, &ep
);
1791 if (m
->reln
!= 'x') {
1793 m
->value
.q
= file_signextend(ms
, m
,
1794 (uint64_t)strtoull(*p
, &ep
, 0));
1803 * Convert a string containing C character escapes. Stop at an unescaped
1805 * Copy the converted version to "m->value.s", and the length in m->vallen.
1806 * Return updated scan pointer as function result. Warn if set.
1808 private const char *
1809 getstr(struct magic_set
*ms
, struct magic
*m
, const char *s
, int warn
)
1811 const char *origs
= s
;
1812 char *p
= m
->value
.s
;
1813 size_t plen
= sizeof(m
->value
.s
);
1815 char *pmax
= p
+ plen
- 1;
1819 while ((c
= *s
++) != '\0') {
1820 if (isspace((unsigned char) c
))
1823 file_error(ms
, 0, "string too long: `%s'", origs
);
1831 file_magwarn(ms
, "incomplete escape");
1837 "escaped tab found, use \\t instead");
1838 warn
= 0; /* already did */
1843 if (isprint((unsigned char)c
)) {
1844 /* Allow escaping of
1846 if (strchr("<>&^=!", c
)
1848 file_magwarn(ms
, "no "
1854 "unknown escape sequence: "
1859 /* space, perhaps force people to use \040? */
1863 * Other things people escape, but shouldn't need to,
1864 * so we disallow them
1877 /* and baskslash itself */
1910 /* \ and up to 3 octal digits */
1920 c
= *s
++; /* try for 2 */
1921 if (c
>= '0' && c
<= '7') {
1922 val
= (val
<< 3) | (c
- '0');
1923 c
= *s
++; /* try for 3 */
1924 if (c
>= '0' && c
<= '7')
1925 val
= (val
<< 3) | (c
-'0');
1934 /* \x and up to 2 hex digits */
1936 val
= 'x'; /* Default if no digits */
1937 c
= hextoint(*s
++); /* Get next char */
1942 val
= (val
<< 4) + c
;
1955 m
->vallen
= CAST(unsigned char, (p
- origp
));
1956 if (m
->type
== FILE_PSTRING
)
1962 /* Single hex char to int; -1 if not a hex char. */
1966 if (!isascii((unsigned char) c
))
1968 if (isdigit((unsigned char) c
))
1970 if ((c
>= 'a') && (c
<= 'f'))
1971 return c
+ 10 - 'a';
1972 if (( c
>= 'A') && (c
<= 'F'))
1973 return c
+ 10 - 'A';
1979 * Print a string containing C character escapes.
1982 file_showstr(FILE *fp
, const char *s
, size_t len
)
1996 if (c
>= 040 && c
<= 0176) /* TODO isprint && !iscntrl */
1997 (void) fputc(c
, fp
);
1999 (void) fputc('\\', fp
);
2002 (void) fputc('a', fp
);
2006 (void) fputc('b', fp
);
2010 (void) fputc('f', fp
);
2014 (void) fputc('n', fp
);
2018 (void) fputc('r', fp
);
2022 (void) fputc('t', fp
);
2026 (void) fputc('v', fp
);
2030 (void) fprintf(fp
, "%.3o", c
& 0377);
2038 * eatsize(): Eat the size spec from a number [eg. 10UL]
2041 eatsize(const char **p
)
2045 if (LOWCASE(*l
) == 'u')
2048 switch (LOWCASE(*l
)) {
2049 case 'l': /* long */
2050 case 's': /* short */
2051 case 'h': /* short */
2052 case 'b': /* char/byte */
2053 case 'c': /* char/byte */
2064 * handle a compiled file.
2067 apprentice_map(struct magic_set
*ms
, struct magic
**magicp
, uint32_t *nmagicp
,
2075 char *dbname
= NULL
;
2078 dbname
= mkdbname(ms
, fn
, 0);
2082 if ((fd
= open(dbname
, O_RDONLY
|O_BINARY
)) == -1)
2085 if (fstat(fd
, &st
) == -1) {
2086 file_error(ms
, errno
, "cannot stat `%s'", dbname
);
2089 if (st
.st_size
< 8) {
2090 file_error(ms
, 0, "file `%s' is too small", dbname
);
2095 if ((mm
= mmap(0, (size_t)st
.st_size
, PROT_READ
|PROT_WRITE
,
2096 MAP_PRIVATE
|MAP_FILE
, fd
, (off_t
)0)) == MAP_FAILED
) {
2097 file_error(ms
, errno
, "cannot map `%s'", dbname
);
2102 if ((mm
= CAST(void *, malloc((size_t)st
.st_size
))) == NULL
) {
2103 file_oomem(ms
, (size_t)st
.st_size
);
2106 if (read(fd
, mm
, (size_t)st
.st_size
) != (ssize_t
)st
.st_size
) {
2112 *magicp
= CAST(struct magic
*, mm
);
2115 ptr
= (uint32_t *)(void *)*magicp
;
2116 if (*ptr
!= MAGICNO
) {
2117 if (swap4(*ptr
) != MAGICNO
) {
2118 file_error(ms
, 0, "bad magic in `%s'", dbname
);
2125 version
= swap4(ptr
[1]);
2128 if (version
!= VERSIONNO
) {
2129 file_error(ms
, 0, "File %d.%d supports only version %d magic "
2130 "files. `%s' is version %d", FILE_VERSION_MAJOR
, patchlevel
,
2131 VERSIONNO
, dbname
, version
);
2134 *nmagicp
= (uint32_t)(st
.st_size
/ sizeof(struct magic
));
2139 byteswap(*magicp
, *nmagicp
);
2148 (void)munmap((void *)mm
, (size_t)st
.st_size
);
2161 private const uint32_t ar
[] = {
2165 * handle an mmaped file.
2168 apprentice_compile(struct magic_set
*ms
, struct magic
**magicp
,
2169 uint32_t *nmagicp
, const char *fn
)
2175 dbname
= mkdbname(ms
, fn
, 1);
2180 if ((fd
= open(dbname
, O_WRONLY
|O_CREAT
|O_TRUNC
|O_BINARY
, 0644)) == -1) {
2181 file_error(ms
, errno
, "cannot open `%s'", dbname
);
2185 if (write(fd
, ar
, sizeof(ar
)) != (ssize_t
)sizeof(ar
)) {
2186 file_error(ms
, errno
, "error writing `%s'", dbname
);
2190 if (lseek(fd
, (off_t
)sizeof(struct magic
), SEEK_SET
)
2191 != sizeof(struct magic
)) {
2192 file_error(ms
, errno
, "error seeking `%s'", dbname
);
2196 if (write(fd
, *magicp
, (sizeof(struct magic
) * *nmagicp
))
2197 != (ssize_t
)(sizeof(struct magic
) * *nmagicp
)) {
2198 file_error(ms
, errno
, "error writing `%s'", dbname
);
2209 private const char ext
[] = ".mgc";
2214 mkdbname(struct magic_set
*ms
, const char *fn
, int strip
)
2220 if ((p
= strrchr(fn
, '/')) != NULL
)
2224 for (q
= fn
; *q
; q
++)
2227 for (p
= ext
+ sizeof(ext
) - 1; p
>= ext
&& q
>= fn
; p
--, q
--)
2231 /* Did not find .mgc, restore q */
2237 /* Compatibility with old code that looked in .mime */
2238 if (ms
->flags
& MAGIC_MIME
) {
2239 asprintf(&buf
, "%.*s.mime%s", (int)(q
- fn
), fn
, ext
);
2240 if (access(buf
, R_OK
) != -1) {
2241 ms
->flags
&= MAGIC_MIME_TYPE
;
2246 asprintf(&buf
, "%.*s%s", (int)(q
- fn
), fn
, ext
);
2248 /* Compatibility with old code that looked in .mime */
2249 if (strstr(p
, ".mime") != NULL
)
2250 ms
->flags
&= MAGIC_MIME_TYPE
;
2255 * Byteswap an mmap'ed file if needed
2258 byteswap(struct magic
*magic
, uint32_t nmagic
)
2261 for (i
= 0; i
< nmagic
; i
++)
2272 uint8_t *s
= (uint8_t *)(void *)&sv
;
2273 uint8_t *d
= (uint8_t *)(void *)&rv
;
2286 uint8_t *s
= (uint8_t *)(void *)&sv
;
2287 uint8_t *d
= (uint8_t *)(void *)&rv
;
2302 uint8_t *s
= (uint8_t *)(void *)&sv
;
2303 uint8_t *d
= (uint8_t *)(void *)&rv
;
2327 * byteswap a single magic entry
2330 bs1(struct magic
*m
)
2332 m
->cont_level
= swap2(m
->cont_level
);
2333 m
->offset
= swap4((uint32_t)m
->offset
);
2334 m
->in_offset
= swap4((uint32_t)m
->in_offset
);
2335 m
->lineno
= swap4((uint32_t)m
->lineno
);
2336 if (IS_STRING(m
->type
)) {
2337 m
->str_range
= swap4(m
->str_range
);
2338 m
->str_flags
= swap4(m
->str_flags
);
2341 m
->value
.q
= swap8(m
->value
.q
);
2342 m
->num_mask
= swap8(m
->num_mask
);