xref: /freebsd/contrib/file/src/file.c (revision 0957b409)
1 /*
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.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  */
28 /*
29  * file - find type of a file or files - main program.
30  */
31 
32 #include "file.h"
33 
34 #ifndef	lint
35 FILE_RCSID("@(#)$File: file.c,v 1.175 2018/03/02 16:11:37 christos Exp $")
36 #endif	/* lint */
37 
38 #include "magic.h"
39 
40 #include <stdlib.h>
41 #include <unistd.h>
42 #include <string.h>
43 #ifdef RESTORE_TIME
44 # if (__COHERENT__ >= 0x420)
45 #  include <sys/utime.h>
46 # else
47 #  ifdef USE_UTIMES
48 #   include <sys/time.h>
49 #  else
50 #   include <utime.h>
51 #  endif
52 # endif
53 #endif
54 #ifdef HAVE_UNISTD_H
55 #include <unistd.h>	/* for read() */
56 #endif
57 #ifdef HAVE_WCHAR_H
58 #include <wchar.h>
59 #endif
60 
61 #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
62 # include <getopt.h>
63 # ifndef HAVE_GETOPT_LONG
64 int getopt_long(int, char * const *, const char *,
65     const struct option *, int *);
66 # endif
67 # else
68 #  include "mygetopt.h"
69 #endif
70 
71 #ifdef S_IFLNK
72 # define IFLNK_h "h"
73 # define IFLNK_L "L"
74 #else
75 # define IFLNK_h ""
76 # define IFLNK_L ""
77 #endif
78 
79 #ifdef HAVE_LIBSECCOMP
80 # define SECCOMP_S "S"
81 #else
82 # define SECCOMP_S ""
83 #endif
84 
85 #define FILE_FLAGS	"bcCdE" IFLNK_h "ik" IFLNK_L "lNnprs" SECCOMP_S "vzZ0"
86 #define OPTSTRING	"bcCde:Ef:F:hiklLm:nNpP:rsSvzZ0"
87 
88 # define USAGE  \
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" \
94     "       %s [--help]\n"
95 
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		*/
101 
102 private const char *separator = ":";	/* Default field separator	*/
103 private const struct option long_options[] = {
104 #define OPT_HELP		1
105 #define OPT_APPLE		2
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"
114 #undef OPT
115 #undef OPT_LONGONLY
116     {0, 0, NULL, 0}
117     };
118 
119 private const struct {
120 	const char *name;
121 	int value;
122 } nv[] = {
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 */
133 };
134 
135 private struct {
136 	const char *name;
137 	int tag;
138 	size_t value;
139 } pm[] = {
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 },
147 };
148 
149 private int posixly;
150 
151 #ifdef __dead
152 __dead
153 #endif
154 private void usage(void);
155 private void docprint(const char *, int);
156 #ifdef __dead
157 __dead
158 #endif
159 private void help(void);
160 
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);
166 
167 
168 /*
169  * main - parse arguments and handle options
170  */
171 int
172 main(int argc, char *argv[])
173 {
174 	int c;
175 	size_t i;
176 	int action = 0, didsomefiles = 0, errflg = 0;
177 	int flags = 0, e = 0;
178 #ifdef HAVE_LIBSECCOMP
179 	int sandbox = 1;
180 #endif
181 	struct magic_set *magic = NULL;
182 	int longindex;
183 	const char *magicfile = NULL;		/* where the magic is	*/
184 	char *progname;
185 
186 	/* makes islower etc work for other langs */
187 #ifdef HAVE_SETLOCALE
188 	(void)setlocale(LC_CTYPE, "");
189 #endif
190 
191 #ifdef __EMX__
192 	/* sh-like wildcard expansion! Shouldn't hurt at least ... */
193 	_wildcard(&argc, &argv);
194 #endif
195 
196 	if ((progname = strrchr(argv[0], '/')) != NULL)
197 		progname++;
198 	else
199 		progname = argv[0];
200 
201 	file_setprogname(progname);
202 
203 
204 #ifdef S_IFLNK
205 	posixly = getenv("POSIXLY_CORRECT") != NULL;
206 	flags |=  posixly ? MAGIC_SYMLINK : 0;
207 #endif
208 	while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
209 	    &longindex)) != -1)
210 		switch (c) {
211 		case OPT_HELP:
212 			help();
213 			break;
214 		case OPT_APPLE:
215 			flags |= MAGIC_APPLE;
216 			break;
217 		case OPT_EXTENSIONS:
218 			flags |= MAGIC_EXTENSION;
219 			break;
220 		case OPT_MIME_TYPE:
221 			flags |= MAGIC_MIME_TYPE;
222 			break;
223 		case OPT_MIME_ENCODING:
224 			flags |= MAGIC_MIME_ENCODING;
225 			break;
226 		case '0':
227 			nulsep++;
228 			break;
229 		case 'b':
230 			bflag++;
231 			break;
232 		case 'c':
233 			action = FILE_CHECK;
234 			break;
235 		case 'C':
236 			action = FILE_COMPILE;
237 			break;
238 		case 'd':
239 			flags |= MAGIC_DEBUG|MAGIC_CHECK;
240 			break;
241 		case 'E':
242 			flags |= MAGIC_ERROR;
243 			break;
244 		case 'e':
245 			for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
246 				if (strcmp(nv[i].name, optarg) == 0)
247 					break;
248 
249 			if (i == sizeof(nv) / sizeof(nv[0]))
250 				errflg++;
251 			else
252 				flags |= nv[i].value;
253 			break;
254 
255 		case 'f':
256 			if(action)
257 				usage();
258 			if (magic == NULL)
259 				if ((magic = load(magicfile, flags)) == NULL)
260 					return 1;
261 			applyparam(magic);
262 			e |= unwrap(magic, optarg);
263 			++didsomefiles;
264 			break;
265 		case 'F':
266 			separator = optarg;
267 			break;
268 		case 'i':
269 			flags |= MAGIC_MIME;
270 			break;
271 		case 'k':
272 			flags |= MAGIC_CONTINUE;
273 			break;
274 		case 'l':
275 			action = FILE_LIST;
276 			break;
277 		case 'm':
278 			magicfile = optarg;
279 			break;
280 		case 'n':
281 			++nobuffer;
282 			break;
283 		case 'N':
284 			++nopad;
285 			break;
286 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
287 		case 'p':
288 			flags |= MAGIC_PRESERVE_ATIME;
289 			break;
290 #endif
291 		case 'P':
292 			setparam(optarg);
293 			break;
294 		case 'r':
295 			flags |= MAGIC_RAW;
296 			break;
297 		case 's':
298 			flags |= MAGIC_DEVICES;
299 			break;
300 #ifdef HAVE_LIBSECCOMP
301 		case 'S':
302 			sandbox = 0;
303 			break;
304 #endif
305 		case 'v':
306 			if (magicfile == NULL)
307 				magicfile = magic_getpath(magicfile, action);
308 			(void)fprintf(stdout, "%s-%s\n", file_getprogname(),
309 			    VERSION);
310 			(void)fprintf(stdout, "magic file from %s\n",
311 			    magicfile);
312 			return 0;
313 		case 'z':
314 			flags |= MAGIC_COMPRESS;
315 			break;
316 
317 		case 'Z':
318 			flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
319 			break;
320 #ifdef S_IFLNK
321 		case 'L':
322 			flags |= MAGIC_SYMLINK;
323 			break;
324 		case 'h':
325 			flags &= ~MAGIC_SYMLINK;
326 			break;
327 #endif
328 		case '?':
329 		default:
330 			errflg++;
331 			break;
332 		}
333 
334 	if (errflg) {
335 		usage();
336 	}
337 	if (e)
338 		return e;
339 
340 #ifdef HAVE_LIBSECCOMP
341 #if 0
342 	if (sandbox && enable_sandbox_basic() == -1)
343 #else
344 	if (sandbox && enable_sandbox_full() == -1)
345 #endif
346 		file_err(EXIT_FAILURE, "SECCOMP initialisation failed");
347 #endif /* HAVE_LIBSECCOMP */
348 
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());
353 
354 	switch(action) {
355 	case FILE_CHECK:
356 	case FILE_COMPILE:
357 	case FILE_LIST:
358 		/*
359 		 * Don't try to check/compile ~/.magic unless we explicitly
360 		 * ask for it.
361 		 */
362 		magic = magic_open(flags|MAGIC_CHECK);
363 		if (magic == NULL) {
364 			file_warn("Can't create magic");
365 			return 1;
366 		}
367 
368 
369 		switch(action) {
370 		case FILE_CHECK:
371 			c = magic_check(magic, magicfile);
372 			break;
373 		case FILE_COMPILE:
374 			c = magic_compile(magic, magicfile);
375 			break;
376 		case FILE_LIST:
377 			c = magic_list(magic, magicfile);
378 			break;
379 		default:
380 			abort();
381 		}
382 		if (c == -1) {
383 			file_warnx("%s", magic_error(magic));
384 			e = 1;
385 			goto out;
386 		}
387 		goto out;
388 	default:
389 		if (magic == NULL)
390 			if ((magic = load(magicfile, flags)) == NULL)
391 				return 1;
392 		applyparam(magic);
393 	}
394 
395 	if (optind == argc) {
396 		if (!didsomefiles)
397 			usage();
398 	}
399 	else {
400 		size_t j, wid, nw;
401 		for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
402 			nw = file_mbswidth(argv[j]);
403 			if (nw > wid)
404 				wid = nw;
405 		}
406 		/*
407 		 * If bflag is only set twice, set it depending on
408 		 * number of files [this is undocumented, and subject to change]
409 		 */
410 		if (bflag == 2) {
411 			bflag = optind >= argc - 1;
412 		}
413 		for (; optind < argc; optind++)
414 			e |= process(magic, argv[optind], wid);
415 	}
416 
417 out:
418 	if (magic)
419 		magic_close(magic);
420 	return e;
421 }
422 
423 private void
424 applyparam(magic_t magic)
425 {
426 	size_t i;
427 
428 	for (i = 0; i < __arraycount(pm); i++) {
429 		if (pm[i].value == 0)
430 			continue;
431 		if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1)
432 			file_err(EXIT_FAILURE, "Can't set %s", pm[i].name);
433 	}
434 }
435 
436 private void
437 setparam(const char *p)
438 {
439 	size_t i;
440 	char *s;
441 
442 	if ((s = strchr(p, '=')) == NULL)
443 		goto badparm;
444 
445 	for (i = 0; i < __arraycount(pm); i++) {
446 		if (strncmp(p, pm[i].name, s - p) != 0)
447 			continue;
448 		pm[i].value = atoi(s + 1);
449 		return;
450 	}
451 badparm:
452 	file_errx(EXIT_FAILURE, "Unknown param %s", p);
453 }
454 
455 private struct magic_set *
456 /*ARGSUSED*/
457 load(const char *magicfile, int flags)
458 {
459 	struct magic_set *magic = magic_open(flags);
460 	const char *e;
461 
462 	if (magic == NULL) {
463 		file_warn("Can't create magic");
464 		return NULL;
465 	}
466 	if (magic_load(magic, magicfile) == -1) {
467 		file_warn("%s", magic_error(magic));
468 		magic_close(magic);
469 		return NULL;
470 	}
471 	if ((e = magic_error(magic)) != NULL)
472 		file_warn("%s", e);
473 	return magic;
474 }
475 
476 /*
477  * unwrap -- read a file of filenames, do each one.
478  */
479 private int
480 unwrap(struct magic_set *ms, const char *fn)
481 {
482 	FILE *f;
483 	ssize_t len;
484 	char *line = NULL;
485 	size_t llen = 0;
486 	int wid = 0, cwid;
487 	int e = 0;
488 
489 	if (strcmp("-", fn) == 0) {
490 		f = stdin;
491 		wid = 1;
492 	} else {
493 		if ((f = fopen(fn, "r")) == NULL) {
494 			file_warn("Cannot open `%s'", fn);
495 			return 1;
496 		}
497 
498 		while ((len = getline(&line, &llen, f)) > 0) {
499 			if (line[len - 1] == '\n')
500 				line[len - 1] = '\0';
501 			cwid = file_mbswidth(line);
502 			if (cwid > wid)
503 				wid = cwid;
504 		}
505 
506 		rewind(f);
507 	}
508 
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);
513 		if(nobuffer)
514 			(void)fflush(stdout);
515 	}
516 
517 	free(line);
518 	(void)fclose(f);
519 	return e;
520 }
521 
522 /*
523  * Called for each input file on the command line (or in a list of files)
524  */
525 private int
526 process(struct magic_set *ms, const char *inname, int wid)
527 {
528 	const char *type, c = nulsep > 1 ? '\0' : '\n';
529 	int std_in = strcmp(inname, "-") == 0;
530 
531 	if (wid > 0 && !bflag) {
532 		(void)printf("%s", std_in ? "/dev/stdin" : inname);
533 		if (nulsep)
534 			(void)putc('\0', stdout);
535 		if (nulsep < 2) {
536 			(void)printf("%s", separator);
537 			(void)printf("%*s ",
538 			    (int) (nopad ? 0 : (wid - file_mbswidth(inname))),
539 			    "");
540 		}
541 	}
542 
543 	type = magic_file(ms, std_in ? NULL : inname);
544 
545 	if (type == NULL) {
546 		(void)printf("ERROR: %s%c", magic_error(ms), c);
547 		return 1;
548 	} else {
549 		(void)printf("%s%c", type, c);
550 		return 0;
551 	}
552 }
553 
554 protected size_t
555 file_mbswidth(const char *s)
556 {
557 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
558 	size_t bytesconsumed, old_n, n, width = 0;
559 	mbstate_t state;
560 	wchar_t nextchar;
561 	(void)memset(&state, 0, sizeof(mbstate_t));
562 	old_n = n = strlen(s);
563 
564 	while (n > 0) {
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 */
569 			return old_n;
570 		}
571 		if (s[0] == '\n') {
572 			/*
573 			 * do what strlen() would do, so that caller
574 			 * is always right
575 			 */
576 			width++;
577 		} else {
578 			int w = wcwidth(nextchar);
579 			if (w > 0)
580 				width += w;
581 		}
582 
583 		s += bytesconsumed, n -= bytesconsumed;
584 	}
585 	return width;
586 #else
587 	return strlen(s);
588 #endif
589 }
590 
591 private void
592 usage(void)
593 {
594 	const char *pn = file_getprogname();
595 	(void)fprintf(stderr, USAGE, pn, pn, pn);
596 	exit(EXIT_FAILURE);
597 }
598 
599 private void
600 defprint(int def)
601 {
602 	if (!def)
603 		return;
604 	if (((def & 1) && posixly) || ((def & 2) && !posixly))
605 		fprintf(stdout, " (default)");
606 	fputc('\n', stdout);
607 }
608 
609 private void
610 docprint(const char *opts, int def)
611 {
612 	size_t i;
613 	int comma;
614 	char *sp, *p;
615 
616 	p = strstr(opts, "%o");
617 	if (p == NULL) {
618 		fprintf(stdout, "%s", opts);
619 		defprint(def);
620 		return;
621 	}
622 
623 	for (sp = p - 1; sp > opts && *sp == ' '; sp--)
624 		continue;
625 
626 	fprintf(stdout, "%.*s", (int)(p - opts), opts);
627 
628 	comma = 0;
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), "");
633 			comma = 0;
634 		}
635 	}
636 
637 	fprintf(stdout, "%s", opts + (p - opts) + 2);
638 }
639 
640 private void
641 help(void)
642 {
643 	(void)fputs(
644 "Usage: file [OPTION...] [FILE...]\n"
645 "Determine type of FILEs.\n"
646 "\n", stdout);
647 #define OPT(shortname, longname, opt, def, doc)      \
648 	fprintf(stdout, "  -%c, --" longname, shortname), \
649 	docprint(doc, def);
650 #define OPT_LONGONLY(longname, opt, def, doc, id)        \
651 	fprintf(stdout, "      --" longname),	\
652 	docprint(doc, def);
653 #include "file_opts.h"
654 #undef OPT
655 #undef OPT_LONGONLY
656 	fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
657 	exit(EXIT_SUCCESS);
658 }
659 
660 private const char *file_progname;
661 
662 protected void
663 file_setprogname(const char *progname)
664 {
665 	file_progname = progname;
666 }
667 
668 protected const char *
669 file_getprogname(void)
670 {
671 	return file_progname;
672 }
673 
674 protected void
675 file_err(int e, const char *fmt, ...)
676 {
677 	va_list ap;
678 	int se = errno;
679 
680 	va_start(ap, fmt);
681 	fprintf(stderr, "%s: ", file_progname);
682 	vfprintf(stderr, fmt, ap);
683 	va_end(ap);
684 	fprintf(stderr, " (%s)\n", strerror(se));
685 	exit(e);
686 }
687 
688 protected void
689 file_errx(int e, const char *fmt, ...)
690 {
691 	va_list ap;
692 
693 	va_start(ap, fmt);
694 	fprintf(stderr, "%s: ", file_progname);
695 	vfprintf(stderr, fmt, ap);
696 	va_end(ap);
697 	fprintf(stderr, "\n");
698 	exit(e);
699 }
700 
701 protected void
702 file_warn(const char *fmt, ...)
703 {
704 	va_list ap;
705 	int se = errno;
706 
707 	va_start(ap, fmt);
708 	fprintf(stderr, "%s: ", file_progname);
709 	vfprintf(stderr, fmt, ap);
710 	va_end(ap);
711 	fprintf(stderr, " (%s)\n", strerror(se));
712 	errno = se;
713 }
714 
715 protected void
716 file_warnx(const char *fmt, ...)
717 {
718 	va_list ap;
719 	int se = errno;
720 
721 	va_start(ap, fmt);
722 	fprintf(stderr, "%s: ", file_progname);
723 	vfprintf(stderr, fmt, ap);
724 	va_end(ap);
725 	fprintf(stderr, "\n");
726 	errno = se;
727 }
728