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.
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
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.
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
29 * file - find type of a file or files - main program.
39 #include <sys/types.h>
40 #include <sys/param.h> /* for MAXPATHLEN */
43 # if (__COHERENT__ >= 0x420)
44 # include <sys/utime.h>
47 # include <sys/time.h>
54 #include <unistd.h> /* for read() */
64 #include <getopt.h> /* for long options (is this portable?)*/
66 #undef HAVE_GETOPT_LONG
69 #include <netinet/in.h> /* for byte swapping */
71 #include "patchlevel.h"
74 FILE_RCSID("@(#)$File: file.c,v 1.111 2007/05/08 14:44:18 christos Exp $")
79 #define SYMLINKFLAG "Lh"
81 #define SYMLINKFLAG ""
84 # define USAGE "Usage: %s [-bcik" SYMLINKFLAG "nNrsvz0] [-e test] [-f namefile] [-F separator] [-m magicfiles] file...\n %s -C -m magicfiles\n"
87 #define MAXPATHLEN 512
90 private int /* Global command-line options */
91 bflag = 0, /* brief output format */
92 nopad = 0, /* Don't pad output */
93 nobuffer = 0, /* Do not buffer stdout */
94 nulsep = 0; /* Append '\0' to the separator */
96 private const char *magicfile = 0; /* where the magic is */
97 private const char *default_magicfile = MAGIC;
98 private const char *separator = ":"; /* Default field separator */
100 private char *progname; /* used throughout */
102 private struct magic_set *magic;
104 private void unwrap(char *);
105 private void usage(void);
106 #ifdef HAVE_GETOPT_LONG
107 private void help(void);
110 private int byteconv4(int, int, int);
111 private short byteconv2(int, int, int);
114 int main(int, char *[]);
115 private void process(const char *, int);
116 private void load(const char *, int);
120 * main - parse arguments and handle options
123 main(int argc, char *argv[])
126 int action = 0, didsomefiles = 0, errflg = 0;
128 char *home, *usermagic;
130 static const char hmagic[] = "/.magic";
131 #define OPTSTRING "bcCde:f:F:hikLm:nNprsvz0"
132 #ifdef HAVE_GETOPT_LONG
134 static const struct option long_options[] =
136 {"version", 0, 0, 'v'},
138 {"brief", 0, 0, 'b'},
139 {"checking-printout", 0, 0, 'c'},
140 {"debug", 0, 0, 'd'},
141 {"exclude", 1, 0, 'e' },
142 {"files-from", 1, 0, 'f'},
143 {"separator", 1, 0, 'F'},
145 {"keep-going", 0, 0, 'k'},
147 {"dereference", 0, 0, 'L'},
148 {"no-dereference", 0, 0, 'h'},
150 {"magic-file", 1, 0, 'm'},
151 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
152 {"preserve-date", 0, 0, 'p'},
154 {"uncompress", 0, 0, 'z'},
156 {"no-buffer", 0, 0, 'n'},
157 {"no-pad", 0, 0, 'N'},
158 {"special-files", 0, 0, 's'},
159 {"compile", 0, 0, 'C'},
160 {"print0", 0, 0, '0'},
165 static const struct {
169 { "apptype", MAGIC_NO_CHECK_APPTYPE },
170 { "ascii", MAGIC_NO_CHECK_ASCII },
171 { "compress", MAGIC_NO_CHECK_COMPRESS },
172 { "elf", MAGIC_NO_CHECK_ELF },
173 { "fortran", MAGIC_NO_CHECK_FORTRAN },
174 { "soft", MAGIC_NO_CHECK_SOFT },
175 { "tar", MAGIC_NO_CHECK_TAR },
176 { "tokens", MAGIC_NO_CHECK_TOKENS },
177 { "troff", MAGIC_NO_CHECK_TROFF },
181 /* makes islower etc work for other langs */
182 (void)setlocale(LC_CTYPE, "");
186 /* sh-like wildcard expansion! Shouldn't hurt at least ... */
187 _wildcard(&argc, &argv);
190 if ((progname = strrchr(argv[0], '/')) != NULL)
195 magicfile = default_magicfile;
196 if ((usermagic = getenv("MAGIC")) != NULL)
197 magicfile = usermagic;
199 if ((home = getenv("HOME")) != NULL) {
200 if ((usermagic = malloc(strlen(home)
201 + sizeof(hmagic))) != NULL) {
202 (void)strcpy(usermagic, home);
203 (void)strcat(usermagic, hmagic);
204 if (stat(usermagic, &sb)<0)
207 magicfile = usermagic;
212 flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
214 #ifndef HAVE_GETOPT_LONG
215 while ((c = getopt(argc, argv, OPTSTRING)) != -1)
217 while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
221 #ifdef HAVE_GETOPT_LONG
237 action = FILE_COMPILE;
240 flags |= MAGIC_DEBUG|MAGIC_CHECK;
243 for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
244 if (strcmp(nv[i].name, optarg) == 0)
247 if (i == sizeof(nv) / sizeof(nv[0]))
250 flags |= nv[i].value;
256 load(magicfile, flags);
267 flags |= MAGIC_CONTINUE;
278 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
280 flags |= MAGIC_PRESERVE_ATIME;
287 flags |= MAGIC_DEVICES;
290 (void)fprintf(stdout, "%s-%d.%.2d\n", progname,
291 FILE_VERSION_MAJOR, patchlevel);
292 (void)fprintf(stdout, "magic file from %s\n",
296 flags |= MAGIC_COMPRESS;
300 flags |= MAGIC_SYMLINK;
303 flags &= ~MAGIC_SYMLINK;
319 magic = magic_open(flags|MAGIC_CHECK);
321 (void)fprintf(stderr, "%s: %s\n", progname,
325 c = action == FILE_CHECK ? magic_check(magic, magicfile) :
326 magic_compile(magic, magicfile);
328 (void)fprintf(stderr, "%s: %s\n", progname,
334 load(magicfile, flags);
338 if (optind == argc) {
345 for (wid = 0, i = optind; i < argc; i++) {
346 nw = file_mbswidth(argv[i]);
350 for (; optind < argc; optind++)
351 process(argv[optind], wid);
361 load(const char *m, int flags)
363 if (magic || m == NULL)
365 magic = magic_open(flags);
367 (void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
370 if (magic_load(magic, magicfile) == -1) {
371 (void)fprintf(stderr, "%s: %s\n",
372 progname, magic_error(magic));
378 * unwrap -- read a file of filenames, do each one.
383 char buf[MAXPATHLEN];
388 if (strcmp("-", fn) == 0) {
392 if ((f = fopen(fn, "r")) == NULL) {
393 (void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
394 progname, fn, strerror(errno));
398 while (fgets(buf, MAXPATHLEN, f) != NULL) {
400 if (len > 0 && buf[len - 1] == '\n')
402 cwid = file_mbswidth(buf);
410 while (fgets(buf, MAXPATHLEN, f) != NULL) {
412 if (len > 0 && buf[len - 1] == '\n')
416 (void)fflush(stdout);
423 * Called for each input file on the command line (or in a list of files)
426 process(const char *inname, int wid)
429 int std_in = strcmp(inname, "-") == 0;
431 if (wid > 0 && !bflag) {
432 (void)printf("%s", std_in ? "/dev/stdin" : inname);
434 (void)putc('\0', stdout);
436 (void)printf("%s", separator);
438 (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
441 type = magic_file(magic, std_in ? NULL : inname);
443 (void)printf("ERROR: %s\n", magic_error(magic));
445 (void)printf("%s\n", type);
453 * from 4 byte quantity to convert
454 * same whether to perform byte swapping
455 * big_endian whether we are a big endian host
458 byteconv4(int from, int same, int big_endian)
462 else if (big_endian) { /* lsb -> msb conversion on msb */
469 retval.c[0] = tmpval.c[3];
470 retval.c[1] = tmpval.c[2];
471 retval.c[2] = tmpval.c[1];
472 retval.c[3] = tmpval.c[0];
477 return ntohl(from); /* msb -> lsb conversion on lsb */
482 * Same as byteconv4, but for shorts
485 byteconv2(int from, int same, int big_endian)
489 else if (big_endian) { /* lsb -> msb conversion on msb */
495 tmpval.s = (short) from;
496 retval.c[0] = tmpval.c[1];
497 retval.c[1] = tmpval.c[0];
502 return ntohs(from); /* msb -> lsb conversion on lsb */
507 file_mbswidth(const char *s)
509 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
510 size_t bytesconsumed, old_n, n, width = 0;
513 (void)memset(&state, 0, sizeof(mbstate_t));
514 old_n = n = strlen(s);
517 bytesconsumed = mbrtowc(&nextchar, s, n, &state);
518 if (bytesconsumed == (size_t)(-1) ||
519 bytesconsumed == (size_t)(-2)) {
520 /* Something went wrong, return something reasonable */
525 * do what strlen() would do, so that caller
530 width += wcwidth(nextchar);
532 s += bytesconsumed, n -= bytesconsumed;
543 (void)fprintf(stderr, USAGE, progname, progname);
544 #ifdef HAVE_GETOPT_LONG
545 (void)fputs("Try `file --help' for more information.\n", stderr);
550 #ifdef HAVE_GETOPT_LONG
555 "Usage: file [OPTION]... [FILE]...\n"
556 "Determine file type of FILEs.\n"
558 " -m, --magic-file LIST use LIST as a colon-separated list of magic\n"
560 " -z, --uncompress try to look inside compressed files\n"
561 " -b, --brief do not prepend filenames to output lines\n"
562 " -c, --checking-printout print the parsed form of the magic file, use in\n"
563 " conjunction with -m to debug a new magic file\n"
564 " before installing it\n"
565 " -e, --exclude exclude test from the list of test to be\n"
566 " performed for file. Valid tests are:\n"
567 " ascii, apptype, elf, compress, soft, tar\n"
568 " -f, --files-from FILE read the filenames to be examined from FILE\n"
569 " -F, --separator string use string as separator instead of `:'\n"
570 " -i, --mime output mime type strings\n"
571 " -k, --keep-going don't stop at the first match\n"
572 " -L, --dereference causes symlinks to be followed\n"
573 " -n, --no-buffer do not buffer output\n"
574 " -N, --no-pad do not pad output\n"
575 " -p, --preserve-date preserve access times on files\n"
576 " -r, --raw don't translate unprintable chars to \\ooo\n"
577 " -s, --special-files treat special (block/char devices) files as\n"
580 " --help display this help and exit\n"
582 " --version output version information and exit\n"
584 " -C, --compile compile file specified by -m\n"