xref: /dflybsd-src/contrib/file/src/file.c (revision e90a7c45c3303ed54c0fde732b2ba32dc80ffd9b)
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.140 2010/11/30 14:58:53 rrt 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 #include "patchlevel.h"
74 
75 #ifdef S_IFLNK
76 #define FILE_FLAGS "-bchikLlNnprsvz0"
77 #else
78 #define FILE_FLAGS "-bciklNnprsvz0"
79 #endif
80 
81 # define USAGE  \
82     "Usage: %s [" FILE_FLAGS \
83 	"] [--apple] [--mime-encoding] [--mime-type]\n" \
84     "            [-e testname] [-F separator] [-f namefile] [-m magicfiles] " \
85     "file ...\n" \
86     "       %s -C [-m magicfiles]\n" \
87     "       %s [--help]\n"
88 
89 #ifndef MAXPATHLEN
90 #define	MAXPATHLEN	1024
91 #endif
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 },
126 };
127 
128 private char *progname;		/* used throughout 		*/
129 
130 private void usage(void);
131 private void help(void);
132 int main(int, char *[]);
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(stderr, "%s-%d.%.2d\n", progname,
259 				       FILE_VERSION_MAJOR, patchlevel);
260 			(void)fprintf(stderr, "magic file from %s\n",
261 				       magicfile);
262 			return 1;
263 		case 'z':
264 			flags |= MAGIC_COMPRESS;
265 			break;
266 #ifdef S_IFLNK
267 		case 'L':
268 			flags |= MAGIC_SYMLINK;
269 			break;
270 		case 'h':
271 			flags &= ~MAGIC_SYMLINK;
272 			break;
273 #endif
274 		case '?':
275 		default:
276 			errflg++;
277 			break;
278 		}
279 
280 	if (errflg) {
281 		usage();
282 	}
283 	if (e)
284 		return e;
285 
286 	switch(action) {
287 	case FILE_CHECK:
288 	case FILE_COMPILE:
289 	case FILE_LIST:
290 		/*
291 		 * Don't try to check/compile ~/.magic unless we explicitly
292 		 * ask for it.
293 		 */
294 		magic = magic_open(flags|MAGIC_CHECK);
295 		if (magic == NULL) {
296 			(void)fprintf(stderr, "%s: %s\n", progname,
297 			    strerror(errno));
298 			return 1;
299 		}
300 		switch(action) {
301 		case FILE_CHECK:
302 			c = magic_check(magic, magicfile);
303 			break;
304 		case FILE_COMPILE:
305 			c = magic_compile(magic, magicfile);
306 			break;
307 		case FILE_LIST:
308 			c = magic_list(magic, magicfile);
309 			break;
310 		default:
311 			abort();
312 		}
313 		if (c == -1) {
314 			(void)fprintf(stderr, "%s: %s\n", progname,
315 			    magic_error(magic));
316 			return 1;
317 		}
318 		return 0;
319 	default:
320 		if (magic == NULL)
321 			if ((magic = load(magicfile, flags)) == NULL)
322 				return 1;
323 		break;
324 	}
325 
326 	if (optind == argc) {
327 		if (!didsomefiles)
328 			usage();
329 	}
330 	else {
331 		size_t j, wid, nw;
332 		for (wid = 0, j = (size_t)optind; j < (size_t)argc; j++) {
333 			nw = file_mbswidth(argv[j]);
334 			if (nw > wid)
335 				wid = nw;
336 		}
337 		/*
338 		 * If bflag is only set twice, set it depending on
339 		 * number of files [this is undocumented, and subject to change]
340 		 */
341 		if (bflag == 2) {
342 			bflag = optind >= argc - 1;
343 		}
344 		for (; optind < argc; optind++)
345 			e |= process(magic, argv[optind], wid);
346 	}
347 
348 	if (magic)
349 		magic_close(magic);
350 	return e;
351 }
352 
353 
354 private struct magic_set *
355 /*ARGSUSED*/
356 load(const char *magicfile, int flags)
357 {
358 	struct magic_set *magic = magic_open(flags);
359 	if (magic == NULL) {
360 		(void)fprintf(stderr, "%s: %s\n", progname, strerror(errno));
361 		return NULL;
362 	}
363 	if (magic_load(magic, magicfile) == -1) {
364 		(void)fprintf(stderr, "%s: %s\n",
365 		    progname, magic_error(magic));
366 		magic_close(magic);
367 		return NULL;
368 	}
369 	return magic;
370 }
371 
372 /*
373  * unwrap -- read a file of filenames, do each one.
374  */
375 private int
376 unwrap(struct magic_set *ms, const char *fn)
377 {
378 	char buf[MAXPATHLEN];
379 	FILE *f;
380 	int wid = 0, cwid;
381 	int e = 0;
382 
383 	if (strcmp("-", fn) == 0) {
384 		f = stdin;
385 		wid = 1;
386 	} else {
387 		if ((f = fopen(fn, "r")) == NULL) {
388 			(void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
389 			    progname, fn, strerror(errno));
390 			return 1;
391 		}
392 
393 		while (fgets(buf, sizeof(buf), f) != NULL) {
394 			buf[strcspn(buf, "\n")] = '\0';
395 			cwid = file_mbswidth(buf);
396 			if (cwid > wid)
397 				wid = cwid;
398 		}
399 
400 		rewind(f);
401 	}
402 
403 	while (fgets(buf, sizeof(buf), f) != NULL) {
404 		buf[strcspn(buf, "\n")] = '\0';
405 		e |= process(ms, buf, wid);
406 		if(nobuffer)
407 			(void)fflush(stdout);
408 	}
409 
410 	(void)fclose(f);
411 	return e;
412 }
413 
414 /*
415  * Called for each input file on the command line (or in a list of files)
416  */
417 private int
418 process(struct magic_set *ms, const char *inname, int wid)
419 {
420 	const char *type;
421 	int std_in = strcmp(inname, "-") == 0;
422 
423 	if (wid > 0 && !bflag) {
424 		(void)printf("%s", std_in ? "/dev/stdin" : inname);
425 		if (nulsep)
426 			(void)putc('\0', stdout);
427 		(void)printf("%s", separator);
428 		(void)printf("%*s ",
429 		    (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
430 	}
431 
432 	type = magic_file(ms, std_in ? NULL : inname);
433 	if (type == NULL) {
434 		(void)printf("ERROR: %s\n", magic_error(ms));
435 		return 1;
436 	} else {
437 		(void)printf("%s\n", type);
438 		return 0;
439 	}
440 }
441 
442 size_t
443 file_mbswidth(const char *s)
444 {
445 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
446 	size_t bytesconsumed, old_n, n, width = 0;
447 	mbstate_t state;
448 	wchar_t nextchar;
449 	(void)memset(&state, 0, sizeof(mbstate_t));
450 	old_n = n = strlen(s);
451 
452 	while (n > 0) {
453 		bytesconsumed = mbrtowc(&nextchar, s, n, &state);
454 		if (bytesconsumed == (size_t)(-1) ||
455 		    bytesconsumed == (size_t)(-2)) {
456 			/* Something went wrong, return something reasonable */
457 			return old_n;
458 		}
459 		if (s[0] == '\n') {
460 			/*
461 			 * do what strlen() would do, so that caller
462 			 * is always right
463 			 */
464 			width++;
465 		} else
466 			width += wcwidth(nextchar);
467 
468 		s += bytesconsumed, n -= bytesconsumed;
469 	}
470 	return width;
471 #else
472 	return strlen(s);
473 #endif
474 }
475 
476 private void
477 usage(void)
478 {
479 	(void)fprintf(stderr, USAGE, progname, progname, progname);
480 	exit(1);
481 }
482 
483 private void
484 help(void)
485 {
486 	(void)fputs(
487 "Usage: file [OPTION...] [FILE...]\n"
488 "Determine type of FILEs.\n"
489 "\n", stderr);
490 #define OPT(shortname, longname, opt, doc)      \
491 	fprintf(stderr, "  -%c, --" longname doc, shortname);
492 #define OPT_LONGONLY(longname, opt, doc)        \
493 	fprintf(stderr, "      --" longname doc);
494 #include "file_opts.h"
495 #undef OPT
496 #undef OPT_LONGONLY
497 	exit(0);
498 }
499