file.c revision 287453
11556Srgrimes/*
21556Srgrimes * Copyright (c) Ian F. Darwin 1986-1995.
31556Srgrimes * Software written by Ian F. Darwin and others;
41556Srgrimes * maintained 1995-present by Christos Zoulas and others.
51556Srgrimes *
61556Srgrimes * Redistribution and use in source and binary forms, with or without
71556Srgrimes * modification, are permitted provided that the following conditions
81556Srgrimes * are met:
91556Srgrimes * 1. Redistributions of source code must retain the above copyright
101556Srgrimes *    notice immediately at the beginning of the file, without modification,
111556Srgrimes *    this list of conditions, and the following disclaimer.
121556Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
131556Srgrimes *    notice, this list of conditions and the following disclaimer in the
141556Srgrimes *    documentation and/or other materials provided with the distribution.
151556Srgrimes *
161556Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
171556Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
181556Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
191556Srgrimes * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
201556Srgrimes * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
211556Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
221556Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
231556Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
241556Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
251556Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
261556Srgrimes * SUCH DAMAGE.
271556Srgrimes */
281556Srgrimes/*
291556Srgrimes * file - find type of a file or files - main program.
301556Srgrimes */
311556Srgrimes
321556Srgrimes#include "file.h"
331556Srgrimes
341556Srgrimes#ifndef	lint
351556SrgrimesFILE_RCSID("@(#)$File: file.c,v 1.165 2015/06/11 12:52:32 christos Exp $")
361556Srgrimes#endif	/* lint */
371556Srgrimes
3850471Speter#include "magic.h"
391556Srgrimes
401556Srgrimes#include <stdlib.h>
411556Srgrimes#include <unistd.h>
421556Srgrimes#include <string.h>
431556Srgrimes#ifdef RESTORE_TIME
441556Srgrimes# if (__COHERENT__ >= 0x420)
451556Srgrimes#  include <sys/utime.h>
461556Srgrimes# else
471556Srgrimes#  ifdef USE_UTIMES
481556Srgrimes#   include <sys/time.h>
491556Srgrimes#  else
501556Srgrimes#   include <utime.h>
511556Srgrimes#  endif
521556Srgrimes# endif
531556Srgrimes#endif
541556Srgrimes#ifdef HAVE_UNISTD_H
551556Srgrimes#include <unistd.h>	/* for read() */
561556Srgrimes#endif
571556Srgrimes#ifdef HAVE_WCHAR_H
581556Srgrimes#include <wchar.h>
591556Srgrimes#endif
601556Srgrimes
611556Srgrimes#if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
621556Srgrimes#include <getopt.h>
631556Srgrimes#ifndef HAVE_GETOPT_LONG
641556Srgrimesint getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
651556Srgrimes#endif
661556Srgrimes#else
671556Srgrimes#include "mygetopt.h"
681556Srgrimes#endif
691556Srgrimes
701556Srgrimes#ifdef S_IFLNK
711556Srgrimes#define FILE_FLAGS "-bcEhikLlNnprsvzZ0"
721556Srgrimes#else
731556Srgrimes#define FILE_FLAGS "-bcEiklNnprsvzZ0"
748855Srgrimes#endif
751556Srgrimes
761556Srgrimes# define USAGE  \
771556Srgrimes    "Usage: %s [" FILE_FLAGS \
781556Srgrimes	"] [--apple] [--extension] [--mime-encoding] [--mime-type]\n" \
791556Srgrimes    "            [-e testname] [-F separator] [-f namefile] [-m magicfiles] " \
801556Srgrimes    "file ...\n" \
811556Srgrimes    "       %s -C [-m magicfiles]\n" \
821556Srgrimes    "       %s [--help]\n"
831556Srgrimes
841556Srgrimesprivate int 		/* Global command-line options 		*/
858855Srgrimes	bflag = 0,	/* brief output format	 		*/
861556Srgrimes	nopad = 0,	/* Don't pad output			*/
871556Srgrimes	nobuffer = 0,   /* Do not buffer stdout 		*/
881556Srgrimes	nulsep = 0;	/* Append '\0' to the separator		*/
891556Srgrimes
901556Srgrimesprivate const char *separator = ":";	/* Default field separator	*/
911556Srgrimesprivate const struct option long_options[] = {
921556Srgrimes#define OPT_HELP		1
931556Srgrimes#define OPT_APPLE		2
941556Srgrimes#define OPT_EXTENSIONS		3
951556Srgrimes#define OPT_MIME_TYPE		4
961556Srgrimes#define OPT_MIME_ENCODING	5
971556Srgrimes#define OPT(shortname, longname, opt, doc)      \
981556Srgrimes    {longname, opt, NULL, shortname},
991556Srgrimes#define OPT_LONGONLY(longname, opt, doc, id)        \
1001556Srgrimes    {longname, opt, NULL, id},
1011556Srgrimes#include "file_opts.h"
1021556Srgrimes#undef OPT
1031556Srgrimes#undef OPT_LONGONLY
1041556Srgrimes    {0, 0, NULL, 0}
1058855Srgrimes};
1061556Srgrimes#define OPTSTRING	"bcCde:Ef:F:hiklLm:nNpP:rsvzZ0"
1071556Srgrimes
1081556Srgrimesprivate const struct {
1091556Srgrimes	const char *name;
1101556Srgrimes	int value;
1111556Srgrimes} nv[] = {
1121556Srgrimes	{ "apptype",	MAGIC_NO_CHECK_APPTYPE },
1131556Srgrimes	{ "ascii",	MAGIC_NO_CHECK_ASCII },
1141556Srgrimes	{ "cdf",	MAGIC_NO_CHECK_CDF },
1151556Srgrimes	{ "compress",	MAGIC_NO_CHECK_COMPRESS },
1161556Srgrimes	{ "elf",	MAGIC_NO_CHECK_ELF },
1171556Srgrimes	{ "encoding",	MAGIC_NO_CHECK_ENCODING },
1181556Srgrimes	{ "soft",	MAGIC_NO_CHECK_SOFT },
1191556Srgrimes	{ "tar",	MAGIC_NO_CHECK_TAR },
1201556Srgrimes	{ "text",	MAGIC_NO_CHECK_TEXT },	/* synonym for ascii */
1211556Srgrimes	{ "tokens",	MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
1221556Srgrimes};
1231556Srgrimes
1241556Srgrimesprivate struct {
1251556Srgrimes	const char *name;
1261556Srgrimes	int tag;
1271556Srgrimes	size_t value;
1281556Srgrimes} pm[] = {
1291556Srgrimes	{ "indir",	MAGIC_PARAM_INDIR_MAX, 0 },
1301556Srgrimes	{ "name",	MAGIC_PARAM_NAME_MAX, 0 },
1311556Srgrimes	{ "elf_phnum",	MAGIC_PARAM_ELF_PHNUM_MAX, 0 },
1321556Srgrimes	{ "elf_shnum",	MAGIC_PARAM_ELF_SHNUM_MAX, 0 },
1331556Srgrimes	{ "elf_notes",	MAGIC_PARAM_ELF_NOTES_MAX, 0 },
1341556Srgrimes};
1351556Srgrimes
1361556Srgrimesprivate char *progname;		/* used throughout 		*/
1371556Srgrimes
1381556Srgrimes#ifdef __dead
1391556Srgrimes__dead
1401556Srgrimes#endif
1411556Srgrimesprivate void usage(void);
1421556Srgrimesprivate void docprint(const char *);
1438855Srgrimes#ifdef __dead
1441556Srgrimes__dead
1451556Srgrimes#endif
1461556Srgrimesprivate void help(void);
1471556Srgrimes
1481556Srgrimesprivate int unwrap(struct magic_set *, const char *);
1491556Srgrimesprivate int process(struct magic_set *ms, const char *, int);
1501556Srgrimesprivate struct magic_set *load(const char *, int);
1511556Srgrimesprivate void setparam(const char *);
1521556Srgrimesprivate void applyparam(magic_t);
153
154
155/*
156 * main - parse arguments and handle options
157 */
158int
159main(int argc, char *argv[])
160{
161	int c;
162	size_t i;
163	int action = 0, didsomefiles = 0, errflg = 0;
164	int flags = 0, e = 0;
165	struct magic_set *magic = NULL;
166	int longindex;
167	const char *magicfile = NULL;		/* where the magic is	*/
168
169	/* makes islower etc work for other langs */
170#ifdef HAVE_SETLOCALE
171	(void)setlocale(LC_CTYPE, "");
172#endif
173
174#ifdef __EMX__
175	/* sh-like wildcard expansion! Shouldn't hurt at least ... */
176	_wildcard(&argc, &argv);
177#endif
178
179	if ((progname = strrchr(argv[0], '/')) != NULL)
180		progname++;
181	else
182		progname = argv[0];
183
184#ifdef S_IFLNK
185	flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
186#endif
187	while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
188	    &longindex)) != -1)
189		switch (c) {
190		case OPT_HELP:
191			help();
192			break;
193		case OPT_APPLE:
194			flags |= MAGIC_APPLE;
195			break;
196		case OPT_EXTENSIONS:
197			flags |= MAGIC_EXTENSION;
198			break;
199		case OPT_MIME_TYPE:
200			flags |= MAGIC_MIME_TYPE;
201			break;
202		case OPT_MIME_ENCODING:
203			flags |= MAGIC_MIME_ENCODING;
204			break;
205		case '0':
206			nulsep = 1;
207			break;
208		case 'b':
209			bflag++;
210			break;
211		case 'c':
212			action = FILE_CHECK;
213			break;
214		case 'C':
215			action = FILE_COMPILE;
216			break;
217		case 'd':
218			flags |= MAGIC_DEBUG|MAGIC_CHECK;
219			break;
220		case 'E':
221			flags |= MAGIC_ERROR;
222			break;
223		case 'e':
224			for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
225				if (strcmp(nv[i].name, optarg) == 0)
226					break;
227
228			if (i == sizeof(nv) / sizeof(nv[0]))
229				errflg++;
230			else
231				flags |= nv[i].value;
232			break;
233
234		case 'f':
235			if(action)
236				usage();
237			if (magic == NULL)
238				if ((magic = load(magicfile, flags)) == NULL)
239					return 1;
240			e |= unwrap(magic, optarg);
241			++didsomefiles;
242			break;
243		case 'F':
244			separator = optarg;
245			break;
246		case 'i':
247			flags |= MAGIC_MIME;
248			break;
249		case 'k':
250			flags |= MAGIC_CONTINUE;
251			break;
252		case 'l':
253			action = FILE_LIST;
254			break;
255		case 'm':
256			magicfile = optarg;
257			break;
258		case 'n':
259			++nobuffer;
260			break;
261		case 'N':
262			++nopad;
263			break;
264#if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
265		case 'p':
266			flags |= MAGIC_PRESERVE_ATIME;
267			break;
268#endif
269		case 'P':
270			setparam(optarg);
271			break;
272		case 'r':
273			flags |= MAGIC_RAW;
274			break;
275		case 's':
276			flags |= MAGIC_DEVICES;
277			break;
278		case 'v':
279			if (magicfile == NULL)
280				magicfile = magic_getpath(magicfile, action);
281			(void)fprintf(stdout, "%s-%s\n", progname, VERSION);
282			(void)fprintf(stdout, "magic file from %s\n",
283				       magicfile);
284			return 0;
285		case 'z':
286			flags |= MAGIC_COMPRESS;
287			break;
288
289		case 'Z':
290			flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
291			break;
292#ifdef S_IFLNK
293		case 'L':
294			flags |= MAGIC_SYMLINK;
295			break;
296		case 'h':
297			flags &= ~MAGIC_SYMLINK;
298			break;
299#endif
300		case '?':
301		default:
302			errflg++;
303			break;
304		}
305
306	if (errflg) {
307		usage();
308	}
309	if (e)
310		return e;
311
312	if (MAGIC_VERSION != magic_version())
313		(void)fprintf(stderr, "%s: compiled magic version [%d] "
314		    "does not match with shared library magic version [%d]\n",
315		    progname, MAGIC_VERSION, magic_version());
316
317	switch(action) {
318	case FILE_CHECK:
319	case FILE_COMPILE:
320	case FILE_LIST:
321		/*
322		 * Don't try to check/compile ~/.magic unless we explicitly
323		 * ask for it.
324		 */
325		magic = magic_open(flags|MAGIC_CHECK);
326		if (magic == NULL) {
327			(void)fprintf(stderr, "%s: %s\n", progname,
328			    strerror(errno));
329			return 1;
330		}
331
332
333		switch(action) {
334		case FILE_CHECK:
335			c = magic_check(magic, magicfile);
336			break;
337		case FILE_COMPILE:
338			c = magic_compile(magic, magicfile);
339			break;
340		case FILE_LIST:
341			c = magic_list(magic, magicfile);
342			break;
343		default:
344			abort();
345		}
346		if (c == -1) {
347			(void)fprintf(stderr, "%s: %s\n", progname,
348			    magic_error(magic));
349			return 1;
350		}
351		return 0;
352	default:
353		if (magic == NULL)
354			if ((magic = load(magicfile, flags)) == NULL)
355				return 1;
356		applyparam(magic);
357	}
358
359	if (optind == argc) {
360		if (!didsomefiles)
361			usage();
362	}
363	else {
364		size_t j, wid, nw;
365		for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
366			nw = file_mbswidth(argv[j]);
367			if (nw > wid)
368				wid = nw;
369		}
370		/*
371		 * If bflag is only set twice, set it depending on
372		 * number of files [this is undocumented, and subject to change]
373		 */
374		if (bflag == 2) {
375			bflag = optind >= argc - 1;
376		}
377		for (; optind < argc; optind++)
378			e |= process(magic, argv[optind], wid);
379	}
380
381	if (magic)
382		magic_close(magic);
383	return e;
384}
385
386private void
387applyparam(magic_t magic)
388{
389	size_t i;
390
391	for (i = 0; i < __arraycount(pm); i++) {
392		if (pm[i].value == 0)
393			continue;
394		if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1) {
395			(void)fprintf(stderr, "%s: Can't set %s %s\n", progname,
396				pm[i].name, strerror(errno));
397			exit(1);
398		}
399	}
400}
401
402private void
403setparam(const char *p)
404{
405	size_t i;
406	char *s;
407
408	if ((s = strchr(p, '=')) == NULL)
409		goto badparm;
410
411	for (i = 0; i < __arraycount(pm); i++) {
412		if (strncmp(p, pm[i].name, s - p) != 0)
413			continue;
414		pm[i].value = atoi(s + 1);
415		return;
416	}
417badparm:
418	(void)fprintf(stderr, "%s: Unknown param %s\n", progname, p);
419	exit(1);
420}
421
422private struct magic_set *
423/*ARGSUSED*/
424load(const char *magicfile, int flags)
425{
426	struct magic_set *magic = magic_open(flags);
427	if (magic == NULL) {
428		(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
429		return NULL;
430	}
431	if (magic_load(magic, magicfile) == -1) {
432		(void)fprintf(stderr, "%s: %s\n",
433		    progname, magic_error(magic));
434		magic_close(magic);
435		return NULL;
436	}
437	return magic;
438}
439
440/*
441 * unwrap -- read a file of filenames, do each one.
442 */
443private int
444unwrap(struct magic_set *ms, const char *fn)
445{
446	FILE *f;
447	ssize_t len;
448	char *line = NULL;
449	size_t llen = 0;
450	int wid = 0, cwid;
451	int e = 0;
452
453	if (strcmp("-", fn) == 0) {
454		f = stdin;
455		wid = 1;
456	} else {
457		if ((f = fopen(fn, "r")) == NULL) {
458			(void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
459			    progname, fn, strerror(errno));
460			return 1;
461		}
462
463		while ((len = getline(&line, &llen, f)) > 0) {
464			if (line[len - 1] == '\n')
465				line[len - 1] = '\0';
466			cwid = file_mbswidth(line);
467			if (cwid > wid)
468				wid = cwid;
469		}
470
471		rewind(f);
472	}
473
474	while ((len = getline(&line, &llen, f)) > 0) {
475		if (line[len - 1] == '\n')
476			line[len - 1] = '\0';
477		e |= process(ms, line, wid);
478		if(nobuffer)
479			(void)fflush(stdout);
480	}
481
482	free(line);
483	(void)fclose(f);
484	return e;
485}
486
487/*
488 * Called for each input file on the command line (or in a list of files)
489 */
490private int
491process(struct magic_set *ms, const char *inname, int wid)
492{
493	const char *type;
494	int std_in = strcmp(inname, "-") == 0;
495
496	if (wid > 0 && !bflag) {
497		(void)printf("%s", std_in ? "/dev/stdin" : inname);
498		if (nulsep)
499			(void)putc('\0', stdout);
500		(void)printf("%s", separator);
501		(void)printf("%*s ",
502		    (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
503	}
504
505	type = magic_file(ms, std_in ? NULL : inname);
506	if (type == NULL) {
507		(void)printf("ERROR: %s\n", magic_error(ms));
508		return 1;
509	} else {
510		(void)printf("%s\n", type);
511		return 0;
512	}
513}
514
515protected size_t
516file_mbswidth(const char *s)
517{
518#if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
519	size_t bytesconsumed, old_n, n, width = 0;
520	mbstate_t state;
521	wchar_t nextchar;
522	(void)memset(&state, 0, sizeof(mbstate_t));
523	old_n = n = strlen(s);
524
525	while (n > 0) {
526		bytesconsumed = mbrtowc(&nextchar, s, n, &state);
527		if (bytesconsumed == (size_t)(-1) ||
528		    bytesconsumed == (size_t)(-2)) {
529			/* Something went wrong, return something reasonable */
530			return old_n;
531		}
532		if (s[0] == '\n') {
533			/*
534			 * do what strlen() would do, so that caller
535			 * is always right
536			 */
537			width++;
538		} else {
539			int w = wcwidth(nextchar);
540			if (w > 0)
541				width += w;
542		}
543
544		s += bytesconsumed, n -= bytesconsumed;
545	}
546	return width;
547#else
548	return strlen(s);
549#endif
550}
551
552private void
553usage(void)
554{
555	(void)fprintf(stderr, USAGE, progname, progname, progname);
556	exit(1);
557}
558
559private void
560docprint(const char *opts)
561{
562	size_t i;
563	int comma;
564	char *sp, *p;
565
566	p = strstr(opts, "%o");
567	if (p == NULL) {
568		fprintf(stdout, "%s", opts);
569		return;
570	}
571
572	for (sp = p - 1; sp > opts && *sp == ' '; sp--)
573		continue;
574
575	fprintf(stdout, "%.*s", (int)(p - opts), opts);
576
577	comma = 0;
578	for (i = 0; i < __arraycount(nv); i++) {
579		fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
580		if (i && i % 5 == 0) {
581			fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
582			comma = 0;
583		}
584	}
585
586	fprintf(stdout, "%s", opts + (p - opts) + 2);
587}
588
589private void
590help(void)
591{
592	(void)fputs(
593"Usage: file [OPTION...] [FILE...]\n"
594"Determine type of FILEs.\n"
595"\n", stdout);
596#define OPT(shortname, longname, opt, doc)      \
597	fprintf(stdout, "  -%c, --" longname, shortname), \
598	docprint(doc);
599#define OPT_LONGONLY(longname, opt, doc, id)        \
600	fprintf(stdout, "      --" longname),	\
601	docprint(doc);
602#include "file_opts.h"
603#undef OPT
604#undef OPT_LONGONLY
605	fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
606	exit(0);
607}
608