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.184 2019/08/03 11:51:59 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 #define FILE_FLAGS "bcCdE" IFLNK_h "ik" IFLNK_L "lNnprsSvzZ0"
80 #define OPTSTRING "bcCde:Ef:F:hiklLm:nNpP:rsSvzZ0"
83 "Usage: %s [-" FILE_FLAGS "] [--apple] [--extension] [--mime-encoding]\n" \
84 " [--mime-type] [-e <testname>] [-F <separator>] " \
85 " [-f <namefile>]\n" \
86 " [-m <magicfiles>] [-P <parameter=value>] <file> ...\n" \
87 " %s -C [-m <magicfiles>]\n" \
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 *separator = ":"; /* Default field separator */
97 private const struct option long_options[] = {
100 #define OPT_EXTENSIONS 3
101 #define OPT_MIME_TYPE 4
102 #define OPT_MIME_ENCODING 5
103 #define OPT(shortname, longname, opt, def, doc) \
104 {longname, opt, NULL, shortname},
105 #define OPT_LONGONLY(longname, opt, def, doc, id) \
106 {longname, opt, NULL, id},
107 #include "file_opts.h"
113 private const struct {
117 { "apptype", MAGIC_NO_CHECK_APPTYPE },
118 { "ascii", MAGIC_NO_CHECK_ASCII },
119 { "cdf", MAGIC_NO_CHECK_CDF },
120 { "compress", MAGIC_NO_CHECK_COMPRESS },
121 { "csv", MAGIC_NO_CHECK_CSV },
122 { "elf", MAGIC_NO_CHECK_ELF },
123 { "encoding", MAGIC_NO_CHECK_ENCODING },
124 { "soft", MAGIC_NO_CHECK_SOFT },
125 { "tar", MAGIC_NO_CHECK_TAR },
126 { "json", MAGIC_NO_CHECK_JSON },
127 { "text", MAGIC_NO_CHECK_TEXT }, /* synonym for ascii */
128 { "tokens", MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
137 { "indir", MAGIC_PARAM_INDIR_MAX, 0, 0 },
138 { "name", MAGIC_PARAM_NAME_MAX, 0, 0 },
139 { "elf_phnum", MAGIC_PARAM_ELF_PHNUM_MAX, 0, 0 },
140 { "elf_shnum", MAGIC_PARAM_ELF_SHNUM_MAX, 0, 0 },
141 { "elf_notes", MAGIC_PARAM_ELF_NOTES_MAX, 0, 0 },
142 { "regex", MAGIC_PARAM_REGEX_MAX, 0, 0 },
143 { "bytes", MAGIC_PARAM_BYTES_MAX, 0, 0 },
151 private void usage(void);
152 private void docprint(const char *, int);
156 private void help(void);
158 private int unwrap(struct magic_set *, const char *);
159 private int process(struct magic_set *ms, const char *, int);
160 private struct magic_set *load(const char *, int);
161 private void setparam(const char *);
162 private void applyparam(magic_t);
166 * main - parse arguments and handle options
169 main(int argc, char *argv[])
173 int action = 0, didsomefiles = 0, errflg = 0;
174 int flags = 0, e = 0;
175 #ifdef HAVE_LIBSECCOMP
178 struct magic_set *magic = NULL;
180 const char *magicfile = NULL; /* where the magic is */
183 /* makes islower etc work for other langs */
184 (void)setlocale(LC_CTYPE, "");
187 /* sh-like wildcard expansion! Shouldn't hurt at least ... */
188 _wildcard(&argc, &argv);
191 if ((progname = strrchr(argv[0], '/')) != NULL)
196 file_setprogname(progname);
200 posixly = getenv("POSIXLY_CORRECT") != NULL;
201 flags |= posixly ? MAGIC_SYMLINK : 0;
203 while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
210 flags |= MAGIC_APPLE;
213 flags |= MAGIC_EXTENSION;
216 flags |= MAGIC_MIME_TYPE;
218 case OPT_MIME_ENCODING:
219 flags |= MAGIC_MIME_ENCODING;
231 action = FILE_COMPILE;
234 flags |= MAGIC_DEBUG|MAGIC_CHECK;
237 flags |= MAGIC_ERROR;
240 for (i = 0; i < __arraycount(nv); i++)
241 if (strcmp(nv[i].name, optarg) == 0)
244 if (i == __arraycount(nv))
247 flags |= nv[i].value;
254 if ((magic = load(magicfile, flags)) == NULL)
257 e |= unwrap(magic, optarg);
267 flags |= MAGIC_CONTINUE;
281 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
283 flags |= MAGIC_PRESERVE_ATIME;
293 flags |= MAGIC_DEVICES;
296 #ifdef HAVE_LIBSECCOMP
301 if (magicfile == NULL)
302 magicfile = magic_getpath(magicfile, action);
303 (void)fprintf(stdout, "%s-%s\n", file_getprogname(),
305 (void)fprintf(stdout, "magic file from %s\n",
307 #ifdef HAVE_LIBSECCOMP
308 (void)fprintf(stdout, "seccomp support included\n");
312 flags |= MAGIC_COMPRESS;
316 flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
320 flags |= MAGIC_SYMLINK;
323 flags &= ~MAGIC_SYMLINK;
338 #ifdef HAVE_LIBSECCOMP
340 if (sandbox && enable_sandbox_basic() == -1)
342 if (sandbox && enable_sandbox_full() == -1)
344 file_err(EXIT_FAILURE, "SECCOMP initialisation failed");
345 #endif /* HAVE_LIBSECCOMP */
347 if (MAGIC_VERSION != magic_version())
348 file_warnx("Compiled magic version [%d] "
349 "does not match with shared library magic version [%d]\n",
350 MAGIC_VERSION, magic_version());
357 * Don't try to check/compile ~/.magic unless we explicitly
360 magic = magic_open(flags|MAGIC_CHECK);
362 file_warn("Can't create magic");
369 c = magic_check(magic, magicfile);
372 c = magic_compile(magic, magicfile);
375 c = magic_list(magic, magicfile);
381 file_warnx("%s", magic_error(magic));
388 if ((magic = load(magicfile, flags)) == NULL)
393 if (optind == argc) {
399 for (wid = 0, j = CAST(size_t, optind); j < CAST(size_t, argc);
401 nw = file_mbswidth(argv[j]);
406 * If bflag is only set twice, set it depending on
407 * number of files [this is undocumented, and subject to change]
410 bflag = optind >= argc - 1;
412 for (; optind < argc; optind++)
413 e |= process(magic, argv[optind], wid);
423 applyparam(magic_t magic)
427 for (i = 0; i < __arraycount(pm); i++) {
430 if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1)
431 file_err(EXIT_FAILURE, "Can't set %s", pm[i].name);
436 setparam(const char *p)
441 if ((s = strchr(p, '=')) == NULL)
444 for (i = 0; i < __arraycount(pm); i++) {
445 if (strncmp(p, pm[i].name, s - p) != 0)
447 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);
537 (void)printf("%*s ", CAST(int, nopad ? 0
538 : (wid - file_mbswidth(inname))), "");
542 type = magic_file(ms, std_in ? NULL : inname);
545 (void)printf("ERROR: %s%c", magic_error(ms), c);
548 (void)printf("%s%c", type, c);
554 file_mbswidth(const char *s)
556 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
557 size_t bytesconsumed, old_n, n, width = 0;
560 (void)memset(&state, 0, sizeof(mbstate_t));
561 old_n = n = strlen(s);
564 bytesconsumed = mbrtowc(&nextchar, s, n, &state);
565 if (bytesconsumed == CAST(size_t, -1) ||
566 bytesconsumed == CAST(size_t, -2)) {
567 /* Something went wrong, return something reasonable */
572 * do what strlen() would do, so that caller
577 int w = wcwidth(nextchar);
582 s += bytesconsumed, n -= bytesconsumed;
593 const char *pn = file_getprogname();
594 (void)fprintf(stderr, USAGE, pn, pn, pn);
603 if (((def & 1) && posixly) || ((def & 2) && !posixly))
604 fprintf(stdout, " (default)");
609 docprint(const char *opts, int def)
615 p = strstr(opts, "%o");
617 fprintf(stdout, "%s", opts);
622 for (sp = p - 1; sp > opts && *sp == ' '; sp--)
625 fprintf(stdout, "%.*s", CAST(int, p - opts), opts);
628 for (i = 0; i < __arraycount(nv); i++) {
629 fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
630 if (i && i % 5 == 0 && i != __arraycount(nv) - 1) {
631 fprintf(stdout, ",\n%*s", CAST(int, p - sp - 1), "");
636 fprintf(stdout, "%s", opts + (p - opts) + 2);
643 "Usage: file [OPTION...] [FILE...]\n"
644 "Determine type of FILEs.\n"
646 #define OPT(shortname, longname, opt, def, doc) \
647 fprintf(stdout, " -%c, --" longname, shortname), \
649 #define OPT_LONGONLY(longname, opt, def, doc, id) \
650 fprintf(stdout, " --" longname), \
652 #include "file_opts.h"
655 fprintf(stdout, "\nReport bugs to https://bugs.astron.com/\n");
659 private const char *file_progname;
662 file_setprogname(const char *progname)
664 file_progname = progname;
667 protected const char *
668 file_getprogname(void)
670 return file_progname;
674 file_err(int e, const char *fmt, ...)
680 fprintf(stderr, "%s: ", file_progname);
681 vfprintf(stderr, fmt, ap);
683 fprintf(stderr, " (%s)\n", strerror(se));
688 file_errx(int e, const char *fmt, ...)
693 fprintf(stderr, "%s: ", file_progname);
694 vfprintf(stderr, fmt, ap);
696 fprintf(stderr, "\n");
701 file_warn(const char *fmt, ...)
707 fprintf(stderr, "%s: ", file_progname);
708 vfprintf(stderr, fmt, ap);
710 fprintf(stderr, " (%s)\n", strerror(se));
715 file_warnx(const char *fmt, ...)
721 fprintf(stderr, "%s: ", file_progname);
722 vfprintf(stderr, fmt, ap);
724 fprintf(stderr, "\n");