file.c 13 KB

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