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.
35 FILE_RCSID("@(#)$File: file.c,v 1.175 2018/03/02 16:11:37 christos Exp $")
44 # if (__COHERENT__ >= 0x420)
45 # include <sys/utime.h>
48 # include <sys/time.h>
55 #include <unistd.h> /* for read() */
61 #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
63 # ifndef HAVE_GETOPT_LONG
64 int getopt_long(int, char * const *, const char *,
65 const struct option *, int *);
68 # include "mygetopt.h"
79 #ifdef HAVE_LIBSECCOMP
80 # define SECCOMP_S "S"
85 #define FILE_FLAGS "bcCdE" IFLNK_h "ik" IFLNK_L "lNnprs" SECCOMP_S "vzZ0"
86 #define OPTSTRING "bcCde:Ef:F:hiklLm:nNpP:rsSvzZ0"
89 "Usage: %s [-" FILE_FLAGS "] [--apple] [--extension] [--mime-encoding]\n" \
90 " [--mime-type] [-e <testname>] [-F <separator>] " \
91 " [-f <namefile>]\n" \
92 " [-m <magicfiles>] [-P <parameter=value>] <file> ...\n" \
93 " %s -C [-m <magicfiles>]\n" \
96 private int /* Global command-line options */
97 bflag = 0, /* brief output format */
98 nopad = 0, /* Don't pad output */
99 nobuffer = 0, /* Do not buffer stdout */
100 nulsep = 0; /* Append '\0' to the separator */
102 private const char *separator = ":"; /* Default field separator */
103 private const struct option long_options[] = {
106 #define OPT_EXTENSIONS 3
107 #define OPT_MIME_TYPE 4
108 #define OPT_MIME_ENCODING 5
109 #define OPT(shortname, longname, opt, def, doc) \
110 {longname, opt, NULL, shortname},
111 #define OPT_LONGONLY(longname, opt, def, doc, id) \
112 {longname, opt, NULL, id},
113 #include "file_opts.h"
119 private const struct {
123 { "apptype", MAGIC_NO_CHECK_APPTYPE },
124 { "ascii", MAGIC_NO_CHECK_ASCII },
125 { "cdf", MAGIC_NO_CHECK_CDF },
126 { "compress", MAGIC_NO_CHECK_COMPRESS },
127 { "elf", MAGIC_NO_CHECK_ELF },
128 { "encoding", MAGIC_NO_CHECK_ENCODING },
129 { "soft", MAGIC_NO_CHECK_SOFT },
130 { "tar", MAGIC_NO_CHECK_TAR },
131 { "text", MAGIC_NO_CHECK_TEXT }, /* synonym for ascii */
132 { "tokens", MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
140 { "indir", MAGIC_PARAM_INDIR_MAX, 0 },
141 { "name", MAGIC_PARAM_NAME_MAX, 0 },
142 { "elf_phnum", MAGIC_PARAM_ELF_PHNUM_MAX, 0 },
143 { "elf_shnum", MAGIC_PARAM_ELF_SHNUM_MAX, 0 },
144 { "elf_notes", MAGIC_PARAM_ELF_NOTES_MAX, 0 },
145 { "regex", MAGIC_PARAM_REGEX_MAX, 0 },
146 { "bytes", MAGIC_PARAM_BYTES_MAX, 0 },
154 private void usage(void);
155 private void docprint(const char *, int);
159 private void help(void);
161 private int unwrap(struct magic_set *, const char *);
162 private int process(struct magic_set *ms, const char *, int);
163 private struct magic_set *load(const char *, int);
164 private void setparam(const char *);
165 private void applyparam(magic_t);
169 * main - parse arguments and handle options
172 main(int argc, char *argv[])
176 int action = 0, didsomefiles = 0, errflg = 0;
177 int flags = 0, e = 0;
178 #ifdef HAVE_LIBSECCOMP
181 struct magic_set *magic = NULL;
183 const char *magicfile = NULL; /* where the magic is */
186 /* makes islower etc work for other langs */
187 #ifdef HAVE_SETLOCALE
188 (void)setlocale(LC_CTYPE, "");
192 /* sh-like wildcard expansion! Shouldn't hurt at least ... */
193 _wildcard(&argc, &argv);
196 if ((progname = strrchr(argv[0], '/')) != NULL)
201 file_setprogname(progname);
205 posixly = getenv("POSIXLY_CORRECT") != NULL;
206 flags |= posixly ? MAGIC_SYMLINK : 0;
208 while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
215 flags |= MAGIC_APPLE;
218 flags |= MAGIC_EXTENSION;
221 flags |= MAGIC_MIME_TYPE;
223 case OPT_MIME_ENCODING:
224 flags |= MAGIC_MIME_ENCODING;
236 action = FILE_COMPILE;
239 flags |= MAGIC_DEBUG|MAGIC_CHECK;
242 flags |= MAGIC_ERROR;
245 for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
246 if (strcmp(nv[i].name, optarg) == 0)
249 if (i == sizeof(nv) / sizeof(nv[0]))
252 flags |= nv[i].value;
259 if ((magic = load(magicfile, flags)) == NULL)
262 e |= unwrap(magic, optarg);
272 flags |= MAGIC_CONTINUE;
286 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
288 flags |= MAGIC_PRESERVE_ATIME;
298 flags |= MAGIC_DEVICES;
300 #ifdef HAVE_LIBSECCOMP
306 if (magicfile == NULL)
307 magicfile = magic_getpath(magicfile, action);
308 (void)fprintf(stdout, "%s-%s\n", file_getprogname(),
310 (void)fprintf(stdout, "magic file from %s\n",
314 flags |= MAGIC_COMPRESS;
318 flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
322 flags |= MAGIC_SYMLINK;
325 flags &= ~MAGIC_SYMLINK;
340 #ifdef HAVE_LIBSECCOMP
342 if (sandbox && enable_sandbox_basic() == -1)
344 if (sandbox && enable_sandbox_full() == -1)
346 file_err(EXIT_FAILURE, "SECCOMP initialisation failed");
347 #endif /* HAVE_LIBSECCOMP */
349 if (MAGIC_VERSION != magic_version())
350 file_warnx("Compiled magic version [%d] "
351 "does not match with shared library magic version [%d]\n",
352 MAGIC_VERSION, magic_version());
359 * Don't try to check/compile ~/.magic unless we explicitly
362 magic = magic_open(flags|MAGIC_CHECK);
364 file_warn("Can't create magic");
371 c = magic_check(magic, magicfile);
374 c = magic_compile(magic, magicfile);
377 c = magic_list(magic, magicfile);
383 file_warnx("%s", magic_error(magic));
390 if ((magic = load(magicfile, flags)) == NULL)
395 if (optind == argc) {
401 for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
402 nw = file_mbswidth(argv[j]);
407 * If bflag is only set twice, set it depending on
408 * number of files [this is undocumented, and subject to change]
411 bflag = optind >= argc - 1;
413 for (; optind < argc; optind++)
414 e |= process(magic, argv[optind], wid);
424 applyparam(magic_t magic)
428 for (i = 0; i < __arraycount(pm); i++) {
429 if (pm[i].value == 0)
431 if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1)
432 file_err(EXIT_FAILURE, "Can't set %s", pm[i].name);
437 setparam(const char *p)
442 if ((s = strchr(p, '=')) == NULL)
445 for (i = 0; i < __arraycount(pm); i++) {
446 if (strncmp(p, pm[i].name, s - p) != 0)
448 pm[i].value = atoi(s + 1);
452 file_errx(EXIT_FAILURE, "Unknown param %s", p);
455 private struct magic_set *
457 load(const char *magicfile, int flags)
459 struct magic_set *magic = magic_open(flags);
463 file_warn("Can't create magic");
466 if (magic_load(magic, magicfile) == -1) {
467 file_warn("%s", magic_error(magic));
471 if ((e = magic_error(magic)) != NULL)
477 * unwrap -- read a file of filenames, do each one.
480 unwrap(struct magic_set *ms, const char *fn)
489 if (strcmp("-", fn) == 0) {
493 if ((f = fopen(fn, "r")) == NULL) {
494 file_warn("Cannot open `%s'", fn);
498 while ((len = getline(&line, &llen, f)) > 0) {
499 if (line[len - 1] == '\n')
500 line[len - 1] = '\0';
501 cwid = file_mbswidth(line);
509 while ((len = getline(&line, &llen, f)) > 0) {
510 if (line[len - 1] == '\n')
511 line[len - 1] = '\0';
512 e |= process(ms, line, wid);
514 (void)fflush(stdout);
523 * Called for each input file on the command line (or in a list of files)
526 process(struct magic_set *ms, const char *inname, int wid)
528 const char *type, c = nulsep > 1 ? '\0' : '\n';
529 int std_in = strcmp(inname, "-") == 0;
531 if (wid > 0 && !bflag) {
532 (void)printf("%s", std_in ? "/dev/stdin" : inname);
534 (void)putc('\0', stdout);
536 (void)printf("%s", separator);
538 (int) (nopad ? 0 : (wid - file_mbswidth(inname))),
543 type = magic_file(ms, std_in ? NULL : inname);
546 (void)printf("ERROR: %s%c", magic_error(ms), c);
549 (void)printf("%s%c", type, c);
555 file_mbswidth(const char *s)
557 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
558 size_t bytesconsumed, old_n, n, width = 0;
561 (void)memset(&state, 0, sizeof(mbstate_t));
562 old_n = n = strlen(s);
565 bytesconsumed = mbrtowc(&nextchar, s, n, &state);
566 if (bytesconsumed == (size_t)(-1) ||
567 bytesconsumed == (size_t)(-2)) {
568 /* Something went wrong, return something reasonable */
573 * do what strlen() would do, so that caller
578 int w = wcwidth(nextchar);
583 s += bytesconsumed, n -= bytesconsumed;
594 const char *pn = file_getprogname();
595 (void)fprintf(stderr, USAGE, pn, pn, pn);
604 if (((def & 1) && posixly) || ((def & 2) && !posixly))
605 fprintf(stdout, " (default)");
610 docprint(const char *opts, int def)
616 p = strstr(opts, "%o");
618 fprintf(stdout, "%s", opts);
623 for (sp = p - 1; sp > opts && *sp == ' '; sp--)
626 fprintf(stdout, "%.*s", (int)(p - opts), opts);
629 for (i = 0; i < __arraycount(nv); i++) {
630 fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
631 if (i && i % 5 == 0) {
632 fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
637 fprintf(stdout, "%s", opts + (p - opts) + 2);
644 "Usage: file [OPTION...] [FILE...]\n"
645 "Determine type of FILEs.\n"
647 #define OPT(shortname, longname, opt, def, doc) \
648 fprintf(stdout, " -%c, --" longname, shortname), \
650 #define OPT_LONGONLY(longname, opt, def, doc, id) \
651 fprintf(stdout, " --" longname), \
653 #include "file_opts.h"
656 fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
660 private const char *file_progname;
663 file_setprogname(const char *progname)
665 file_progname = progname;
668 protected const char *
669 file_getprogname(void)
671 return file_progname;
675 file_err(int e, const char *fmt, ...)
681 fprintf(stderr, "%s: ", file_progname);
682 vfprintf(stderr, fmt, ap);
684 fprintf(stderr, " (%s)\n", strerror(se));
689 file_errx(int e, const char *fmt, ...)
694 fprintf(stderr, "%s: ", file_progname);
695 vfprintf(stderr, fmt, ap);
697 fprintf(stderr, "\n");
702 file_warn(const char *fmt, ...)
708 fprintf(stderr, "%s: ", file_progname);
709 vfprintf(stderr, fmt, ap);
711 fprintf(stderr, " (%s)\n", strerror(se));
716 file_warnx(const char *fmt, ...)
722 fprintf(stderr, "%s: ", file_progname);
723 vfprintf(stderr, fmt, ap);
725 fprintf(stderr, "\n");