file.c 12 KB

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