xref: /freebsd/contrib/file/src/file.c (revision 39ee7a7a6bdd1557b1c3532abf60d139798ac88b)
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.167 2015/09/11 17:24:09 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 argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
65 #endif
66 #else
67 #include "mygetopt.h"
68 #endif
69 
70 #ifdef S_IFLNK
71 #define FILE_FLAGS "-bcEhikLlNnprsvzZ0"
72 #else
73 #define FILE_FLAGS "-bcEiklNnprsvzZ0"
74 #endif
75 
76 # define USAGE  \
77     "Usage: %s [" FILE_FLAGS \
78 	"] [--apple] [--extension] [--mime-encoding] [--mime-type]\n" \
79     "            [-e testname] [-F separator] [-f namefile] [-m magicfiles] " \
80     "file ...\n" \
81     "       %s -C [-m magicfiles]\n" \
82     "       %s [--help]\n"
83 
84 private int 		/* Global command-line options 		*/
85 	bflag = 0,	/* brief output format	 		*/
86 	nopad = 0,	/* Don't pad output			*/
87 	nobuffer = 0,   /* Do not buffer stdout 		*/
88 	nulsep = 0;	/* Append '\0' to the separator		*/
89 
90 private const char *separator = ":";	/* Default field separator	*/
91 private const struct option long_options[] = {
92 #define OPT_HELP		1
93 #define OPT_APPLE		2
94 #define OPT_EXTENSIONS		3
95 #define OPT_MIME_TYPE		4
96 #define OPT_MIME_ENCODING	5
97 #define OPT(shortname, longname, opt, doc)      \
98     {longname, opt, NULL, shortname},
99 #define OPT_LONGONLY(longname, opt, doc, id)        \
100     {longname, opt, NULL, id},
101 #include "file_opts.h"
102 #undef OPT
103 #undef OPT_LONGONLY
104     {0, 0, NULL, 0}
105 };
106 #define OPTSTRING	"bcCde:Ef:F:hiklLm:nNpP:rsvzZ0"
107 
108 private const struct {
109 	const char *name;
110 	int value;
111 } nv[] = {
112 	{ "apptype",	MAGIC_NO_CHECK_APPTYPE },
113 	{ "ascii",	MAGIC_NO_CHECK_ASCII },
114 	{ "cdf",	MAGIC_NO_CHECK_CDF },
115 	{ "compress",	MAGIC_NO_CHECK_COMPRESS },
116 	{ "elf",	MAGIC_NO_CHECK_ELF },
117 	{ "encoding",	MAGIC_NO_CHECK_ENCODING },
118 	{ "soft",	MAGIC_NO_CHECK_SOFT },
119 	{ "tar",	MAGIC_NO_CHECK_TAR },
120 	{ "text",	MAGIC_NO_CHECK_TEXT },	/* synonym for ascii */
121 	{ "tokens",	MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
122 };
123 
124 private struct {
125 	const char *name;
126 	int tag;
127 	size_t value;
128 } pm[] = {
129 	{ "indir",	MAGIC_PARAM_INDIR_MAX, 0 },
130 	{ "name",	MAGIC_PARAM_NAME_MAX, 0 },
131 	{ "elf_phnum",	MAGIC_PARAM_ELF_PHNUM_MAX, 0 },
132 	{ "elf_shnum",	MAGIC_PARAM_ELF_SHNUM_MAX, 0 },
133 	{ "elf_notes",	MAGIC_PARAM_ELF_NOTES_MAX, 0 },
134 	{ "regex",	MAGIC_PARAM_REGEX_MAX, 0 },
135 };
136 
137 private char *progname;		/* used throughout 		*/
138 
139 #ifdef __dead
140 __dead
141 #endif
142 private void usage(void);
143 private void docprint(const char *);
144 #ifdef __dead
145 __dead
146 #endif
147 private void help(void);
148 
149 private int unwrap(struct magic_set *, const char *);
150 private int process(struct magic_set *ms, const char *, int);
151 private struct magic_set *load(const char *, int);
152 private void setparam(const char *);
153 private void applyparam(magic_t);
154 
155 
156 /*
157  * main - parse arguments and handle options
158  */
159 int
160 main(int argc, char *argv[])
161 {
162 	int c;
163 	size_t i;
164 	int action = 0, didsomefiles = 0, errflg = 0;
165 	int flags = 0, e = 0;
166 	struct magic_set *magic = NULL;
167 	int longindex;
168 	const char *magicfile = NULL;		/* where the magic is	*/
169 
170 	/* makes islower etc work for other langs */
171 #ifdef HAVE_SETLOCALE
172 	(void)setlocale(LC_CTYPE, "");
173 #endif
174 
175 #ifdef __EMX__
176 	/* sh-like wildcard expansion! Shouldn't hurt at least ... */
177 	_wildcard(&argc, &argv);
178 #endif
179 
180 	if ((progname = strrchr(argv[0], '/')) != NULL)
181 		progname++;
182 	else
183 		progname = argv[0];
184 
185 #ifdef S_IFLNK
186 	flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
187 #endif
188 	while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
189 	    &longindex)) != -1)
190 		switch (c) {
191 		case OPT_HELP:
192 			help();
193 			break;
194 		case OPT_APPLE:
195 			flags |= MAGIC_APPLE;
196 			break;
197 		case OPT_EXTENSIONS:
198 			flags |= MAGIC_EXTENSION;
199 			break;
200 		case OPT_MIME_TYPE:
201 			flags |= MAGIC_MIME_TYPE;
202 			break;
203 		case OPT_MIME_ENCODING:
204 			flags |= MAGIC_MIME_ENCODING;
205 			break;
206 		case '0':
207 			nulsep = 1;
208 			break;
209 		case 'b':
210 			bflag++;
211 			break;
212 		case 'c':
213 			action = FILE_CHECK;
214 			break;
215 		case 'C':
216 			action = FILE_COMPILE;
217 			break;
218 		case 'd':
219 			flags |= MAGIC_DEBUG|MAGIC_CHECK;
220 			break;
221 		case 'E':
222 			flags |= MAGIC_ERROR;
223 			break;
224 		case 'e':
225 			for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
226 				if (strcmp(nv[i].name, optarg) == 0)
227 					break;
228 
229 			if (i == sizeof(nv) / sizeof(nv[0]))
230 				errflg++;
231 			else
232 				flags |= nv[i].value;
233 			break;
234 
235 		case 'f':
236 			if(action)
237 				usage();
238 			if (magic == NULL)
239 				if ((magic = load(magicfile, flags)) == NULL)
240 					return 1;
241 			applyparam(magic);
242 			e |= unwrap(magic, optarg);
243 			++didsomefiles;
244 			break;
245 		case 'F':
246 			separator = optarg;
247 			break;
248 		case 'i':
249 			flags |= MAGIC_MIME;
250 			break;
251 		case 'k':
252 			flags |= MAGIC_CONTINUE;
253 			break;
254 		case 'l':
255 			action = FILE_LIST;
256 			break;
257 		case 'm':
258 			magicfile = optarg;
259 			break;
260 		case 'n':
261 			++nobuffer;
262 			break;
263 		case 'N':
264 			++nopad;
265 			break;
266 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
267 		case 'p':
268 			flags |= MAGIC_PRESERVE_ATIME;
269 			break;
270 #endif
271 		case 'P':
272 			setparam(optarg);
273 			break;
274 		case 'r':
275 			flags |= MAGIC_RAW;
276 			break;
277 		case 's':
278 			flags |= MAGIC_DEVICES;
279 			break;
280 		case 'v':
281 			if (magicfile == NULL)
282 				magicfile = magic_getpath(magicfile, action);
283 			(void)fprintf(stdout, "%s-%s\n", progname, VERSION);
284 			(void)fprintf(stdout, "magic file from %s\n",
285 				       magicfile);
286 			return 0;
287 		case 'z':
288 			flags |= MAGIC_COMPRESS;
289 			break;
290 
291 		case 'Z':
292 			flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
293 			break;
294 #ifdef S_IFLNK
295 		case 'L':
296 			flags |= MAGIC_SYMLINK;
297 			break;
298 		case 'h':
299 			flags &= ~MAGIC_SYMLINK;
300 			break;
301 #endif
302 		case '?':
303 		default:
304 			errflg++;
305 			break;
306 		}
307 
308 	if (errflg) {
309 		usage();
310 	}
311 	if (e)
312 		return e;
313 
314 	if (MAGIC_VERSION != magic_version())
315 		(void)fprintf(stderr, "%s: compiled magic version [%d] "
316 		    "does not match with shared library magic version [%d]\n",
317 		    progname, MAGIC_VERSION, magic_version());
318 
319 	switch(action) {
320 	case FILE_CHECK:
321 	case FILE_COMPILE:
322 	case FILE_LIST:
323 		/*
324 		 * Don't try to check/compile ~/.magic unless we explicitly
325 		 * ask for it.
326 		 */
327 		magic = magic_open(flags|MAGIC_CHECK);
328 		if (magic == NULL) {
329 			(void)fprintf(stderr, "%s: %s\n", progname,
330 			    strerror(errno));
331 			return 1;
332 		}
333 
334 
335 		switch(action) {
336 		case FILE_CHECK:
337 			c = magic_check(magic, magicfile);
338 			break;
339 		case FILE_COMPILE:
340 			c = magic_compile(magic, magicfile);
341 			break;
342 		case FILE_LIST:
343 			c = magic_list(magic, magicfile);
344 			break;
345 		default:
346 			abort();
347 		}
348 		if (c == -1) {
349 			(void)fprintf(stderr, "%s: %s\n", progname,
350 			    magic_error(magic));
351 			return 1;
352 		}
353 		return 0;
354 	default:
355 		if (magic == NULL)
356 			if ((magic = load(magicfile, flags)) == NULL)
357 				return 1;
358 		applyparam(magic);
359 	}
360 
361 	if (optind == argc) {
362 		if (!didsomefiles)
363 			usage();
364 	}
365 	else {
366 		size_t j, wid, nw;
367 		for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
368 			nw = file_mbswidth(argv[j]);
369 			if (nw > wid)
370 				wid = nw;
371 		}
372 		/*
373 		 * If bflag is only set twice, set it depending on
374 		 * number of files [this is undocumented, and subject to change]
375 		 */
376 		if (bflag == 2) {
377 			bflag = optind >= argc - 1;
378 		}
379 		for (; optind < argc; optind++)
380 			e |= process(magic, argv[optind], wid);
381 	}
382 
383 	if (magic)
384 		magic_close(magic);
385 	return e;
386 }
387 
388 private void
389 applyparam(magic_t magic)
390 {
391 	size_t i;
392 
393 	for (i = 0; i < __arraycount(pm); i++) {
394 		if (pm[i].value == 0)
395 			continue;
396 		if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1) {
397 			(void)fprintf(stderr, "%s: Can't set %s %s\n", progname,
398 				pm[i].name, strerror(errno));
399 			exit(1);
400 		}
401 	}
402 }
403 
404 private void
405 setparam(const char *p)
406 {
407 	size_t i;
408 	char *s;
409 
410 	if ((s = strchr(p, '=')) == NULL)
411 		goto badparm;
412 
413 	for (i = 0; i < __arraycount(pm); i++) {
414 		if (strncmp(p, pm[i].name, s - p) != 0)
415 			continue;
416 		pm[i].value = atoi(s + 1);
417 		return;
418 	}
419 badparm:
420 	(void)fprintf(stderr, "%s: Unknown param %s\n", progname, p);
421 	exit(1);
422 }
423 
424 private struct magic_set *
425 /*ARGSUSED*/
426 load(const char *magicfile, int flags)
427 {
428 	struct magic_set *magic = magic_open(flags);
429 	if (magic == NULL) {
430 		(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
431 		return NULL;
432 	}
433 	if (magic_load(magic, magicfile) == -1) {
434 		(void)fprintf(stderr, "%s: %s\n",
435 		    progname, magic_error(magic));
436 		magic_close(magic);
437 		return NULL;
438 	}
439 	return magic;
440 }
441 
442 /*
443  * unwrap -- read a file of filenames, do each one.
444  */
445 private int
446 unwrap(struct magic_set *ms, const char *fn)
447 {
448 	FILE *f;
449 	ssize_t len;
450 	char *line = NULL;
451 	size_t llen = 0;
452 	int wid = 0, cwid;
453 	int e = 0;
454 
455 	if (strcmp("-", fn) == 0) {
456 		f = stdin;
457 		wid = 1;
458 	} else {
459 		if ((f = fopen(fn, "r")) == NULL) {
460 			(void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
461 			    progname, fn, strerror(errno));
462 			return 1;
463 		}
464 
465 		while ((len = getline(&line, &llen, f)) > 0) {
466 			if (line[len - 1] == '\n')
467 				line[len - 1] = '\0';
468 			cwid = file_mbswidth(line);
469 			if (cwid > wid)
470 				wid = cwid;
471 		}
472 
473 		rewind(f);
474 	}
475 
476 	while ((len = getline(&line, &llen, f)) > 0) {
477 		if (line[len - 1] == '\n')
478 			line[len - 1] = '\0';
479 		e |= process(ms, line, wid);
480 		if(nobuffer)
481 			(void)fflush(stdout);
482 	}
483 
484 	free(line);
485 	(void)fclose(f);
486 	return e;
487 }
488 
489 /*
490  * Called for each input file on the command line (or in a list of files)
491  */
492 private int
493 process(struct magic_set *ms, const char *inname, int wid)
494 {
495 	const char *type;
496 	int std_in = strcmp(inname, "-") == 0;
497 
498 	if (wid > 0 && !bflag) {
499 		(void)printf("%s", std_in ? "/dev/stdin" : inname);
500 		if (nulsep)
501 			(void)putc('\0', stdout);
502 		(void)printf("%s", separator);
503 		(void)printf("%*s ",
504 		    (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
505 	}
506 
507 	type = magic_file(ms, std_in ? NULL : inname);
508 	if (type == NULL) {
509 		(void)printf("ERROR: %s\n", magic_error(ms));
510 		return 1;
511 	} else {
512 		(void)printf("%s\n", type);
513 		return 0;
514 	}
515 }
516 
517 protected size_t
518 file_mbswidth(const char *s)
519 {
520 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
521 	size_t bytesconsumed, old_n, n, width = 0;
522 	mbstate_t state;
523 	wchar_t nextchar;
524 	(void)memset(&state, 0, sizeof(mbstate_t));
525 	old_n = n = strlen(s);
526 
527 	while (n > 0) {
528 		bytesconsumed = mbrtowc(&nextchar, s, n, &state);
529 		if (bytesconsumed == (size_t)(-1) ||
530 		    bytesconsumed == (size_t)(-2)) {
531 			/* Something went wrong, return something reasonable */
532 			return old_n;
533 		}
534 		if (s[0] == '\n') {
535 			/*
536 			 * do what strlen() would do, so that caller
537 			 * is always right
538 			 */
539 			width++;
540 		} else {
541 			int w = wcwidth(nextchar);
542 			if (w > 0)
543 				width += w;
544 		}
545 
546 		s += bytesconsumed, n -= bytesconsumed;
547 	}
548 	return width;
549 #else
550 	return strlen(s);
551 #endif
552 }
553 
554 private void
555 usage(void)
556 {
557 	(void)fprintf(stderr, USAGE, progname, progname, progname);
558 	exit(1);
559 }
560 
561 private void
562 docprint(const char *opts)
563 {
564 	size_t i;
565 	int comma;
566 	char *sp, *p;
567 
568 	p = strstr(opts, "%o");
569 	if (p == NULL) {
570 		fprintf(stdout, "%s", opts);
571 		return;
572 	}
573 
574 	for (sp = p - 1; sp > opts && *sp == ' '; sp--)
575 		continue;
576 
577 	fprintf(stdout, "%.*s", (int)(p - opts), opts);
578 
579 	comma = 0;
580 	for (i = 0; i < __arraycount(nv); i++) {
581 		fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
582 		if (i && i % 5 == 0) {
583 			fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
584 			comma = 0;
585 		}
586 	}
587 
588 	fprintf(stdout, "%s", opts + (p - opts) + 2);
589 }
590 
591 private void
592 help(void)
593 {
594 	(void)fputs(
595 "Usage: file [OPTION...] [FILE...]\n"
596 "Determine type of FILEs.\n"
597 "\n", stdout);
598 #define OPT(shortname, longname, opt, doc)      \
599 	fprintf(stdout, "  -%c, --" longname, shortname), \
600 	docprint(doc);
601 #define OPT_LONGONLY(longname, opt, doc, id)        \
602 	fprintf(stdout, "      --" longname),	\
603 	docprint(doc);
604 #include "file_opts.h"
605 #undef OPT
606 #undef OPT_LONGONLY
607 	fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
608 	exit(0);
609 }
610