file.c 12 KB

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