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.187 2020/06/07 17:38:30 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>] [--exclude-quiet]\n" \
88 " %s -C [-m <magicfiles>]\n" \
91 private int /* Global command-line options */
92 bflag = 0, /* brief output format */
93 nopad = 0, /* Don't pad output */
94 nobuffer = 0, /* Do not buffer stdout */
95 nulsep = 0; /* Append '\0' to the separator */
97 private const char *separator = ":"; /* Default field separator */
98 private const struct option long_options[] = {
101 #define OPT_EXTENSIONS 3
102 #define OPT_MIME_TYPE 4
103 #define OPT_MIME_ENCODING 5
104 #define OPT_EXCLUDE_QUIET 6
105 #define OPT(shortname, longname, opt, def, doc) \
106 {longname, opt, NULL, shortname},
107 #define OPT_LONGONLY(longname, opt, def, doc, id) \
108 {longname, opt, NULL, id},
109 #include "file_opts.h"
115 private const struct {
119 { "apptype", MAGIC_NO_CHECK_APPTYPE },
120 { "ascii", MAGIC_NO_CHECK_ASCII },
121 { "cdf", MAGIC_NO_CHECK_CDF },
122 { "compress", MAGIC_NO_CHECK_COMPRESS },
123 { "csv", MAGIC_NO_CHECK_CSV },
124 { "elf", MAGIC_NO_CHECK_ELF },
125 { "encoding", MAGIC_NO_CHECK_ENCODING },
126 { "soft", MAGIC_NO_CHECK_SOFT },
127 { "tar", MAGIC_NO_CHECK_TAR },
128 { "json", MAGIC_NO_CHECK_JSON },
129 { "text", MAGIC_NO_CHECK_TEXT }, /* synonym for ascii */
130 { "tokens", MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
141 { "bytes", MAGIC_PARAM_BYTES_MAX, 0, 0, FILE_BYTES_MAX,
142 "max bytes to look inside file" },
143 { "elf_notes", MAGIC_PARAM_ELF_NOTES_MAX, 0, 0, FILE_ELF_NOTES_MAX,
144 "max ELF notes processed" },
145 { "elf_phnum", MAGIC_PARAM_ELF_PHNUM_MAX, 0, 0, FILE_ELF_PHNUM_MAX,
146 "max ELF prog sections processed" },
147 { "elf_shnum", MAGIC_PARAM_ELF_SHNUM_MAX, 0, 0, FILE_ELF_SHNUM_MAX,
148 "max ELF sections processed" },
149 { "indir", MAGIC_PARAM_INDIR_MAX, 0, 0, FILE_INDIR_MAX,
150 "recursion limit for indirection" },
151 { "name", MAGIC_PARAM_NAME_MAX, 0, 0, FILE_NAME_MAX,
152 "use limit for name/use magic" },
153 { "regex", MAGIC_PARAM_REGEX_MAX, 0, 0, FILE_REGEX_MAX,
154 "length limit for REGEX searches" },
162 private void usage(void);
163 private void docprint(const char *, int);
167 private void help(void);
169 private int unwrap(struct magic_set *, const char *);
170 private int process(struct magic_set *ms, const char *, int);
171 private struct magic_set *load(const char *, int);
172 private void setparam(const char *);
173 private void applyparam(magic_t);
177 * main - parse arguments and handle options
180 main(int argc, char *argv[])
184 int action = 0, didsomefiles = 0, errflg = 0;
185 int flags = 0, e = 0;
186 #ifdef HAVE_LIBSECCOMP
189 struct magic_set *magic = NULL;
191 const char *magicfile = NULL; /* where the magic is */
194 /* makes islower etc work for other langs */
195 (void)setlocale(LC_CTYPE, "");
198 /* sh-like wildcard expansion! Shouldn't hurt at least ... */
199 _wildcard(&argc, &argv);
202 if ((progname = strrchr(argv[0], '/')) != NULL)
207 file_setprogname(progname);
211 posixly = getenv("POSIXLY_CORRECT") != NULL;
212 flags |= posixly ? MAGIC_SYMLINK : 0;
214 while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
221 flags |= MAGIC_APPLE;
224 flags |= MAGIC_EXTENSION;
227 flags |= MAGIC_MIME_TYPE;
229 case OPT_MIME_ENCODING:
230 flags |= MAGIC_MIME_ENCODING;
242 action = FILE_COMPILE;
245 flags |= MAGIC_DEBUG|MAGIC_CHECK;
248 flags |= MAGIC_ERROR;
251 case OPT_EXCLUDE_QUIET:
252 for (i = 0; i < __arraycount(nv); i++)
253 if (strcmp(nv[i].name, optarg) == 0)
256 if (i == __arraycount(nv)) {
257 if (c != OPT_EXCLUDE_QUIET)
260 flags |= nv[i].value;
267 if ((magic = load(magicfile, flags)) == NULL)
270 e |= unwrap(magic, optarg);
280 flags |= MAGIC_CONTINUE;
294 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
296 flags |= MAGIC_PRESERVE_ATIME;
306 flags |= MAGIC_DEVICES;
309 #ifdef HAVE_LIBSECCOMP
314 if (magicfile == NULL)
315 magicfile = magic_getpath(magicfile, action);
316 (void)fprintf(stdout, "%s-%s\n", file_getprogname(),
318 (void)fprintf(stdout, "magic file from %s\n",
320 #ifdef HAVE_LIBSECCOMP
321 (void)fprintf(stdout, "seccomp support included\n");
325 flags |= MAGIC_COMPRESS;
329 flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
333 flags |= MAGIC_SYMLINK;
336 flags &= ~MAGIC_SYMLINK;
351 #ifdef HAVE_LIBSECCOMP
353 if (sandbox && enable_sandbox_basic() == -1)
355 if (sandbox && enable_sandbox_full() == -1)
357 file_err(EXIT_FAILURE, "SECCOMP initialisation failed");
358 #endif /* HAVE_LIBSECCOMP */
360 if (MAGIC_VERSION != magic_version())
361 file_warnx("Compiled magic version [%d] "
362 "does not match with shared library magic version [%d]\n",
363 MAGIC_VERSION, magic_version());
370 * Don't try to check/compile ~/.magic unless we explicitly
373 magic = magic_open(flags|MAGIC_CHECK);
375 file_warn("Can't create magic");
382 c = magic_check(magic, magicfile);
385 c = magic_compile(magic, magicfile);
388 c = magic_list(magic, magicfile);
394 file_warnx("%s", magic_error(magic));
401 if ((magic = load(magicfile, flags)) == NULL)
406 if (optind == argc) {
412 for (wid = 0, j = CAST(size_t, optind); j < CAST(size_t, argc);
414 nw = file_mbswidth(argv[j]);
419 * If bflag is only set twice, set it depending on
420 * number of files [this is undocumented, and subject to change]
423 bflag = optind >= argc - 1;
425 for (; optind < argc; optind++)
426 e |= process(magic, argv[optind], wid);
436 applyparam(magic_t magic)
440 for (i = 0; i < __arraycount(pm); i++) {
443 if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1)
444 file_err(EXIT_FAILURE, "Can't set %s", pm[i].name);
449 setparam(const char *p)
454 if ((s = strchr(p, '=')) == NULL)
457 for (i = 0; i < __arraycount(pm); i++) {
458 if (strncmp(p, pm[i].name, s - p) != 0)
460 pm[i].value = atoi(s + 1);
465 file_errx(EXIT_FAILURE, "Unknown param %s", p);
468 private struct magic_set *
470 load(const char *magicfile, int flags)
472 struct magic_set *magic = magic_open(flags);
476 file_warn("Can't create magic");
479 if (magic_load(magic, magicfile) == -1) {
480 file_warn("%s", magic_error(magic));
484 if ((e = magic_error(magic)) != NULL)
490 * unwrap -- read a file of filenames, do each one.
493 unwrap(struct magic_set *ms, const char *fn)
502 if (strcmp("-", fn) == 0) {
506 if ((f = fopen(fn, "r")) == NULL) {
507 file_warn("Cannot open `%s'", fn);
511 while ((len = getline(&line, &llen, f)) > 0) {
512 if (line[len - 1] == '\n')
513 line[len - 1] = '\0';
514 cwid = file_mbswidth(line);
522 while ((len = getline(&line, &llen, f)) > 0) {
523 if (line[len - 1] == '\n')
524 line[len - 1] = '\0';
525 e |= process(ms, line, wid);
527 (void)fflush(stdout);
536 * Called for each input file on the command line (or in a list of files)
539 process(struct magic_set *ms, const char *inname, int wid)
541 const char *type, c = nulsep > 1 ? '\0' : '\n';
542 int std_in = strcmp(inname, "-") == 0;
544 if (wid > 0 && !bflag) {
545 (void)printf("%s", std_in ? "/dev/stdin" : inname);
547 (void)putc('\0', stdout);
549 (void)printf("%s", separator);
550 (void)printf("%*s ", CAST(int, nopad ? 0
551 : (wid - file_mbswidth(inname))), "");
555 type = magic_file(ms, std_in ? NULL : inname);
558 (void)printf("ERROR: %s%c", magic_error(ms), c);
561 (void)printf("%s%c", type, c);
567 file_mbswidth(const char *s)
569 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
570 size_t bytesconsumed, old_n, n, width = 0;
573 (void)memset(&state, 0, sizeof(mbstate_t));
574 old_n = n = strlen(s);
577 bytesconsumed = mbrtowc(&nextchar, s, n, &state);
578 if (bytesconsumed == CAST(size_t, -1) ||
579 bytesconsumed == CAST(size_t, -2)) {
580 /* Something went wrong, return something reasonable */
585 * do what strlen() would do, so that caller
590 int w = wcwidth(nextchar);
595 s += bytesconsumed, n -= bytesconsumed;
606 const char *pn = file_getprogname();
607 (void)fprintf(stderr, USAGE, pn, pn, pn);
616 if (((def & 1) && posixly) || ((def & 2) && !posixly))
617 fprintf(stdout, " (default)");
622 docprint(const char *opts, int def)
628 p = strchr(opts, '%');
630 fprintf(stdout, "%s", opts);
635 for (sp = p - 1; sp > opts && *sp == ' '; sp--)
638 fprintf(stdout, "%.*s", CAST(int, p - opts), opts);
639 pad = (int)CAST(int, p - sp - 1);
644 for (i = 0; i < __arraycount(nv); i++) {
645 fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
646 if (i && i % 5 == 0 && i != __arraycount(nv) - 1) {
647 fprintf(stdout, ",\n%*s", pad, "");
653 for (i = 0; i < __arraycount(pm); i++) {
654 fprintf(stdout, "%9s %7zu %s", pm[i].name, pm[i].def,
656 if (i != __arraycount(pm) - 1)
657 fprintf(stdout, "\n%*s", pad, "");
661 file_errx(EXIT_FAILURE, "Unknown escape `%c' in long options",
665 fprintf(stdout, "%s", opts + (p - opts) + 1);
673 "Usage: file [OPTION...] [FILE...]\n"
674 "Determine type of FILEs.\n"
676 #define OPT(shortname, longname, opt, def, doc) \
677 fprintf(stdout, " -%c, --" longname, shortname), \
679 #define OPT_LONGONLY(longname, opt, def, doc, id) \
680 fprintf(stdout, " --" longname), \
682 #include "file_opts.h"
685 fprintf(stdout, "\nReport bugs to https://bugs.astron.com/\n");
689 private const char *file_progname;
692 file_setprogname(const char *progname)
694 file_progname = progname;
697 protected const char *
698 file_getprogname(void)
700 return file_progname;
704 file_err(int e, const char *fmt, ...)
710 fprintf(stderr, "%s: ", file_progname);
711 vfprintf(stderr, fmt, ap);
714 fprintf(stderr, " (%s)\n", strerror(se));
721 file_errx(int e, const char *fmt, ...)
726 fprintf(stderr, "%s: ", file_progname);
727 vfprintf(stderr, fmt, ap);
729 fprintf(stderr, "\n");
734 file_warn(const char *fmt, ...)
740 fprintf(stderr, "%s: ", file_progname);
741 vfprintf(stderr, fmt, ap);
744 fprintf(stderr, " (%s)\n", strerror(se));
751 file_warnx(const char *fmt, ...)
757 fprintf(stderr, "%s: ", file_progname);
758 vfprintf(stderr, fmt, ap);
760 fprintf(stderr, "\n");