magic.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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.106 2018/10/01 18:45:39 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, (struct magic **)bufs, sizes, nbufs);
  270. }
  271. #endif
  272. public int
  273. magic_compile(struct magic_set *ms, const char *magicfile)
  274. {
  275. if (ms == NULL)
  276. return -1;
  277. return file_apprentice(ms, magicfile, FILE_COMPILE);
  278. }
  279. public int
  280. magic_check(struct magic_set *ms, const char *magicfile)
  281. {
  282. if (ms == NULL)
  283. return -1;
  284. return file_apprentice(ms, magicfile, FILE_CHECK);
  285. }
  286. public int
  287. magic_list(struct magic_set *ms, const char *magicfile)
  288. {
  289. if (ms == NULL)
  290. return -1;
  291. return file_apprentice(ms, magicfile, FILE_LIST);
  292. }
  293. private void
  294. close_and_restore(const struct magic_set *ms, const char *name, int fd,
  295. const struct stat *sb)
  296. {
  297. if (fd == STDIN_FILENO || name == NULL)
  298. return;
  299. (void) close(fd);
  300. if ((ms->flags & MAGIC_PRESERVE_ATIME) != 0) {
  301. /*
  302. * Try to restore access, modification times if read it.
  303. * This is really *bad* because it will modify the status
  304. * time of the file... And of course this will affect
  305. * backup programs
  306. */
  307. #ifdef HAVE_UTIMES
  308. struct timeval utsbuf[2];
  309. (void)memset(utsbuf, 0, sizeof(utsbuf));
  310. utsbuf[0].tv_sec = sb->st_atime;
  311. utsbuf[1].tv_sec = sb->st_mtime;
  312. (void) utimes(name, utsbuf); /* don't care if loses */
  313. #elif defined(HAVE_UTIME_H) || defined(HAVE_SYS_UTIME_H)
  314. struct utimbuf utbuf;
  315. (void)memset(&utbuf, 0, sizeof(utbuf));
  316. utbuf.actime = sb->st_atime;
  317. utbuf.modtime = sb->st_mtime;
  318. (void) utime(name, &utbuf); /* don't care if loses */
  319. #endif
  320. }
  321. }
  322. #ifndef COMPILE_ONLY
  323. /*
  324. * find type of descriptor
  325. */
  326. public const char *
  327. magic_descriptor(struct magic_set *ms, int fd)
  328. {
  329. if (ms == NULL)
  330. return NULL;
  331. return file_or_fd(ms, NULL, fd);
  332. }
  333. /*
  334. * find type of named file
  335. */
  336. public const char *
  337. magic_file(struct magic_set *ms, const char *inname)
  338. {
  339. if (ms == NULL)
  340. return NULL;
  341. return file_or_fd(ms, inname, STDIN_FILENO);
  342. }
  343. private const char *
  344. file_or_fd(struct magic_set *ms, const char *inname, int fd)
  345. {
  346. int rv = -1;
  347. unsigned char *buf;
  348. struct stat sb;
  349. ssize_t nbytes = 0; /* number of bytes read from a datafile */
  350. int ispipe = 0;
  351. off_t pos = (off_t)-1;
  352. if (file_reset(ms, 1) == -1)
  353. goto out;
  354. /*
  355. * one extra for terminating '\0', and
  356. * some overlapping space for matches near EOF
  357. */
  358. #define SLOP (1 + sizeof(union VALUETYPE))
  359. if ((buf = CAST(unsigned char *, malloc(ms->bytes_max + SLOP))) == NULL)
  360. return NULL;
  361. switch (file_fsmagic(ms, inname, &sb)) {
  362. case -1: /* error */
  363. goto done;
  364. case 0: /* nothing found */
  365. break;
  366. default: /* matched it and printed type */
  367. rv = 0;
  368. goto done;
  369. }
  370. #ifdef WIN32
  371. /* Place stdin in binary mode, so EOF (Ctrl+Z) doesn't stop early. */
  372. if (fd == STDIN_FILENO)
  373. _setmode(STDIN_FILENO, O_BINARY);
  374. #endif
  375. if (inname != NULL) {
  376. int flags = O_RDONLY|O_BINARY|O_NONBLOCK;
  377. errno = 0;
  378. if ((fd = open(inname, flags)) < 0) {
  379. int okstat = stat(inname, &sb) == 0;
  380. if (okstat && S_ISFIFO(sb.st_mode))
  381. ispipe = 1;
  382. #ifdef WIN32
  383. /*
  384. * Can't stat, can't open. It may have been opened in
  385. * fsmagic, so if the user doesn't have read permission,
  386. * allow it to say so; otherwise an error was probably
  387. * displayed in fsmagic.
  388. */
  389. if (!okstat && errno == EACCES) {
  390. sb.st_mode = S_IFBLK;
  391. okstat = 1;
  392. }
  393. #endif
  394. if (okstat &&
  395. unreadable_info(ms, sb.st_mode, inname) == -1)
  396. goto done;
  397. rv = 0;
  398. goto done;
  399. }
  400. }
  401. if (fd != -1) {
  402. if (fstat(fd, &sb) == 0 && S_ISFIFO(sb.st_mode))
  403. ispipe = 1;
  404. if (inname == NULL)
  405. pos = lseek(fd, (off_t)0, SEEK_CUR);
  406. }
  407. /*
  408. * try looking at the first ms->bytes_max bytes
  409. */
  410. if (ispipe) {
  411. ssize_t r = 0;
  412. while ((r = sread(fd, (void *)&buf[nbytes],
  413. (size_t)(ms->bytes_max - nbytes), 1)) > 0) {
  414. nbytes += r;
  415. if (r < PIPE_BUF) break;
  416. }
  417. if (nbytes == 0 && inname) {
  418. /* We can not read it, but we were able to stat it. */
  419. if (unreadable_info(ms, sb.st_mode, inname) == -1)
  420. goto done;
  421. rv = 0;
  422. goto done;
  423. }
  424. } else {
  425. /* Windows refuses to read from a big console buffer. */
  426. size_t howmany =
  427. #if defined(WIN32)
  428. _isatty(fd) ? 8 * 1024 :
  429. #endif
  430. ms->bytes_max;
  431. if ((nbytes = read(fd, (char *)buf, howmany)) == -1) {
  432. if (inname == NULL && fd != STDIN_FILENO)
  433. file_error(ms, errno, "cannot read fd %d", fd);
  434. else
  435. file_error(ms, errno, "cannot read `%s'",
  436. inname == NULL ? "/dev/stdin" : inname);
  437. goto done;
  438. }
  439. }
  440. (void)memset(buf + nbytes, 0, SLOP); /* NUL terminate */
  441. if (file_buffer(ms, fd, inname, buf, (size_t)nbytes) == -1)
  442. goto done;
  443. rv = 0;
  444. done:
  445. free(buf);
  446. if (fd != -1) {
  447. if (pos != (off_t)-1)
  448. (void)lseek(fd, pos, SEEK_SET);
  449. close_and_restore(ms, inname, fd, &sb);
  450. }
  451. out:
  452. return rv == 0 ? file_getbuffer(ms) : NULL;
  453. }
  454. public const char *
  455. magic_buffer(struct magic_set *ms, const void *buf, size_t nb)
  456. {
  457. if (ms == NULL)
  458. return NULL;
  459. if (file_reset(ms, 1) == -1)
  460. return NULL;
  461. /*
  462. * The main work is done here!
  463. * We have the file name and/or the data buffer to be identified.
  464. */
  465. if (file_buffer(ms, -1, NULL, buf, nb) == -1) {
  466. return NULL;
  467. }
  468. return file_getbuffer(ms);
  469. }
  470. #endif
  471. public const char *
  472. magic_error(struct magic_set *ms)
  473. {
  474. if (ms == NULL)
  475. return "Magic database is not open";
  476. return (ms->event_flags & EVENT_HAD_ERR) ? ms->o.buf : NULL;
  477. }
  478. public int
  479. magic_errno(struct magic_set *ms)
  480. {
  481. if (ms == NULL)
  482. return EINVAL;
  483. return (ms->event_flags & EVENT_HAD_ERR) ? ms->error : 0;
  484. }
  485. public int
  486. magic_getflags(struct magic_set *ms)
  487. {
  488. if (ms == NULL)
  489. return -1;
  490. return ms->flags;
  491. }
  492. public int
  493. magic_setflags(struct magic_set *ms, int flags)
  494. {
  495. if (ms == NULL)
  496. return -1;
  497. #if !defined(HAVE_UTIME) && !defined(HAVE_UTIMES)
  498. if (flags & MAGIC_PRESERVE_ATIME)
  499. return -1;
  500. #endif
  501. ms->flags = flags;
  502. return 0;
  503. }
  504. public int
  505. magic_version(void)
  506. {
  507. return MAGIC_VERSION;
  508. }
  509. public int
  510. magic_setparam(struct magic_set *ms, int param, const void *val)
  511. {
  512. if (ms == NULL)
  513. return -1;
  514. switch (param) {
  515. case MAGIC_PARAM_INDIR_MAX:
  516. ms->indir_max = (uint16_t)*(const size_t *)val;
  517. return 0;
  518. case MAGIC_PARAM_NAME_MAX:
  519. ms->name_max = (uint16_t)*(const size_t *)val;
  520. return 0;
  521. case MAGIC_PARAM_ELF_PHNUM_MAX:
  522. ms->elf_phnum_max = (uint16_t)*(const size_t *)val;
  523. return 0;
  524. case MAGIC_PARAM_ELF_SHNUM_MAX:
  525. ms->elf_shnum_max = (uint16_t)*(const size_t *)val;
  526. return 0;
  527. case MAGIC_PARAM_ELF_NOTES_MAX:
  528. ms->elf_notes_max = (uint16_t)*(const size_t *)val;
  529. return 0;
  530. case MAGIC_PARAM_REGEX_MAX:
  531. ms->elf_notes_max = (uint16_t)*(const size_t *)val;
  532. return 0;
  533. case MAGIC_PARAM_BYTES_MAX:
  534. ms->bytes_max = *(const size_t *)val;
  535. return 0;
  536. default:
  537. errno = EINVAL;
  538. return -1;
  539. }
  540. }
  541. public int
  542. magic_getparam(struct magic_set *ms, int param, void *val)
  543. {
  544. if (ms == NULL)
  545. return -1;
  546. switch (param) {
  547. case MAGIC_PARAM_INDIR_MAX:
  548. *(size_t *)val = ms->indir_max;
  549. return 0;
  550. case MAGIC_PARAM_NAME_MAX:
  551. *(size_t *)val = ms->name_max;
  552. return 0;
  553. case MAGIC_PARAM_ELF_PHNUM_MAX:
  554. *(size_t *)val = ms->elf_phnum_max;
  555. return 0;
  556. case MAGIC_PARAM_ELF_SHNUM_MAX:
  557. *(size_t *)val = ms->elf_shnum_max;
  558. return 0;
  559. case MAGIC_PARAM_ELF_NOTES_MAX:
  560. *(size_t *)val = ms->elf_notes_max;
  561. return 0;
  562. case MAGIC_PARAM_REGEX_MAX:
  563. *(size_t *)val = ms->regex_max;
  564. return 0;
  565. case MAGIC_PARAM_BYTES_MAX:
  566. *(size_t *)val = ms->bytes_max;
  567. return 0;
  568. default:
  569. errno = EINVAL;
  570. return -1;
  571. }
  572. }