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.125 2026/01/19 18:53:58 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 file_private void close_and_restore(const struct magic_set *, const char *, int, 73 const struct stat *); 74 file_private int unreadable_info(struct magic_set *, mode_t, const char *); 75 file_private const char* get_default_magic(void); 76 #ifndef COMPILE_ONLY 77 file_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 file_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%c%s", hmagicpath, PATHSEP, 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 /* Before anything else, try to get a magic file from user HOME */ 225 if ((home = getenv("HOME")) != NULL) 226 _w32_append_path(&hmagicpath, "%s%s", home, hmagic); 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 file_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 file_public struct magic_set * 267 magic_open(int flags) 268 { 269 return file_ms_alloc(flags); 270 } 271 272 file_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 #ifndef WIN32 281 if (access(file, X_OK) == 0) 282 if (file_printf(ms, "executable, ") == -1) 283 return -1; 284 #else 285 /* X_OK doesn't work well on MS-Windows */ 286 { 287 const char *p = strrchr(file, '.'); 288 if (p && (stricmp(p, ".exe") 289 || stricmp(p, ".dll") 290 || stricmp(p, ".bat") 291 || stricmp(p, ".cmd"))) 292 if (file_printf(ms, "writable, ") == -1) 293 return -1; 294 } 295 #endif 296 } 297 if (S_ISREG(md)) 298 if (file_printf(ms, "regular file, ") == -1) 299 return -1; 300 if (file_printf(ms, "no read permission") == -1) 301 return -1; 302 return 0; 303 } 304 305 file_public void 306 magic_close(struct magic_set *ms) 307 { 308 if (ms == NULL) 309 return; 310 file_ms_free(ms); 311 } 312 313 /* 314 * load a magic file 315 */ 316 file_public int 317 magic_load(struct magic_set *ms, const char *magicfile) 318 { 319 if (ms == NULL) 320 return -1; 321 return file_apprentice(ms, magicfile, FILE_LOAD); 322 } 323 324 #ifndef COMPILE_ONLY 325 /* 326 * Install a set of compiled magic buffers. 327 */ 328 file_public int 329 magic_load_buffers(struct magic_set *ms, void **bufs, size_t *sizes, 330 size_t nbufs) 331 { 332 if (ms == NULL) 333 return -1; 334 return buffer_apprentice(ms, RCAST(struct magic **, bufs), 335 sizes, nbufs); 336 } 337 #endif 338 339 file_public int 340 magic_compile(struct magic_set *ms, const char *magicfile) 341 { 342 if (ms == NULL) 343 return -1; 344 return file_apprentice(ms, magicfile, FILE_COMPILE); 345 } 346 347 file_public int 348 magic_check(struct magic_set *ms, const char *magicfile) 349 { 350 if (ms == NULL) 351 return -1; 352 return file_apprentice(ms, magicfile, FILE_CHECK); 353 } 354 355 file_public int 356 magic_list(struct magic_set *ms, const char *magicfile) 357 { 358 if (ms == NULL) 359 return -1; 360 return file_apprentice(ms, magicfile, FILE_LIST); 361 } 362 363 file_private void 364 close_and_restore(const struct magic_set *ms, const char *name, int fd, 365 const struct stat *sb) 366 { 367 if (fd == STDIN_FILENO || name == NULL) 368 return; 369 (void) close(fd); 370 371 if (sb == NULL || (ms->flags & MAGIC_PRESERVE_ATIME) == 0) 372 return; 373 374 /* 375 * Try to restore access, modification times if read it. 376 * This is really *bad* because it will modify the status 377 * time of the file... And of course this will affect 378 * backup programs 379 */ 380 #ifdef HAVE_UTIMES 381 struct timeval utsbuf[2]; 382 (void)memset(utsbuf, 0, sizeof(utsbuf)); 383 utsbuf[0].tv_sec = sb->st_atime; 384 utsbuf[1].tv_sec = sb->st_mtime; 385 386 (void) utimes(name, utsbuf); /* don't care if loses */ 387 #elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H) 388 struct utimbuf utbuf; 389 390 (void)memset(&utbuf, 0, sizeof(utbuf)); 391 utbuf.actime = sb->st_atime; 392 utbuf.modtime = sb->st_mtime; 393 (void) utime(name, &utbuf); /* don't care if loses */ 394 #endif 395 } 396 397 #ifndef COMPILE_ONLY 398 399 /* 400 * find type of descriptor 401 */ 402 file_public const char * 403 magic_descriptor(struct magic_set *ms, int fd) 404 { 405 if (ms == NULL) 406 return NULL; 407 return file_or_fd(ms, NULL, fd); 408 } 409 410 /* 411 * find type of named file 412 */ 413 file_public const char * 414 magic_file(struct magic_set *ms, const char *inname) 415 { 416 if (ms == NULL) 417 return NULL; 418 return file_or_fd(ms, inname, STDIN_FILENO); 419 } 420 421 file_private const char * 422 file_or_fd(struct magic_set *ms, const char *inname, int fd) 423 { 424 int rv = -1; 425 unsigned char *buf; 426 struct stat sb; 427 ssize_t nbytes = 0; /* number of bytes read from a datafile */ 428 int ispipe = 0; 429 int okstat = 0; 430 off_t pos = CAST(off_t, -1); 431 432 if (file_reset(ms, 1) == -1) 433 goto out; 434 435 /* 436 * one extra for terminating '\0', and 437 * some overlapping space for matches near EOF 438 */ 439 #define SLOP (1 + sizeof(union VALUETYPE)) 440 if ((buf = CAST(unsigned char *, malloc(ms->bytes_max + SLOP))) == NULL) 441 return NULL; 442 443 switch (file_fsmagic(ms, inname, &sb)) { 444 case -1: /* error */ 445 goto done; 446 case 0: /* nothing found */ 447 break; 448 default: /* matched it and printed type */ 449 rv = 0; 450 goto done; 451 } 452 453 #ifdef WIN32 454 /* Place stdin in binary mode, so EOF (Ctrl+Z) doesn't stop early. */ 455 if (fd == STDIN_FILENO) 456 _setmode(STDIN_FILENO, O_BINARY); 457 #endif 458 if (inname != NULL) { 459 int flags = O_RDONLY|O_BINARY|O_NONBLOCK|O_CLOEXEC; 460 errno = 0; 461 if ((fd = open(inname, flags)) < 0) { 462 okstat = stat(inname, &sb) == 0; 463 #ifdef WIN32 464 /* 465 * Can't stat, can't open. It may have been opened in 466 * fsmagic, so if the user doesn't have read permission, 467 * allow it to say so; otherwise an error was probably 468 * displayed in fsmagic. 469 */ 470 if (!okstat && errno == EACCES) { 471 sb.st_mode = S_IFBLK; 472 okstat = 1; 473 } 474 #endif 475 if (okstat && 476 unreadable_info(ms, sb.st_mode, inname) == -1) 477 goto done; 478 rv = 0; 479 goto done; 480 } 481 #if O_CLOEXEC == 0 && defined(F_SETFD) 482 (void)fcntl(fd, F_SETFD, FD_CLOEXEC); 483 #endif 484 } 485 486 if (fd != -1) { 487 okstat = fstat(fd, &sb) == 0; 488 if (okstat && S_ISFIFO(sb.st_mode)) 489 ispipe = 1; 490 if (inname == NULL) 491 pos = lseek(fd, CAST(off_t, 0), SEEK_CUR); 492 } 493 494 /* 495 * try looking at the first ms->bytes_max bytes 496 */ 497 if (ispipe) { 498 if (fd != -1) { 499 ssize_t r = 0; 500 501 while ((r = sread(fd, RCAST(void *, &buf[nbytes]), 502 CAST(size_t, ms->bytes_max - nbytes), 1)) > 0) { 503 nbytes += r; 504 if (r < PIPE_BUF) break; 505 } 506 } 507 508 if (nbytes == 0 && inname) { 509 /* We can not read it, but we were able to stat it. */ 510 if (unreadable_info(ms, sb.st_mode, inname) == -1) 511 goto done; 512 rv = 0; 513 goto done; 514 } 515 516 } else if (fd != -1) { 517 /* Windows refuses to read from a big console buffer. */ 518 size_t howmany = 519 #ifdef WIN32 520 _isatty(fd) ? 8 * 1024 : 521 #endif 522 ms->bytes_max; 523 if ((nbytes = read(fd, RCAST(void *, buf), howmany)) == -1) { 524 if (inname == NULL && fd != STDIN_FILENO) 525 file_error(ms, errno, "cannot read fd %d", fd); 526 else 527 file_error(ms, errno, "cannot read `%s'", 528 inname == NULL ? "/dev/stdin" : inname); 529 goto done; 530 } 531 } 532 533 (void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */ 534 if (file_buffer(ms, fd, okstat ? &sb : NULL, inname, buf, 535 CAST(size_t, nbytes)) == -1) 536 goto done; 537 rv = 0; 538 done: 539 free(buf); 540 if (fd != -1) { 541 if (pos != CAST(off_t, -1)) 542 (void)lseek(fd, pos, SEEK_SET); 543 close_and_restore(ms, inname, fd, okstat ? &sb : NULL); 544 } 545 out: 546 return rv == 0 ? file_getbuffer(ms) : NULL; 547 } 548 549 550 file_public const char * 551 magic_buffer(struct magic_set *ms, const void *buf, size_t nb) 552 { 553 if (ms == NULL) 554 return NULL; 555 if (file_reset(ms, 1) == -1) 556 return NULL; 557 /* 558 * The main work is done here! 559 * We have the file name and/or the data buffer to be identified. 560 */ 561 if (file_buffer(ms, -1, NULL, NULL, buf, nb) == -1) { 562 return NULL; 563 } 564 return file_getbuffer(ms); 565 } 566 #endif 567 568 file_public const char * 569 magic_error(struct magic_set *ms) 570 { 571 if (ms == NULL) 572 return "Magic database is not open"; 573 return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL; 574 } 575 576 file_public int 577 magic_errno(struct magic_set *ms) 578 { 579 if (ms == NULL) 580 return EINVAL; 581 return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0; 582 } 583 584 file_public int 585 magic_getflags(struct magic_set *ms) 586 { 587 if (ms == NULL) 588 return -1; 589 590 return ms->flags; 591 } 592 593 file_public int 594 magic_setflags(struct magic_set *ms, int flags) 595 { 596 if (ms == NULL) 597 return -1; 598 #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES) 599 if (flags & MAGIC_PRESERVE_ATIME) 600 return -1; 601 #endif 602 ms->flags = flags; 603 return 0; 604 } 605 606 file_public int 607 magic_version(void) 608 { 609 return MAGIC_VERSION; 610 } 611 612 file_public int 613 magic_setparam(struct magic_set *ms, int param, const void *val) 614 { 615 if (ms == NULL) 616 return -1; 617 const size_t v = *CAST(const size_t *, val); 618 switch (param) { 619 case MAGIC_PARAM_INDIR_MAX: 620 ms->indir_max = CAST(uint16_t, v); 621 return 0; 622 case MAGIC_PARAM_NAME_MAX: 623 ms->name_max = CAST(uint16_t, v); 624 return 0; 625 case MAGIC_PARAM_ELF_PHNUM_MAX: 626 ms->elf_phnum_max = CAST(uint16_t, v); 627 return 0; 628 case MAGIC_PARAM_ELF_SHNUM_MAX: 629 ms->elf_shnum_max = CAST(uint16_t, v); 630 return 0; 631 case MAGIC_PARAM_ELF_SHSIZE_MAX: 632 ms->elf_shsize_max = v; 633 return 0; 634 case MAGIC_PARAM_ELF_NOTES_MAX: 635 ms->elf_notes_max = CAST(uint16_t, v); 636 return 0; 637 case MAGIC_PARAM_REGEX_MAX: 638 ms->regex_max = CAST(uint16_t, v); 639 return 0; 640 case MAGIC_PARAM_BYTES_MAX: 641 ms->bytes_max = v; 642 return 0; 643 case MAGIC_PARAM_ENCODING_MAX: 644 ms->encoding_max = v; 645 return 0; 646 case MAGIC_PARAM_MAGWARN_MAX: 647 ms->magwarn_max = v; 648 return 0; 649 default: 650 errno = EINVAL; 651 return -1; 652 } 653 } 654 655 file_public int 656 magic_getparam(struct magic_set *ms, int param, void *val) 657 { 658 if (ms == NULL) 659 return -1; 660 switch (param) { 661 case MAGIC_PARAM_INDIR_MAX: 662 *CAST(size_t *, val) = ms->indir_max; 663 return 0; 664 case MAGIC_PARAM_NAME_MAX: 665 *CAST(size_t *, val) = ms->name_max; 666 return 0; 667 case MAGIC_PARAM_ELF_PHNUM_MAX: 668 *CAST(size_t *, val) = ms->elf_phnum_max; 669 return 0; 670 case MAGIC_PARAM_ELF_SHNUM_MAX: 671 *CAST(size_t *, val) = ms->elf_shnum_max; 672 return 0; 673 case MAGIC_PARAM_ELF_SHSIZE_MAX: 674 *CAST(size_t *, val) = ms->elf_shsize_max; 675 return 0; 676 case MAGIC_PARAM_ELF_NOTES_MAX: 677 *CAST(size_t *, val) = ms->elf_notes_max; 678 return 0; 679 case MAGIC_PARAM_REGEX_MAX: 680 *CAST(size_t *, val) = ms->regex_max; 681 return 0; 682 case MAGIC_PARAM_BYTES_MAX: 683 *CAST(size_t *, val) = ms->bytes_max; 684 return 0; 685 case MAGIC_PARAM_ENCODING_MAX: 686 *CAST(size_t *, val) = ms->encoding_max; 687 return 0; 688 case MAGIC_PARAM_MAGWARN_MAX: 689 *CAST(size_t *, val) = ms->magwarn_max; 690 return 0; 691 default: 692 errno = EINVAL; 693 return -1; 694 } 695 } 696