file.c 12 KB

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