file.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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.149 2013/01/07 18:20:19 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 "-bchikLlNnprsvz0"
  69. #else
  70. #define FILE_FLAGS "-bciklNnprsvz0"
  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:f: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. for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
  180. if (strcmp(nv[i].name, optarg) == 0)
  181. break;
  182. if (i == sizeof(nv) / sizeof(nv[0]))
  183. errflg++;
  184. else
  185. flags |= nv[i].value;
  186. break;
  187. case 'f':
  188. if(action)
  189. usage();
  190. if (magic == NULL)
  191. if ((magic = load(magicfile, flags)) == NULL)
  192. return 1;
  193. e |= unwrap(magic, optarg);
  194. ++didsomefiles;
  195. break;
  196. case 'F':
  197. separator = optarg;
  198. break;
  199. case 'i':
  200. flags |= MAGIC_MIME;
  201. break;
  202. case 'k':
  203. flags |= MAGIC_CONTINUE;
  204. break;
  205. case 'l':
  206. action = FILE_LIST;
  207. break;
  208. case 'm':
  209. magicfile = optarg;
  210. break;
  211. case 'n':
  212. ++nobuffer;
  213. break;
  214. case 'N':
  215. ++nopad;
  216. break;
  217. #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
  218. case 'p':
  219. flags |= MAGIC_PRESERVE_ATIME;
  220. break;
  221. #endif
  222. case 'r':
  223. flags |= MAGIC_RAW;
  224. break;
  225. case 's':
  226. flags |= MAGIC_DEVICES;
  227. break;
  228. case 'v':
  229. if (magicfile == NULL)
  230. magicfile = magic_getpath(magicfile, action);
  231. (void)fprintf(stdout, "%s-%s\n", progname, VERSION);
  232. (void)fprintf(stdout, "magic file from %s\n",
  233. magicfile);
  234. return 0;
  235. case 'z':
  236. flags |= MAGIC_COMPRESS;
  237. break;
  238. #ifdef S_IFLNK
  239. case 'L':
  240. flags |= MAGIC_SYMLINK;
  241. break;
  242. case 'h':
  243. flags &= ~MAGIC_SYMLINK;
  244. break;
  245. #endif
  246. case '?':
  247. default:
  248. errflg++;
  249. break;
  250. }
  251. if (errflg) {
  252. usage();
  253. }
  254. if (e)
  255. return e;
  256. if (MAGIC_VERSION != magic_version())
  257. (void)fprintf(stderr, "%s: compiled magic version [%d] "
  258. "does not match with shared library magic version [%d]\n",
  259. progname, MAGIC_VERSION, magic_version());
  260. switch(action) {
  261. case FILE_CHECK:
  262. case FILE_COMPILE:
  263. case FILE_LIST:
  264. /*
  265. * Don't try to check/compile ~/.magic unless we explicitly
  266. * ask for it.
  267. */
  268. magic = magic_open(flags|MAGIC_CHECK);
  269. if (magic == NULL) {
  270. (void)fprintf(stderr, "%s: %s\n", progname,
  271. strerror(errno));
  272. return 1;
  273. }
  274. switch(action) {
  275. case FILE_CHECK:
  276. c = magic_check(magic, magicfile);
  277. break;
  278. case FILE_COMPILE:
  279. c = magic_compile(magic, magicfile);
  280. break;
  281. case FILE_LIST:
  282. c = magic_list(magic, magicfile);
  283. break;
  284. default:
  285. abort();
  286. }
  287. if (c == -1) {
  288. (void)fprintf(stderr, "%s: %s\n", progname,
  289. magic_error(magic));
  290. return 1;
  291. }
  292. return 0;
  293. default:
  294. if (magic == NULL)
  295. if ((magic = load(magicfile, flags)) == NULL)
  296. return 1;
  297. break;
  298. }
  299. if (optind == argc) {
  300. if (!didsomefiles)
  301. usage();
  302. }
  303. else {
  304. size_t j, wid, nw;
  305. for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
  306. nw = file_mbswidth(argv[j]);
  307. if (nw > wid)
  308. wid = nw;
  309. }
  310. /*
  311. * If bflag is only set twice, set it depending on
  312. * number of files [this is undocumented, and subject to change]
  313. */
  314. if (bflag == 2) {
  315. bflag = optind >= argc - 1;
  316. }
  317. for (; optind < argc; optind++)
  318. e |= process(magic, argv[optind], wid);
  319. }
  320. if (magic)
  321. magic_close(magic);
  322. return e;
  323. }
  324. private struct magic_set *
  325. /*ARGSUSED*/
  326. load(const char *magicfile, int flags)
  327. {
  328. struct magic_set *magic = magic_open(flags);
  329. if (magic == NULL) {
  330. (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
  331. return NULL;
  332. }
  333. if (magic_load(magic, magicfile) == -1) {
  334. (void)fprintf(stderr, "%s: %s\n",
  335. progname, magic_error(magic));
  336. magic_close(magic);
  337. return NULL;
  338. }
  339. return magic;
  340. }
  341. /*
  342. * unwrap -- read a file of filenames, do each one.
  343. */
  344. private int
  345. unwrap(struct magic_set *ms, const char *fn)
  346. {
  347. FILE *f;
  348. ssize_t len;
  349. char *line = NULL;
  350. size_t llen = 0;
  351. int wid = 0, cwid;
  352. int e = 0;
  353. if (strcmp("-", fn) == 0) {
  354. f = stdin;
  355. wid = 1;
  356. } else {
  357. if ((f = fopen(fn, "r")) == NULL) {
  358. (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
  359. progname, fn, strerror(errno));
  360. return 1;
  361. }
  362. while ((len = getline(&line, &llen, f)) > 0) {
  363. if (line[len - 1] == '\n')
  364. line[len - 1] = '\0';
  365. cwid = file_mbswidth(line);
  366. if (cwid > wid)
  367. wid = cwid;
  368. }
  369. rewind(f);
  370. }
  371. while ((len = getline(&line, &llen, f)) > 0) {
  372. if (line[len - 1] == '\n')
  373. line[len - 1] = '\0';
  374. e |= process(ms, line, wid);
  375. if(nobuffer)
  376. (void)fflush(stdout);
  377. }
  378. free(line);
  379. (void)fclose(f);
  380. return e;
  381. }
  382. /*
  383. * Called for each input file on the command line (or in a list of files)
  384. */
  385. private int
  386. process(struct magic_set *ms, const char *inname, int wid)
  387. {
  388. const char *type;
  389. int std_in = strcmp(inname, "-") == 0;
  390. if (wid > 0 && !bflag) {
  391. (void)printf("%s", std_in ? "/dev/stdin" : inname);
  392. if (nulsep)
  393. (void)putc('\0', stdout);
  394. (void)printf("%s", separator);
  395. (void)printf("%*s ",
  396. (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
  397. }
  398. type = magic_file(ms, std_in ? NULL : inname);
  399. if (type == NULL) {
  400. (void)printf("ERROR: %s\n", magic_error(ms));
  401. return 1;
  402. } else {
  403. (void)printf("%s\n", type);
  404. return 0;
  405. }
  406. }
  407. protected size_t
  408. file_mbswidth(const char *s)
  409. {
  410. #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
  411. size_t bytesconsumed, old_n, n, width = 0;
  412. mbstate_t state;
  413. wchar_t nextchar;
  414. (void)memset(&state, 0, sizeof(mbstate_t));
  415. old_n = n = strlen(s);
  416. while (n > 0) {
  417. bytesconsumed = mbrtowc(&nextchar, s, n, &state);
  418. if (bytesconsumed == (size_t)(-1) ||
  419. bytesconsumed == (size_t)(-2)) {
  420. /* Something went wrong, return something reasonable */
  421. return old_n;
  422. }
  423. if (s[0] == '\n') {
  424. /*
  425. * do what strlen() would do, so that caller
  426. * is always right
  427. */
  428. width++;
  429. } else
  430. width += wcwidth(nextchar);
  431. s += bytesconsumed, n -= bytesconsumed;
  432. }
  433. return width;
  434. #else
  435. return strlen(s);
  436. #endif
  437. }
  438. private void
  439. usage(void)
  440. {
  441. (void)fprintf(stderr, USAGE, progname, progname, progname);
  442. exit(1);
  443. }
  444. private void
  445. docprint(const char *opts)
  446. {
  447. size_t i;
  448. int comma;
  449. char *sp, *p;
  450. p = strstr(opts, "%o");
  451. if (p == NULL) {
  452. fprintf(stdout, "%s", opts);
  453. return;
  454. }
  455. for (sp = p - 1; sp > opts && *sp == ' '; sp--)
  456. continue;
  457. fprintf(stdout, "%.*s", (int)(p - opts), opts);
  458. comma = 0;
  459. for (i = 0; i < __arraycount(nv); i++) {
  460. fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
  461. if (i && i % 5 == 0) {
  462. fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
  463. comma = 0;
  464. }
  465. }
  466. fprintf(stdout, "%s", opts + (p - opts) + 2);
  467. }
  468. private void
  469. help(void)
  470. {
  471. (void)fputs(
  472. "Usage: file [OPTION...] [FILE...]\n"
  473. "Determine type of FILEs.\n"
  474. "\n", stdout);
  475. #define OPT(shortname, longname, opt, doc) \
  476. fprintf(stdout, " -%c, --" longname, shortname), \
  477. docprint(doc);
  478. #define OPT_LONGONLY(longname, opt, doc) \
  479. fprintf(stdout, " --" longname), \
  480. docprint(doc);
  481. #include "file_opts.h"
  482. #undef OPT
  483. #undef OPT_LONGONLY
  484. fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
  485. exit(0);
  486. }