file.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  1. /*
  2. * file - find type of a file or files - main program.
  3. *
  4. * Copyright (c) Ian F. Darwin, 1987.
  5. * Written by Ian F. Darwin.
  6. *
  7. * This software is not subject to any license of the American Telephone
  8. * and Telegraph Company or of the Regents of the University of California.
  9. *
  10. * Permission is granted to anyone to use this software for any purpose on
  11. * any computer system, and to alter it and redistribute it freely, subject
  12. * to the following restrictions:
  13. *
  14. * 1. The author is not responsible for the consequences of use of this
  15. * software, no matter how awful, even if they arise from flaws in it.
  16. *
  17. * 2. The origin of this software must not be misrepresented, either by
  18. * explicit claim or by omission. Since few users ever read sources,
  19. * credits must appear in the documentation.
  20. *
  21. * 3. Altered versions must be plainly marked as such, and must not be
  22. * misrepresented as being the original software. Since few users
  23. * ever read sources, credits must appear in the documentation.
  24. *
  25. * 4. This notice may not be removed or altered.
  26. */
  27. #ifdef HAVE_CONFIG_H
  28. #include <config.h>
  29. #endif
  30. #include <stdio.h>
  31. #include <stdlib.h>
  32. #include <unistd.h>
  33. #include <string.h>
  34. #include <sys/types.h>
  35. #include <sys/param.h> /* for MAXPATHLEN */
  36. #include <sys/stat.h>
  37. #include <fcntl.h> /* for open() */
  38. #ifdef RESTORE_TIME
  39. # if (__COHERENT__ >= 0x420)
  40. # include <sys/utime.h>
  41. # else
  42. # ifdef USE_UTIMES
  43. # include <sys/time.h>
  44. # else
  45. # include <utime.h>
  46. # endif
  47. # endif
  48. #endif
  49. #ifdef HAVE_UNISTD_H
  50. #include <unistd.h> /* for read() */
  51. #endif
  52. #ifdef HAVE_LOCALE_H
  53. #include <locale.h>
  54. #endif
  55. #include <getopt.h> /* for long options (is this portable?)*/
  56. #include <netinet/in.h> /* for byte swapping */
  57. #include "file.h"
  58. #include "patchlevel.h"
  59. #ifndef lint
  60. FILE_RCSID("@(#)$Id: file.c,v 1.59 2001/07/23 00:02:32 christos Exp $")
  61. #endif /* lint */
  62. #ifdef S_IFLNK
  63. # define USAGE "Usage: %s [-bciknsvzL] [-f namefile] [-m magicfiles] file...\n"
  64. #else
  65. # define USAGE "Usage: %s [-bciknsvz] [-f namefile] [-m magicfiles] file...\n"
  66. #endif
  67. #ifndef MAGIC
  68. # define MAGIC "/etc/magic"
  69. #endif
  70. #ifndef MAXPATHLEN
  71. #define MAXPATHLEN 512
  72. #endif
  73. int /* Global command-line options */
  74. debug = 0, /* debugging */
  75. lflag = 0, /* follow Symlinks (BSD only) */
  76. bflag = 0, /* brief output format */
  77. zflag = 0, /* follow (uncompress) compressed files */
  78. sflag = 0, /* read block special files */
  79. iflag = 0,
  80. nobuffer = 0, /* Do not buffer stdout */
  81. kflag = 0; /* Keep going after the first match */
  82. int /* Misc globals */
  83. nmagic = 0; /* number of valid magic[]s */
  84. struct magic *magic; /* array of magic entries */
  85. const char *magicfile = 0; /* where the magic is */
  86. const char *default_magicfile = MAGIC;
  87. char *progname; /* used throughout */
  88. int lineno; /* line number in the magic file */
  89. static void unwrap __P((char *fn));
  90. static void usage __P((void));
  91. #if 0
  92. static int byteconv4 __P((int, int, int));
  93. static short byteconv2 __P((int, int, int));
  94. #endif
  95. int main __P((int, char *[]));
  96. void help()
  97. {
  98. puts(
  99. "Usage: file [OPTION]... [FILE]...
  100. Determine file type of FILEs.
  101. -m, --magic-file LIST use LIST as a colon-separated list of magic
  102. number files
  103. -z, --uncompress try to look inside compressed files
  104. -b, --brief do not prepend filenames to output lines
  105. -c, --checking-printout print the parsed form of the magic file, use in
  106. conjunction with -m to debug a new magic file
  107. before installing it
  108. -f, --files-from FILE read the filenames to be examined from FILE
  109. -i, --mime output mime type strings
  110. -k, --keep-going don't stop at the first match
  111. -L, --dereference causes symlinks to be followed
  112. -n, --no-buffer do not buffer output
  113. -s, --special-files treat special (block/char devices) files as
  114. ordinary ones
  115. --help display this help and exit
  116. --version output version information and exit");
  117. exit(0);
  118. }
  119. /*
  120. * main - parse arguments and handle options
  121. */
  122. int
  123. main(argc, argv)
  124. int argc;
  125. char *argv[];
  126. {
  127. int c, longindex;
  128. int action = 0, didsomefiles = 0, errflg = 0, ret = 0, app = 0;
  129. char *mime, *home, *usermagic;
  130. struct stat sb;
  131. static struct option long_options[] =
  132. {
  133. {"version", 0, 0, 'v'},
  134. {"help", 0, 0, 0},
  135. {"brief", 0, 0, 'b'},
  136. {"checking-printout", 0, 0, 'c'},
  137. {"debug", 0, 0, 'd'},
  138. {"files-from", 1, 0, 'f'},
  139. {"mime", 0, 0, 'i'},
  140. {"keep-going", 0, 0, 'k'},
  141. #ifdef S_IFLNK
  142. {"dereference", 0, 0, 'L'},
  143. #endif
  144. {"magic-file", 1, 0, 'm'},
  145. {"uncompress", 0, 0, 'z'},
  146. {"no-buffer", 0, 0, 'n'},
  147. {"special-files", 0, 0, 's'},
  148. {"compile", 0, 0, 'C'},
  149. {0, 0, 0, 0},
  150. };
  151. #ifdef LC_CTYPE
  152. setlocale(LC_CTYPE, ""); /* makes islower etc work for other langs */
  153. #endif
  154. if ((progname = strrchr(argv[0], '/')) != NULL)
  155. progname++;
  156. else
  157. progname = argv[0];
  158. magicfile = default_magicfile;
  159. if ((usermagic = getenv("MAGIC")) != NULL)
  160. magicfile = usermagic;
  161. else
  162. if ((home = getenv("HOME")) != NULL) {
  163. if ((usermagic = malloc(strlen(home) + 8)) != NULL) {
  164. (void)strcpy(usermagic, home);
  165. (void)strcat(usermagic, "/.magic");
  166. if (stat(usermagic, &sb)<0)
  167. free(usermagic);
  168. else
  169. magicfile = usermagic;
  170. }
  171. }
  172. while ((c = getopt_long(argc, argv, "bcdf:ikm:nsvzCL", long_options, &longindex)) != EOF)
  173. switch (c) {
  174. case 0 :
  175. if (longindex==1)
  176. help();
  177. break;
  178. case 'b':
  179. ++bflag;
  180. break;
  181. case 'c':
  182. action = CHECK;
  183. break;
  184. case 'C':
  185. action = COMPILE;
  186. break;
  187. case 'd':
  188. ++debug;
  189. break;
  190. case 'f':
  191. if (!app) {
  192. ret = apprentice(magicfile, action);
  193. if (action)
  194. exit(ret);
  195. app = 1;
  196. }
  197. unwrap(optarg);
  198. ++didsomefiles;
  199. break;
  200. case 'i':
  201. iflag++;
  202. if ((mime = malloc(strlen(magicfile) + 6)) != NULL) {
  203. (void)strcpy(mime, magicfile);
  204. (void)strcat(mime, ".mime");
  205. magicfile = mime;
  206. }
  207. break;
  208. case 'k':
  209. kflag = 1;
  210. break;
  211. case 'm':
  212. magicfile = optarg;
  213. break;
  214. case 'n':
  215. ++nobuffer;
  216. break;
  217. case 's':
  218. sflag++;
  219. break;
  220. case 'v':
  221. (void) fprintf(stdout, "%s-"VERSION"\n", progname);
  222. (void) fprintf(stdout, "magic data from %s\n",
  223. magicfile);
  224. return 1;
  225. case 'z':
  226. zflag++;
  227. break;
  228. #ifdef S_IFLNK
  229. case 'L':
  230. ++lflag;
  231. break;
  232. #endif
  233. case '?':
  234. default:
  235. errflg++;
  236. break;
  237. }
  238. if (errflg) {
  239. usage();
  240. fputs("Try `file --help' for more information.\n",stderr);
  241. }
  242. if (!app) {
  243. ret = apprentice(magicfile, action);
  244. if (action)
  245. exit(ret);
  246. app = 1;
  247. }
  248. if (optind == argc) {
  249. if (!didsomefiles) {
  250. usage();
  251. }
  252. }
  253. else {
  254. int i, wid, nw;
  255. for (wid = 0, i = optind; i < argc; i++) {
  256. nw = strlen(argv[i]);
  257. if (nw > wid)
  258. wid = nw;
  259. }
  260. for (; optind < argc; optind++)
  261. process(argv[optind], wid);
  262. }
  263. return 0;
  264. }
  265. /*
  266. * unwrap -- read a file of filenames, do each one.
  267. */
  268. static void
  269. unwrap(fn)
  270. char *fn;
  271. {
  272. char buf[MAXPATHLEN];
  273. FILE *f;
  274. int wid = 0, cwid;
  275. if (strcmp("-", fn) == 0) {
  276. f = stdin;
  277. wid = 1;
  278. } else {
  279. if ((f = fopen(fn, "r")) == NULL) {
  280. error("Cannot open `%s' (%m).\n", fn);
  281. /*NOTREACHED*/
  282. }
  283. while (fgets(buf, MAXPATHLEN, f) != NULL) {
  284. cwid = strlen(buf) - 1;
  285. if (cwid > wid)
  286. wid = cwid;
  287. }
  288. rewind(f);
  289. }
  290. while (fgets(buf, MAXPATHLEN, f) != NULL) {
  291. buf[strlen(buf)-1] = '\0';
  292. process(buf, wid);
  293. if(nobuffer)
  294. (void) fflush(stdout);
  295. }
  296. (void) fclose(f);
  297. }
  298. #if 0
  299. /*
  300. * byteconv4
  301. * Input:
  302. * from 4 byte quantity to convert
  303. * same whether to perform byte swapping
  304. * big_endian whether we are a big endian host
  305. */
  306. static int
  307. byteconv4(from, same, big_endian)
  308. int from;
  309. int same;
  310. int big_endian;
  311. {
  312. if (same)
  313. return from;
  314. else if (big_endian) { /* lsb -> msb conversion on msb */
  315. union {
  316. int i;
  317. char c[4];
  318. } retval, tmpval;
  319. tmpval.i = from;
  320. retval.c[0] = tmpval.c[3];
  321. retval.c[1] = tmpval.c[2];
  322. retval.c[2] = tmpval.c[1];
  323. retval.c[3] = tmpval.c[0];
  324. return retval.i;
  325. }
  326. else
  327. return ntohl(from); /* msb -> lsb conversion on lsb */
  328. }
  329. /*
  330. * byteconv2
  331. * Same as byteconv4, but for shorts
  332. */
  333. static short
  334. byteconv2(from, same, big_endian)
  335. int from;
  336. int same;
  337. int big_endian;
  338. {
  339. if (same)
  340. return from;
  341. else if (big_endian) { /* lsb -> msb conversion on msb */
  342. union {
  343. short s;
  344. char c[2];
  345. } retval, tmpval;
  346. tmpval.s = (short) from;
  347. retval.c[0] = tmpval.c[1];
  348. retval.c[1] = tmpval.c[0];
  349. return retval.s;
  350. }
  351. else
  352. return ntohs(from); /* msb -> lsb conversion on lsb */
  353. }
  354. #endif
  355. /*
  356. * process - process input file
  357. */
  358. void
  359. process(inname, wid)
  360. const char *inname;
  361. int wid;
  362. {
  363. int fd = 0;
  364. static const char stdname[] = "standard input";
  365. unsigned char buf[HOWMANY+1]; /* one extra for terminating '\0' */
  366. struct stat sb;
  367. int nbytes = 0; /* number of bytes read from a datafile */
  368. char match = '\0';
  369. if (strcmp("-", inname) == 0) {
  370. if (fstat(0, &sb)<0) {
  371. error("cannot fstat `%s' (%m).\n", stdname);
  372. /*NOTREACHED*/
  373. }
  374. inname = stdname;
  375. }
  376. if (wid > 0 && !bflag)
  377. (void) printf("%s:%*s ", inname,
  378. (int) (wid - strlen(inname)), "");
  379. if (inname != stdname) {
  380. /*
  381. * first try judging the file based on its filesystem status
  382. */
  383. if (fsmagic(inname, &sb) != 0) {
  384. putchar('\n');
  385. return;
  386. }
  387. if ((fd = open(inname, O_RDONLY)) < 0) {
  388. /* We can't open it, but we were able to stat it. */
  389. if (sb.st_mode & 0002) ckfputs("writeable, ", stdout);
  390. if (sb.st_mode & 0111) ckfputs("executable, ", stdout);
  391. ckfprintf(stdout, "can't read `%s' (%s).\n",
  392. inname, strerror(errno));
  393. return;
  394. }
  395. }
  396. /*
  397. * try looking at the first HOWMANY bytes
  398. */
  399. if ((nbytes = read(fd, (char *)buf, HOWMANY)) == -1) {
  400. error("read failed (%m).\n");
  401. /*NOTREACHED*/
  402. }
  403. if (nbytes == 0)
  404. ckfputs(iflag ? "application/x-empty" : "empty", stdout);
  405. else {
  406. buf[nbytes++] = '\0'; /* null-terminate it */
  407. match = tryit(buf, nbytes, zflag);
  408. }
  409. #ifdef BUILTIN_ELF
  410. if (match == 's' && nbytes > 5) {
  411. /*
  412. * We matched something in the file, so this *might*
  413. * be an ELF file, and the file is at least 5 bytes long,
  414. * so if it's an ELF file it has at least one byte
  415. * past the ELF magic number - try extracting information
  416. * from the ELF headers that can't easily be extracted
  417. * with rules in the magic file.
  418. */
  419. tryelf(fd, buf, nbytes);
  420. }
  421. #endif
  422. if (inname != stdname) {
  423. #ifdef RESTORE_TIME
  424. /*
  425. * Try to restore access, modification times if read it.
  426. * This is really *bad* because it will modify the status
  427. * time of the file... And of course this will affect
  428. * backup programs
  429. */
  430. # ifdef USE_UTIMES
  431. struct timeval utsbuf[2];
  432. utsbuf[0].tv_sec = sb.st_atime;
  433. utsbuf[1].tv_sec = sb.st_mtime;
  434. (void) utimes(inname, utsbuf); /* don't care if loses */
  435. # else
  436. struct utimbuf utbuf;
  437. utbuf.actime = sb.st_atime;
  438. utbuf.modtime = sb.st_mtime;
  439. (void) utime(inname, &utbuf); /* don't care if loses */
  440. # endif
  441. #endif
  442. (void) close(fd);
  443. }
  444. (void) putchar('\n');
  445. }
  446. int
  447. tryit(buf, nb, zfl)
  448. unsigned char *buf;
  449. int nb, zfl;
  450. {
  451. /* try compression stuff */
  452. if (zfl && zmagic(buf, nb))
  453. return 'z';
  454. /* try tests in /etc/magic (or surrogate magic file) */
  455. if (softmagic(buf, nb))
  456. return 's';
  457. /* try known keywords, check whether it is ASCII */
  458. if (ascmagic(buf, nb))
  459. return 'a';
  460. /* abandon hope, all ye who remain here */
  461. ckfputs("data", stdout);
  462. return '\0';
  463. }
  464. static void
  465. usage()
  466. {
  467. (void)fprintf(stderr, USAGE, progname);
  468. (void)fprintf(stderr, "Usage: %s -C [-m magic]\n", progname);
  469. exit(1);
  470. }