file.c 11 KB

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