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