xref: /minix3/external/bsd/file/dist/src/file.c (revision 0b98e8aad89f2bd4ba80b523d73cf29e9dd82ce1)
1 /*	$NetBSD: file.c,v 1.1.1.5 2013/03/23 15:49:16 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.149 2013/01/07 18:20:19 christos Exp $")
39 #else
40 __RCSID("$NetBSD: file.c,v 1.1.1.5 2013/03/23 15:49:16 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 	if (MAGIC_VERSION != magic_version())
286 		(void)fprintf(stderr, "%s: compiled magic version [%d] "
287 		    "does not match with shared library magic version [%d]\n",
288 		    progname, MAGIC_VERSION, magic_version());
289 
290 	switch(action) {
291 	case FILE_CHECK:
292 	case FILE_COMPILE:
293 	case FILE_LIST:
294 		/*
295 		 * Don't try to check/compile ~/.magic unless we explicitly
296 		 * ask for it.
297 		 */
298 		magic = magic_open(flags|MAGIC_CHECK);
299 		if (magic == NULL) {
300 			(void)fprintf(stderr, "%s: %s\n", progname,
301 			    strerror(errno));
302 			return 1;
303 		}
304 		switch(action) {
305 		case FILE_CHECK:
306 			c = magic_check(magic, magicfile);
307 			break;
308 		case FILE_COMPILE:
309 			c = magic_compile(magic, magicfile);
310 			break;
311 		case FILE_LIST:
312 			c = magic_list(magic, magicfile);
313 			break;
314 		default:
315 			abort();
316 		}
317 		if (c == -1) {
318 			(void)fprintf(stderr, "%s: %s\n", progname,
319 			    magic_error(magic));
320 			return 1;
321 		}
322 		return 0;
323 	default:
324 		if (magic == NULL)
325 			if ((magic = load(magicfile, flags)) == NULL)
326 				return 1;
327 		break;
328 	}
329 
330 	if (optind == argc) {
331 		if (!didsomefiles)
332 			usage();
333 	}
334 	else {
335 		size_t j, wid, nw;
336 		for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
337 			nw = file_mbswidth(argv[j]);
338 			if (nw > wid)
339 				wid = nw;
340 		}
341 		/*
342 		 * If bflag is only set twice, set it depending on
343 		 * number of files [this is undocumented, and subject to change]
344 		 */
345 		if (bflag == 2) {
346 			bflag = optind >= argc - 1;
347 		}
348 		for (; optind < argc; optind++)
349 			e |= process(magic, argv[optind], wid);
350 	}
351 
352 	if (magic)
353 		magic_close(magic);
354 	return e;
355 }
356 
357 
358 private struct magic_set *
359 /*ARGSUSED*/
360 load(const char *magicfile, int flags)
361 {
362 	struct magic_set *magic = magic_open(flags);
363 	if (magic == NULL) {
364 		(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
365 		return NULL;
366 	}
367 	if (magic_load(magic, magicfile) == -1) {
368 		(void)fprintf(stderr, "%s: %s\n",
369 		    progname, magic_error(magic));
370 		magic_close(magic);
371 		return NULL;
372 	}
373 	return magic;
374 }
375 
376 /*
377  * unwrap -- read a file of filenames, do each one.
378  */
379 private int
380 unwrap(struct magic_set *ms, const char *fn)
381 {
382 	FILE *f;
383 	ssize_t len;
384 	char *line = NULL;
385 	size_t llen = 0;
386 	int wid = 0, cwid;
387 	int e = 0;
388 
389 	if (strcmp("-", fn) == 0) {
390 		f = stdin;
391 		wid = 1;
392 	} else {
393 		if ((f = fopen(fn, "r")) == NULL) {
394 			(void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
395 			    progname, fn, strerror(errno));
396 			return 1;
397 		}
398 
399 		while ((len = getline(&line, &llen, f)) > 0) {
400 			if (line[len - 1] == '\n')
401 				line[len - 1] = '\0';
402 			cwid = file_mbswidth(line);
403 			if (cwid > wid)
404 				wid = cwid;
405 		}
406 
407 		rewind(f);
408 	}
409 
410 	while ((len = getline(&line, &llen, f)) > 0) {
411 		if (line[len - 1] == '\n')
412 			line[len - 1] = '\0';
413 		e |= process(ms, line, wid);
414 		if(nobuffer)
415 			(void)fflush(stdout);
416 	}
417 
418 	free(line);
419 	(void)fclose(f);
420 	return e;
421 }
422 
423 /*
424  * Called for each input file on the command line (or in a list of files)
425  */
426 private int
427 process(struct magic_set *ms, const char *inname, int wid)
428 {
429 	const char *type;
430 	int std_in = strcmp(inname, "-") == 0;
431 
432 	if (wid > 0 && !bflag) {
433 		(void)printf("%s", std_in ? "/dev/stdin" : inname);
434 		if (nulsep)
435 			(void)putc('\0', stdout);
436 		(void)printf("%s", separator);
437 		(void)printf("%*s ",
438 		    (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
439 	}
440 
441 	type = magic_file(ms, std_in ? NULL : inname);
442 	if (type == NULL) {
443 		(void)printf("ERROR: %s\n", magic_error(ms));
444 		return 1;
445 	} else {
446 		(void)printf("%s\n", type);
447 		return 0;
448 	}
449 }
450 
451 protected size_t
452 file_mbswidth(const char *s)
453 {
454 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
455 	size_t bytesconsumed, old_n, n, width = 0;
456 	mbstate_t state;
457 	wchar_t nextchar;
458 	(void)memset(&state, 0, sizeof(mbstate_t));
459 	old_n = n = strlen(s);
460 
461 	while (n > 0) {
462 		bytesconsumed = mbrtowc(&nextchar, s, n, &state);
463 		if (bytesconsumed == (size_t)(-1) ||
464 		    bytesconsumed == (size_t)(-2)) {
465 			/* Something went wrong, return something reasonable */
466 			return old_n;
467 		}
468 		if (s[0] == '\n') {
469 			/*
470 			 * do what strlen() would do, so that caller
471 			 * is always right
472 			 */
473 			width++;
474 		} else
475 			width += wcwidth(nextchar);
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