file.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  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.111 2007/05/08 14:44:18 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, i;
  108. int action = 0, didsomefiles = 0, errflg = 0;
  109. int flags = 0;
  110. char *home, *usermagic;
  111. struct stat sb;
  112. static const char hmagic[] = "/.magic";
  113. #define OPTSTRING "bcCde:f:F:hikLm:nNprsvz0"
  114. #ifdef HAVE_GETOPT_LONG
  115. int longindex;
  116. static const struct option long_options[] =
  117. {
  118. {"version", 0, 0, 'v'},
  119. {"help", 0, 0, 0},
  120. {"brief", 0, 0, 'b'},
  121. {"checking-printout", 0, 0, 'c'},
  122. {"debug", 0, 0, 'd'},
  123. {"exclude", 1, 0, 'e' },
  124. {"files-from", 1, 0, 'f'},
  125. {"separator", 1, 0, 'F'},
  126. {"mime", 0, 0, 'i'},
  127. {"keep-going", 0, 0, 'k'},
  128. #ifdef S_IFLNK
  129. {"dereference", 0, 0, 'L'},
  130. {"no-dereference", 0, 0, 'h'},
  131. #endif
  132. {"magic-file", 1, 0, 'm'},
  133. #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
  134. {"preserve-date", 0, 0, 'p'},
  135. #endif
  136. {"uncompress", 0, 0, 'z'},
  137. {"raw", 0, 0, 'r'},
  138. {"no-buffer", 0, 0, 'n'},
  139. {"no-pad", 0, 0, 'N'},
  140. {"special-files", 0, 0, 's'},
  141. {"compile", 0, 0, 'C'},
  142. {"print0", 0, 0, '0'},
  143. {0, 0, 0, 0},
  144. };
  145. #endif
  146. static const struct {
  147. const char *name;
  148. int value;
  149. } nv[] = {
  150. { "apptype", MAGIC_NO_CHECK_APPTYPE },
  151. { "ascii", MAGIC_NO_CHECK_ASCII },
  152. { "compress", MAGIC_NO_CHECK_COMPRESS },
  153. { "elf", MAGIC_NO_CHECK_ELF },
  154. { "fortran", MAGIC_NO_CHECK_FORTRAN },
  155. { "soft", MAGIC_NO_CHECK_SOFT },
  156. { "tar", MAGIC_NO_CHECK_TAR },
  157. { "tokens", MAGIC_NO_CHECK_TOKENS },
  158. { "troff", MAGIC_NO_CHECK_TROFF },
  159. };
  160. #ifdef LC_CTYPE
  161. /* makes islower etc work for other langs */
  162. (void)setlocale(LC_CTYPE, "");
  163. #endif
  164. #ifdef __EMX__
  165. /* sh-like wildcard expansion! Shouldn't hurt at least ... */
  166. _wildcard(&argc, &argv);
  167. #endif
  168. if ((progname = strrchr(argv[0], '/')) != NULL)
  169. progname++;
  170. else
  171. progname = argv[0];
  172. magicfile = default_magicfile;
  173. if ((usermagic = getenv("MAGIC")) != NULL)
  174. magicfile = usermagic;
  175. else
  176. if ((home = getenv("HOME")) != NULL) {
  177. if ((usermagic = malloc(strlen(home)
  178. + sizeof(hmagic))) != NULL) {
  179. (void)strcpy(usermagic, home);
  180. (void)strcat(usermagic, hmagic);
  181. if (stat(usermagic, &sb)<0)
  182. free(usermagic);
  183. else
  184. magicfile = usermagic;
  185. }
  186. }
  187. #ifdef S_IFLNK
  188. flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
  189. #endif
  190. #ifndef HAVE_GETOPT_LONG
  191. while ((c = getopt(argc, argv, OPTSTRING)) != -1)
  192. #else
  193. while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
  194. &longindex)) != -1)
  195. #endif
  196. switch (c) {
  197. #ifdef HAVE_GETOPT_LONG
  198. case 0 :
  199. if (longindex == 1)
  200. help();
  201. break;
  202. #endif
  203. case '0':
  204. nulsep = 1;
  205. break;
  206. case 'b':
  207. ++bflag;
  208. break;
  209. case 'c':
  210. action = FILE_CHECK;
  211. break;
  212. case 'C':
  213. action = FILE_COMPILE;
  214. break;
  215. case 'd':
  216. flags |= MAGIC_DEBUG|MAGIC_CHECK;
  217. break;
  218. case 'e':
  219. for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
  220. if (strcmp(nv[i].name, optarg) == 0)
  221. break;
  222. if (i == sizeof(nv) / sizeof(nv[0]))
  223. errflg++;
  224. else
  225. flags |= nv[i].value;
  226. break;
  227. case 'f':
  228. if(action)
  229. usage();
  230. load(magicfile, flags);
  231. unwrap(optarg);
  232. ++didsomefiles;
  233. break;
  234. case 'F':
  235. separator = optarg;
  236. break;
  237. case 'i':
  238. flags |= MAGIC_MIME;
  239. break;
  240. case 'k':
  241. flags |= MAGIC_CONTINUE;
  242. break;
  243. case 'm':
  244. magicfile = optarg;
  245. break;
  246. case 'n':
  247. ++nobuffer;
  248. break;
  249. case 'N':
  250. ++nopad;
  251. break;
  252. #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
  253. case 'p':
  254. flags |= MAGIC_PRESERVE_ATIME;
  255. break;
  256. #endif
  257. case 'r':
  258. flags |= MAGIC_RAW;
  259. break;
  260. case 's':
  261. flags |= MAGIC_DEVICES;
  262. break;
  263. case 'v':
  264. (void)fprintf(stdout, "%s-%d.%.2d\n", progname,
  265. FILE_VERSION_MAJOR, patchlevel);
  266. (void)fprintf(stdout, "magic file from %s\n",
  267. magicfile);
  268. return 1;
  269. case 'z':
  270. flags |= MAGIC_COMPRESS;
  271. break;
  272. #ifdef S_IFLNK
  273. case 'L':
  274. flags |= MAGIC_SYMLINK;
  275. break;
  276. case 'h':
  277. flags &= ~MAGIC_SYMLINK;
  278. break;
  279. #endif
  280. case '?':
  281. default:
  282. errflg++;
  283. break;
  284. }
  285. if (errflg) {
  286. usage();
  287. }
  288. switch(action) {
  289. case FILE_CHECK:
  290. case FILE_COMPILE:
  291. magic = magic_open(flags|MAGIC_CHECK);
  292. if (magic == NULL) {
  293. (void)fprintf(stderr, "%s: %s\n", progname,
  294. strerror(errno));
  295. return 1;
  296. }
  297. c = action == FILE_CHECK ? magic_check(magic, magicfile) :
  298. magic_compile(magic, magicfile);
  299. if (c == -1) {
  300. (void)fprintf(stderr, "%s: %s\n", progname,
  301. magic_error(magic));
  302. return -1;
  303. }
  304. return 0;
  305. default:
  306. load(magicfile, flags);
  307. break;
  308. }
  309. if (optind == argc) {
  310. if (!didsomefiles) {
  311. usage();
  312. }
  313. }
  314. else {
  315. int i, wid, nw;
  316. for (wid = 0, i = optind; i < argc; i++) {
  317. nw = file_mbswidth(argv[i]);
  318. if (nw > wid)
  319. wid = nw;
  320. }
  321. for (; optind < argc; optind++)
  322. process(argv[optind], wid);
  323. }
  324. magic_close(magic);
  325. return 0;
  326. }
  327. private void
  328. /*ARGSUSED*/
  329. load(const char *m, int flags)
  330. {
  331. if (magic || m == NULL)
  332. return;
  333. magic = magic_open(flags);
  334. if (magic == NULL) {
  335. (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
  336. exit(1);
  337. }
  338. if (magic_load(magic, magicfile) == -1) {
  339. (void)fprintf(stderr, "%s: %s\n",
  340. progname, magic_error(magic));
  341. exit(1);
  342. }
  343. }
  344. /*
  345. * unwrap -- read a file of filenames, do each one.
  346. */
  347. private void
  348. unwrap(char *fn)
  349. {
  350. char buf[MAXPATHLEN];
  351. FILE *f;
  352. int wid = 0, cwid;
  353. size_t len;
  354. if (strcmp("-", fn) == 0) {
  355. f = stdin;
  356. wid = 1;
  357. } else {
  358. if ((f = fopen(fn, "r")) == NULL) {
  359. (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
  360. progname, fn, strerror(errno));
  361. exit(1);
  362. }
  363. while (fgets(buf, MAXPATHLEN, f) != NULL) {
  364. len = strlen(buf);
  365. if (len > 0 && buf[len - 1] == '\n')
  366. buf[len - 1] = '\0';
  367. cwid = file_mbswidth(buf);
  368. if (cwid > wid)
  369. wid = cwid;
  370. }
  371. rewind(f);
  372. }
  373. while (fgets(buf, MAXPATHLEN, f) != NULL) {
  374. len = strlen(buf);
  375. if (len > 0 && buf[len - 1] == '\n')
  376. buf[len - 1] = '\0';
  377. process(buf, wid);
  378. if(nobuffer)
  379. (void)fflush(stdout);
  380. }
  381. (void)fclose(f);
  382. }
  383. /*
  384. * Called for each input file on the command line (or in a list of files)
  385. */
  386. private void
  387. process(const char *inname, int wid)
  388. {
  389. const char *type;
  390. int std_in = strcmp(inname, "-") == 0;
  391. if (wid > 0 && !bflag) {
  392. (void)printf("%s", std_in ? "/dev/stdin" : inname);
  393. if (nulsep)
  394. (void)putc('\0', stdout);
  395. else
  396. (void)printf("%s", separator);
  397. (void)printf("%*s ",
  398. (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
  399. }
  400. type = magic_file(magic, std_in ? NULL : inname);
  401. if (type == NULL)
  402. (void)printf("ERROR: %s\n", magic_error(magic));
  403. else
  404. (void)printf("%s\n", type);
  405. }
  406. #if 0
  407. /*
  408. * byteconv4
  409. * Input:
  410. * from 4 byte quantity to convert
  411. * same whether to perform byte swapping
  412. * big_endian whether we are a big endian host
  413. */
  414. private int
  415. byteconv4(int from, int same, int big_endian)
  416. {
  417. if (same)
  418. return from;
  419. else if (big_endian) { /* lsb -> msb conversion on msb */
  420. union {
  421. int i;
  422. char c[4];
  423. } retval, tmpval;
  424. tmpval.i = from;
  425. retval.c[0] = tmpval.c[3];
  426. retval.c[1] = tmpval.c[2];
  427. retval.c[2] = tmpval.c[1];
  428. retval.c[3] = tmpval.c[0];
  429. return retval.i;
  430. }
  431. else
  432. return ntohl(from); /* msb -> lsb conversion on lsb */
  433. }
  434. /*
  435. * byteconv2
  436. * Same as byteconv4, but for shorts
  437. */
  438. private short
  439. byteconv2(int from, int same, int big_endian)
  440. {
  441. if (same)
  442. return from;
  443. else if (big_endian) { /* lsb -> msb conversion on msb */
  444. union {
  445. short s;
  446. char c[2];
  447. } retval, tmpval;
  448. tmpval.s = (short) from;
  449. retval.c[0] = tmpval.c[1];
  450. retval.c[1] = tmpval.c[0];
  451. return retval.s;
  452. }
  453. else
  454. return ntohs(from); /* msb -> lsb conversion on lsb */
  455. }
  456. #endif
  457. size_t
  458. file_mbswidth(const char *s)
  459. {
  460. #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
  461. size_t bytesconsumed, old_n, n, width = 0;
  462. mbstate_t state;
  463. wchar_t nextchar;
  464. (void)memset(&state, 0, sizeof(mbstate_t));
  465. old_n = n = strlen(s);
  466. while (n > 0) {
  467. bytesconsumed = mbrtowc(&nextchar, s, n, &state);
  468. if (bytesconsumed == (size_t)(-1) ||
  469. bytesconsumed == (size_t)(-2)) {
  470. /* Something went wrong, return something reasonable */
  471. return old_n;
  472. }
  473. if (s[0] == '\n') {
  474. /*
  475. * do what strlen() would do, so that caller
  476. * is always right
  477. */
  478. width++;
  479. } else
  480. width += wcwidth(nextchar);
  481. s += bytesconsumed, n -= bytesconsumed;
  482. }
  483. return width;
  484. #else
  485. return strlen(s);
  486. #endif
  487. }
  488. private void
  489. usage(void)
  490. {
  491. (void)fprintf(stderr, USAGE, progname, progname);
  492. #ifdef HAVE_GETOPT_LONG
  493. (void)fputs("Try `file --help' for more information.\n", stderr);
  494. #endif
  495. exit(1);
  496. }
  497. #ifdef HAVE_GETOPT_LONG
  498. private void
  499. help(void)
  500. {
  501. (void)puts(
  502. "Usage: file [OPTION]... [FILE]...\n"
  503. "Determine file type of FILEs.\n"
  504. "\n"
  505. " -m, --magic-file LIST use LIST as a colon-separated list of magic\n"
  506. " number files\n"
  507. " -z, --uncompress try to look inside compressed files\n"
  508. " -b, --brief do not prepend filenames to output lines\n"
  509. " -c, --checking-printout print the parsed form of the magic file, use in\n"
  510. " conjunction with -m to debug a new magic file\n"
  511. " before installing it\n"
  512. " -e, --exclude exclude test from the list of test to be\n"
  513. " performed for file. Valid tests are:\n"
  514. " ascii, apptype, elf, compress, soft, tar\n"
  515. " -f, --files-from FILE read the filenames to be examined from FILE\n"
  516. " -F, --separator string use string as separator instead of `:'\n"
  517. " -i, --mime output mime type strings\n"
  518. " -k, --keep-going don't stop at the first match\n"
  519. " -L, --dereference causes symlinks to be followed\n"
  520. " -n, --no-buffer do not buffer output\n"
  521. " -N, --no-pad do not pad output\n"
  522. " -p, --preserve-date preserve access times on files\n"
  523. " -r, --raw don't translate unprintable chars to \\ooo\n"
  524. " -s, --special-files treat special (block/char devices) files as\n"
  525. " ordinary ones\n"
  526. "or\n"
  527. " --help display this help and exit\n"
  528. "or\n"
  529. " --version output version information and exit\n"
  530. "or\n"
  531. " -C, --compile compile file specified by -m\n"
  532. );
  533. exit(0);
  534. }
  535. #endif