file.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. #include "magic.h"
  33. #include <stdio.h>
  34. #include <stdlib.h>
  35. #include <unistd.h>
  36. #include <string.h>
  37. #include <sys/types.h>
  38. #include <sys/param.h> /* for MAXPATHLEN */
  39. #include <sys/stat.h>
  40. #ifdef RESTORE_TIME
  41. # if (__COHERENT__ >= 0x420)
  42. # include <sys/utime.h>
  43. # else
  44. # ifdef USE_UTIMES
  45. # include <sys/time.h>
  46. # else
  47. # include <utime.h>
  48. # endif
  49. # endif
  50. #endif
  51. #ifdef HAVE_UNISTD_H
  52. #include <unistd.h> /* for read() */
  53. #endif
  54. #ifdef HAVE_LOCALE_H
  55. #include <locale.h>
  56. #endif
  57. #ifdef HAVE_WCHAR_H
  58. #include <wchar.h>
  59. #endif
  60. #ifdef HAVE_GETOPT_H
  61. #include <getopt.h>
  62. #else
  63. #include "mygetopt.h"
  64. #endif
  65. #ifndef HAVE_GETOPT_LONG
  66. int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
  67. #endif
  68. #include <netinet/in.h> /* for byte swapping */
  69. #include "patchlevel.h"
  70. #ifndef lint
  71. FILE_RCSID("@(#)$File: file.c,v 1.121 2008/07/03 15:48:18 christos Exp $")
  72. #endif /* lint */
  73. #ifdef S_IFLNK
  74. #define SYMLINKFLAG "Lh"
  75. #else
  76. #define SYMLINKFLAG ""
  77. #endif
  78. # define USAGE "Usage: %s [-bcik" SYMLINKFLAG "nNrsvz0] [-e test] [-f namefile] [-F separator] [-m magicfiles] file...\n %s -C -m magicfiles\n"
  79. #ifndef MAXPATHLEN
  80. #define MAXPATHLEN 512
  81. #endif
  82. private int /* Global command-line options */
  83. bflag = 0, /* brief output format */
  84. nopad = 0, /* Don't pad output */
  85. nobuffer = 0, /* Do not buffer stdout */
  86. nulsep = 0; /* Append '\0' to the separator */
  87. private const char *magicfile = 0; /* where the magic is */
  88. private const char *default_magicfile = MAGIC;
  89. private const char *separator = ":"; /* Default field separator */
  90. private char *progname; /* used throughout */
  91. private struct magic_set *magic;
  92. private void unwrap(char *);
  93. private void usage(void);
  94. private void help(void);
  95. int main(int, char *[]);
  96. private void process(const char *, int);
  97. private void load(const char *, int);
  98. /*
  99. * main - parse arguments and handle options
  100. */
  101. int
  102. main(int argc, char *argv[])
  103. {
  104. int c;
  105. size_t i;
  106. int action = 0, didsomefiles = 0, errflg = 0;
  107. int flags = 0;
  108. char *home, *usermagic;
  109. struct stat sb;
  110. static const char hmagic[] = "/.magic";
  111. #define OPTSTRING "bcCde:f:F:hikLm:nNprsvz0"
  112. int longindex;
  113. static const struct option long_options[] =
  114. {
  115. #define OPT(shortname, longname, opt, doc) \
  116. {longname, opt, NULL, shortname},
  117. #define OPT_LONGONLY(longname, opt, doc) \
  118. {longname, opt, NULL, 0},
  119. #include "file_opts.h"
  120. #undef OPT
  121. #undef OPT_LONGONLY
  122. {0, 0, NULL, 0}
  123. };
  124. static const struct {
  125. const char *name;
  126. int value;
  127. } nv[] = {
  128. { "apptype", MAGIC_NO_CHECK_APPTYPE },
  129. { "ascii", MAGIC_NO_CHECK_ASCII },
  130. { "compress", MAGIC_NO_CHECK_COMPRESS },
  131. { "elf", MAGIC_NO_CHECK_ELF },
  132. { "soft", MAGIC_NO_CHECK_SOFT },
  133. { "tar", MAGIC_NO_CHECK_TAR },
  134. { "tokens", MAGIC_NO_CHECK_TOKENS },
  135. };
  136. /* makes islower etc work for other langs */
  137. (void)setlocale(LC_CTYPE, "");
  138. #ifdef __EMX__
  139. /* sh-like wildcard expansion! Shouldn't hurt at least ... */
  140. _wildcard(&argc, &argv);
  141. #endif
  142. if ((progname = strrchr(argv[0], '/')) != NULL)
  143. progname++;
  144. else
  145. progname = argv[0];
  146. magicfile = default_magicfile;
  147. if ((usermagic = getenv("MAGIC")) != NULL)
  148. magicfile = usermagic;
  149. else
  150. if ((home = getenv("HOME")) != NULL) {
  151. if ((usermagic = malloc(strlen(home)
  152. + sizeof(hmagic))) != NULL) {
  153. (void)strcpy(usermagic, home);
  154. (void)strcat(usermagic, hmagic);
  155. if (stat(usermagic, &sb)<0)
  156. free(usermagic);
  157. else
  158. magicfile = usermagic;
  159. }
  160. }
  161. #ifdef S_IFLNK
  162. flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
  163. #endif
  164. while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
  165. &longindex)) != -1)
  166. switch (c) {
  167. case 0 :
  168. switch (longindex) {
  169. case 0:
  170. help();
  171. break;
  172. case 10:
  173. flags |= MAGIC_MIME_TYPE;
  174. break;
  175. case 11:
  176. flags |= MAGIC_MIME_ENCODING;
  177. break;
  178. }
  179. break;
  180. case '0':
  181. nulsep = 1;
  182. break;
  183. case 'b':
  184. bflag++;
  185. break;
  186. case 'c':
  187. action = FILE_CHECK;
  188. break;
  189. case 'C':
  190. action = FILE_COMPILE;
  191. break;
  192. case 'd':
  193. flags |= MAGIC_DEBUG|MAGIC_CHECK;
  194. break;
  195. case 'e':
  196. for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
  197. if (strcmp(nv[i].name, optarg) == 0)
  198. break;
  199. if (i == sizeof(nv) / sizeof(nv[0]))
  200. errflg++;
  201. else
  202. flags |= nv[i].value;
  203. break;
  204. case 'f':
  205. if(action)
  206. usage();
  207. load(magicfile, flags);
  208. unwrap(optarg);
  209. ++didsomefiles;
  210. break;
  211. case 'F':
  212. separator = optarg;
  213. break;
  214. case 'i':
  215. flags |= MAGIC_MIME;
  216. break;
  217. case 'k':
  218. flags |= MAGIC_CONTINUE;
  219. break;
  220. case 'm':
  221. magicfile = optarg;
  222. break;
  223. case 'n':
  224. ++nobuffer;
  225. break;
  226. case 'N':
  227. ++nopad;
  228. break;
  229. #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
  230. case 'p':
  231. flags |= MAGIC_PRESERVE_ATIME;
  232. break;
  233. #endif
  234. case 'r':
  235. flags |= MAGIC_RAW;
  236. break;
  237. case 's':
  238. flags |= MAGIC_DEVICES;
  239. break;
  240. case 'v':
  241. (void)fprintf(stderr, "%s-%d.%.2d\n", progname,
  242. FILE_VERSION_MAJOR, patchlevel);
  243. (void)fprintf(stderr, "magic file from %s\n",
  244. magicfile);
  245. return 1;
  246. case 'z':
  247. flags |= MAGIC_COMPRESS;
  248. break;
  249. #ifdef S_IFLNK
  250. case 'L':
  251. flags |= MAGIC_SYMLINK;
  252. break;
  253. case 'h':
  254. flags &= ~MAGIC_SYMLINK;
  255. break;
  256. #endif
  257. case '?':
  258. default:
  259. errflg++;
  260. break;
  261. }
  262. if (errflg) {
  263. usage();
  264. }
  265. switch(action) {
  266. case FILE_CHECK:
  267. case FILE_COMPILE:
  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. c = action == FILE_CHECK ? magic_check(magic, magicfile) :
  275. magic_compile(magic, magicfile);
  276. if (c == -1) {
  277. (void)fprintf(stderr, "%s: %s\n", progname,
  278. magic_error(magic));
  279. return -1;
  280. }
  281. return 0;
  282. default:
  283. load(magicfile, flags);
  284. break;
  285. }
  286. if (optind == argc) {
  287. if (!didsomefiles) {
  288. usage();
  289. }
  290. }
  291. else {
  292. size_t j, wid, nw;
  293. for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
  294. nw = file_mbswidth(argv[j]);
  295. if (nw > wid)
  296. wid = nw;
  297. }
  298. /*
  299. * If bflag is only set twice, set it depending on
  300. * number of files [this is undocumented, and subject to change]
  301. */
  302. if (bflag == 2) {
  303. bflag = optind >= argc - 1;
  304. }
  305. for (; optind < argc; optind++)
  306. process(argv[optind], wid);
  307. }
  308. c = magic->haderr ? 1 : 0;
  309. magic_close(magic);
  310. return c;
  311. }
  312. private void
  313. /*ARGSUSED*/
  314. load(const char *m, int flags)
  315. {
  316. if (magic || m == NULL)
  317. return;
  318. magic = magic_open(flags);
  319. if (magic == NULL) {
  320. (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
  321. exit(1);
  322. }
  323. if (magic_load(magic, magicfile) == -1) {
  324. (void)fprintf(stderr, "%s: %s\n",
  325. progname, magic_error(magic));
  326. exit(1);
  327. }
  328. }
  329. /*
  330. * unwrap -- read a file of filenames, do each one.
  331. */
  332. private void
  333. unwrap(char *fn)
  334. {
  335. char buf[MAXPATHLEN];
  336. FILE *f;
  337. int wid = 0, cwid;
  338. if (strcmp("-", fn) == 0) {
  339. f = stdin;
  340. wid = 1;
  341. } else {
  342. if ((f = fopen(fn, "r")) == NULL) {
  343. (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
  344. progname, fn, strerror(errno));
  345. exit(1);
  346. }
  347. while (fgets(buf, sizeof(buf), f) != NULL) {
  348. buf[strcspn(buf, "\n")] = '\0';
  349. cwid = file_mbswidth(buf);
  350. if (cwid > wid)
  351. wid = cwid;
  352. }
  353. rewind(f);
  354. }
  355. while (fgets(buf, sizeof(buf), f) != NULL) {
  356. buf[strcspn(buf, "\n")] = '\0';
  357. process(buf, wid);
  358. if(nobuffer)
  359. (void)fflush(stdout);
  360. }
  361. (void)fclose(f);
  362. }
  363. /*
  364. * Called for each input file on the command line (or in a list of files)
  365. */
  366. private void
  367. process(const char *inname, int wid)
  368. {
  369. const char *type;
  370. int std_in = strcmp(inname, "-") == 0;
  371. if (wid > 0 && !bflag) {
  372. (void)printf("%s", std_in ? "/dev/stdin" : inname);
  373. if (nulsep)
  374. (void)putc('\0', stdout);
  375. else
  376. (void)printf("%s", separator);
  377. (void)printf("%*s ",
  378. (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
  379. }
  380. type = magic_file(magic, std_in ? NULL : inname);
  381. if (type == NULL)
  382. (void)printf("ERROR: %s\n", magic_error(magic));
  383. else
  384. (void)printf("%s\n", type);
  385. }
  386. size_t
  387. file_mbswidth(const char *s)
  388. {
  389. #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
  390. size_t bytesconsumed, old_n, n, width = 0;
  391. mbstate_t state;
  392. wchar_t nextchar;
  393. (void)memset(&state, 0, sizeof(mbstate_t));
  394. old_n = n = strlen(s);
  395. while (n > 0) {
  396. bytesconsumed = mbrtowc(&nextchar, s, n, &state);
  397. if (bytesconsumed == (size_t)(-1) ||
  398. bytesconsumed == (size_t)(-2)) {
  399. /* Something went wrong, return something reasonable */
  400. return old_n;
  401. }
  402. if (s[0] == '\n') {
  403. /*
  404. * do what strlen() would do, so that caller
  405. * is always right
  406. */
  407. width++;
  408. } else
  409. width += wcwidth(nextchar);
  410. s += bytesconsumed, n -= bytesconsumed;
  411. }
  412. return width;
  413. #else
  414. return strlen(s);
  415. #endif
  416. }
  417. private void
  418. usage(void)
  419. {
  420. (void)fprintf(stderr, USAGE, progname, progname);
  421. (void)fputs("Try `file --help' for more information.\n", stderr);
  422. exit(1);
  423. }
  424. private void
  425. help(void)
  426. {
  427. (void)fputs(
  428. "Usage: file [OPTION...] [FILE...]\n"
  429. "Determine type of FILEs.\n"
  430. "\n", stderr);
  431. #define OPT(shortname, longname, opt, doc) \
  432. fprintf(stderr, " -%c, --" longname doc, shortname);
  433. #define OPT_LONGONLY(longname, opt, doc) \
  434. fprintf(stderr, " --" longname doc);
  435. #include "file_opts.h"
  436. #undef OPT
  437. #undef OPT_LONGONLY
  438. exit(0);
  439. }