file.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. /*
  2. * Copyright (c) Ian F. Darwin 1986-1995.
  3. * Software written by Ian F. Darwin and others;
  4. * maintained 1995-present by Christos Zoulas and others.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions
  8. * are met:
  9. * 1. Redistributions of source code must retain the above copyright
  10. * notice immediately at the beginning of the file, without modification,
  11. * this list of conditions, and the following disclaimer.
  12. * 2. Redistributions in binary form must reproduce the above copyright
  13. * notice, this list of conditions and the following disclaimer in the
  14. * documentation and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  17. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  19. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
  20. * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  22. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  23. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  24. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  25. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  26. * SUCH DAMAGE.
  27. */
  28. /*
  29. * file - find type of a file or files - main program.
  30. */
  31. #include "file.h"
  32. #ifndef lint
  33. FILE_RCSID("@(#)$File: file.c,v 1.172 2016/10/24 15:21:07 christos Exp $")
  34. #endif /* lint */
  35. #include "magic.h"
  36. #include <stdlib.h>
  37. #include <unistd.h>
  38. #include <string.h>
  39. #ifdef RESTORE_TIME
  40. # if (__COHERENT__ >= 0x420)
  41. # include <sys/utime.h>
  42. # else
  43. # ifdef USE_UTIMES
  44. # include <sys/time.h>
  45. # else
  46. # include <utime.h>
  47. # endif
  48. # endif
  49. #endif
  50. #ifdef HAVE_UNISTD_H
  51. #include <unistd.h> /* for read() */
  52. #endif
  53. #ifdef HAVE_WCHAR_H
  54. #include <wchar.h>
  55. #endif
  56. #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
  57. #include <getopt.h>
  58. #ifndef HAVE_GETOPT_LONG
  59. int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
  60. #endif
  61. #else
  62. #include "mygetopt.h"
  63. #endif
  64. #ifdef S_IFLNK
  65. #define FILE_FLAGS "-bcEhikLlNnprsvzZ0"
  66. #else
  67. #define FILE_FLAGS "-bcEiklNnprsvzZ0"
  68. #endif
  69. # define USAGE \
  70. "Usage: %s [" FILE_FLAGS \
  71. "] [--apple] [--extension] [--mime-encoding] [--mime-type]\n" \
  72. " [-e testname] [-F separator] [-f namefile] [-m magicfiles] " \
  73. "file ...\n" \
  74. " %s -C [-m magicfiles]\n" \
  75. " %s [--help]\n"
  76. private int /* Global command-line options */
  77. bflag = 0, /* brief output format */
  78. nopad = 0, /* Don't pad output */
  79. nobuffer = 0, /* Do not buffer stdout */
  80. nulsep = 0; /* Append '\0' to the separator */
  81. private const char *separator = ":"; /* Default field separator */
  82. private const struct option long_options[] = {
  83. #define OPT_HELP 1
  84. #define OPT_APPLE 2
  85. #define OPT_EXTENSIONS 3
  86. #define OPT_MIME_TYPE 4
  87. #define OPT_MIME_ENCODING 5
  88. #define OPT(shortname, longname, opt, def, doc) \
  89. {longname, opt, NULL, shortname},
  90. #define OPT_LONGONLY(longname, opt, def, doc, id) \
  91. {longname, opt, NULL, id},
  92. #include "file_opts.h"
  93. #undef OPT
  94. #undef OPT_LONGONLY
  95. {0, 0, NULL, 0}
  96. };
  97. #define OPTSTRING "bcCde:Ef:F:hiklLm:nNpP:rsvzZ0"
  98. private const struct {
  99. const char *name;
  100. int value;
  101. } nv[] = {
  102. { "apptype", MAGIC_NO_CHECK_APPTYPE },
  103. { "ascii", MAGIC_NO_CHECK_ASCII },
  104. { "cdf", MAGIC_NO_CHECK_CDF },
  105. { "compress", MAGIC_NO_CHECK_COMPRESS },
  106. { "elf", MAGIC_NO_CHECK_ELF },
  107. { "encoding", MAGIC_NO_CHECK_ENCODING },
  108. { "soft", MAGIC_NO_CHECK_SOFT },
  109. { "tar", MAGIC_NO_CHECK_TAR },
  110. { "text", MAGIC_NO_CHECK_TEXT }, /* synonym for ascii */
  111. { "tokens", MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
  112. };
  113. private struct {
  114. const char *name;
  115. int tag;
  116. size_t value;
  117. } pm[] = {
  118. { "indir", MAGIC_PARAM_INDIR_MAX, 0 },
  119. { "name", MAGIC_PARAM_NAME_MAX, 0 },
  120. { "elf_phnum", MAGIC_PARAM_ELF_PHNUM_MAX, 0 },
  121. { "elf_shnum", MAGIC_PARAM_ELF_SHNUM_MAX, 0 },
  122. { "elf_notes", MAGIC_PARAM_ELF_NOTES_MAX, 0 },
  123. { "regex", MAGIC_PARAM_REGEX_MAX, 0 },
  124. { "bytes", MAGIC_PARAM_BYTES_MAX, 0 },
  125. };
  126. private char *progname; /* used throughout */
  127. private int posixly;
  128. #ifdef __dead
  129. __dead
  130. #endif
  131. private void usage(void);
  132. private void docprint(const char *, int);
  133. #ifdef __dead
  134. __dead
  135. #endif
  136. private void help(void);
  137. private int unwrap(struct magic_set *, const char *);
  138. private int process(struct magic_set *ms, const char *, int);
  139. private struct magic_set *load(const char *, int);
  140. private void setparam(const char *);
  141. private void applyparam(magic_t);
  142. /*
  143. * main - parse arguments and handle options
  144. */
  145. int
  146. main(int argc, char *argv[])
  147. {
  148. int c;
  149. size_t i;
  150. int action = 0, didsomefiles = 0, errflg = 0;
  151. int flags = 0, e = 0;
  152. struct magic_set *magic = NULL;
  153. int longindex;
  154. const char *magicfile = NULL; /* where the magic is */
  155. /* makes islower etc work for other langs */
  156. #ifdef HAVE_SETLOCALE
  157. (void)setlocale(LC_CTYPE, "");
  158. #endif
  159. #ifdef __EMX__
  160. /* sh-like wildcard expansion! Shouldn't hurt at least ... */
  161. _wildcard(&argc, &argv);
  162. #endif
  163. if ((progname = strrchr(argv[0], '/')) != NULL)
  164. progname++;
  165. else
  166. progname = argv[0];
  167. #ifdef S_IFLNK
  168. posixly = getenv("POSIXLY_CORRECT") != NULL;
  169. flags |= posixly ? MAGIC_SYMLINK : 0;
  170. #endif
  171. while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
  172. &longindex)) != -1)
  173. switch (c) {
  174. case OPT_HELP:
  175. help();
  176. break;
  177. case OPT_APPLE:
  178. flags |= MAGIC_APPLE;
  179. break;
  180. case OPT_EXTENSIONS:
  181. flags |= MAGIC_EXTENSION;
  182. break;
  183. case OPT_MIME_TYPE:
  184. flags |= MAGIC_MIME_TYPE;
  185. break;
  186. case OPT_MIME_ENCODING:
  187. flags |= MAGIC_MIME_ENCODING;
  188. break;
  189. case '0':
  190. nulsep++;
  191. break;
  192. case 'b':
  193. bflag++;
  194. break;
  195. case 'c':
  196. action = FILE_CHECK;
  197. break;
  198. case 'C':
  199. action = FILE_COMPILE;
  200. break;
  201. case 'd':
  202. flags |= MAGIC_DEBUG|MAGIC_CHECK;
  203. break;
  204. case 'E':
  205. flags |= MAGIC_ERROR;
  206. break;
  207. case 'e':
  208. for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
  209. if (strcmp(nv[i].name, optarg) == 0)
  210. break;
  211. if (i == sizeof(nv) / sizeof(nv[0]))
  212. errflg++;
  213. else
  214. flags |= nv[i].value;
  215. break;
  216. case 'f':
  217. if(action)
  218. usage();
  219. if (magic == NULL)
  220. if ((magic = load(magicfile, flags)) == NULL)
  221. return 1;
  222. applyparam(magic);
  223. e |= unwrap(magic, optarg);
  224. ++didsomefiles;
  225. break;
  226. case 'F':
  227. separator = optarg;
  228. break;
  229. case 'i':
  230. flags |= MAGIC_MIME;
  231. break;
  232. case 'k':
  233. flags |= MAGIC_CONTINUE;
  234. break;
  235. case 'l':
  236. action = FILE_LIST;
  237. break;
  238. case 'm':
  239. magicfile = optarg;
  240. break;
  241. case 'n':
  242. ++nobuffer;
  243. break;
  244. case 'N':
  245. ++nopad;
  246. break;
  247. #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
  248. case 'p':
  249. flags |= MAGIC_PRESERVE_ATIME;
  250. break;
  251. #endif
  252. case 'P':
  253. setparam(optarg);
  254. break;
  255. case 'r':
  256. flags |= MAGIC_RAW;
  257. break;
  258. case 's':
  259. flags |= MAGIC_DEVICES;
  260. break;
  261. case 'v':
  262. if (magicfile == NULL)
  263. magicfile = magic_getpath(magicfile, action);
  264. (void)fprintf(stdout, "%s-%s\n", progname, VERSION);
  265. (void)fprintf(stdout, "magic file from %s\n",
  266. magicfile);
  267. return 0;
  268. case 'z':
  269. flags |= MAGIC_COMPRESS;
  270. break;
  271. case 'Z':
  272. flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
  273. break;
  274. #ifdef S_IFLNK
  275. case 'L':
  276. flags |= MAGIC_SYMLINK;
  277. break;
  278. case 'h':
  279. flags &= ~MAGIC_SYMLINK;
  280. break;
  281. #endif
  282. case '?':
  283. default:
  284. errflg++;
  285. break;
  286. }
  287. if (errflg) {
  288. usage();
  289. }
  290. if (e)
  291. return e;
  292. if (MAGIC_VERSION != magic_version())
  293. (void)fprintf(stderr, "%s: compiled magic version [%d] "
  294. "does not match with shared library magic version [%d]\n",
  295. progname, MAGIC_VERSION, magic_version());
  296. switch(action) {
  297. case FILE_CHECK:
  298. case FILE_COMPILE:
  299. case FILE_LIST:
  300. /*
  301. * Don't try to check/compile ~/.magic unless we explicitly
  302. * ask for it.
  303. */
  304. magic = magic_open(flags|MAGIC_CHECK);
  305. if (magic == NULL) {
  306. (void)fprintf(stderr, "%s: %s\n", progname,
  307. strerror(errno));
  308. return 1;
  309. }
  310. switch(action) {
  311. case FILE_CHECK:
  312. c = magic_check(magic, magicfile);
  313. break;
  314. case FILE_COMPILE:
  315. c = magic_compile(magic, magicfile);
  316. break;
  317. case FILE_LIST:
  318. c = magic_list(magic, magicfile);
  319. break;
  320. default:
  321. abort();
  322. }
  323. if (c == -1) {
  324. (void)fprintf(stderr, "%s: %s\n", progname,
  325. magic_error(magic));
  326. e = 1;
  327. goto out;
  328. }
  329. goto out;
  330. default:
  331. if (magic == NULL)
  332. if ((magic = load(magicfile, flags)) == NULL)
  333. return 1;
  334. applyparam(magic);
  335. }
  336. if (optind == argc) {
  337. if (!didsomefiles)
  338. usage();
  339. }
  340. else {
  341. size_t j, wid, nw;
  342. for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
  343. nw = file_mbswidth(argv[j]);
  344. if (nw > wid)
  345. wid = nw;
  346. }
  347. /*
  348. * If bflag is only set twice, set it depending on
  349. * number of files [this is undocumented, and subject to change]
  350. */
  351. if (bflag == 2) {
  352. bflag = optind >= argc - 1;
  353. }
  354. for (; optind < argc; optind++)
  355. e |= process(magic, argv[optind], wid);
  356. }
  357. out:
  358. if (magic)
  359. magic_close(magic);
  360. return e;
  361. }
  362. private void
  363. applyparam(magic_t magic)
  364. {
  365. size_t i;
  366. for (i = 0; i < __arraycount(pm); i++) {
  367. if (pm[i].value == 0)
  368. continue;
  369. if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1) {
  370. (void)fprintf(stderr, "%s: Can't set %s %s\n", progname,
  371. pm[i].name, strerror(errno));
  372. exit(1);
  373. }
  374. }
  375. }
  376. private void
  377. setparam(const char *p)
  378. {
  379. size_t i;
  380. char *s;
  381. if ((s = strchr(p, '=')) == NULL)
  382. goto badparm;
  383. for (i = 0; i < __arraycount(pm); i++) {
  384. if (strncmp(p, pm[i].name, s - p) != 0)
  385. continue;
  386. pm[i].value = atoi(s + 1);
  387. return;
  388. }
  389. badparm:
  390. (void)fprintf(stderr, "%s: Unknown param %s\n", progname, p);
  391. exit(1);
  392. }
  393. private struct magic_set *
  394. /*ARGSUSED*/
  395. load(const char *magicfile, int flags)
  396. {
  397. struct magic_set *magic = magic_open(flags);
  398. const char *e;
  399. if (magic == NULL) {
  400. (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
  401. return NULL;
  402. }
  403. if (magic_load(magic, magicfile) == -1) {
  404. (void)fprintf(stderr, "%s: %s\n",
  405. progname, magic_error(magic));
  406. magic_close(magic);
  407. return NULL;
  408. }
  409. if ((e = magic_error(magic)) != NULL)
  410. (void)fprintf(stderr, "%s: Warning: %s\n", progname, e);
  411. return magic;
  412. }
  413. /*
  414. * unwrap -- read a file of filenames, do each one.
  415. */
  416. private int
  417. unwrap(struct magic_set *ms, const char *fn)
  418. {
  419. FILE *f;
  420. ssize_t len;
  421. char *line = NULL;
  422. size_t llen = 0;
  423. int wid = 0, cwid;
  424. int e = 0;
  425. if (strcmp("-", fn) == 0) {
  426. f = stdin;
  427. wid = 1;
  428. } else {
  429. if ((f = fopen(fn, "r")) == NULL) {
  430. (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
  431. progname, fn, strerror(errno));
  432. return 1;
  433. }
  434. while ((len = getline(&line, &llen, f)) > 0) {
  435. if (line[len - 1] == '\n')
  436. line[len - 1] = '\0';
  437. cwid = file_mbswidth(line);
  438. if (cwid > wid)
  439. wid = cwid;
  440. }
  441. rewind(f);
  442. }
  443. while ((len = getline(&line, &llen, f)) > 0) {
  444. if (line[len - 1] == '\n')
  445. line[len - 1] = '\0';
  446. e |= process(ms, line, wid);
  447. if(nobuffer)
  448. (void)fflush(stdout);
  449. }
  450. free(line);
  451. (void)fclose(f);
  452. return e;
  453. }
  454. /*
  455. * Called for each input file on the command line (or in a list of files)
  456. */
  457. private int
  458. process(struct magic_set *ms, const char *inname, int wid)
  459. {
  460. const char *type, c = nulsep > 1 ? '\0' : '\n';
  461. int std_in = strcmp(inname, "-") == 0;
  462. if (wid > 0 && !bflag) {
  463. (void)printf("%s", std_in ? "/dev/stdin" : inname);
  464. if (nulsep)
  465. (void)putc('\0', stdout);
  466. if (nulsep < 2) {
  467. (void)printf("%s", separator);
  468. (void)printf("%*s ",
  469. (int) (nopad ? 0 : (wid - file_mbswidth(inname))),
  470. "");
  471. }
  472. }
  473. type = magic_file(ms, std_in ? NULL : inname);
  474. if (type == NULL) {
  475. (void)printf("ERROR: %s%c", magic_error(ms), c);
  476. return 1;
  477. } else {
  478. (void)printf("%s%c", type, c);
  479. return 0;
  480. }
  481. }
  482. protected size_t
  483. file_mbswidth(const char *s)
  484. {
  485. #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
  486. size_t bytesconsumed, old_n, n, width = 0;
  487. mbstate_t state;
  488. wchar_t nextchar;
  489. (void)memset(&state, 0, sizeof(mbstate_t));
  490. old_n = n = strlen(s);
  491. while (n > 0) {
  492. bytesconsumed = mbrtowc(&nextchar, s, n, &state);
  493. if (bytesconsumed == (size_t)(-1) ||
  494. bytesconsumed == (size_t)(-2)) {
  495. /* Something went wrong, return something reasonable */
  496. return old_n;
  497. }
  498. if (s[0] == '\n') {
  499. /*
  500. * do what strlen() would do, so that caller
  501. * is always right
  502. */
  503. width++;
  504. } else {
  505. int w = wcwidth(nextchar);
  506. if (w > 0)
  507. width += w;
  508. }
  509. s += bytesconsumed, n -= bytesconsumed;
  510. }
  511. return width;
  512. #else
  513. return strlen(s);
  514. #endif
  515. }
  516. private void
  517. usage(void)
  518. {
  519. (void)fprintf(stderr, USAGE, progname, progname, progname);
  520. exit(1);
  521. }
  522. private void
  523. defprint(int def)
  524. {
  525. if (!def)
  526. return;
  527. if (((def & 1) && posixly) || ((def & 2) && !posixly))
  528. fprintf(stdout, " (default)");
  529. fputc('\n', stdout);
  530. }
  531. private void
  532. docprint(const char *opts, int def)
  533. {
  534. size_t i;
  535. int comma;
  536. char *sp, *p;
  537. p = strstr(opts, "%o");
  538. if (p == NULL) {
  539. fprintf(stdout, "%s", opts);
  540. defprint(def);
  541. return;
  542. }
  543. for (sp = p - 1; sp > opts && *sp == ' '; sp--)
  544. continue;
  545. fprintf(stdout, "%.*s", (int)(p - opts), opts);
  546. comma = 0;
  547. for (i = 0; i < __arraycount(nv); i++) {
  548. fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
  549. if (i && i % 5 == 0) {
  550. fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
  551. comma = 0;
  552. }
  553. }
  554. fprintf(stdout, "%s", opts + (p - opts) + 2);
  555. }
  556. private void
  557. help(void)
  558. {
  559. (void)fputs(
  560. "Usage: file [OPTION...] [FILE...]\n"
  561. "Determine type of FILEs.\n"
  562. "\n", stdout);
  563. #define OPT(shortname, longname, opt, def, doc) \
  564. fprintf(stdout, " -%c, --" longname, shortname), \
  565. docprint(doc, def);
  566. #define OPT_LONGONLY(longname, opt, def, doc, id) \
  567. fprintf(stdout, " --" longname), \
  568. docprint(doc, def);
  569. #include "file_opts.h"
  570. #undef OPT
  571. #undef OPT_LONGONLY
  572. fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
  573. exit(0);
  574. }