1 /* $NetBSD: magic.c,v 1.13 2018/10/19 00:11:48 christos Exp $ */ 2 3 /* 4 * Copyright (c) Christos Zoulas 2003. 5 * All Rights Reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice immediately at the beginning of the file, without modification, 12 * this list of conditions, and the following disclaimer. 13 * 2. Redistributions in binary form must reproduce the above copyright 14 * notice, this list of conditions and the following disclaimer in the 15 * documentation and/or other materials provided with the distribution. 16 * 17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 20 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR 21 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 27 * SUCH DAMAGE. 28 */ 29 30 #ifdef WIN32 31 #include <windows.h> 32 #include <shlwapi.h> 33 #endif 34 35 #include "file.h" 36 37 #ifndef lint 38 #if 0 39 FILE_RCSID("@(#)$File: magic.c,v 1.106 2018/10/01 18:45:39 christos Exp $") 40 #else 41 __RCSID("$NetBSD: magic.c,v 1.13 2018/10/19 00:11:48 christos Exp $"); 42 #endif 43 #endif /* lint */ 44 45 #include "magic.h" 46 47 #include <stdlib.h> 48 #include <unistd.h> 49 #include <string.h> 50 #ifdef QUICK 51 #include <sys/mman.h> 52 #endif 53 #include <limits.h> /* for PIPE_BUF */ 54 55 #if defined(HAVE_UTIMES) 56 # include <sys/time.h> 57 #elif defined(HAVE_UTIME) 58 # if defined(HAVE_SYS_UTIME_H) 59 # include <sys/utime.h> 60 # elif defined(HAVE_UTIME_H) 61 # include <utime.h> 62 # endif 63 #endif 64 65 #ifdef HAVE_UNISTD_H 66 #include <unistd.h> /* for read() */ 67 #endif 68 69 #ifndef PIPE_BUF 70 /* Get the PIPE_BUF from pathconf */ 71 #ifdef _PC_PIPE_BUF 72 #define PIPE_BUF pathconf(".", _PC_PIPE_BUF) 73 #else 74 #define PIPE_BUF 512 75 #endif 76 #endif 77 78 private void close_and_restore(const struct magic_set *, const char *, int, 79 const struct stat *); 80 private int unreadable_info(struct magic_set *, mode_t, const char *); 81 private const char* get_default_magic(void); 82 #ifndef COMPILE_ONLY 83 private const char *file_or_fd(struct magic_set *, const char *, int); 84 #endif 85 86 #ifndef STDIN_FILENO 87 #define STDIN_FILENO 0 88 #endif 89 90 #ifdef WIN32 91 /* HINSTANCE of this shared library. Needed for get_default_magic() */ 92 static HINSTANCE _w32_dll_instance = NULL; 93 94 static void 95 _w32_append_path(char **hmagicpath, const char *fmt, ...) 96 { 97 char *tmppath; 98 char *newpath; 99 va_list ap; 100 101 va_start(ap, fmt); 102 if (vasprintf(&tmppath, fmt, ap) < 0) { 103 va_end(ap); 104 return; 105 } 106 va_end(ap); 107 108 if (access(tmppath, R_OK) == -1) 109 goto out; 110 111 if (*hmagicpath == NULL) { 112 *hmagicpath = tmppath; 113 return; 114 } 115 116 if (asprintf(&newpath, "%s%c%s", *hmagicpath, PATHSEP, tmppath) < 0) 117 goto out; 118 119 free(*hmagicpath); 120 free(tmppath); 121 *hmagicpath = newpath; 122 return; 123 out: 124 free(tmppath); 125 } 126 127 static void 128 _w32_get_magic_relative_to(char **hmagicpath, HINSTANCE module) 129 { 130 static const char *trypaths[] = { 131 "%s/share/misc/magic.mgc", 132 "%s/magic.mgc", 133 }; 134 LPSTR dllpath; 135 size_t sp; 136 137 dllpath = calloc(MAX_PATH + 1, sizeof(*dllpath)); 138 139 if (!GetModuleFileNameA(module, dllpath, MAX_PATH)) 140 goto out; 141 142 PathRemoveFileSpecA(dllpath); 143 144 if (module) { 145 char exepath[MAX_PATH]; 146 GetModuleFileNameA(NULL, exepath, MAX_PATH); 147 PathRemoveFileSpecA(exepath); 148 if (stricmp(exepath, dllpath) == 0) 149 goto out; 150 } 151 152 sp = strlen(dllpath); 153 if (sp > 3 && stricmp(&dllpath[sp - 3], "bin") == 0) { 154 _w32_append_path(hmagicpath, 155 "%s/../share/misc/magic.mgc", dllpath); 156 goto out; 157 } 158 159 for (sp = 0; sp < __arraycount(trypaths); sp++) 160 _w32_append_path(hmagicpath, trypaths[sp], dllpath); 161 out: 162 free(dllpath); 163 } 164 165 /* Placate GCC by offering a sacrificial previous prototype */ 166 BOOL WINAPI DllMain(HINSTANCE, DWORD, LPVOID); 167 168 BOOL WINAPI 169 DllMain(HINSTANCE hinstDLL, DWORD fdwReason, 170 LPVOID lpvReserved __attribute__((__unused__))) 171 { 172 if (fdwReason == DLL_PROCESS_ATTACH) 173 _w32_dll_instance = hinstDLL; 174 return 1; 175 } 176 #endif 177 178 private const char * 179 get_default_magic(void) 180 { 181 static const char hmagic[] = "/.magic/magic.mgc"; 182 static char *default_magic; 183 char *home, *hmagicpath; 184 185 #ifndef WIN32 186 struct stat st; 187 188 if (default_magic) { 189 free(default_magic); 190 default_magic = NULL; 191 } 192 if ((home = getenv("HOME")) == NULL) 193 return MAGIC; 194 195 if (asprintf(&hmagicpath, "%s/.magic.mgc", home) < 0) 196 return MAGIC; 197 if (stat(hmagicpath, &st) == -1) { 198 free(hmagicpath); 199 if (asprintf(&hmagicpath, "%s/.magic", home) < 0) 200 return MAGIC; 201 if (stat(hmagicpath, &st) == -1) 202 goto out; 203 if (S_ISDIR(st.st_mode)) { 204 free(hmagicpath); 205 if (asprintf(&hmagicpath, "%s/%s", home, hmagic) < 0) 206 return MAGIC; 207 if (access(hmagicpath, R_OK) == -1) 208 goto out; 209 } 210 } 211 212 if (asprintf(&default_magic, "%s:%s", hmagicpath, MAGIC) < 0) 213 goto out; 214 free(hmagicpath); 215 return default_magic; 216 out: 217 default_magic = NULL; 218 free(hmagicpath); 219 return MAGIC; 220 #else 221 hmagicpath = NULL; 222 223 if (default_magic) { 224 free(default_magic); 225 default_magic = NULL; 226 } 227 228 /* First, try to get a magic file from user-application data */ 229 if ((home = getenv("LOCALAPPDATA")) != NULL) 230 _w32_append_path(&hmagicpath, "%s%s", home, hmagic); 231 232 /* Second, try to get a magic file from the user profile data */ 233 if ((home = getenv("USERPROFILE")) != NULL) 234 _w32_append_path(&hmagicpath, 235 "%s/Local Settings/Application Data%s", home, hmagic); 236 237 /* Third, try to get a magic file from Common Files */ 238 if ((home = getenv("COMMONPROGRAMFILES")) != NULL) 239 _w32_append_path(&hmagicpath, "%s%s", home, hmagic); 240 241 /* Fourth, try to get magic file relative to exe location */ 242 _w32_get_magic_relative_to(&hmagicpath, NULL); 243 244 /* Fifth, try to get magic file relative to dll location */ 245 _w32_get_magic_relative_to(&hmagicpath, _w32_dll_instance); 246 247 /* Avoid MAGIC constant - it likely points to a file within MSys tree */ 248 default_magic = hmagicpath; 249 return default_magic; 250 #endif 251 } 252 253 public const char * 254 magic_getpath(const char *magicfile, int action) 255 { 256 if (magicfile != NULL) 257 return magicfile; 258 259 magicfile = getenv("MAGIC"); 260 if (magicfile != NULL) 261 return magicfile; 262 263 return action == FILE_LOAD ? get_default_magic() : MAGIC; 264 } 265 266 public struct magic_set * 267 magic_open(int flags) 268 { 269 return file_ms_alloc(flags); 270 } 271 272 private int 273 unreadable_info(struct magic_set *ms, mode_t md, const char *file) 274 { 275 if (file) { 276 /* We cannot open it, but we were able to stat it. */ 277 if (access(file, W_OK) == 0) 278 if (file_printf(ms, "writable, ") == -1) 279 return -1; 280 if (access(file, X_OK) == 0) 281 if (file_printf(ms, "executable, ") == -1) 282 return -1; 283 } 284 if (S_ISREG(md)) 285 if (file_printf(ms, "regular file, ") == -1) 286 return -1; 287 if (file_printf(ms, "no read permission") == -1) 288 return -1; 289 return 0; 290 } 291 292 public void 293 magic_close(struct magic_set *ms) 294 { 295 if (ms == NULL) 296 return; 297 file_ms_free(ms); 298 } 299 300 /* 301 * load a magic file 302 */ 303 public int 304 magic_load(struct magic_set *ms, const char *magicfile) 305 { 306 if (ms == NULL) 307 return -1; 308 return file_apprentice(ms, magicfile, FILE_LOAD); 309 } 310 311 #ifndef COMPILE_ONLY 312 /* 313 * Install a set of compiled magic buffers. 314 */ 315 public int 316 magic_load_buffers(struct magic_set *ms, void **bufs, size_t *sizes, 317 size_t nbufs) 318 { 319 if (ms == NULL) 320 return -1; 321 return buffer_apprentice(ms, (struct magic **)bufs, sizes, nbufs); 322 } 323 #endif 324 325 public int 326 magic_compile(struct magic_set *ms, const char *magicfile) 327 { 328 if (ms == NULL) 329 return -1; 330 return file_apprentice(ms, magicfile, FILE_COMPILE); 331 } 332 333 public int 334 magic_check(struct magic_set *ms, const char *magicfile) 335 { 336 if (ms == NULL) 337 return -1; 338 return file_apprentice(ms, magicfile, FILE_CHECK); 339 } 340 341 public int 342 magic_list(struct magic_set *ms, const char *magicfile) 343 { 344 if (ms == NULL) 345 return -1; 346 return file_apprentice(ms, magicfile, FILE_LIST); 347 } 348 349 private void 350 close_and_restore(const struct magic_set *ms, const char *name, int fd, 351 const struct stat *sb) 352 { 353 if (fd == STDIN_FILENO || name == NULL) 354 return; 355 (void) close(fd); 356 357 if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) { 358 /* 359 * Try to restore access, modification times if read it. 360 * This is really *bad* because it will modify the status 361 * time of the file... And of course this will affect 362 * backup programs 363 */ 364 #ifdef HAVE_UTIMES 365 struct timeval utsbuf[2]; 366 (void)memset(utsbuf, 0, sizeof(utsbuf)); 367 utsbuf[0].tv_sec = sb->st_atime; 368 utsbuf[1].tv_sec = sb->st_mtime; 369 370 (void) utimes(name, utsbuf); /* don't care if loses */ 371 #elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H) 372 struct utimbuf utbuf; 373 374 (void)memset(&utbuf, 0, sizeof(utbuf)); 375 utbuf.actime = sb->st_atime; 376 utbuf.modtime = sb->st_mtime; 377 (void) utime(name, &utbuf); /* don't care if loses */ 378 #endif 379 } 380 } 381 382 #ifndef COMPILE_ONLY 383 384 /* 385 * find type of descriptor 386 */ 387 public const char * 388 magic_descriptor(struct magic_set *ms, int fd) 389 { 390 if (ms == NULL) 391 return NULL; 392 return file_or_fd(ms, NULL, fd); 393 } 394 395 /* 396 * find type of named file 397 */ 398 public const char * 399 magic_file(struct magic_set *ms, const char *inname) 400 { 401 if (ms == NULL) 402 return NULL; 403 return file_or_fd(ms, inname, STDIN_FILENO); 404 } 405 406 private const char * 407 file_or_fd(struct magic_set *ms, const char *inname, int fd) 408 { 409 int rv = -1; 410 unsigned char *buf; 411 struct stat sb; 412 ssize_t nbytes = 0; /* number of bytes read from a datafile */ 413 int ispipe = 0; 414 off_t pos = (off_t)-1; 415 416 if (file_reset(ms, 1) == -1) 417 goto out; 418 419 /* 420 * one extra for terminating '\0', and 421 * some overlapping space for matches near EOF 422 */ 423 #define SLOP (1 + sizeof(union VALUETYPE)) 424 if ((buf = CAST(unsigned char *, malloc(ms->bytes_max + SLOP))) == NULL) 425 return NULL; 426 427 switch (file_fsmagic(ms, inname, &sb)) { 428 case -1: /* error */ 429 goto done; 430 case 0: /* nothing found */ 431 break; 432 default: /* matched it and printed type */ 433 rv = 0; 434 goto done; 435 } 436 437 #ifdef WIN32 438 /* Place stdin in binary mode, so EOF (Ctrl+Z) doesn't stop early. */ 439 if (fd == STDIN_FILENO) 440 _setmode(STDIN_FILENO, O_BINARY); 441 #endif 442 if (inname != NULL) { 443 int flags = O_RDONLY|O_BINARY|O_NONBLOCK; 444 errno = 0; 445 if ((fd = open(inname, flags)) < 0) { 446 int okstat = stat(inname, &sb) == 0; 447 if (okstat && S_ISFIFO(sb.st_mode)) 448 ispipe = 1; 449 #ifdef WIN32 450 /* 451 * Can't stat, can't open. It may have been opened in 452 * fsmagic, so if the user doesn't have read permission, 453 * allow it to say so; otherwise an error was probably 454 * displayed in fsmagic. 455 */ 456 if (!okstat && errno == EACCES) { 457 sb.st_mode = S_IFBLK; 458 okstat = 1; 459 } 460 #endif 461 if (okstat && 462 unreadable_info(ms, sb.st_mode, inname) == -1) 463 goto done; 464 rv = 0; 465 goto done; 466 } 467 } 468 469 if (fd != -1) { 470 if (fstat(fd, &sb) == 0 && S_ISFIFO(sb.st_mode)) 471 ispipe = 1; 472 if (inname == NULL) 473 pos = lseek(fd, (off_t)0, SEEK_CUR); 474 } 475 476 /* 477 * try looking at the first ms->bytes_max bytes 478 */ 479 if (ispipe) { 480 ssize_t r = 0; 481 482 while ((r = sread(fd, (void *)&buf[nbytes], 483 (size_t)(ms->bytes_max - nbytes), 1)) > 0) { 484 nbytes += r; 485 if (r < PIPE_BUF) break; 486 } 487 488 if (nbytes == 0 && inname) { 489 /* We can not read it, but we were able to stat it. */ 490 if (unreadable_info(ms, sb.st_mode, inname) == -1) 491 goto done; 492 rv = 0; 493 goto done; 494 } 495 496 } else { 497 /* Windows refuses to read from a big console buffer. */ 498 size_t howmany = 499 #if defined(WIN32) 500 _isatty(fd) ? 8 * 1024 : 501 #endif 502 ms->bytes_max; 503 if ((nbytes = read(fd, (char *)buf, howmany)) == -1) { 504 if (inname == NULL && fd != STDIN_FILENO) 505 file_error(ms, errno, "cannot read fd %d", fd); 506 else 507 file_error(ms, errno, "cannot read `%s'", 508 inname == NULL ? "/dev/stdin" : inname); 509 goto done; 510 } 511 } 512 513 (void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */ 514 if (file_buffer(ms, fd, inname, buf, (size_t)nbytes) == -1) 515 goto done; 516 rv = 0; 517 done: 518 free(buf); 519 if (fd != -1) { 520 if (pos != (off_t)-1) 521 (void)lseek(fd, pos, SEEK_SET); 522 close_and_restore(ms, inname, fd, &sb); 523 } 524 out: 525 return rv == 0 ? file_getbuffer(ms) : NULL; 526 } 527 528 529 public const char * 530 magic_buffer(struct magic_set *ms, const void *buf, size_t nb) 531 { 532 if (ms == NULL) 533 return NULL; 534 if (file_reset(ms, 1) == -1) 535 return NULL; 536 /* 537 * The main work is done here! 538 * We have the file name and/or the data buffer to be identified. 539 */ 540 if (file_buffer(ms, -1, NULL, buf, nb) == -1) { 541 return NULL; 542 } 543 return file_getbuffer(ms); 544 } 545 #endif 546 547 public const char * 548 magic_error(struct magic_set *ms) 549 { 550 if (ms == NULL) 551 return "Magic database is not open"; 552 return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL; 553 } 554 555 public int 556 magic_errno(struct magic_set *ms) 557 { 558 if (ms == NULL) 559 return EINVAL; 560 return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0; 561 } 562 563 public int 564 magic_getflags(struct magic_set *ms) 565 { 566 if (ms == NULL) 567 return -1; 568 569 return ms->flags; 570 } 571 572 public int 573 magic_setflags(struct magic_set *ms, int flags) 574 { 575 if (ms == NULL) 576 return -1; 577 #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES) 578 if (flags & MAGIC_PRESERVE_ATIME) 579 return -1; 580 #endif 581 ms->flags = flags; 582 return 0; 583 } 584 585 public int 586 magic_version(void) 587 { 588 return MAGIC_VERSION; 589 } 590 591 public int 592 magic_setparam(struct magic_set *ms, int param, const void *val) 593 { 594 if (ms == NULL) 595 return -1; 596 switch (param) { 597 case MAGIC_PARAM_INDIR_MAX: 598 ms->indir_max = (uint16_t)*(const size_t *)val; 599 return 0; 600 case MAGIC_PARAM_NAME_MAX: 601 ms->name_max = (uint16_t)*(const size_t *)val; 602 return 0; 603 case MAGIC_PARAM_ELF_PHNUM_MAX: 604 ms->elf_phnum_max = (uint16_t)*(const size_t *)val; 605 return 0; 606 case MAGIC_PARAM_ELF_SHNUM_MAX: 607 ms->elf_shnum_max = (uint16_t)*(const size_t *)val; 608 return 0; 609 case MAGIC_PARAM_ELF_NOTES_MAX: 610 ms->elf_notes_max = (uint16_t)*(const size_t *)val; 611 return 0; 612 case MAGIC_PARAM_REGEX_MAX: 613 ms->elf_notes_max = (uint16_t)*(const size_t *)val; 614 return 0; 615 case MAGIC_PARAM_BYTES_MAX: 616 ms->bytes_max = *(const size_t *)val; 617 return 0; 618 default: 619 errno = EINVAL; 620 return -1; 621 } 622 } 623 624 public int 625 magic_getparam(struct magic_set *ms, int param, void *val) 626 { 627 if (ms == NULL) 628 return -1; 629 switch (param) { 630 case MAGIC_PARAM_INDIR_MAX: 631 *(size_t *)val = ms->indir_max; 632 return 0; 633 case MAGIC_PARAM_NAME_MAX: 634 *(size_t *)val = ms->name_max; 635 return 0; 636 case MAGIC_PARAM_ELF_PHNUM_MAX: 637 *(size_t *)val = ms->elf_phnum_max; 638 return 0; 639 case MAGIC_PARAM_ELF_SHNUM_MAX: 640 *(size_t *)val = ms->elf_shnum_max; 641 return 0; 642 case MAGIC_PARAM_ELF_NOTES_MAX: 643 *(size_t *)val = ms->elf_notes_max; 644 return 0; 645 case MAGIC_PARAM_REGEX_MAX: 646 *(size_t *)val = ms->regex_max; 647 return 0; 648 case MAGIC_PARAM_BYTES_MAX: 649 *(size_t *)val = ms->bytes_max; 650 return 0; 651 default: 652 errno = EINVAL; 653 return -1; 654 } 655 } 656