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