file.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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.154 2014/09/10 18:41:51 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:nNprsvz0"
  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 char *progname; /* used throughout */
  109. private void usage(void);
  110. private void docprint(const char *);
  111. private void help(void);
  112. private int unwrap(struct magic_set *, const char *);
  113. private int process(struct magic_set *ms, const char *, int);
  114. private struct magic_set *load(const char *, int);
  115. /*
  116. * main - parse arguments and handle options
  117. */
  118. int
  119. main(int argc, char *argv[])
  120. {
  121. int c;
  122. size_t i;
  123. int action = 0, didsomefiles = 0, errflg = 0;
  124. int flags = 0, e = 0;
  125. struct magic_set *magic = NULL;
  126. int longindex;
  127. const char *magicfile = NULL; /* where the magic is */
  128. /* makes islower etc work for other langs */
  129. (void)setlocale(LC_CTYPE, "");
  130. #ifdef __EMX__
  131. /* sh-like wildcard expansion! Shouldn't hurt at least ... */
  132. _wildcard(&argc, &argv);
  133. #endif
  134. if ((progname = strrchr(argv[0], '/')) != NULL)
  135. progname++;
  136. else
  137. progname = argv[0];
  138. #ifdef S_IFLNK
  139. flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
  140. #endif
  141. while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
  142. &longindex)) != -1)
  143. switch (c) {
  144. case 0 :
  145. switch (longindex) {
  146. case 0:
  147. help();
  148. break;
  149. case 10:
  150. flags |= MAGIC_APPLE;
  151. break;
  152. case 11:
  153. flags |= MAGIC_MIME_TYPE;
  154. break;
  155. case 12:
  156. flags |= MAGIC_MIME_ENCODING;
  157. break;
  158. }
  159. break;
  160. case '0':
  161. nulsep = 1;
  162. break;
  163. case 'b':
  164. bflag++;
  165. break;
  166. case 'c':
  167. action = FILE_CHECK;
  168. break;
  169. case 'C':
  170. action = FILE_COMPILE;
  171. break;
  172. case 'd':
  173. flags |= MAGIC_DEBUG|MAGIC_CHECK;
  174. break;
  175. case 'E':
  176. flags |= MAGIC_ERROR;
  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. int w = wcwidth(nextchar);
  431. if (w > 0)
  432. width += w;
  433. }
  434. s += bytesconsumed, n -= bytesconsumed;
  435. }
  436. return width;
  437. #else
  438. return strlen(s);
  439. #endif
  440. }
  441. private void
  442. usage(void)
  443. {
  444. (void)fprintf(stderr, USAGE, progname, progname, progname);
  445. exit(1);
  446. }
  447. private void
  448. docprint(const char *opts)
  449. {
  450. size_t i;
  451. int comma;
  452. char *sp, *p;
  453. p = strstr(opts, "%o");
  454. if (p == NULL) {
  455. fprintf(stdout, "%s", opts);
  456. return;
  457. }
  458. for (sp = p - 1; sp > opts && *sp == ' '; sp--)
  459. continue;
  460. fprintf(stdout, "%.*s", (int)(p - opts), opts);
  461. comma = 0;
  462. for (i = 0; i < __arraycount(nv); i++) {
  463. fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
  464. if (i && i % 5 == 0) {
  465. fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
  466. comma = 0;
  467. }
  468. }
  469. fprintf(stdout, "%s", opts + (p - opts) + 2);
  470. }
  471. private void
  472. help(void)
  473. {
  474. (void)fputs(
  475. "Usage: file [OPTION...] [FILE...]\n"
  476. "Determine type of FILEs.\n"
  477. "\n", stdout);
  478. #define OPT(shortname, longname, opt, doc) \
  479. fprintf(stdout, " -%c, --" longname, shortname), \
  480. docprint(doc);
  481. #define OPT_LONGONLY(longname, opt, doc) \
  482. fprintf(stdout, " --" longname), \
  483. docprint(doc);
  484. #include "file_opts.h"
  485. #undef OPT
  486. #undef OPT_LONGONLY
  487. fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
  488. exit(0);
  489. }