1 /* $NetBSD: apprentice.c,v 1.14 2015/01/02 21:15:32 christos Exp $ */ 2 3 /* 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. 7 * 8 * Redistribution and use in source and binary forms, with or without 9 * modification, are permitted provided that the following conditions 10 * are met: 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. 17 * 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 28 * SUCH DAMAGE. 29 */ 30 /* 31 * apprentice - make one pass through /etc/magic, learning its secrets. 32 */ 33 34 #include "file.h" 35 36 #ifndef lint 37 #if 0 38 FILE_RCSID("@(#)$File: apprentice.c,v 1.229 2015/01/01 17:07:34 christos Exp $") 39 #else 40 __RCSID("$NetBSD: apprentice.c,v 1.14 2015/01/02 21:15:32 christos Exp $"); 41 #endif 42 #endif /* lint */ 43 44 #include "magic.h" 45 #include <stdlib.h> 46 #ifdef HAVE_UNISTD_H 47 #include <unistd.h> 48 #endif 49 #ifdef HAVE_STDDEF_H 50 #include <stddef.h> 51 #endif 52 #include <string.h> 53 #include <assert.h> 54 #include <ctype.h> 55 #include <fcntl.h> 56 #ifdef QUICK 57 #include <sys/mman.h> 58 #endif 59 #include <dirent.h> 60 #if defined(HAVE_LIMITS_H) 61 #include <limits.h> 62 #endif 63 64 #ifndef SSIZE_MAX 65 #define MAXMAGIC_SIZE ((ssize_t)0x7fffffff) 66 #else 67 #define MAXMAGIC_SIZE SSIZE_MAX 68 #endif 69 70 #define EATAB {while (isascii((unsigned char) *l) && \ 71 isspace((unsigned char) *l)) ++l;} 72 #define LOWCASE(l) (isupper((unsigned char) (l)) ? \ 73 tolower((unsigned char) (l)) : (l)) 74 /* 75 * Work around a bug in headers on Digital Unix. 76 * At least confirmed for: OSF1 V4.0 878 77 */ 78 #if defined(__osf__) && defined(__DECC) 79 #ifdef MAP_FAILED 80 #undef MAP_FAILED 81 #endif 82 #endif 83 84 #ifndef MAP_FAILED 85 #define MAP_FAILED (void *) -1 86 #endif 87 88 #ifndef MAP_FILE 89 #define MAP_FILE 0 90 #endif 91 92 #define ALLOC_CHUNK (size_t)10 93 #define ALLOC_INCR (size_t)200 94 95 #define MAP_TYPE_MMAP 0 96 #define MAP_TYPE_MALLOC 1 97 #define MAP_TYPE_USER 2 98 99 struct magic_entry { 100 struct magic *mp; 101 uint32_t cont_count; 102 uint32_t max_count; 103 }; 104 105 struct magic_entry_set { 106 struct magic_entry *me; 107 uint32_t count; 108 uint32_t max; 109 }; 110 111 struct magic_map { 112 void *p; 113 size_t len; 114 int type; 115 struct magic *magic[MAGIC_SETS]; 116 uint32_t nmagic[MAGIC_SETS]; 117 }; 118 119 int file_formats[FILE_NAMES_SIZE]; 120 const size_t file_nformats = FILE_NAMES_SIZE; 121 const char *file_names[FILE_NAMES_SIZE]; 122 const size_t file_nnames = FILE_NAMES_SIZE; 123 124 private int getvalue(struct magic_set *ms, struct magic *, const char **, int); 125 private int hextoint(int); 126 private const char *getstr(struct magic_set *, struct magic *, const char *, 127 int); 128 private int parse(struct magic_set *, struct magic_entry *, const char *, 129 size_t, int); 130 private void eatsize(const char **); 131 private int apprentice_1(struct magic_set *, const char *, int); 132 private size_t apprentice_magic_strength(const struct magic *); 133 private int apprentice_sort(const void *, const void *); 134 private void apprentice_list(struct mlist *, int ); 135 private struct magic_map *apprentice_load(struct magic_set *, 136 const char *, int); 137 private struct mlist *mlist_alloc(void); 138 private void mlist_free(struct mlist *); 139 private void byteswap(struct magic *, uint32_t); 140 private void bs1(struct magic *); 141 private uint16_t swap2(uint16_t); 142 private uint32_t swap4(uint32_t); 143 private uint64_t swap8(uint64_t); 144 private char *mkdbname(struct magic_set *, const char *, int); 145 private struct magic_map *apprentice_buf(struct magic_set *, struct magic *, 146 size_t); 147 private struct magic_map *apprentice_map(struct magic_set *, const char *); 148 private int check_buffer(struct magic_set *, struct magic_map *, const char *); 149 private void apprentice_unmap(struct magic_map *); 150 private int apprentice_compile(struct magic_set *, struct magic_map *, 151 const char *); 152 private int check_format_type(const char *, int); 153 private int check_format(struct magic_set *, struct magic *); 154 private int get_op(char); 155 private int parse_mime(struct magic_set *, struct magic_entry *, const char *); 156 private int parse_strength(struct magic_set *, struct magic_entry *, const char *); 157 private int parse_apple(struct magic_set *, struct magic_entry *, const char *); 158 159 160 private size_t magicsize = sizeof(struct magic); 161 162 private const char usg_hdr[] = "cont\toffset\ttype\topcode\tmask\tvalue\tdesc"; 163 164 private struct { 165 const char *name; 166 size_t len; 167 int (*fun)(struct magic_set *, struct magic_entry *, const char *); 168 } bang[] = { 169 #define DECLARE_FIELD(name) { # name, sizeof(# name) - 1, parse_ ## name } 170 DECLARE_FIELD(mime), 171 DECLARE_FIELD(apple), 172 DECLARE_FIELD(strength), 173 #undef DECLARE_FIELD 174 { NULL, 0, NULL } 175 }; 176 177 #ifdef COMPILE_ONLY 178 179 int main(int, char *[]); 180 181 int 182 main(int argc, char *argv[]) 183 { 184 int ret; 185 struct magic_set *ms; 186 char *progname; 187 188 if ((progname = strrchr(argv[0], '/')) != NULL) 189 progname++; 190 else 191 progname = argv[0]; 192 193 if (argc != 2) { 194 (void)fprintf(stderr, "Usage: %s file\n", progname); 195 return 1; 196 } 197 198 if ((ms = magic_open(MAGIC_CHECK)) == NULL) { 199 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno)); 200 return 1; 201 } 202 ret = magic_compile(ms, argv[1]) == -1 ? 1 : 0; 203 if (ret == 1) 204 (void)fprintf(stderr, "%s: %s\n", progname, magic_error(ms)); 205 magic_close(ms); 206 return ret; 207 } 208 #endif /* COMPILE_ONLY */ 209 210 struct type_tbl_s { 211 const char name[16]; 212 const size_t len; 213 const int type; 214 const int format; 215 }; 216 217 /* 218 * XXX - the actual Single UNIX Specification says that "long" means "long", 219 * as in the C data type, but we treat it as meaning "4-byte integer". 220 * Given that the OS X version of file 5.04 did the same, I guess that passes 221 * the actual test; having "long" be dependent on how big a "long" is on 222 * the machine running "file" is silly. 223 */ 224 static const struct type_tbl_s type_tbl[] = { 225 # define XX(s) s, (sizeof(s) - 1) 226 # define XX_NULL "", 0 227 { XX("invalid"), FILE_INVALID, FILE_FMT_NONE }, 228 { XX("byte"), FILE_BYTE, FILE_FMT_NUM }, 229 { XX("short"), FILE_SHORT, FILE_FMT_NUM }, 230 { XX("default"), FILE_DEFAULT, FILE_FMT_NONE }, 231 { XX("long"), FILE_LONG, FILE_FMT_NUM }, 232 { XX("string"), FILE_STRING, FILE_FMT_STR }, 233 { XX("date"), FILE_DATE, FILE_FMT_STR }, 234 { XX("beshort"), FILE_BESHORT, FILE_FMT_NUM }, 235 { XX("belong"), FILE_BELONG, FILE_FMT_NUM }, 236 { XX("bedate"), FILE_BEDATE, FILE_FMT_STR }, 237 { XX("leshort"), FILE_LESHORT, FILE_FMT_NUM }, 238 { XX("lelong"), FILE_LELONG, FILE_FMT_NUM }, 239 { XX("ledate"), FILE_LEDATE, FILE_FMT_STR }, 240 { XX("pstring"), FILE_PSTRING, FILE_FMT_STR }, 241 { XX("ldate"), FILE_LDATE, FILE_FMT_STR }, 242 { XX("beldate"), FILE_BELDATE, FILE_FMT_STR }, 243 { XX("leldate"), FILE_LELDATE, FILE_FMT_STR }, 244 { XX("regex"), FILE_REGEX, FILE_FMT_STR }, 245 { XX("bestring16"), FILE_BESTRING16, FILE_FMT_STR }, 246 { XX("lestring16"), FILE_LESTRING16, FILE_FMT_STR }, 247 { XX("search"), FILE_SEARCH, FILE_FMT_STR }, 248 { XX("medate"), FILE_MEDATE, FILE_FMT_STR }, 249 { XX("meldate"), FILE_MELDATE, FILE_FMT_STR }, 250 { XX("melong"), FILE_MELONG, FILE_FMT_NUM }, 251 { XX("quad"), FILE_QUAD, FILE_FMT_QUAD }, 252 { XX("lequad"), FILE_LEQUAD, FILE_FMT_QUAD }, 253 { XX("bequad"), FILE_BEQUAD, FILE_FMT_QUAD }, 254 { XX("qdate"), FILE_QDATE, FILE_FMT_STR }, 255 { XX("leqdate"), FILE_LEQDATE, FILE_FMT_STR }, 256 { XX("beqdate"), FILE_BEQDATE, FILE_FMT_STR }, 257 { XX("qldate"), FILE_QLDATE, FILE_FMT_STR }, 258 { XX("leqldate"), FILE_LEQLDATE, FILE_FMT_STR }, 259 { XX("beqldate"), FILE_BEQLDATE, FILE_FMT_STR }, 260 { XX("float"), FILE_FLOAT, FILE_FMT_FLOAT }, 261 { XX("befloat"), FILE_BEFLOAT, FILE_FMT_FLOAT }, 262 { XX("lefloat"), FILE_LEFLOAT, FILE_FMT_FLOAT }, 263 { XX("double"), FILE_DOUBLE, FILE_FMT_DOUBLE }, 264 { XX("bedouble"), FILE_BEDOUBLE, FILE_FMT_DOUBLE }, 265 { XX("ledouble"), FILE_LEDOUBLE, FILE_FMT_DOUBLE }, 266 { XX("leid3"), FILE_LEID3, FILE_FMT_NUM }, 267 { XX("beid3"), FILE_BEID3, FILE_FMT_NUM }, 268 { XX("indirect"), FILE_INDIRECT, FILE_FMT_NUM }, 269 { XX("qwdate"), FILE_QWDATE, FILE_FMT_STR }, 270 { XX("leqwdate"), FILE_LEQWDATE, FILE_FMT_STR }, 271 { XX("beqwdate"), FILE_BEQWDATE, FILE_FMT_STR }, 272 { XX("name"), FILE_NAME, FILE_FMT_NONE }, 273 { XX("use"), FILE_USE, FILE_FMT_NONE }, 274 { XX("clear"), FILE_CLEAR, FILE_FMT_NONE }, 275 { XX_NULL, FILE_INVALID, FILE_FMT_NONE }, 276 }; 277 278 /* 279 * These are not types, and cannot be preceded by "u" to make them 280 * unsigned. 281 */ 282 static const struct type_tbl_s special_tbl[] = { 283 { XX("name"), FILE_NAME, FILE_FMT_STR }, 284 { XX("use"), FILE_USE, FILE_FMT_STR }, 285 { XX_NULL, FILE_INVALID, FILE_FMT_NONE }, 286 }; 287 # undef XX 288 # undef XX_NULL 289 290 private int 291 get_type(const struct type_tbl_s *tbl, const char *l, const char **t) 292 { 293 const struct type_tbl_s *p; 294 295 for (p = tbl; p->len; p++) { 296 if (strncmp(l, p->name, p->len) == 0) { 297 if (t) 298 *t = l + p->len; 299 break; 300 } 301 } 302 return p->type; 303 } 304 305 private int 306 get_standard_integer_type(const char *l, const char **t) 307 { 308 int type; 309 310 if (isalpha((unsigned char)l[1])) { 311 switch (l[1]) { 312 case 'C': 313 /* "dC" and "uC" */ 314 type = FILE_BYTE; 315 break; 316 case 'S': 317 /* "dS" and "uS" */ 318 type = FILE_SHORT; 319 break; 320 case 'I': 321 case 'L': 322 /* 323 * "dI", "dL", "uI", and "uL". 324 * 325 * XXX - the actual Single UNIX Specification says 326 * that "L" means "long", as in the C data type, 327 * but we treat it as meaning "4-byte integer". 328 * Given that the OS X version of file 5.04 did 329 * the same, I guess that passes the actual SUS 330 * validation suite; having "dL" be dependent on 331 * how big a "long" is on the machine running 332 * "file" is silly. 333 */ 334 type = FILE_LONG; 335 break; 336 case 'Q': 337 /* "dQ" and "uQ" */ 338 type = FILE_QUAD; 339 break; 340 default: 341 /* "d{anything else}", "u{anything else}" */ 342 return FILE_INVALID; 343 } 344 l += 2; 345 } else if (isdigit((unsigned char)l[1])) { 346 /* 347 * "d{num}" and "u{num}"; we only support {num} values 348 * of 1, 2, 4, and 8 - the Single UNIX Specification 349 * doesn't say anything about whether arbitrary 350 * values should be supported, but both the Solaris 10 351 * and OS X Mountain Lion versions of file passed the 352 * Single UNIX Specification validation suite, and 353 * neither of them support values bigger than 8 or 354 * non-power-of-2 values. 355 */ 356 if (isdigit((unsigned char)l[2])) { 357 /* Multi-digit, so > 9 */ 358 return FILE_INVALID; 359 } 360 switch (l[1]) { 361 case '1': 362 type = FILE_BYTE; 363 break; 364 case '2': 365 type = FILE_SHORT; 366 break; 367 case '4': 368 type = FILE_LONG; 369 break; 370 case '8': 371 type = FILE_QUAD; 372 break; 373 default: 374 /* XXX - what about 3, 5, 6, or 7? */ 375 return FILE_INVALID; 376 } 377 l += 2; 378 } else { 379 /* 380 * "d" or "u" by itself. 381 */ 382 type = FILE_LONG; 383 ++l; 384 } 385 if (t) 386 *t = l; 387 return type; 388 } 389 390 private void 391 init_file_tables(void) 392 { 393 static int done = 0; 394 const struct type_tbl_s *p; 395 396 if (done) 397 return; 398 done++; 399 400 for (p = type_tbl; p->len; p++) { 401 assert(p->type < FILE_NAMES_SIZE); 402 file_names[p->type] = p->name; 403 file_formats[p->type] = p->format; 404 } 405 assert(p - type_tbl == FILE_NAMES_SIZE); 406 } 407 408 private int 409 add_mlist(struct mlist *mlp, struct magic_map *map, size_t idx) 410 { 411 struct mlist *ml; 412 413 mlp->map = idx == 0 ? map : NULL; 414 if ((ml = CAST(struct mlist *, malloc(sizeof(*ml)))) == NULL) 415 return -1; 416 417 ml->map = NULL; 418 ml->magic = map->magic[idx]; 419 ml->nmagic = map->nmagic[idx]; 420 421 mlp->prev->next = ml; 422 ml->prev = mlp->prev; 423 ml->next = mlp; 424 mlp->prev = ml; 425 return 0; 426 } 427 428 /* 429 * Handle one file or directory. 430 */ 431 private int 432 apprentice_1(struct magic_set *ms, const char *fn, int action) 433 { 434 struct magic_map *map; 435 #ifndef COMPILE_ONLY 436 struct mlist *ml; 437 size_t i; 438 #endif 439 440 if (magicsize != FILE_MAGICSIZE) { 441 file_error(ms, 0, "magic element size %lu != %lu", 442 (unsigned long)sizeof(*map->magic[0]), 443 (unsigned long)FILE_MAGICSIZE); 444 return -1; 445 } 446 447 if (action == FILE_COMPILE) { 448 map = apprentice_load(ms, fn, action); 449 if (map == NULL) 450 return -1; 451 return apprentice_compile(ms, map, fn); 452 } 453 454 #ifndef COMPILE_ONLY 455 map = apprentice_map(ms, fn); 456 if (map == NULL) { 457 if (ms->flags & MAGIC_CHECK) 458 file_magwarn(ms, "using regular magic file `%s'", fn); 459 map = apprentice_load(ms, fn, action); 460 if (map == NULL) 461 return -1; 462 } 463 464 for (i = 0; i < MAGIC_SETS; i++) { 465 if (add_mlist(ms->mlist[i], map, i) == -1) { 466 file_oomem(ms, sizeof(*ml)); 467 goto fail; 468 } 469 } 470 471 if (action == FILE_LIST) { 472 for (i = 0; i < MAGIC_SETS; i++) { 473 printf("Set %" SIZE_T_FORMAT "u:\nBinary patterns:\n", 474 i); 475 apprentice_list(ms->mlist[i], BINTEST); 476 printf("Text patterns:\n"); 477 apprentice_list(ms->mlist[i], TEXTTEST); 478 } 479 } 480 return 0; 481 fail: 482 for (i = 0; i < MAGIC_SETS; i++) { 483 mlist_free(ms->mlist[i]); 484 ms->mlist[i] = NULL; 485 } 486 return -1; 487 #else 488 return 0; 489 #endif /* COMPILE_ONLY */ 490 } 491 492 protected void 493 file_ms_free(struct magic_set *ms) 494 { 495 size_t i; 496 if (ms == NULL) 497 return; 498 for (i = 0; i < MAGIC_SETS; i++) 499 mlist_free(ms->mlist[i]); 500 free(ms->o.pbuf); 501 free(ms->o.buf); 502 free(ms->c.li); 503 free(ms); 504 } 505 506 protected struct magic_set * 507 file_ms_alloc(int flags) 508 { 509 struct magic_set *ms; 510 size_t i, len; 511 512 if ((ms = CAST(struct magic_set *, calloc((size_t)1, 513 sizeof(struct magic_set)))) == NULL) 514 return NULL; 515 516 if (magic_setflags(ms, flags) == -1) { 517 errno = EINVAL; 518 goto free; 519 } 520 521 ms->o.buf = ms->o.pbuf = NULL; 522 len = (ms->c.len = 10) * sizeof(*ms->c.li); 523 524 if ((ms->c.li = CAST(struct level_info *, malloc(len))) == NULL) 525 goto free; 526 527 ms->event_flags = 0; 528 ms->error = -1; 529 for (i = 0; i < MAGIC_SETS; i++) 530 ms->mlist[i] = NULL; 531 ms->file = "unknown"; 532 ms->line = 0; 533 ms->indir_max = FILE_INDIR_MAX; 534 ms->name_max = FILE_NAME_MAX; 535 ms->elf_shnum_max = FILE_ELF_SHNUM_MAX; 536 ms->elf_phnum_max = FILE_ELF_PHNUM_MAX; 537 ms->elf_notes_max = FILE_ELF_NOTES_MAX; 538 return ms; 539 free: 540 free(ms); 541 return NULL; 542 } 543 544 private void 545 apprentice_unmap(struct magic_map *map) 546 { 547 if (map == NULL) 548 return; 549 550 switch (map->type) { 551 #ifdef QUICK 552 case MAP_TYPE_MMAP: 553 if (map->p) 554 (void)munmap(map->p, map->len); 555 break; 556 #endif 557 case MAP_TYPE_MALLOC: 558 free(map->p); 559 break; 560 case MAP_TYPE_USER: 561 break; 562 default: 563 abort(); 564 } 565 free(map); 566 } 567 568 private struct mlist * 569 mlist_alloc(void) 570 { 571 struct mlist *mlist; 572 if ((mlist = CAST(struct mlist *, calloc(1, sizeof(*mlist)))) == NULL) { 573 return NULL; 574 } 575 mlist->next = mlist->prev = mlist; 576 return mlist; 577 } 578 579 private void 580 mlist_free(struct mlist *mlist) 581 { 582 struct mlist *ml, *next; 583 584 if (mlist == NULL) 585 return; 586 587 ml = mlist->next; 588 for (ml = mlist->next; (next = ml->next) != NULL; ml = next) { 589 if (ml->map) 590 apprentice_unmap(ml->map); 591 free(ml); 592 if (ml == mlist) 593 break; 594 } 595 } 596 597 #ifndef COMPILE_ONLY 598 /* void **bufs: an array of compiled magic files */ 599 protected int 600 buffer_apprentice(struct magic_set *ms, struct magic **bufs, 601 size_t *sizes, size_t nbufs) 602 { 603 size_t i, j; 604 struct mlist *ml; 605 struct magic_map *map; 606 607 if (nbufs == 0) 608 return -1; 609 610 if (ms->mlist[0] != NULL) 611 file_reset(ms); 612 613 init_file_tables(); 614 615 for (i = 0; i < MAGIC_SETS; i++) { 616 mlist_free(ms->mlist[i]); 617 if ((ms->mlist[i] = mlist_alloc()) == NULL) { 618 file_oomem(ms, sizeof(*ms->mlist[i])); 619 goto fail; 620 } 621 } 622 623 for (i = 0; i < nbufs; i++) { 624 map = apprentice_buf(ms, bufs[i], sizes[i]); 625 if (map == NULL) 626 goto fail; 627 628 for (j = 0; j < MAGIC_SETS; j++) { 629 if (add_mlist(ms->mlist[j], map, j) == -1) { 630 file_oomem(ms, sizeof(*ml)); 631 goto fail; 632 } 633 } 634 } 635 636 return 0; 637 fail: 638 for (i = 0; i < MAGIC_SETS; i++) { 639 mlist_free(ms->mlist[i]); 640 ms->mlist[i] = NULL; 641 } 642 return -1; 643 } 644 #endif 645 646 /* const char *fn: list of magic files and directories */ 647 protected int 648 file_apprentice(struct magic_set *ms, const char *fn, int action) 649 { 650 char *p, *mfn; 651 int file_err, errs = -1; 652 size_t i; 653 654 if (ms->mlist[0] != NULL) 655 file_reset(ms); 656 657 if ((fn = magic_getpath(fn, action)) == NULL) 658 return -1; 659 660 init_file_tables(); 661 662 if ((mfn = strdup(fn)) == NULL) { 663 file_oomem(ms, strlen(fn)); 664 return -1; 665 } 666 667 for (i = 0; i < MAGIC_SETS; i++) { 668 mlist_free(ms->mlist[i]); 669 if ((ms->mlist[i] = mlist_alloc()) == NULL) { 670 file_oomem(ms, sizeof(*ms->mlist[i])); 671 while (i-- > 0) { 672 mlist_free(ms->mlist[i]); 673 ms->mlist[i] = NULL; 674 } 675 free(mfn); 676 return -1; 677 } 678 } 679 fn = mfn; 680 681 while (fn) { 682 p = strchr(fn, PATHSEP); 683 if (p) 684 *p++ = '\0'; 685 if (*fn == '\0') 686 break; 687 file_err = apprentice_1(ms, fn, action); 688 errs = MAX(errs, file_err); 689 fn = p; 690 } 691 692 free(mfn); 693 694 if (errs == -1) { 695 for (i = 0; i < MAGIC_SETS; i++) { 696 mlist_free(ms->mlist[i]); 697 ms->mlist[i] = NULL; 698 } 699 file_error(ms, 0, "could not find any valid magic files!"); 700 return -1; 701 } 702 703 #if 0 704 /* 705 * Always leave the database loaded 706 */ 707 if (action == FILE_LOAD) 708 return 0; 709 710 for (i = 0; i < MAGIC_SETS; i++) { 711 mlist_free(ms->mlist[i]); 712 ms->mlist[i] = NULL; 713 } 714 #endif 715 716 switch (action) { 717 case FILE_LOAD: 718 case FILE_COMPILE: 719 case FILE_CHECK: 720 case FILE_LIST: 721 return 0; 722 default: 723 file_error(ms, 0, "Invalid action %d", action); 724 return -1; 725 } 726 } 727 728 /* 729 * Compute the real length of a magic expression, for the purposes 730 * of determining how "strong" a magic expression is (approximating 731 * how specific its matches are): 732 * - magic characters count 0 unless escaped. 733 * - [] expressions count 1 734 * - {} expressions count 0 735 * - regular characters or escaped magic characters count 1 736 * - 0 length expressions count as one 737 */ 738 private size_t 739 nonmagic(const char *str) 740 { 741 const char *p; 742 size_t rv = 0; 743 744 for (p = str; *p; p++) 745 switch (*p) { 746 case '\\': /* Escaped anything counts 1 */ 747 if (!*++p) 748 p--; 749 rv++; 750 continue; 751 case '?': /* Magic characters count 0 */ 752 case '*': 753 case '.': 754 case '+': 755 case '^': 756 case '$': 757 continue; 758 case '[': /* Bracketed expressions count 1 the ']' */ 759 while (*p && *p != ']') 760 p++; 761 p--; 762 continue; 763 case '{': /* Braced expressions count 0 */ 764 while (*p && *p != '}') 765 p++; 766 if (!*p) 767 p--; 768 continue; 769 default: /* Anything else counts 1 */ 770 rv++; 771 continue; 772 } 773 774 return rv == 0 ? 1 : rv; /* Return at least 1 */ 775 } 776 777 /* 778 * Get weight of this magic entry, for sorting purposes. 779 */ 780 private size_t 781 apprentice_magic_strength(const struct magic *m) 782 { 783 #define MULT 10 784 size_t v, val = 2 * MULT; /* baseline strength */ 785 786 switch (m->type) { 787 case FILE_DEFAULT: /* make sure this sorts last */ 788 if (m->factor_op != FILE_FACTOR_OP_NONE) 789 abort(); 790 return 0; 791 792 case FILE_BYTE: 793 val += 1 * MULT; 794 break; 795 796 case FILE_SHORT: 797 case FILE_LESHORT: 798 case FILE_BESHORT: 799 val += 2 * MULT; 800 break; 801 802 case FILE_LONG: 803 case FILE_LELONG: 804 case FILE_BELONG: 805 case FILE_MELONG: 806 val += 4 * MULT; 807 break; 808 809 case FILE_PSTRING: 810 case FILE_STRING: 811 val += m->vallen * MULT; 812 break; 813 814 case FILE_BESTRING16: 815 case FILE_LESTRING16: 816 val += m->vallen * MULT / 2; 817 break; 818 819 case FILE_SEARCH: 820 val += m->vallen * MAX(MULT / m->vallen, 1); 821 break; 822 823 case FILE_REGEX: 824 v = nonmagic(m->value.s); 825 val += v * MAX(MULT / v, 1); 826 break; 827 828 case FILE_DATE: 829 case FILE_LEDATE: 830 case FILE_BEDATE: 831 case FILE_MEDATE: 832 case FILE_LDATE: 833 case FILE_LELDATE: 834 case FILE_BELDATE: 835 case FILE_MELDATE: 836 case FILE_FLOAT: 837 case FILE_BEFLOAT: 838 case FILE_LEFLOAT: 839 val += 4 * MULT; 840 break; 841 842 case FILE_QUAD: 843 case FILE_BEQUAD: 844 case FILE_LEQUAD: 845 case FILE_QDATE: 846 case FILE_LEQDATE: 847 case FILE_BEQDATE: 848 case FILE_QLDATE: 849 case FILE_LEQLDATE: 850 case FILE_BEQLDATE: 851 case FILE_QWDATE: 852 case FILE_LEQWDATE: 853 case FILE_BEQWDATE: 854 case FILE_DOUBLE: 855 case FILE_BEDOUBLE: 856 case FILE_LEDOUBLE: 857 val += 8 * MULT; 858 break; 859 860 case FILE_INDIRECT: 861 case FILE_NAME: 862 case FILE_USE: 863 break; 864 865 default: 866 (void)fprintf(stderr, "Bad type %d\n", m->type); 867 abort(); 868 } 869 870 switch (m->reln) { 871 case 'x': /* matches anything penalize */ 872 case '!': /* matches almost anything penalize */ 873 val = 0; 874 break; 875 876 case '=': /* Exact match, prefer */ 877 val += MULT; 878 break; 879 880 case '>': 881 case '<': /* comparison match reduce strength */ 882 val -= 2 * MULT; 883 break; 884 885 case '^': 886 case '&': /* masking bits, we could count them too */ 887 val -= MULT; 888 break; 889 890 default: 891 (void)fprintf(stderr, "Bad relation %c\n", m->reln); 892 abort(); 893 } 894 895 if (val == 0) /* ensure we only return 0 for FILE_DEFAULT */ 896 val = 1; 897 898 switch (m->factor_op) { 899 case FILE_FACTOR_OP_NONE: 900 break; 901 case FILE_FACTOR_OP_PLUS: 902 val += m->factor; 903 break; 904 case FILE_FACTOR_OP_MINUS: 905 val -= m->factor; 906 break; 907 case FILE_FACTOR_OP_TIMES: 908 val *= m->factor; 909 break; 910 case FILE_FACTOR_OP_DIV: 911 val /= m->factor; 912 break; 913 default: 914 abort(); 915 } 916 917 /* 918 * Magic entries with no description get a bonus because they depend 919 * on subsequent magic entries to print something. 920 */ 921 if (m->desc[0] == '\0') 922 val++; 923 return val; 924 } 925 926 /* 927 * Sort callback for sorting entries by "strength" (basically length) 928 */ 929 private int 930 apprentice_sort(const void *a, const void *b) 931 { 932 const struct magic_entry *ma = CAST(const struct magic_entry *, a); 933 const struct magic_entry *mb = CAST(const struct magic_entry *, b); 934 size_t sa = apprentice_magic_strength(ma->mp); 935 size_t sb = apprentice_magic_strength(mb->mp); 936 if (sa == sb) 937 return 0; 938 else if (sa > sb) 939 return -1; 940 else 941 return 1; 942 } 943 944 /* 945 * Shows sorted patterns list in the order which is used for the matching 946 */ 947 private void 948 apprentice_list(struct mlist *mlist, int mode) 949 { 950 uint32_t magindex = 0; 951 struct mlist *ml; 952 for (ml = mlist->next; ml != mlist; ml = ml->next) { 953 for (magindex = 0; magindex < ml->nmagic; magindex++) { 954 struct magic *m = &ml->magic[magindex]; 955 if ((m->flag & mode) != mode) { 956 /* Skip sub-tests */ 957 while (magindex + 1 < ml->nmagic && 958 ml->magic[magindex + 1].cont_level != 0) 959 ++magindex; 960 continue; /* Skip to next top-level test*/ 961 } 962 963 /* 964 * Try to iterate over the tree until we find item with 965 * description/mimetype. 966 */ 967 while (magindex + 1 < ml->nmagic && 968 ml->magic[magindex + 1].cont_level != 0 && 969 *ml->magic[magindex].desc == '\0' && 970 *ml->magic[magindex].mimetype == '\0') 971 magindex++; 972 973 printf("Strength = %3" SIZE_T_FORMAT "u : %s [%s]\n", 974 apprentice_magic_strength(m), 975 ml->magic[magindex].desc, 976 ml->magic[magindex].mimetype); 977 } 978 } 979 } 980 981 private void 982 set_test_type(struct magic *mstart, struct magic *m) 983 { 984 switch (m->type) { 985 case FILE_BYTE: 986 case FILE_SHORT: 987 case FILE_LONG: 988 case FILE_DATE: 989 case FILE_BESHORT: 990 case FILE_BELONG: 991 case FILE_BEDATE: 992 case FILE_LESHORT: 993 case FILE_LELONG: 994 case FILE_LEDATE: 995 case FILE_LDATE: 996 case FILE_BELDATE: 997 case FILE_LELDATE: 998 case FILE_MEDATE: 999 case FILE_MELDATE: 1000 case FILE_MELONG: 1001 case FILE_QUAD: 1002 case FILE_LEQUAD: 1003 case FILE_BEQUAD: 1004 case FILE_QDATE: 1005 case FILE_LEQDATE: 1006 case FILE_BEQDATE: 1007 case FILE_QLDATE: 1008 case FILE_LEQLDATE: 1009 case FILE_BEQLDATE: 1010 case FILE_QWDATE: 1011 case FILE_LEQWDATE: 1012 case FILE_BEQWDATE: 1013 case FILE_FLOAT: 1014 case FILE_BEFLOAT: 1015 case FILE_LEFLOAT: 1016 case FILE_DOUBLE: 1017 case FILE_BEDOUBLE: 1018 case FILE_LEDOUBLE: 1019 mstart->flag |= BINTEST; 1020 break; 1021 case FILE_STRING: 1022 case FILE_PSTRING: 1023 case FILE_BESTRING16: 1024 case FILE_LESTRING16: 1025 /* Allow text overrides */ 1026 if (mstart->str_flags & STRING_TEXTTEST) 1027 mstart->flag |= TEXTTEST; 1028 else 1029 mstart->flag |= BINTEST; 1030 break; 1031 case FILE_REGEX: 1032 case FILE_SEARCH: 1033 /* Check for override */ 1034 if (mstart->str_flags & STRING_BINTEST) 1035 mstart->flag |= BINTEST; 1036 if (mstart->str_flags & STRING_TEXTTEST) 1037 mstart->flag |= TEXTTEST; 1038 1039 if (mstart->flag & (TEXTTEST|BINTEST)) 1040 break; 1041 1042 /* binary test if pattern is not text */ 1043 if (file_looks_utf8(m->value.us, (size_t)m->vallen, NULL, 1044 NULL) <= 0) 1045 mstart->flag |= BINTEST; 1046 else 1047 mstart->flag |= TEXTTEST; 1048 break; 1049 case FILE_DEFAULT: 1050 /* can't deduce anything; we shouldn't see this at the 1051 top level anyway */ 1052 break; 1053 case FILE_INVALID: 1054 default: 1055 /* invalid search type, but no need to complain here */ 1056 break; 1057 } 1058 } 1059 1060 private int 1061 addentry(struct magic_set *ms, struct magic_entry *me, 1062 struct magic_entry_set *mset) 1063 { 1064 size_t i = me->mp->type == FILE_NAME ? 1 : 0; 1065 if (mset[i].count == mset[i].max) { 1066 struct magic_entry *mp; 1067 1068 mset[i].max += ALLOC_INCR; 1069 if ((mp = CAST(struct magic_entry *, 1070 realloc(mset[i].me, sizeof(*mp) * mset[i].max))) == 1071 NULL) { 1072 file_oomem(ms, sizeof(*mp) * mset[i].max); 1073 return -1; 1074 } 1075 (void)memset(&mp[mset[i].count], 0, sizeof(*mp) * 1076 ALLOC_INCR); 1077 mset[i].me = mp; 1078 } 1079 mset[i].me[mset[i].count++] = *me; 1080 memset(me, 0, sizeof(*me)); 1081 return 0; 1082 } 1083 1084 /* 1085 * Load and parse one file. 1086 */ 1087 private void 1088 load_1(struct magic_set *ms, int action, const char *fn, int *errs, 1089 struct magic_entry_set *mset) 1090 { 1091 size_t lineno = 0, llen = 0; 1092 char *line = NULL; 1093 ssize_t len; 1094 struct magic_entry me; 1095 1096 FILE *f = fopen(ms->file = fn, "r"); 1097 if (f == NULL) { 1098 if (errno != ENOENT) 1099 file_error(ms, errno, "cannot read magic file `%s'", 1100 fn); 1101 (*errs)++; 1102 return; 1103 } 1104 1105 memset(&me, 0, sizeof(me)); 1106 /* read and parse this file */ 1107 for (ms->line = 1; (len = getline(&line, &llen, f)) != -1; 1108 ms->line++) { 1109 if (len == 0) /* null line, garbage, etc */ 1110 continue; 1111 if (line[len - 1] == '\n') { 1112 lineno++; 1113 line[len - 1] = '\0'; /* delete newline */ 1114 } 1115 switch (line[0]) { 1116 case '\0': /* empty, do not parse */ 1117 case '#': /* comment, do not parse */ 1118 continue; 1119 case '!': 1120 if (line[1] == ':') { 1121 size_t i; 1122 1123 for (i = 0; bang[i].name != NULL; i++) { 1124 if ((size_t)(len - 2) > bang[i].len && 1125 memcmp(bang[i].name, line + 2, 1126 bang[i].len) == 0) 1127 break; 1128 } 1129 if (bang[i].name == NULL) { 1130 file_error(ms, 0, 1131 "Unknown !: entry `%s'", line); 1132 (*errs)++; 1133 continue; 1134 } 1135 if (me.mp == NULL) { 1136 file_error(ms, 0, 1137 "No current entry for :!%s type", 1138 bang[i].name); 1139 (*errs)++; 1140 continue; 1141 } 1142 if ((*bang[i].fun)(ms, &me, 1143 line + bang[i].len + 2) != 0) { 1144 (*errs)++; 1145 continue; 1146 } 1147 continue; 1148 } 1149 /*FALLTHROUGH*/ 1150 default: 1151 again: 1152 switch (parse(ms, &me, line, lineno, action)) { 1153 case 0: 1154 continue; 1155 case 1: 1156 (void)addentry(ms, &me, mset); 1157 goto again; 1158 default: 1159 (*errs)++; 1160 break; 1161 } 1162 } 1163 } 1164 if (me.mp) 1165 (void)addentry(ms, &me, mset); 1166 free(line); 1167 (void)fclose(f); 1168 } 1169 1170 /* 1171 * parse a file or directory of files 1172 * const char *fn: name of magic file or directory 1173 */ 1174 private int 1175 cmpstrp(const void *p1, const void *p2) 1176 { 1177 return strcmp(*(char *const *)p1, *(char *const *)p2); 1178 } 1179 1180 1181 private uint32_t 1182 set_text_binary(struct magic_set *ms, struct magic_entry *me, uint32_t nme, 1183 uint32_t starttest) 1184 { 1185 static const char text[] = "text"; 1186 static const char binary[] = "binary"; 1187 static const size_t len = sizeof(text); 1188 1189 uint32_t i = starttest; 1190 1191 do { 1192 set_test_type(me[starttest].mp, me[i].mp); 1193 if ((ms->flags & MAGIC_DEBUG) == 0) 1194 continue; 1195 (void)fprintf(stderr, "%s%s%s: %s\n", 1196 me[i].mp->mimetype, 1197 me[i].mp->mimetype[0] == '\0' ? "" : "; ", 1198 me[i].mp->desc[0] ? me[i].mp->desc : "(no description)", 1199 me[i].mp->flag & BINTEST ? binary : text); 1200 if (me[i].mp->flag & BINTEST) { 1201 char *p = strstr(me[i].mp->desc, text); 1202 if (p && (p == me[i].mp->desc || 1203 isspace((unsigned char)p[-1])) && 1204 (p + len - me[i].mp->desc == MAXstring 1205 || (p[len] == '\0' || 1206 isspace((unsigned char)p[len])))) 1207 (void)fprintf(stderr, "*** Possible " 1208 "binary test for text type\n"); 1209 } 1210 } while (++i < nme && me[i].mp->cont_level != 0); 1211 return i; 1212 } 1213 1214 private void 1215 set_last_default(struct magic_set *ms, struct magic_entry *me, uint32_t nme) 1216 { 1217 uint32_t i; 1218 for (i = 0; i < nme; i++) { 1219 if (me[i].mp->cont_level == 0 && 1220 me[i].mp->type == FILE_DEFAULT) { 1221 while (++i < nme) 1222 if (me[i].mp->cont_level == 0) 1223 break; 1224 if (i != nme) { 1225 /* XXX - Ugh! */ 1226 ms->line = me[i].mp->lineno; 1227 file_magwarn(ms, 1228 "level 0 \"default\" did not sort last"); 1229 } 1230 return; 1231 } 1232 } 1233 } 1234 1235 private int 1236 coalesce_entries(struct magic_set *ms, struct magic_entry *me, uint32_t nme, 1237 struct magic **ma, uint32_t *nma) 1238 { 1239 uint32_t i, mentrycount = 0; 1240 size_t slen; 1241 1242 for (i = 0; i < nme; i++) 1243 mentrycount += me[i].cont_count; 1244 1245 slen = sizeof(**ma) * mentrycount; 1246 if ((*ma = CAST(struct magic *, malloc(slen))) == NULL) { 1247 file_oomem(ms, slen); 1248 return -1; 1249 } 1250 1251 mentrycount = 0; 1252 for (i = 0; i < nme; i++) { 1253 (void)memcpy(*ma + mentrycount, me[i].mp, 1254 me[i].cont_count * sizeof(**ma)); 1255 mentrycount += me[i].cont_count; 1256 } 1257 *nma = mentrycount; 1258 return 0; 1259 } 1260 1261 private void 1262 magic_entry_free(struct magic_entry *me, uint32_t nme) 1263 { 1264 uint32_t i; 1265 if (me == NULL) 1266 return; 1267 for (i = 0; i < nme; i++) 1268 free(me[i].mp); 1269 free(me); 1270 } 1271 1272 private struct magic_map * 1273 apprentice_load(struct magic_set *ms, const char *fn, int action) 1274 { 1275 int errs = 0; 1276 uint32_t i, j; 1277 size_t files = 0, maxfiles = 0; 1278 char **filearr = NULL, *mfn; 1279 struct stat st; 1280 struct magic_map *map; 1281 struct magic_entry_set mset[MAGIC_SETS]; 1282 DIR *dir; 1283 struct dirent *d; 1284 1285 memset(mset, 0, sizeof(mset)); 1286 ms->flags |= MAGIC_CHECK; /* Enable checks for parsed files */ 1287 1288 1289 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) 1290 { 1291 file_oomem(ms, sizeof(*map)); 1292 return NULL; 1293 } 1294 1295 /* print silly verbose header for USG compat. */ 1296 if (action == FILE_CHECK) 1297 (void)fprintf(stderr, "%s\n", usg_hdr); 1298 1299 /* load directory or file */ 1300 if (stat(fn, &st) == 0 && S_ISDIR(st.st_mode)) { 1301 dir = opendir(fn); 1302 if (!dir) { 1303 errs++; 1304 goto out; 1305 } 1306 while ((d = readdir(dir)) != NULL) { 1307 if (asprintf(&mfn, "%s/%s", fn, d->d_name) < 0) { 1308 file_oomem(ms, 1309 strlen(fn) + strlen(d->d_name) + 2); 1310 errs++; 1311 closedir(dir); 1312 goto out; 1313 } 1314 if (stat(mfn, &st) == -1 || !S_ISREG(st.st_mode)) { 1315 free(mfn); 1316 continue; 1317 } 1318 if (files >= maxfiles) { 1319 size_t mlen; 1320 maxfiles = (maxfiles + 1) * 2; 1321 mlen = maxfiles * sizeof(*filearr); 1322 if ((filearr = CAST(char **, 1323 realloc(filearr, mlen))) == NULL) { 1324 file_oomem(ms, mlen); 1325 free(mfn); 1326 closedir(dir); 1327 errs++; 1328 goto out; 1329 } 1330 } 1331 filearr[files++] = mfn; 1332 } 1333 closedir(dir); 1334 qsort(filearr, files, sizeof(*filearr), cmpstrp); 1335 for (i = 0; i < files; i++) { 1336 load_1(ms, action, filearr[i], &errs, mset); 1337 free(filearr[i]); 1338 } 1339 free(filearr); 1340 } else 1341 load_1(ms, action, fn, &errs, mset); 1342 if (errs) 1343 goto out; 1344 1345 for (j = 0; j < MAGIC_SETS; j++) { 1346 /* Set types of tests */ 1347 for (i = 0; i < mset[j].count; ) { 1348 if (mset[j].me[i].mp->cont_level != 0) { 1349 i++; 1350 continue; 1351 } 1352 i = set_text_binary(ms, mset[j].me, mset[j].count, i); 1353 } 1354 qsort(mset[j].me, mset[j].count, sizeof(*mset[j].me), 1355 apprentice_sort); 1356 1357 /* 1358 * Make sure that any level 0 "default" line is last 1359 * (if one exists). 1360 */ 1361 set_last_default(ms, mset[j].me, mset[j].count); 1362 1363 /* coalesce per file arrays into a single one */ 1364 if (coalesce_entries(ms, mset[j].me, mset[j].count, 1365 &map->magic[j], &map->nmagic[j]) == -1) { 1366 errs++; 1367 goto out; 1368 } 1369 } 1370 1371 out: 1372 for (j = 0; j < MAGIC_SETS; j++) 1373 magic_entry_free(mset[j].me, mset[j].count); 1374 1375 if (errs) { 1376 apprentice_unmap(map); 1377 return NULL; 1378 } 1379 return map; 1380 } 1381 1382 /* 1383 * extend the sign bit if the comparison is to be signed 1384 */ 1385 protected uint64_t 1386 file_signextend(struct magic_set *ms, struct magic *m, uint64_t v) 1387 { 1388 if (!(m->flag & UNSIGNED)) { 1389 switch(m->type) { 1390 /* 1391 * Do not remove the casts below. They are 1392 * vital. When later compared with the data, 1393 * the sign extension must have happened. 1394 */ 1395 case FILE_BYTE: 1396 v = (signed char) v; 1397 break; 1398 case FILE_SHORT: 1399 case FILE_BESHORT: 1400 case FILE_LESHORT: 1401 v = (short) v; 1402 break; 1403 case FILE_DATE: 1404 case FILE_BEDATE: 1405 case FILE_LEDATE: 1406 case FILE_MEDATE: 1407 case FILE_LDATE: 1408 case FILE_BELDATE: 1409 case FILE_LELDATE: 1410 case FILE_MELDATE: 1411 case FILE_LONG: 1412 case FILE_BELONG: 1413 case FILE_LELONG: 1414 case FILE_MELONG: 1415 case FILE_FLOAT: 1416 case FILE_BEFLOAT: 1417 case FILE_LEFLOAT: 1418 v = (int32_t) v; 1419 break; 1420 case FILE_QUAD: 1421 case FILE_BEQUAD: 1422 case FILE_LEQUAD: 1423 case FILE_QDATE: 1424 case FILE_QLDATE: 1425 case FILE_QWDATE: 1426 case FILE_BEQDATE: 1427 case FILE_BEQLDATE: 1428 case FILE_BEQWDATE: 1429 case FILE_LEQDATE: 1430 case FILE_LEQLDATE: 1431 case FILE_LEQWDATE: 1432 case FILE_DOUBLE: 1433 case FILE_BEDOUBLE: 1434 case FILE_LEDOUBLE: 1435 v = (int64_t) v; 1436 break; 1437 case FILE_STRING: 1438 case FILE_PSTRING: 1439 case FILE_BESTRING16: 1440 case FILE_LESTRING16: 1441 case FILE_REGEX: 1442 case FILE_SEARCH: 1443 case FILE_DEFAULT: 1444 case FILE_INDIRECT: 1445 case FILE_NAME: 1446 case FILE_USE: 1447 case FILE_CLEAR: 1448 break; 1449 default: 1450 if (ms->flags & MAGIC_CHECK) 1451 file_magwarn(ms, "cannot happen: m->type=%d\n", 1452 m->type); 1453 return ~0U; 1454 } 1455 } 1456 return v; 1457 } 1458 1459 private int 1460 string_modifier_check(struct magic_set *ms, struct magic *m) 1461 { 1462 if ((ms->flags & MAGIC_CHECK) == 0) 1463 return 0; 1464 1465 if ((m->type != FILE_REGEX || (m->str_flags & REGEX_LINE_COUNT) == 0) && 1466 (m->type != FILE_PSTRING && (m->str_flags & PSTRING_LEN) != 0)) { 1467 file_magwarn(ms, 1468 "'/BHhLl' modifiers are only allowed for pascal strings\n"); 1469 return -1; 1470 } 1471 switch (m->type) { 1472 case FILE_BESTRING16: 1473 case FILE_LESTRING16: 1474 if (m->str_flags != 0) { 1475 file_magwarn(ms, 1476 "no modifiers allowed for 16-bit strings\n"); 1477 return -1; 1478 } 1479 break; 1480 case FILE_STRING: 1481 case FILE_PSTRING: 1482 if ((m->str_flags & REGEX_OFFSET_START) != 0) { 1483 file_magwarn(ms, 1484 "'/%c' only allowed on regex and search\n", 1485 CHAR_REGEX_OFFSET_START); 1486 return -1; 1487 } 1488 break; 1489 case FILE_SEARCH: 1490 if (m->str_range == 0) { 1491 file_magwarn(ms, 1492 "missing range; defaulting to %d\n", 1493 STRING_DEFAULT_RANGE); 1494 m->str_range = STRING_DEFAULT_RANGE; 1495 return -1; 1496 } 1497 break; 1498 case FILE_REGEX: 1499 if ((m->str_flags & STRING_COMPACT_WHITESPACE) != 0) { 1500 file_magwarn(ms, "'/%c' not allowed on regex\n", 1501 CHAR_COMPACT_WHITESPACE); 1502 return -1; 1503 } 1504 if ((m->str_flags & STRING_COMPACT_OPTIONAL_WHITESPACE) != 0) { 1505 file_magwarn(ms, "'/%c' not allowed on regex\n", 1506 CHAR_COMPACT_OPTIONAL_WHITESPACE); 1507 return -1; 1508 } 1509 break; 1510 default: 1511 file_magwarn(ms, "coding error: m->type=%d\n", 1512 m->type); 1513 return -1; 1514 } 1515 return 0; 1516 } 1517 1518 private int 1519 get_op(char c) 1520 { 1521 switch (c) { 1522 case '&': 1523 return FILE_OPAND; 1524 case '|': 1525 return FILE_OPOR; 1526 case '^': 1527 return FILE_OPXOR; 1528 case '+': 1529 return FILE_OPADD; 1530 case '-': 1531 return FILE_OPMINUS; 1532 case '*': 1533 return FILE_OPMULTIPLY; 1534 case '/': 1535 return FILE_OPDIVIDE; 1536 case '%': 1537 return FILE_OPMODULO; 1538 default: 1539 return -1; 1540 } 1541 } 1542 1543 #ifdef ENABLE_CONDITIONALS 1544 private int 1545 get_cond(const char *l, const char **t) 1546 { 1547 static const struct cond_tbl_s { 1548 char name[8]; 1549 size_t len; 1550 int cond; 1551 } cond_tbl[] = { 1552 { "if", 2, COND_IF }, 1553 { "elif", 4, COND_ELIF }, 1554 { "else", 4, COND_ELSE }, 1555 { "", 0, COND_NONE }, 1556 }; 1557 const struct cond_tbl_s *p; 1558 1559 for (p = cond_tbl; p->len; p++) { 1560 if (strncmp(l, p->name, p->len) == 0 && 1561 isspace((unsigned char)l[p->len])) { 1562 if (t) 1563 *t = l + p->len; 1564 break; 1565 } 1566 } 1567 return p->cond; 1568 } 1569 1570 private int 1571 check_cond(struct magic_set *ms, int cond, uint32_t cont_level) 1572 { 1573 int last_cond; 1574 last_cond = ms->c.li[cont_level].last_cond; 1575 1576 switch (cond) { 1577 case COND_IF: 1578 if (last_cond != COND_NONE && last_cond != COND_ELIF) { 1579 if (ms->flags & MAGIC_CHECK) 1580 file_magwarn(ms, "syntax error: `if'"); 1581 return -1; 1582 } 1583 last_cond = COND_IF; 1584 break; 1585 1586 case COND_ELIF: 1587 if (last_cond != COND_IF && last_cond != COND_ELIF) { 1588 if (ms->flags & MAGIC_CHECK) 1589 file_magwarn(ms, "syntax error: `elif'"); 1590 return -1; 1591 } 1592 last_cond = COND_ELIF; 1593 break; 1594 1595 case COND_ELSE: 1596 if (last_cond != COND_IF && last_cond != COND_ELIF) { 1597 if (ms->flags & MAGIC_CHECK) 1598 file_magwarn(ms, "syntax error: `else'"); 1599 return -1; 1600 } 1601 last_cond = COND_NONE; 1602 break; 1603 1604 case COND_NONE: 1605 last_cond = COND_NONE; 1606 break; 1607 } 1608 1609 ms->c.li[cont_level].last_cond = last_cond; 1610 return 0; 1611 } 1612 #endif /* ENABLE_CONDITIONALS */ 1613 1614 private int 1615 parse_indirect_modifier(struct magic_set *ms, struct magic *m, const char **lp) 1616 { 1617 const char *l = *lp; 1618 1619 while (!isspace((unsigned char)*++l)) 1620 switch (*l) { 1621 case CHAR_INDIRECT_RELATIVE: 1622 m->str_flags |= INDIRECT_RELATIVE; 1623 break; 1624 default: 1625 if (ms->flags & MAGIC_CHECK) 1626 file_magwarn(ms, "indirect modifier `%c' " 1627 "invalid", *l); 1628 *lp = l; 1629 return -1; 1630 } 1631 *lp = l; 1632 return 0; 1633 } 1634 1635 private void 1636 parse_op_modifier(struct magic_set *ms, struct magic *m, const char **lp, 1637 int op) 1638 { 1639 const char *l = *lp; 1640 char *t; 1641 uint64_t val; 1642 1643 ++l; 1644 m->mask_op |= op; 1645 val = (uint64_t)strtoull(l, &t, 0); 1646 l = t; 1647 m->num_mask = file_signextend(ms, m, val); 1648 eatsize(&l); 1649 *lp = l; 1650 } 1651 1652 private int 1653 parse_string_modifier(struct magic_set *ms, struct magic *m, const char **lp) 1654 { 1655 const char *l = *lp; 1656 char *t; 1657 int have_range = 0; 1658 1659 while (!isspace((unsigned char)*++l)) { 1660 switch (*l) { 1661 case '0': case '1': case '2': 1662 case '3': case '4': case '5': 1663 case '6': case '7': case '8': 1664 case '9': 1665 if (have_range && (ms->flags & MAGIC_CHECK)) 1666 file_magwarn(ms, "multiple ranges"); 1667 have_range = 1; 1668 m->str_range = CAST(uint32_t, strtoul(l, &t, 0)); 1669 if (m->str_range == 0) 1670 file_magwarn(ms, "zero range"); 1671 l = t - 1; 1672 break; 1673 case CHAR_COMPACT_WHITESPACE: 1674 m->str_flags |= STRING_COMPACT_WHITESPACE; 1675 break; 1676 case CHAR_COMPACT_OPTIONAL_WHITESPACE: 1677 m->str_flags |= STRING_COMPACT_OPTIONAL_WHITESPACE; 1678 break; 1679 case CHAR_IGNORE_LOWERCASE: 1680 m->str_flags |= STRING_IGNORE_LOWERCASE; 1681 break; 1682 case CHAR_IGNORE_UPPERCASE: 1683 m->str_flags |= STRING_IGNORE_UPPERCASE; 1684 break; 1685 case CHAR_REGEX_OFFSET_START: 1686 m->str_flags |= REGEX_OFFSET_START; 1687 break; 1688 case CHAR_BINTEST: 1689 m->str_flags |= STRING_BINTEST; 1690 break; 1691 case CHAR_TEXTTEST: 1692 m->str_flags |= STRING_TEXTTEST; 1693 break; 1694 case CHAR_TRIM: 1695 m->str_flags |= STRING_TRIM; 1696 break; 1697 case CHAR_PSTRING_1_LE: 1698 #define SET_LENGTH(a) m->str_flags = (m->str_flags & ~PSTRING_LEN) | (a) 1699 if (m->type != FILE_PSTRING) 1700 goto bad; 1701 SET_LENGTH(PSTRING_1_LE); 1702 break; 1703 case CHAR_PSTRING_2_BE: 1704 if (m->type != FILE_PSTRING) 1705 goto bad; 1706 SET_LENGTH(PSTRING_2_BE); 1707 break; 1708 case CHAR_PSTRING_2_LE: 1709 if (m->type != FILE_PSTRING) 1710 goto bad; 1711 SET_LENGTH(PSTRING_2_LE); 1712 break; 1713 case CHAR_PSTRING_4_BE: 1714 if (m->type != FILE_PSTRING) 1715 goto bad; 1716 SET_LENGTH(PSTRING_4_BE); 1717 break; 1718 case CHAR_PSTRING_4_LE: 1719 switch (m->type) { 1720 case FILE_PSTRING: 1721 case FILE_REGEX: 1722 break; 1723 default: 1724 goto bad; 1725 } 1726 SET_LENGTH(PSTRING_4_LE); 1727 break; 1728 case CHAR_PSTRING_LENGTH_INCLUDES_ITSELF: 1729 if (m->type != FILE_PSTRING) 1730 goto bad; 1731 m->str_flags |= PSTRING_LENGTH_INCLUDES_ITSELF; 1732 break; 1733 default: 1734 bad: 1735 if (ms->flags & MAGIC_CHECK) 1736 file_magwarn(ms, "string modifier `%c' " 1737 "invalid", *l); 1738 goto out; 1739 } 1740 /* allow multiple '/' for readability */ 1741 if (l[1] == '/' && !isspace((unsigned char)l[2])) 1742 l++; 1743 } 1744 if (string_modifier_check(ms, m) == -1) 1745 goto out; 1746 *lp = l; 1747 return 0; 1748 out: 1749 *lp = l; 1750 return -1; 1751 } 1752 1753 /* 1754 * parse one line from magic file, put into magic[index++] if valid 1755 */ 1756 private int 1757 parse(struct magic_set *ms, struct magic_entry *me, const char *line, 1758 size_t lineno, int action) 1759 { 1760 #ifdef ENABLE_CONDITIONALS 1761 static uint32_t last_cont_level = 0; 1762 #endif 1763 size_t i; 1764 struct magic *m; 1765 const char *l = line; 1766 char *t; 1767 int op; 1768 uint32_t cont_level; 1769 int32_t diff; 1770 1771 cont_level = 0; 1772 1773 /* 1774 * Parse the offset. 1775 */ 1776 while (*l == '>') { 1777 ++l; /* step over */ 1778 cont_level++; 1779 } 1780 #ifdef ENABLE_CONDITIONALS 1781 if (cont_level == 0 || cont_level > last_cont_level) 1782 if (file_check_mem(ms, cont_level) == -1) 1783 return -1; 1784 last_cont_level = cont_level; 1785 #endif 1786 if (cont_level != 0) { 1787 if (me->mp == NULL) { 1788 file_magerror(ms, "No current entry for continuation"); 1789 return -1; 1790 } 1791 if (me->cont_count == 0) { 1792 file_magerror(ms, "Continuations present with 0 count"); 1793 return -1; 1794 } 1795 m = &me->mp[me->cont_count - 1]; 1796 diff = (int32_t)cont_level - (int32_t)m->cont_level; 1797 if (diff > 1) 1798 file_magwarn(ms, "New continuation level %u is more " 1799 "than one larger than current level %u", cont_level, 1800 m->cont_level); 1801 if (me->cont_count == me->max_count) { 1802 struct magic *nm; 1803 size_t cnt = me->max_count + ALLOC_CHUNK; 1804 if ((nm = CAST(struct magic *, realloc(me->mp, 1805 sizeof(*nm) * cnt))) == NULL) { 1806 file_oomem(ms, sizeof(*nm) * cnt); 1807 return -1; 1808 } 1809 me->mp = m = nm; 1810 me->max_count = CAST(uint32_t, cnt); 1811 } 1812 m = &me->mp[me->cont_count++]; 1813 (void)memset(m, 0, sizeof(*m)); 1814 m->cont_level = cont_level; 1815 } else { 1816 static const size_t len = sizeof(*m) * ALLOC_CHUNK; 1817 if (me->mp != NULL) 1818 return 1; 1819 if ((m = CAST(struct magic *, malloc(len))) == NULL) { 1820 file_oomem(ms, len); 1821 return -1; 1822 } 1823 me->mp = m; 1824 me->max_count = ALLOC_CHUNK; 1825 (void)memset(m, 0, sizeof(*m)); 1826 m->factor_op = FILE_FACTOR_OP_NONE; 1827 m->cont_level = 0; 1828 me->cont_count = 1; 1829 } 1830 m->lineno = CAST(uint32_t, lineno); 1831 1832 if (*l == '&') { /* m->cont_level == 0 checked below. */ 1833 ++l; /* step over */ 1834 m->flag |= OFFADD; 1835 } 1836 if (*l == '(') { 1837 ++l; /* step over */ 1838 m->flag |= INDIR; 1839 if (m->flag & OFFADD) 1840 m->flag = (m->flag & ~OFFADD) | INDIROFFADD; 1841 1842 if (*l == '&') { /* m->cont_level == 0 checked below */ 1843 ++l; /* step over */ 1844 m->flag |= OFFADD; 1845 } 1846 } 1847 /* Indirect offsets are not valid at level 0. */ 1848 if (m->cont_level == 0 && (m->flag & (OFFADD | INDIROFFADD))) 1849 if (ms->flags & MAGIC_CHECK) 1850 file_magwarn(ms, "relative offset at level 0"); 1851 1852 /* get offset, then skip over it */ 1853 m->offset = (uint32_t)strtoul(l, &t, 0); 1854 if (l == t) 1855 if (ms->flags & MAGIC_CHECK) 1856 file_magwarn(ms, "offset `%s' invalid", l); 1857 l = t; 1858 1859 if (m->flag & INDIR) { 1860 m->in_type = FILE_LONG; 1861 m->in_offset = 0; 1862 /* 1863 * read [.lbs][+-]nnnnn) 1864 */ 1865 if (*l == '.') { 1866 l++; 1867 switch (*l) { 1868 case 'l': 1869 m->in_type = FILE_LELONG; 1870 break; 1871 case 'L': 1872 m->in_type = FILE_BELONG; 1873 break; 1874 case 'm': 1875 m->in_type = FILE_MELONG; 1876 break; 1877 case 'h': 1878 case 's': 1879 m->in_type = FILE_LESHORT; 1880 break; 1881 case 'H': 1882 case 'S': 1883 m->in_type = FILE_BESHORT; 1884 break; 1885 case 'c': 1886 case 'b': 1887 case 'C': 1888 case 'B': 1889 m->in_type = FILE_BYTE; 1890 break; 1891 case 'e': 1892 case 'f': 1893 case 'g': 1894 m->in_type = FILE_LEDOUBLE; 1895 break; 1896 case 'E': 1897 case 'F': 1898 case 'G': 1899 m->in_type = FILE_BEDOUBLE; 1900 break; 1901 case 'i': 1902 m->in_type = FILE_LEID3; 1903 break; 1904 case 'I': 1905 m->in_type = FILE_BEID3; 1906 break; 1907 default: 1908 if (ms->flags & MAGIC_CHECK) 1909 file_magwarn(ms, 1910 "indirect offset type `%c' invalid", 1911 *l); 1912 break; 1913 } 1914 l++; 1915 } 1916 1917 m->in_op = 0; 1918 if (*l == '~') { 1919 m->in_op |= FILE_OPINVERSE; 1920 l++; 1921 } 1922 if ((op = get_op(*l)) != -1) { 1923 m->in_op |= op; 1924 l++; 1925 } 1926 if (*l == '(') { 1927 m->in_op |= FILE_OPINDIRECT; 1928 l++; 1929 } 1930 if (isdigit((unsigned char)*l) || *l == '-') { 1931 m->in_offset = (int32_t)strtol(l, &t, 0); 1932 if (l == t) 1933 if (ms->flags & MAGIC_CHECK) 1934 file_magwarn(ms, 1935 "in_offset `%s' invalid", l); 1936 l = t; 1937 } 1938 if (*l++ != ')' || 1939 ((m->in_op & FILE_OPINDIRECT) && *l++ != ')')) 1940 if (ms->flags & MAGIC_CHECK) 1941 file_magwarn(ms, 1942 "missing ')' in indirect offset"); 1943 } 1944 EATAB; 1945 1946 #ifdef ENABLE_CONDITIONALS 1947 m->cond = get_cond(l, &l); 1948 if (check_cond(ms, m->cond, cont_level) == -1) 1949 return -1; 1950 1951 EATAB; 1952 #endif 1953 1954 /* 1955 * Parse the type. 1956 */ 1957 if (*l == 'u') { 1958 /* 1959 * Try it as a keyword type prefixed by "u"; match what 1960 * follows the "u". If that fails, try it as an SUS 1961 * integer type. 1962 */ 1963 m->type = get_type(type_tbl, l + 1, &l); 1964 if (m->type == FILE_INVALID) { 1965 /* 1966 * Not a keyword type; parse it as an SUS type, 1967 * 'u' possibly followed by a number or C/S/L. 1968 */ 1969 m->type = get_standard_integer_type(l, &l); 1970 } 1971 /* It's unsigned. */ 1972 if (m->type != FILE_INVALID) 1973 m->flag |= UNSIGNED; 1974 } else { 1975 /* 1976 * Try it as a keyword type. If that fails, try it as 1977 * an SUS integer type if it begins with "d" or as an 1978 * SUS string type if it begins with "s". In any case, 1979 * it's not unsigned. 1980 */ 1981 m->type = get_type(type_tbl, l, &l); 1982 if (m->type == FILE_INVALID) { 1983 /* 1984 * Not a keyword type; parse it as an SUS type, 1985 * either 'd' possibly followed by a number or 1986 * C/S/L, or just 's'. 1987 */ 1988 if (*l == 'd') 1989 m->type = get_standard_integer_type(l, &l); 1990 else if (*l == 's' && !isalpha((unsigned char)l[1])) { 1991 m->type = FILE_STRING; 1992 ++l; 1993 } 1994 } 1995 } 1996 1997 if (m->type == FILE_INVALID) { 1998 /* Not found - try it as a special keyword. */ 1999 m->type = get_type(special_tbl, l, &l); 2000 } 2001 2002 if (m->type == FILE_INVALID) { 2003 if (ms->flags & MAGIC_CHECK) 2004 file_magwarn(ms, "type `%s' invalid", l); 2005 return -1; 2006 } 2007 2008 /* New-style anding: "0 byte&0x80 =0x80 dynamically linked" */ 2009 /* New and improved: ~ & | ^ + - * / % -- exciting, isn't it? */ 2010 2011 m->mask_op = 0; 2012 if (*l == '~') { 2013 if (!IS_STRING(m->type)) 2014 m->mask_op |= FILE_OPINVERSE; 2015 else if (ms->flags & MAGIC_CHECK) 2016 file_magwarn(ms, "'~' invalid for string types"); 2017 ++l; 2018 } 2019 m->str_range = 0; 2020 m->str_flags = m->type == FILE_PSTRING ? PSTRING_1_LE : 0; 2021 if ((op = get_op(*l)) != -1) { 2022 if (IS_STRING(m->type)) { 2023 int r; 2024 2025 if (op != FILE_OPDIVIDE) { 2026 if (ms->flags & MAGIC_CHECK) 2027 file_magwarn(ms, 2028 "invalid string/indirect op: " 2029 "`%c'", *t); 2030 return -1; 2031 } 2032 2033 if (m->type == FILE_INDIRECT) 2034 r = parse_indirect_modifier(ms, m, &l); 2035 else 2036 r = parse_string_modifier(ms, m, &l); 2037 if (r == -1) 2038 return -1; 2039 } else 2040 parse_op_modifier(ms, m, &l, op); 2041 } 2042 2043 /* 2044 * We used to set mask to all 1's here, instead let's just not do 2045 * anything if mask = 0 (unless you have a better idea) 2046 */ 2047 EATAB; 2048 2049 switch (*l) { 2050 case '>': 2051 case '<': 2052 m->reln = *l; 2053 ++l; 2054 if (*l == '=') { 2055 if (ms->flags & MAGIC_CHECK) { 2056 file_magwarn(ms, "%c= not supported", 2057 m->reln); 2058 return -1; 2059 } 2060 ++l; 2061 } 2062 break; 2063 /* Old-style anding: "0 byte &0x80 dynamically linked" */ 2064 case '&': 2065 case '^': 2066 case '=': 2067 m->reln = *l; 2068 ++l; 2069 if (*l == '=') { 2070 /* HP compat: ignore &= etc. */ 2071 ++l; 2072 } 2073 break; 2074 case '!': 2075 m->reln = *l; 2076 ++l; 2077 break; 2078 default: 2079 m->reln = '='; /* the default relation */ 2080 if (*l == 'x' && ((isascii((unsigned char)l[1]) && 2081 isspace((unsigned char)l[1])) || !l[1])) { 2082 m->reln = *l; 2083 ++l; 2084 } 2085 break; 2086 } 2087 /* 2088 * Grab the value part, except for an 'x' reln. 2089 */ 2090 if (m->reln != 'x' && getvalue(ms, m, &l, action)) 2091 return -1; 2092 2093 /* 2094 * TODO finish this macro and start using it! 2095 * #define offsetcheck {if (offset > HOWMANY-1) 2096 * magwarn("offset too big"); } 2097 */ 2098 2099 /* 2100 * Now get last part - the description 2101 */ 2102 EATAB; 2103 if (l[0] == '\b') { 2104 ++l; 2105 m->flag |= NOSPACE; 2106 } else if ((l[0] == '\\') && (l[1] == 'b')) { 2107 ++l; 2108 ++l; 2109 m->flag |= NOSPACE; 2110 } 2111 for (i = 0; (m->desc[i++] = *l++) != '\0' && i < sizeof(m->desc); ) 2112 continue; 2113 if (i == sizeof(m->desc)) { 2114 m->desc[sizeof(m->desc) - 1] = '\0'; 2115 if (ms->flags & MAGIC_CHECK) 2116 file_magwarn(ms, "description `%s' truncated", m->desc); 2117 } 2118 2119 /* 2120 * We only do this check while compiling, or if any of the magic 2121 * files were not compiled. 2122 */ 2123 if (ms->flags & MAGIC_CHECK) { 2124 if (check_format(ms, m) == -1) 2125 return -1; 2126 } 2127 #ifndef COMPILE_ONLY 2128 if (action == FILE_CHECK) { 2129 file_mdump(m); 2130 } 2131 #endif 2132 m->mimetype[0] = '\0'; /* initialise MIME type to none */ 2133 return 0; 2134 } 2135 2136 /* 2137 * parse a STRENGTH annotation line from magic file, put into magic[index - 1] 2138 * if valid 2139 */ 2140 private int 2141 parse_strength(struct magic_set *ms, struct magic_entry *me, const char *line) 2142 { 2143 const char *l = line; 2144 char *el; 2145 unsigned long factor; 2146 struct magic *m = &me->mp[0]; 2147 2148 if (m->factor_op != FILE_FACTOR_OP_NONE) { 2149 file_magwarn(ms, 2150 "Current entry already has a strength type: %c %d", 2151 m->factor_op, m->factor); 2152 return -1; 2153 } 2154 if (m->type == FILE_NAME) { 2155 file_magwarn(ms, "%s: Strength setting is not supported in " 2156 "\"name\" magic entries", m->value.s); 2157 return -1; 2158 } 2159 EATAB; 2160 switch (*l) { 2161 case FILE_FACTOR_OP_NONE: 2162 case FILE_FACTOR_OP_PLUS: 2163 case FILE_FACTOR_OP_MINUS: 2164 case FILE_FACTOR_OP_TIMES: 2165 case FILE_FACTOR_OP_DIV: 2166 m->factor_op = *l++; 2167 break; 2168 default: 2169 file_magwarn(ms, "Unknown factor op `%c'", *l); 2170 return -1; 2171 } 2172 EATAB; 2173 factor = strtoul(l, &el, 0); 2174 if (factor > 255) { 2175 file_magwarn(ms, "Too large factor `%lu'", factor); 2176 goto out; 2177 } 2178 if (*el && !isspace((unsigned char)*el)) { 2179 file_magwarn(ms, "Bad factor `%s'", l); 2180 goto out; 2181 } 2182 m->factor = (uint8_t)factor; 2183 if (m->factor == 0 && m->factor_op == FILE_FACTOR_OP_DIV) { 2184 file_magwarn(ms, "Cannot have factor op `%c' and factor %u", 2185 m->factor_op, m->factor); 2186 goto out; 2187 } 2188 return 0; 2189 out: 2190 m->factor_op = FILE_FACTOR_OP_NONE; 2191 m->factor = 0; 2192 return -1; 2193 } 2194 2195 private int 2196 goodchar(unsigned char x, const char *extra) 2197 { 2198 return (isascii(x) && isalnum(x)) || strchr(extra, x); 2199 } 2200 2201 private int 2202 parse_extra(struct magic_set *ms, struct magic_entry *me, const char *line, 2203 off_t off, size_t len, const char *name, const char *extra, int nt) 2204 { 2205 size_t i; 2206 const char *l = line; 2207 struct magic *m = &me->mp[me->cont_count == 0 ? 0 : me->cont_count - 1]; 2208 char *buf = CAST(char *, CAST(void *, m)) + off; 2209 2210 if (buf[0] != '\0') { 2211 len = nt ? strlen(buf) : len; 2212 file_magwarn(ms, "Current entry already has a %s type " 2213 "`%.*s', new type `%s'", name, (int)len, buf, l); 2214 return -1; 2215 } 2216 2217 if (*m->desc == '\0') { 2218 file_magwarn(ms, "Current entry does not yet have a " 2219 "description for adding a %s type", name); 2220 return -1; 2221 } 2222 2223 EATAB; 2224 for (i = 0; *l && i < len && goodchar(*l, extra); buf[i++] = *l++) 2225 continue; 2226 2227 if (i == len && *l) { 2228 if (nt) 2229 buf[len - 1] = '\0'; 2230 if (ms->flags & MAGIC_CHECK) 2231 file_magwarn(ms, "%s type `%s' truncated %" 2232 SIZE_T_FORMAT "u", name, line, i); 2233 } else { 2234 if (!isspace((unsigned char)*l) && !goodchar(*l, extra)) 2235 file_magwarn(ms, "%s type `%s' has bad char '%c'", 2236 name, line, *l); 2237 if (nt) 2238 buf[i] = '\0'; 2239 } 2240 2241 if (i > 0) 2242 return 0; 2243 2244 file_magerror(ms, "Bad magic entry '%s'", line); 2245 return -1; 2246 } 2247 2248 /* 2249 * Parse an Apple CREATOR/TYPE annotation from magic file and put it into 2250 * magic[index - 1] 2251 */ 2252 private int 2253 parse_apple(struct magic_set *ms, struct magic_entry *me, const char *line) 2254 { 2255 struct magic *m = &me->mp[0]; 2256 2257 return parse_extra(ms, me, line, 2258 CAST(off_t, offsetof(struct magic, apple)), 2259 sizeof(m->apple), "APPLE", "!+-./", 0); 2260 } 2261 2262 /* 2263 * parse a MIME annotation line from magic file, put into magic[index - 1] 2264 * if valid 2265 */ 2266 private int 2267 parse_mime(struct magic_set *ms, struct magic_entry *me, const char *line) 2268 { 2269 struct magic *m = &me->mp[0]; 2270 2271 return parse_extra(ms, me, line, 2272 CAST(off_t, offsetof(struct magic, mimetype)), 2273 sizeof(m->mimetype), "MIME", "+-/.", 1); 2274 } 2275 2276 private int 2277 check_format_type(const char *ptr, int type) 2278 { 2279 int quad = 0, h; 2280 if (*ptr == '\0') { 2281 /* Missing format string; bad */ 2282 return -1; 2283 } 2284 2285 switch (file_formats[type]) { 2286 case FILE_FMT_QUAD: 2287 quad = 1; 2288 /*FALLTHROUGH*/ 2289 case FILE_FMT_NUM: 2290 if (quad == 0) { 2291 switch (type) { 2292 case FILE_BYTE: 2293 h = 2; 2294 break; 2295 case FILE_SHORT: 2296 case FILE_BESHORT: 2297 case FILE_LESHORT: 2298 h = 1; 2299 break; 2300 case FILE_LONG: 2301 case FILE_BELONG: 2302 case FILE_LELONG: 2303 case FILE_MELONG: 2304 case FILE_LEID3: 2305 case FILE_BEID3: 2306 case FILE_INDIRECT: 2307 h = 0; 2308 break; 2309 default: 2310 abort(); 2311 } 2312 } else 2313 h = 0; 2314 if (*ptr == '-') 2315 ptr++; 2316 if (*ptr == '.') 2317 ptr++; 2318 while (isdigit((unsigned char)*ptr)) ptr++; 2319 if (*ptr == '.') 2320 ptr++; 2321 while (isdigit((unsigned char)*ptr)) ptr++; 2322 if (quad) { 2323 if (*ptr++ != 'l') 2324 return -1; 2325 if (*ptr++ != 'l') 2326 return -1; 2327 } 2328 2329 switch (*ptr++) { 2330 #ifdef STRICT_FORMAT /* "long" formats are int formats for us */ 2331 /* so don't accept the 'l' modifier */ 2332 case 'l': 2333 switch (*ptr++) { 2334 case 'i': 2335 case 'd': 2336 case 'u': 2337 case 'o': 2338 case 'x': 2339 case 'X': 2340 return h != 0 ? -1 : 0; 2341 default: 2342 return -1; 2343 } 2344 2345 /* 2346 * Don't accept h and hh modifiers. They make writing 2347 * magic entries more complicated, for very little benefit 2348 */ 2349 case 'h': 2350 if (h-- <= 0) 2351 return -1; 2352 switch (*ptr++) { 2353 case 'h': 2354 if (h-- <= 0) 2355 return -1; 2356 switch (*ptr++) { 2357 case 'i': 2358 case 'd': 2359 case 'u': 2360 case 'o': 2361 case 'x': 2362 case 'X': 2363 return 0; 2364 default: 2365 return -1; 2366 } 2367 case 'i': 2368 case 'd': 2369 case 'u': 2370 case 'o': 2371 case 'x': 2372 case 'X': 2373 return h != 0 ? -1 : 0; 2374 default: 2375 return -1; 2376 } 2377 #endif 2378 case 'c': 2379 return h != 2 ? -1 : 0; 2380 case 'i': 2381 case 'd': 2382 case 'u': 2383 case 'o': 2384 case 'x': 2385 case 'X': 2386 #ifdef STRICT_FORMAT 2387 return h != 0 ? -1 : 0; 2388 #else 2389 return 0; 2390 #endif 2391 default: 2392 return -1; 2393 } 2394 2395 case FILE_FMT_FLOAT: 2396 case FILE_FMT_DOUBLE: 2397 if (*ptr == '-') 2398 ptr++; 2399 if (*ptr == '.') 2400 ptr++; 2401 while (isdigit((unsigned char)*ptr)) ptr++; 2402 if (*ptr == '.') 2403 ptr++; 2404 while (isdigit((unsigned char)*ptr)) ptr++; 2405 2406 switch (*ptr++) { 2407 case 'e': 2408 case 'E': 2409 case 'f': 2410 case 'F': 2411 case 'g': 2412 case 'G': 2413 return 0; 2414 2415 default: 2416 return -1; 2417 } 2418 2419 2420 case FILE_FMT_STR: 2421 if (*ptr == '-') 2422 ptr++; 2423 while (isdigit((unsigned char )*ptr)) 2424 ptr++; 2425 if (*ptr == '.') { 2426 ptr++; 2427 while (isdigit((unsigned char )*ptr)) 2428 ptr++; 2429 } 2430 2431 switch (*ptr++) { 2432 case 's': 2433 return 0; 2434 default: 2435 return -1; 2436 } 2437 2438 default: 2439 /* internal error */ 2440 abort(); 2441 } 2442 /*NOTREACHED*/ 2443 return -1; 2444 } 2445 2446 /* 2447 * Check that the optional printf format in description matches 2448 * the type of the magic. 2449 */ 2450 private int 2451 check_format(struct magic_set *ms, struct magic *m) 2452 { 2453 char *ptr; 2454 2455 for (ptr = m->desc; *ptr; ptr++) 2456 if (*ptr == '%') 2457 break; 2458 if (*ptr == '\0') { 2459 /* No format string; ok */ 2460 return 1; 2461 } 2462 2463 assert(file_nformats == file_nnames); 2464 2465 if (m->type >= file_nformats) { 2466 file_magwarn(ms, "Internal error inconsistency between " 2467 "m->type and format strings"); 2468 return -1; 2469 } 2470 if (file_formats[m->type] == FILE_FMT_NONE) { 2471 file_magwarn(ms, "No format string for `%s' with description " 2472 "`%s'", m->desc, file_names[m->type]); 2473 return -1; 2474 } 2475 2476 ptr++; 2477 if (check_format_type(ptr, m->type) == -1) { 2478 /* 2479 * TODO: this error message is unhelpful if the format 2480 * string is not one character long 2481 */ 2482 file_magwarn(ms, "Printf format `%c' is not valid for type " 2483 "`%s' in description `%s'", *ptr ? *ptr : '?', 2484 file_names[m->type], m->desc); 2485 return -1; 2486 } 2487 2488 for (; *ptr; ptr++) { 2489 if (*ptr == '%') { 2490 file_magwarn(ms, 2491 "Too many format strings (should have at most one) " 2492 "for `%s' with description `%s'", 2493 file_names[m->type], m->desc); 2494 return -1; 2495 } 2496 } 2497 return 0; 2498 } 2499 2500 /* 2501 * Read a numeric value from a pointer, into the value union of a magic 2502 * pointer, according to the magic type. Update the string pointer to point 2503 * just after the number read. Return 0 for success, non-zero for failure. 2504 */ 2505 private int 2506 getvalue(struct magic_set *ms, struct magic *m, const char **p, int action) 2507 { 2508 switch (m->type) { 2509 case FILE_BESTRING16: 2510 case FILE_LESTRING16: 2511 case FILE_STRING: 2512 case FILE_PSTRING: 2513 case FILE_REGEX: 2514 case FILE_SEARCH: 2515 case FILE_NAME: 2516 case FILE_USE: 2517 *p = getstr(ms, m, *p, action == FILE_COMPILE); 2518 if (*p == NULL) { 2519 if (ms->flags & MAGIC_CHECK) 2520 file_magwarn(ms, "cannot get string from `%s'", 2521 m->value.s); 2522 return -1; 2523 } 2524 if (m->type == FILE_REGEX) { 2525 file_regex_t rx; 2526 int rc = file_regcomp(&rx, m->value.s, REG_EXTENDED); 2527 if (rc) { 2528 if (ms->flags & MAGIC_CHECK) 2529 file_regerror(&rx, rc, ms); 2530 } 2531 file_regfree(&rx); 2532 return rc ? -1 : 0; 2533 } 2534 return 0; 2535 case FILE_FLOAT: 2536 case FILE_BEFLOAT: 2537 case FILE_LEFLOAT: 2538 if (m->reln != 'x') { 2539 char *ep; 2540 #ifdef HAVE_STRTOF 2541 m->value.f = strtof(*p, &ep); 2542 #else 2543 m->value.f = (float)strtod(*p, &ep); 2544 #endif 2545 *p = ep; 2546 } 2547 return 0; 2548 case FILE_DOUBLE: 2549 case FILE_BEDOUBLE: 2550 case FILE_LEDOUBLE: 2551 if (m->reln != 'x') { 2552 char *ep; 2553 m->value.d = strtod(*p, &ep); 2554 *p = ep; 2555 } 2556 return 0; 2557 default: 2558 if (m->reln != 'x') { 2559 char *ep; 2560 m->value.q = file_signextend(ms, m, 2561 (uint64_t)strtoull(*p, &ep, 0)); 2562 *p = ep; 2563 eatsize(p); 2564 } 2565 return 0; 2566 } 2567 } 2568 2569 /* 2570 * Convert a string containing C character escapes. Stop at an unescaped 2571 * space or tab. 2572 * Copy the converted version to "m->value.s", and the length in m->vallen. 2573 * Return updated scan pointer as function result. Warn if set. 2574 */ 2575 private const char * 2576 getstr(struct magic_set *ms, struct magic *m, const char *s, int warn) 2577 { 2578 const char *origs = s; 2579 char *p = m->value.s; 2580 size_t plen = sizeof(m->value.s); 2581 char *origp = p; 2582 char *pmax = p + plen - 1; 2583 int c; 2584 int val; 2585 2586 while ((c = *s++) != '\0') { 2587 if (isspace((unsigned char) c)) 2588 break; 2589 if (p >= pmax) { 2590 file_error(ms, 0, "string too long: `%s'", origs); 2591 return NULL; 2592 } 2593 if (c == '\\') { 2594 switch(c = *s++) { 2595 2596 case '\0': 2597 if (warn) 2598 file_magwarn(ms, "incomplete escape"); 2599 goto out; 2600 2601 case '\t': 2602 if (warn) { 2603 file_magwarn(ms, 2604 "escaped tab found, use \\t instead"); 2605 warn = 0; /* already did */ 2606 } 2607 /*FALLTHROUGH*/ 2608 default: 2609 if (warn) { 2610 if (isprint((unsigned char)c)) { 2611 /* Allow escaping of 2612 * ``relations'' */ 2613 if (strchr("<>&^=!", c) == NULL 2614 && (m->type != FILE_REGEX || 2615 strchr("[]().*?^$|{}", c) 2616 == NULL)) { 2617 file_magwarn(ms, "no " 2618 "need to escape " 2619 "`%c'", c); 2620 } 2621 } else { 2622 file_magwarn(ms, 2623 "unknown escape sequence: " 2624 "\\%03o", c); 2625 } 2626 } 2627 /*FALLTHROUGH*/ 2628 /* space, perhaps force people to use \040? */ 2629 case ' ': 2630 #if 0 2631 /* 2632 * Other things people escape, but shouldn't need to, 2633 * so we disallow them 2634 */ 2635 case '\'': 2636 case '"': 2637 case '?': 2638 #endif 2639 /* Relations */ 2640 case '>': 2641 case '<': 2642 case '&': 2643 case '^': 2644 case '=': 2645 case '!': 2646 /* and baskslash itself */ 2647 case '\\': 2648 *p++ = (char) c; 2649 break; 2650 2651 case 'a': 2652 *p++ = '\a'; 2653 break; 2654 2655 case 'b': 2656 *p++ = '\b'; 2657 break; 2658 2659 case 'f': 2660 *p++ = '\f'; 2661 break; 2662 2663 case 'n': 2664 *p++ = '\n'; 2665 break; 2666 2667 case 'r': 2668 *p++ = '\r'; 2669 break; 2670 2671 case 't': 2672 *p++ = '\t'; 2673 break; 2674 2675 case 'v': 2676 *p++ = '\v'; 2677 break; 2678 2679 /* \ and up to 3 octal digits */ 2680 case '0': 2681 case '1': 2682 case '2': 2683 case '3': 2684 case '4': 2685 case '5': 2686 case '6': 2687 case '7': 2688 val = c - '0'; 2689 c = *s++; /* try for 2 */ 2690 if (c >= '0' && c <= '7') { 2691 val = (val << 3) | (c - '0'); 2692 c = *s++; /* try for 3 */ 2693 if (c >= '0' && c <= '7') 2694 val = (val << 3) | (c-'0'); 2695 else 2696 --s; 2697 } 2698 else 2699 --s; 2700 *p++ = (char)val; 2701 break; 2702 2703 /* \x and up to 2 hex digits */ 2704 case 'x': 2705 val = 'x'; /* Default if no digits */ 2706 c = hextoint(*s++); /* Get next char */ 2707 if (c >= 0) { 2708 val = c; 2709 c = hextoint(*s++); 2710 if (c >= 0) 2711 val = (val << 4) + c; 2712 else 2713 --s; 2714 } else 2715 --s; 2716 *p++ = (char)val; 2717 break; 2718 } 2719 } else 2720 *p++ = (char)c; 2721 } 2722 out: 2723 *p = '\0'; 2724 m->vallen = CAST(unsigned char, (p - origp)); 2725 if (m->type == FILE_PSTRING) 2726 m->vallen += (unsigned char)file_pstring_length_size(m); 2727 return s; 2728 } 2729 2730 2731 /* Single hex char to int; -1 if not a hex char. */ 2732 private int 2733 hextoint(int c) 2734 { 2735 if (!isascii((unsigned char) c)) 2736 return -1; 2737 if (isdigit((unsigned char) c)) 2738 return c - '0'; 2739 if ((c >= 'a') && (c <= 'f')) 2740 return c + 10 - 'a'; 2741 if (( c>= 'A') && (c <= 'F')) 2742 return c + 10 - 'A'; 2743 return -1; 2744 } 2745 2746 2747 /* 2748 * Print a string containing C character escapes. 2749 */ 2750 protected void 2751 file_showstr(FILE *fp, const char *s, size_t len) 2752 { 2753 char c; 2754 2755 for (;;) { 2756 if (len == ~0U) { 2757 c = *s++; 2758 if (c == '\0') 2759 break; 2760 } 2761 else { 2762 if (len-- == 0) 2763 break; 2764 c = *s++; 2765 } 2766 if (c >= 040 && c <= 0176) /* TODO isprint && !iscntrl */ 2767 (void) fputc(c, fp); 2768 else { 2769 (void) fputc('\\', fp); 2770 switch (c) { 2771 case '\a': 2772 (void) fputc('a', fp); 2773 break; 2774 2775 case '\b': 2776 (void) fputc('b', fp); 2777 break; 2778 2779 case '\f': 2780 (void) fputc('f', fp); 2781 break; 2782 2783 case '\n': 2784 (void) fputc('n', fp); 2785 break; 2786 2787 case '\r': 2788 (void) fputc('r', fp); 2789 break; 2790 2791 case '\t': 2792 (void) fputc('t', fp); 2793 break; 2794 2795 case '\v': 2796 (void) fputc('v', fp); 2797 break; 2798 2799 default: 2800 (void) fprintf(fp, "%.3o", c & 0377); 2801 break; 2802 } 2803 } 2804 } 2805 } 2806 2807 /* 2808 * eatsize(): Eat the size spec from a number [eg. 10UL] 2809 */ 2810 private void 2811 eatsize(const char **p) 2812 { 2813 const char *l = *p; 2814 2815 if (LOWCASE(*l) == 'u') 2816 l++; 2817 2818 switch (LOWCASE(*l)) { 2819 case 'l': /* long */ 2820 case 's': /* short */ 2821 case 'h': /* short */ 2822 case 'b': /* char/byte */ 2823 case 'c': /* char/byte */ 2824 l++; 2825 /*FALLTHROUGH*/ 2826 default: 2827 break; 2828 } 2829 2830 *p = l; 2831 } 2832 2833 /* 2834 * handle a buffer containing a compiled file. 2835 */ 2836 private struct magic_map * 2837 apprentice_buf(struct magic_set *ms, struct magic *buf, size_t len) 2838 { 2839 struct magic_map *map; 2840 2841 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) { 2842 file_oomem(ms, sizeof(*map)); 2843 return NULL; 2844 } 2845 map->len = len; 2846 map->p = buf; 2847 map->type = MAP_TYPE_USER; 2848 if (check_buffer(ms, map, "buffer") != 0) { 2849 apprentice_unmap(map); 2850 return NULL; 2851 } 2852 return map; 2853 } 2854 2855 /* 2856 * handle a compiled file. 2857 */ 2858 2859 private struct magic_map * 2860 apprentice_map(struct magic_set *ms, const char *fn) 2861 { 2862 int fd; 2863 struct stat st; 2864 char *dbname = NULL; 2865 struct magic_map *map; 2866 2867 fd = -1; 2868 if ((map = CAST(struct magic_map *, calloc(1, sizeof(*map)))) == NULL) { 2869 file_oomem(ms, sizeof(*map)); 2870 goto error; 2871 } 2872 2873 dbname = mkdbname(ms, fn, 0); 2874 if (dbname == NULL) 2875 goto error; 2876 2877 if ((fd = open(dbname, O_RDONLY|O_BINARY)) == -1) 2878 goto error; 2879 2880 if (fstat(fd, &st) == -1) { 2881 file_error(ms, errno, "cannot stat `%s'", dbname); 2882 goto error; 2883 } 2884 if (st.st_size < 8 || st.st_size > MAXMAGIC_SIZE) { 2885 file_error(ms, 0, "file `%s' is too %s", dbname, 2886 st.st_size < 8 ? "small" : "large"); 2887 goto error; 2888 } 2889 2890 map->len = (size_t)st.st_size; 2891 #ifdef QUICK 2892 if ((map->p = mmap(0, (size_t)st.st_size, PROT_READ|PROT_WRITE, 2893 MAP_PRIVATE|MAP_FILE, fd, (off_t)0)) == MAP_FAILED) { 2894 file_error(ms, errno, "cannot map `%s'", dbname); 2895 goto error; 2896 } 2897 map->type = MAP_TYPE_MMAP; 2898 #else 2899 if ((map->p = CAST(void *, malloc(map->len))) == NULL) { 2900 file_oomem(ms, map->len); 2901 goto error; 2902 } 2903 if (read(fd, map->p, map->len) != (ssize_t)map->len) { 2904 file_badread(ms); 2905 goto error; 2906 } 2907 map->type = MAP_TYPE_MALLOC; 2908 #define RET 1 2909 #endif 2910 (void)close(fd); 2911 fd = -1; 2912 2913 if (check_buffer(ms, map, dbname) != 0) 2914 goto error; 2915 2916 free(dbname); 2917 return map; 2918 2919 error: 2920 if (fd != -1) 2921 (void)close(fd); 2922 apprentice_unmap(map); 2923 free(dbname); 2924 return NULL; 2925 } 2926 2927 private int 2928 check_buffer(struct magic_set *ms, struct magic_map *map, const char *dbname) 2929 { 2930 uint32_t *ptr; 2931 uint32_t entries, nentries; 2932 uint32_t version; 2933 int i, needsbyteswap; 2934 2935 ptr = CAST(uint32_t *, map->p); 2936 if (*ptr != MAGICNO) { 2937 if (swap4(*ptr) != MAGICNO) { 2938 file_error(ms, 0, "bad magic in `%s'", dbname); 2939 return -1; 2940 } 2941 needsbyteswap = 1; 2942 } else 2943 needsbyteswap = 0; 2944 if (needsbyteswap) 2945 version = swap4(ptr[1]); 2946 else 2947 version = ptr[1]; 2948 if (version != VERSIONNO) { 2949 file_error(ms, 0, "File %s supports only version %d magic " 2950 "files. `%s' is version %d", VERSION, 2951 VERSIONNO, dbname, version); 2952 return -1; 2953 } 2954 entries = (uint32_t)(map->len / sizeof(struct magic)); 2955 if ((entries * sizeof(struct magic)) != map->len) { 2956 file_error(ms, 0, "Size of `%s' %" SIZE_T_FORMAT "u is not " 2957 "a multiple of %" SIZE_T_FORMAT "u", 2958 dbname, map->len, sizeof(struct magic)); 2959 return -1; 2960 } 2961 map->magic[0] = CAST(struct magic *, map->p) + 1; 2962 nentries = 0; 2963 for (i = 0; i < MAGIC_SETS; i++) { 2964 if (needsbyteswap) 2965 map->nmagic[i] = swap4(ptr[i + 2]); 2966 else 2967 map->nmagic[i] = ptr[i + 2]; 2968 if (i != MAGIC_SETS - 1) 2969 map->magic[i + 1] = map->magic[i] + map->nmagic[i]; 2970 nentries += map->nmagic[i]; 2971 } 2972 if (entries != nentries + 1) { 2973 file_error(ms, 0, "Inconsistent entries in `%s' %u != %u", 2974 dbname, entries, nentries + 1); 2975 return -1; 2976 } 2977 if (needsbyteswap) 2978 for (i = 0; i < MAGIC_SETS; i++) 2979 byteswap(map->magic[i], map->nmagic[i]); 2980 return 0; 2981 } 2982 2983 /* 2984 * handle an mmaped file. 2985 */ 2986 private int 2987 apprentice_compile(struct magic_set *ms, struct magic_map *map, const char *fn) 2988 { 2989 static const size_t nm = sizeof(*map->nmagic) * MAGIC_SETS; 2990 static const size_t m = sizeof(**map->magic); 2991 int fd = -1; 2992 size_t len; 2993 char *dbname; 2994 int rv = -1; 2995 uint32_t i; 2996 union { 2997 struct magic m; 2998 uint32_t h[2 + MAGIC_SETS]; 2999 } hdr; 3000 3001 dbname = mkdbname(ms, fn, 1); 3002 3003 if (dbname == NULL) 3004 goto out; 3005 3006 if ((fd = open(dbname, O_WRONLY|O_CREAT|O_TRUNC|O_BINARY, 0644)) == -1) 3007 { 3008 file_error(ms, errno, "cannot open `%s'", dbname); 3009 goto out; 3010 } 3011 memset(&hdr, 0, sizeof(hdr)); 3012 hdr.h[0] = MAGICNO; 3013 hdr.h[1] = VERSIONNO; 3014 memcpy(hdr.h + 2, map->nmagic, nm); 3015 3016 if (write(fd, &hdr, sizeof(hdr)) != (ssize_t)sizeof(hdr)) { 3017 file_error(ms, errno, "error writing `%s'", dbname); 3018 goto out; 3019 } 3020 3021 for (i = 0; i < MAGIC_SETS; i++) { 3022 len = m * map->nmagic[i]; 3023 if (write(fd, map->magic[i], len) != (ssize_t)len) { 3024 file_error(ms, errno, "error writing `%s'", dbname); 3025 goto out; 3026 } 3027 } 3028 3029 if (fd != -1) 3030 (void)close(fd); 3031 rv = 0; 3032 out: 3033 free(dbname); 3034 return rv; 3035 } 3036 3037 private const char ext[] = ".mgc"; 3038 /* 3039 * make a dbname 3040 */ 3041 private char * 3042 mkdbname(struct magic_set *ms, const char *fn, int strip) 3043 { 3044 const char *p, *q; 3045 char *buf; 3046 3047 if (strip) { 3048 if ((p = strrchr(fn, '/')) != NULL) 3049 fn = ++p; 3050 } 3051 3052 for (q = fn; *q; q++) 3053 continue; 3054 /* Look for .mgc */ 3055 for (p = ext + sizeof(ext) - 1; p >= ext && q >= fn; p--, q--) 3056 if (*p != *q) 3057 break; 3058 3059 /* Did not find .mgc, restore q */ 3060 if (p >= ext) 3061 while (*q) 3062 q++; 3063 3064 q++; 3065 /* Compatibility with old code that looked in .mime */ 3066 if (ms->flags & MAGIC_MIME) { 3067 if (asprintf(&buf, "%.*s.mime%s", (int)(q - fn), fn, ext) < 0) 3068 return NULL; 3069 if (access(buf, R_OK) != -1) { 3070 ms->flags &= MAGIC_MIME_TYPE; 3071 return buf; 3072 } 3073 free(buf); 3074 } 3075 if (asprintf(&buf, "%.*s%s", (int)(q - fn), fn, ext) < 0) 3076 return NULL; 3077 3078 /* Compatibility with old code that looked in .mime */ 3079 if (strstr(p, ".mime") != NULL) 3080 ms->flags &= MAGIC_MIME_TYPE; 3081 return buf; 3082 } 3083 3084 /* 3085 * Byteswap an mmap'ed file if needed 3086 */ 3087 private void 3088 byteswap(struct magic *magic, uint32_t nmagic) 3089 { 3090 uint32_t i; 3091 for (i = 0; i < nmagic; i++) 3092 bs1(&magic[i]); 3093 } 3094 3095 /* 3096 * swap a short 3097 */ 3098 private uint16_t 3099 swap2(uint16_t sv) 3100 { 3101 uint16_t rv; 3102 uint8_t *s = (uint8_t *)(void *)&sv; 3103 uint8_t *d = (uint8_t *)(void *)&rv; 3104 d[0] = s[1]; 3105 d[1] = s[0]; 3106 return rv; 3107 } 3108 3109 /* 3110 * swap an int 3111 */ 3112 private uint32_t 3113 swap4(uint32_t sv) 3114 { 3115 uint32_t rv; 3116 uint8_t *s = (uint8_t *)(void *)&sv; 3117 uint8_t *d = (uint8_t *)(void *)&rv; 3118 d[0] = s[3]; 3119 d[1] = s[2]; 3120 d[2] = s[1]; 3121 d[3] = s[0]; 3122 return rv; 3123 } 3124 3125 /* 3126 * swap a quad 3127 */ 3128 private uint64_t 3129 swap8(uint64_t sv) 3130 { 3131 uint64_t rv; 3132 uint8_t *s = (uint8_t *)(void *)&sv; 3133 uint8_t *d = (uint8_t *)(void *)&rv; 3134 #if 0 3135 d[0] = s[3]; 3136 d[1] = s[2]; 3137 d[2] = s[1]; 3138 d[3] = s[0]; 3139 d[4] = s[7]; 3140 d[5] = s[6]; 3141 d[6] = s[5]; 3142 d[7] = s[4]; 3143 #else 3144 d[0] = s[7]; 3145 d[1] = s[6]; 3146 d[2] = s[5]; 3147 d[3] = s[4]; 3148 d[4] = s[3]; 3149 d[5] = s[2]; 3150 d[6] = s[1]; 3151 d[7] = s[0]; 3152 #endif 3153 return rv; 3154 } 3155 3156 /* 3157 * byteswap a single magic entry 3158 */ 3159 private void 3160 bs1(struct magic *m) 3161 { 3162 m->cont_level = swap2(m->cont_level); 3163 m->offset = swap4((uint32_t)m->offset); 3164 m->in_offset = swap4((uint32_t)m->in_offset); 3165 m->lineno = swap4((uint32_t)m->lineno); 3166 if (IS_STRING(m->type)) { 3167 m->str_range = swap4(m->str_range); 3168 m->str_flags = swap4(m->str_flags); 3169 } 3170 else { 3171 m->value.q = swap8(m->value.q); 3172 m->num_mask = swap8(m->num_mask); 3173 } 3174 } 3175 3176 protected size_t 3177 file_pstring_length_size(const struct magic *m) 3178 { 3179 switch (m->str_flags & PSTRING_LEN) { 3180 case PSTRING_1_LE: 3181 return 1; 3182 case PSTRING_2_LE: 3183 case PSTRING_2_BE: 3184 return 2; 3185 case PSTRING_4_LE: 3186 case PSTRING_4_BE: 3187 return 4; 3188 default: 3189 abort(); /* Impossible */ 3190 return 1; 3191 } 3192 } 3193 protected size_t 3194 file_pstring_get_length(const struct magic *m, const char *s) 3195 { 3196 size_t len = 0; 3197 3198 switch (m->str_flags & PSTRING_LEN) { 3199 case PSTRING_1_LE: 3200 len = *s; 3201 break; 3202 case PSTRING_2_LE: 3203 len = (s[1] << 8) | s[0]; 3204 break; 3205 case PSTRING_2_BE: 3206 len = (s[0] << 8) | s[1]; 3207 break; 3208 case PSTRING_4_LE: 3209 len = (s[3] << 24) | (s[2] << 16) | (s[1] << 8) | s[0]; 3210 break; 3211 case PSTRING_4_BE: 3212 len = (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3]; 3213 break; 3214 default: 3215 abort(); /* Impossible */ 3216 } 3217 3218 if (m->str_flags & PSTRING_LENGTH_INCLUDES_ITSELF) 3219 len -= file_pstring_length_size(m); 3220 3221 return len; 3222 } 3223 3224 protected int 3225 file_magicfind(struct magic_set *ms, const char *name, struct mlist *v) 3226 { 3227 uint32_t i, j; 3228 struct mlist *mlist, *ml; 3229 3230 mlist = ms->mlist[1]; 3231 3232 for (ml = mlist->next; ml != mlist; ml = ml->next) { 3233 struct magic *ma = ml->magic; 3234 uint32_t nma = ml->nmagic; 3235 for (i = 0; i < nma; i++) { 3236 if (ma[i].type != FILE_NAME) 3237 continue; 3238 if (strcmp(ma[i].value.s, name) == 0) { 3239 v->magic = &ma[i]; 3240 for (j = i + 1; j < nma; j++) 3241 if (ma[j].cont_level == 0) 3242 break; 3243 v->nmagic = j - i; 3244 return 0; 3245 } 3246 } 3247 } 3248 return -1; 3249 } 3250