file.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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.165 2015/06/11 12:52:32 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, doc) \
  89. {longname, opt, NULL, shortname},
  90. #define OPT_LONGONLY(longname, opt, 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. };
  124. private char *progname; /* used throughout */
  125. #ifdef __dead
  126. __dead
  127. #endif
  128. private void usage(void);
  129. private void docprint(const char *);
  130. #ifdef __dead
  131. __dead
  132. #endif
  133. private void help(void);
  134. private int unwrap(struct magic_set *, const char *);
  135. private int process(struct magic_set *ms, const char *, int);
  136. private struct magic_set *load(const char *, int);
  137. private void setparam(const char *);
  138. private void applyparam(magic_t);
  139. /*
  140. * main - parse arguments and handle options
  141. */
  142. int
  143. main(int argc, char *argv[])
  144. {
  145. int c;
  146. size_t i;
  147. int action = 0, didsomefiles = 0, errflg = 0;
  148. int flags = 0, e = 0;
  149. struct magic_set *magic = NULL;
  150. int longindex;
  151. const char *magicfile = NULL; /* where the magic is */
  152. /* makes islower etc work for other langs */
  153. #ifdef HAVE_SETLOCALE
  154. (void)setlocale(LC_CTYPE, "");
  155. #endif
  156. #ifdef __EMX__
  157. /* sh-like wildcard expansion! Shouldn't hurt at least ... */
  158. _wildcard(&argc, &argv);
  159. #endif
  160. if ((progname = strrchr(argv[0], '/')) != NULL)
  161. progname++;
  162. else
  163. progname = argv[0];
  164. #ifdef S_IFLNK
  165. flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
  166. #endif
  167. while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
  168. &longindex)) != -1)
  169. switch (c) {
  170. case OPT_HELP:
  171. help();
  172. break;
  173. case OPT_APPLE:
  174. flags |= MAGIC_APPLE;
  175. break;
  176. case OPT_EXTENSIONS:
  177. flags |= MAGIC_EXTENSION;
  178. break;
  179. case OPT_MIME_TYPE:
  180. flags |= MAGIC_MIME_TYPE;
  181. break;
  182. case OPT_MIME_ENCODING:
  183. flags |= MAGIC_MIME_ENCODING;
  184. break;
  185. case '0':
  186. nulsep = 1;
  187. break;
  188. case 'b':
  189. bflag++;
  190. break;
  191. case 'c':
  192. action = FILE_CHECK;
  193. break;
  194. case 'C':
  195. action = FILE_COMPILE;
  196. break;
  197. case 'd':
  198. flags |= MAGIC_DEBUG|MAGIC_CHECK;
  199. break;
  200. case 'E':
  201. flags |= MAGIC_ERROR;
  202. break;
  203. case 'e':
  204. for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
  205. if (strcmp(nv[i].name, optarg) == 0)
  206. break;
  207. if (i == sizeof(nv) / sizeof(nv[0]))
  208. errflg++;
  209. else
  210. flags |= nv[i].value;
  211. break;
  212. case 'f':
  213. if(action)
  214. usage();
  215. if (magic == NULL)
  216. if ((magic = load(magicfile, flags)) == NULL)
  217. return 1;
  218. e |= unwrap(magic, optarg);
  219. ++didsomefiles;
  220. break;
  221. case 'F':
  222. separator = optarg;
  223. break;
  224. case 'i':
  225. flags |= MAGIC_MIME;
  226. break;
  227. case 'k':
  228. flags |= MAGIC_CONTINUE;
  229. break;
  230. case 'l':
  231. action = FILE_LIST;
  232. break;
  233. case 'm':
  234. magicfile = optarg;
  235. break;
  236. case 'n':
  237. ++nobuffer;
  238. break;
  239. case 'N':
  240. ++nopad;
  241. break;
  242. #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
  243. case 'p':
  244. flags |= MAGIC_PRESERVE_ATIME;
  245. break;
  246. #endif
  247. case 'P':
  248. setparam(optarg);
  249. break;
  250. case 'r':
  251. flags |= MAGIC_RAW;
  252. break;
  253. case 's':
  254. flags |= MAGIC_DEVICES;
  255. break;
  256. case 'v':
  257. if (magicfile == NULL)
  258. magicfile = magic_getpath(magicfile, action);
  259. (void)fprintf(stdout, "%s-%s\n", progname, VERSION);
  260. (void)fprintf(stdout, "magic file from %s\n",
  261. magicfile);
  262. return 0;
  263. case 'z':
  264. flags |= MAGIC_COMPRESS;
  265. break;
  266. case 'Z':
  267. flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
  268. break;
  269. #ifdef S_IFLNK
  270. case 'L':
  271. flags |= MAGIC_SYMLINK;
  272. break;
  273. case 'h':
  274. flags &= ~MAGIC_SYMLINK;
  275. break;
  276. #endif
  277. case '?':
  278. default:
  279. errflg++;
  280. break;
  281. }
  282. if (errflg) {
  283. usage();
  284. }
  285. if (e)
  286. return e;
  287. if (MAGIC_VERSION != magic_version())
  288. (void)fprintf(stderr, "%s: compiled magic version [%d] "
  289. "does not match with shared library magic version [%d]\n",
  290. progname, MAGIC_VERSION, magic_version());
  291. switch(action) {
  292. case FILE_CHECK:
  293. case FILE_COMPILE:
  294. case FILE_LIST:
  295. /*
  296. * Don't try to check/compile ~/.magic unless we explicitly
  297. * ask for it.
  298. */
  299. magic = magic_open(flags|MAGIC_CHECK);
  300. if (magic == NULL) {
  301. (void)fprintf(stderr, "%s: %s\n", progname,
  302. strerror(errno));
  303. return 1;
  304. }
  305. switch(action) {
  306. case FILE_CHECK:
  307. c = magic_check(magic, magicfile);
  308. break;
  309. case FILE_COMPILE:
  310. c = magic_compile(magic, magicfile);
  311. break;
  312. case FILE_LIST:
  313. c = magic_list(magic, magicfile);
  314. break;
  315. default:
  316. abort();
  317. }
  318. if (c == -1) {
  319. (void)fprintf(stderr, "%s: %s\n", progname,
  320. magic_error(magic));
  321. return 1;
  322. }
  323. return 0;
  324. default:
  325. if (magic == NULL)
  326. if ((magic = load(magicfile, flags)) == NULL)
  327. return 1;
  328. applyparam(magic);
  329. }
  330. if (optind == argc) {
  331. if (!didsomefiles)
  332. usage();
  333. }
  334. else {
  335. size_t j, wid, nw;
  336. for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
  337. nw = file_mbswidth(argv[j]);
  338. if (nw > wid)
  339. wid = nw;
  340. }
  341. /*
  342. * If bflag is only set twice, set it depending on
  343. * number of files [this is undocumented, and subject to change]
  344. */
  345. if (bflag == 2) {
  346. bflag = optind >= argc - 1;
  347. }
  348. for (; optind < argc; optind++)
  349. e |= process(magic, argv[optind], wid);
  350. }
  351. if (magic)
  352. magic_close(magic);
  353. return e;
  354. }
  355. private void
  356. applyparam(magic_t magic)
  357. {
  358. size_t i;
  359. for (i = 0; i < __arraycount(pm); i++) {
  360. if (pm[i].value == 0)
  361. continue;
  362. if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1) {
  363. (void)fprintf(stderr, "%s: Can't set %s %s\n", progname,
  364. pm[i].name, strerror(errno));
  365. exit(1);
  366. }
  367. }
  368. }
  369. private void
  370. setparam(const char *p)
  371. {
  372. size_t i;
  373. char *s;
  374. if ((s = strchr(p, '=')) == NULL)
  375. goto badparm;
  376. for (i = 0; i < __arraycount(pm); i++) {
  377. if (strncmp(p, pm[i].name, s - p) != 0)
  378. continue;
  379. pm[i].value = atoi(s + 1);
  380. return;
  381. }
  382. badparm:
  383. (void)fprintf(stderr, "%s: Unknown param %s\n", progname, p);
  384. exit(1);
  385. }
  386. private struct magic_set *
  387. /*ARGSUSED*/
  388. load(const char *magicfile, int flags)
  389. {
  390. struct magic_set *magic = magic_open(flags);
  391. if (magic == NULL) {
  392. (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
  393. return NULL;
  394. }
  395. if (magic_load(magic, magicfile) == -1) {
  396. (void)fprintf(stderr, "%s: %s\n",
  397. progname, magic_error(magic));
  398. magic_close(magic);
  399. return NULL;
  400. }
  401. return magic;
  402. }
  403. /*
  404. * unwrap -- read a file of filenames, do each one.
  405. */
  406. private int
  407. unwrap(struct magic_set *ms, const char *fn)
  408. {
  409. FILE *f;
  410. ssize_t len;
  411. char *line = NULL;
  412. size_t llen = 0;
  413. int wid = 0, cwid;
  414. int e = 0;
  415. if (strcmp("-", fn) == 0) {
  416. f = stdin;
  417. wid = 1;
  418. } else {
  419. if ((f = fopen(fn, "r")) == NULL) {
  420. (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
  421. progname, fn, strerror(errno));
  422. return 1;
  423. }
  424. while ((len = getline(&line, &llen, f)) > 0) {
  425. if (line[len - 1] == '\n')
  426. line[len - 1] = '\0';
  427. cwid = file_mbswidth(line);
  428. if (cwid > wid)
  429. wid = cwid;
  430. }
  431. rewind(f);
  432. }
  433. while ((len = getline(&line, &llen, f)) > 0) {
  434. if (line[len - 1] == '\n')
  435. line[len - 1] = '\0';
  436. e |= process(ms, line, wid);
  437. if(nobuffer)
  438. (void)fflush(stdout);
  439. }
  440. free(line);
  441. (void)fclose(f);
  442. return e;
  443. }
  444. /*
  445. * Called for each input file on the command line (or in a list of files)
  446. */
  447. private int
  448. process(struct magic_set *ms, const char *inname, int wid)
  449. {
  450. const char *type;
  451. int std_in = strcmp(inname, "-") == 0;
  452. if (wid > 0 && !bflag) {
  453. (void)printf("%s", std_in ? "/dev/stdin" : inname);
  454. if (nulsep)
  455. (void)putc('\0', stdout);
  456. (void)printf("%s", separator);
  457. (void)printf("%*s ",
  458. (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
  459. }
  460. type = magic_file(ms, std_in ? NULL : inname);
  461. if (type == NULL) {
  462. (void)printf("ERROR: %s\n", magic_error(ms));
  463. return 1;
  464. } else {
  465. (void)printf("%s\n", type);
  466. return 0;
  467. }
  468. }
  469. protected size_t
  470. file_mbswidth(const char *s)
  471. {
  472. #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
  473. size_t bytesconsumed, old_n, n, width = 0;
  474. mbstate_t state;
  475. wchar_t nextchar;
  476. (void)memset(&state, 0, sizeof(mbstate_t));
  477. old_n = n = strlen(s);
  478. while (n > 0) {
  479. bytesconsumed = mbrtowc(&nextchar, s, n, &state);
  480. if (bytesconsumed == (size_t)(-1) ||
  481. bytesconsumed == (size_t)(-2)) {
  482. /* Something went wrong, return something reasonable */
  483. return old_n;
  484. }
  485. if (s[0] == '\n') {
  486. /*
  487. * do what strlen() would do, so that caller
  488. * is always right
  489. */
  490. width++;
  491. } else {
  492. int w = wcwidth(nextchar);
  493. if (w > 0)
  494. width += w;
  495. }
  496. s += bytesconsumed, n -= bytesconsumed;
  497. }
  498. return width;
  499. #else
  500. return strlen(s);
  501. #endif
  502. }
  503. private void
  504. usage(void)
  505. {
  506. (void)fprintf(stderr, USAGE, progname, progname, progname);
  507. exit(1);
  508. }
  509. private void
  510. docprint(const char *opts)
  511. {
  512. size_t i;
  513. int comma;
  514. char *sp, *p;
  515. p = strstr(opts, "%o");
  516. if (p == NULL) {
  517. fprintf(stdout, "%s", opts);
  518. return;
  519. }
  520. for (sp = p - 1; sp > opts && *sp == ' '; sp--)
  521. continue;
  522. fprintf(stdout, "%.*s", (int)(p - opts), opts);
  523. comma = 0;
  524. for (i = 0; i < __arraycount(nv); i++) {
  525. fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
  526. if (i && i % 5 == 0) {
  527. fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
  528. comma = 0;
  529. }
  530. }
  531. fprintf(stdout, "%s", opts + (p - opts) + 2);
  532. }
  533. private void
  534. help(void)
  535. {
  536. (void)fputs(
  537. "Usage: file [OPTION...] [FILE...]\n"
  538. "Determine type of FILEs.\n"
  539. "\n", stdout);
  540. #define OPT(shortname, longname, opt, doc) \
  541. fprintf(stdout, " -%c, --" longname, shortname), \
  542. docprint(doc);
  543. #define OPT_LONGONLY(longname, opt, doc, id) \
  544. fprintf(stdout, " --" longname), \
  545. docprint(doc);
  546. #include "file_opts.h"
  547. #undef OPT
  548. #undef OPT_LONGONLY
  549. fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
  550. exit(0);
  551. }