xref: /netbsd-src/external/bsd/file/dist/src/file.c (revision ba65fde2d7fefa7d39838fa5fa855e62bd606b5e)
1 /*	$NetBSD: file.c,v 1.1.1.4 2013/01/03 16:27:53 christos Exp $	*/
2 
3 /*
4  * Copyright (c) Ian F. Darwin 1986-1995.
5  * Software written by Ian F. Darwin and others;
6  * maintained 1995-present by Christos Zoulas and others.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice immediately at the beginning of the file, without modification,
13  *    this list of conditions, and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
22  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 /*
31  * file - find type of a file or files - main program.
32  */
33 
34 #include "file.h"
35 
36 #ifndef	lint
37 #if 0
38 FILE_RCSID("@(#)$File: file.c,v 1.148 2012/11/21 16:27:39 christos Exp $")
39 #else
40 __RCSID("$NetBSD: file.c,v 1.1.1.4 2013/01/03 16:27:53 christos Exp $");
41 #endif
42 #endif	/* lint */
43 
44 #include "magic.h"
45 
46 #include <stdlib.h>
47 #include <unistd.h>
48 #include <string.h>
49 #ifdef RESTORE_TIME
50 # if (__COHERENT__ >= 0x420)
51 #  include <sys/utime.h>
52 # else
53 #  ifdef USE_UTIMES
54 #   include <sys/time.h>
55 #  else
56 #   include <utime.h>
57 #  endif
58 # endif
59 #endif
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>	/* for read() */
62 #endif
63 #ifdef HAVE_LOCALE_H
64 #include <locale.h>
65 #endif
66 #ifdef HAVE_WCHAR_H
67 #include <wchar.h>
68 #endif
69 
70 #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
71 #include <getopt.h>
72 #ifndef HAVE_GETOPT_LONG
73 int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
74 #endif
75 #else
76 #include "mygetopt.h"
77 #endif
78 
79 #ifdef S_IFLNK
80 #define FILE_FLAGS "-bchikLlNnprsvz0"
81 #else
82 #define FILE_FLAGS "-bciklNnprsvz0"
83 #endif
84 
85 # define USAGE  \
86     "Usage: %s [" FILE_FLAGS \
87 	"] [--apple] [--mime-encoding] [--mime-type]\n" \
88     "            [-e testname] [-F separator] [-f namefile] [-m magicfiles] " \
89     "file ...\n" \
90     "       %s -C [-m magicfiles]\n" \
91     "       %s [--help]\n"
92 
93 private int 		/* Global command-line options 		*/
94 	bflag = 0,	/* brief output format	 		*/
95 	nopad = 0,	/* Don't pad output			*/
96 	nobuffer = 0,   /* Do not buffer stdout 		*/
97 	nulsep = 0;	/* Append '\0' to the separator		*/
98 
99 private const char *separator = ":";	/* Default field separator	*/
100 private const struct option long_options[] = {
101 #define OPT(shortname, longname, opt, doc)      \
102     {longname, opt, NULL, shortname},
103 #define OPT_LONGONLY(longname, opt, doc)        \
104     {longname, opt, NULL, 0},
105 #include "file_opts.h"
106 #undef OPT
107 #undef OPT_LONGONLY
108     {0, 0, NULL, 0}
109 };
110 #define OPTSTRING	"bcCde:f:F:hiklLm:nNprsvz0"
111 
112 private const struct {
113 	const char *name;
114 	int value;
115 } nv[] = {
116 	{ "apptype",	MAGIC_NO_CHECK_APPTYPE },
117 	{ "ascii",	MAGIC_NO_CHECK_ASCII },
118 	{ "cdf",	MAGIC_NO_CHECK_CDF },
119 	{ "compress",	MAGIC_NO_CHECK_COMPRESS },
120 	{ "elf",	MAGIC_NO_CHECK_ELF },
121 	{ "encoding",	MAGIC_NO_CHECK_ENCODING },
122 	{ "soft",	MAGIC_NO_CHECK_SOFT },
123 	{ "tar",	MAGIC_NO_CHECK_TAR },
124 	{ "text",	MAGIC_NO_CHECK_TEXT },	/* synonym for ascii */
125 	{ "tokens",	MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
126 };
127 
128 private char *progname;		/* used throughout 		*/
129 
130 private void usage(void);
131 private void docprint(const char *);
132 private void help(void);
133 
134 private int unwrap(struct magic_set *, const char *);
135 private int process(struct magic_set *ms, const char *, int);
136 private struct magic_set *load(const char *, int);
137 
138 
139 /*
140  * main - parse arguments and handle options
141  */
142 int
143 main(int argc, char *argv[])
144 {
145 	int c;
146 	size_t i;
147 	int action = 0, didsomefiles = 0, errflg = 0;
148 	int flags = 0, e = 0;
149 	struct magic_set *magic = NULL;
150 	int longindex;
151 	const char *magicfile = NULL;		/* where the magic is	*/
152 
153 	/* makes islower etc work for other langs */
154 	(void)setlocale(LC_CTYPE, "");
155 
156 #ifdef __EMX__
157 	/* sh-like wildcard expansion! Shouldn't hurt at least ... */
158 	_wildcard(&argc, &argv);
159 #endif
160 
161 	if ((progname = strrchr(argv[0], '/')) != NULL)
162 		progname++;
163 	else
164 		progname = argv[0];
165 
166 #ifdef S_IFLNK
167 	flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
168 #endif
169 	while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
170 	    &longindex)) != -1)
171 		switch (c) {
172 		case 0 :
173 			switch (longindex) {
174 			case 0:
175 				help();
176 				break;
177 			case 10:
178 				flags |= MAGIC_APPLE;
179 				break;
180 			case 11:
181 				flags |= MAGIC_MIME_TYPE;
182 				break;
183 			case 12:
184 				flags |= MAGIC_MIME_ENCODING;
185 				break;
186 			}
187 			break;
188 		case '0':
189 			nulsep = 1;
190 			break;
191 		case 'b':
192 			bflag++;
193 			break;
194 		case 'c':
195 			action = FILE_CHECK;
196 			break;
197 		case 'C':
198 			action = FILE_COMPILE;
199 			break;
200 		case 'd':
201 			flags |= MAGIC_DEBUG|MAGIC_CHECK;
202 			break;
203 		case 'e':
204 			for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
205 				if (strcmp(nv[i].name, optarg) == 0)
206 					break;
207 
208 			if (i == sizeof(nv) / sizeof(nv[0]))
209 				errflg++;
210 			else
211 				flags |= nv[i].value;
212 			break;
213 
214 		case 'f':
215 			if(action)
216 				usage();
217 			if (magic == NULL)
218 				if ((magic = load(magicfile, flags)) == NULL)
219 					return 1;
220 			e |= unwrap(magic, optarg);
221 			++didsomefiles;
222 			break;
223 		case 'F':
224 			separator = optarg;
225 			break;
226 		case 'i':
227 			flags |= MAGIC_MIME;
228 			break;
229 		case 'k':
230 			flags |= MAGIC_CONTINUE;
231 			break;
232 		case 'l':
233 			action = FILE_LIST;
234 			break;
235 		case 'm':
236 			magicfile = optarg;
237 			break;
238 		case 'n':
239 			++nobuffer;
240 			break;
241 		case 'N':
242 			++nopad;
243 			break;
244 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
245 		case 'p':
246 			flags |= MAGIC_PRESERVE_ATIME;
247 			break;
248 #endif
249 		case 'r':
250 			flags |= MAGIC_RAW;
251 			break;
252 		case 's':
253 			flags |= MAGIC_DEVICES;
254 			break;
255 		case 'v':
256 			if (magicfile == NULL)
257 				magicfile = magic_getpath(magicfile, action);
258 			(void)fprintf(stdout, "%s-%s\n", progname, VERSION);
259 			(void)fprintf(stdout, "magic file from %s\n",
260 				       magicfile);
261 			return 0;
262 		case 'z':
263 			flags |= MAGIC_COMPRESS;
264 			break;
265 #ifdef S_IFLNK
266 		case 'L':
267 			flags |= MAGIC_SYMLINK;
268 			break;
269 		case 'h':
270 			flags &= ~MAGIC_SYMLINK;
271 			break;
272 #endif
273 		case '?':
274 		default:
275 			errflg++;
276 			break;
277 		}
278 
279 	if (errflg) {
280 		usage();
281 	}
282 	if (e)
283 		return e;
284 
285 	switch(action) {
286 	case FILE_CHECK:
287 	case FILE_COMPILE:
288 	case FILE_LIST:
289 		/*
290 		 * Don't try to check/compile ~/.magic unless we explicitly
291 		 * ask for it.
292 		 */
293 		magic = magic_open(flags|MAGIC_CHECK);
294 		if (magic == NULL) {
295 			(void)fprintf(stderr, "%s: %s\n", progname,
296 			    strerror(errno));
297 			return 1;
298 		}
299 		switch(action) {
300 		case FILE_CHECK:
301 			c = magic_check(magic, magicfile);
302 			break;
303 		case FILE_COMPILE:
304 			c = magic_compile(magic, magicfile);
305 			break;
306 		case FILE_LIST:
307 			c = magic_list(magic, magicfile);
308 			break;
309 		default:
310 			abort();
311 		}
312 		if (c == -1) {
313 			(void)fprintf(stderr, "%s: %s\n", progname,
314 			    magic_error(magic));
315 			return 1;
316 		}
317 		return 0;
318 	default:
319 		if (magic == NULL)
320 			if ((magic = load(magicfile, flags)) == NULL)
321 				return 1;
322 		break;
323 	}
324 
325 	if (optind == argc) {
326 		if (!didsomefiles)
327 			usage();
328 	}
329 	else {
330 		size_t j, wid, nw;
331 		for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
332 			nw = file_mbswidth(argv[j]);
333 			if (nw > wid)
334 				wid = nw;
335 		}
336 		/*
337 		 * If bflag is only set twice, set it depending on
338 		 * number of files [this is undocumented, and subject to change]
339 		 */
340 		if (bflag == 2) {
341 			bflag = optind >= argc - 1;
342 		}
343 		for (; optind < argc; optind++)
344 			e |= process(magic, argv[optind], wid);
345 	}
346 
347 	if (magic)
348 		magic_close(magic);
349 	return e;
350 }
351 
352 
353 private struct magic_set *
354 /*ARGSUSED*/
355 load(const char *magicfile, int flags)
356 {
357 	struct magic_set *magic = magic_open(flags);
358 	if (magic == NULL) {
359 		(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
360 		return NULL;
361 	}
362 	if (magic_load(magic, magicfile) == -1) {
363 		(void)fprintf(stderr, "%s: %s\n",
364 		    progname, magic_error(magic));
365 		magic_close(magic);
366 		return NULL;
367 	}
368 	return magic;
369 }
370 
371 /*
372  * unwrap -- read a file of filenames, do each one.
373  */
374 private int
375 unwrap(struct magic_set *ms, const char *fn)
376 {
377 	FILE *f;
378 	ssize_t len;
379 	char *line = NULL;
380 	size_t llen = 0;
381 	int wid = 0, cwid;
382 	int e = 0;
383 
384 	if (strcmp("-", fn) == 0) {
385 		f = stdin;
386 		wid = 1;
387 	} else {
388 		if ((f = fopen(fn, "r")) == NULL) {
389 			(void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
390 			    progname, fn, strerror(errno));
391 			return 1;
392 		}
393 
394 		while ((len = getline(&line, &llen, f)) > 0) {
395 			if (line[len - 1] == '\n')
396 				line[len - 1] = '\0';
397 			cwid = file_mbswidth(line);
398 			if (cwid > wid)
399 				wid = cwid;
400 		}
401 
402 		rewind(f);
403 	}
404 
405 	while ((len = getline(&line, &llen, f)) > 0) {
406 		if (line[len - 1] == '\n')
407 			line[len - 1] = '\0';
408 		e |= process(ms, line, wid);
409 		if(nobuffer)
410 			(void)fflush(stdout);
411 	}
412 
413 	free(line);
414 	(void)fclose(f);
415 	return e;
416 }
417 
418 /*
419  * Called for each input file on the command line (or in a list of files)
420  */
421 private int
422 process(struct magic_set *ms, const char *inname, int wid)
423 {
424 	const char *type;
425 	int std_in = strcmp(inname, "-") == 0;
426 
427 	if (wid > 0 && !bflag) {
428 		(void)printf("%s", std_in ? "/dev/stdin" : inname);
429 		if (nulsep)
430 			(void)putc('\0', stdout);
431 		(void)printf("%s", separator);
432 		(void)printf("%*s ",
433 		    (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
434 	}
435 
436 	type = magic_file(ms, std_in ? NULL : inname);
437 	if (type == NULL) {
438 		(void)printf("ERROR: %s\n", magic_error(ms));
439 		return 1;
440 	} else {
441 		(void)printf("%s\n", type);
442 		return 0;
443 	}
444 }
445 
446 protected size_t
447 file_mbswidth(const char *s)
448 {
449 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
450 	size_t bytesconsumed, old_n, n, width = 0;
451 	mbstate_t state;
452 	wchar_t nextchar;
453 	(void)memset(&state, 0, sizeof(mbstate_t));
454 	old_n = n = strlen(s);
455 
456 	while (n > 0) {
457 		bytesconsumed = mbrtowc(&nextchar, s, n, &state);
458 		if (bytesconsumed == (size_t)(-1) ||
459 		    bytesconsumed == (size_t)(-2)) {
460 			/* Something went wrong, return something reasonable */
461 			return old_n;
462 		}
463 		if (s[0] == '\n') {
464 			/*
465 			 * do what strlen() would do, so that caller
466 			 * is always right
467 			 */
468 			width++;
469 		} else
470 			width += wcwidth(nextchar);
471 
472 		s += bytesconsumed, n -= bytesconsumed;
473 	}
474 	return width;
475 #else
476 	return strlen(s);
477 #endif
478 }
479 
480 private void
481 usage(void)
482 {
483 	(void)fprintf(stderr, USAGE, progname, progname, progname);
484 	exit(1);
485 }
486 
487 private void
488 docprint(const char *opts)
489 {
490 	size_t i;
491 	int comma;
492 	char *sp, *p;
493 
494 	p = strstr(opts, "%o");
495 	if (p == NULL) {
496 		fprintf(stdout, "%s", opts);
497 		return;
498 	}
499 
500 	for (sp = p - 1; sp > opts && *sp == ' '; sp--)
501 		continue;
502 
503 	fprintf(stdout, "%.*s", (int)(p - opts), opts);
504 
505 	comma = 0;
506 	for (i = 0; i < __arraycount(nv); i++) {
507 		fprintf(stdout, "%s%s", comma++ ? ", " : "", nv[i].name);
508 		if (i && i % 5 == 0) {
509 			fprintf(stdout, ",\n%*s", (int)(p - sp - 1), "");
510 			comma = 0;
511 		}
512 	}
513 
514 	fprintf(stdout, "%s", opts + (p - opts) + 2);
515 }
516 
517 private void
518 help(void)
519 {
520 	(void)fputs(
521 "Usage: file [OPTION...] [FILE...]\n"
522 "Determine type of FILEs.\n"
523 "\n", stdout);
524 #define OPT(shortname, longname, opt, doc)      \
525 	fprintf(stdout, "  -%c, --" longname, shortname), \
526 	docprint(doc);
527 #define OPT_LONGONLY(longname, opt, doc)        \
528 	fprintf(stdout, "      --" longname),	\
529 	docprint(doc);
530 #include "file_opts.h"
531 #undef OPT
532 #undef OPT_LONGONLY
533 	fprintf(stdout, "\nReport bugs to http://bugs.gw.com/\n");
534 	exit(0);
535 }
536