magic.c 15 KB

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