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