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