file.c 13 KB

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