xref: /netbsd-src/external/bsd/file/dist/src/file.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: file.c,v 1.1.1.1 2009/05/08 16:35:06 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.131 2009/02/13 18:48:05 christos Exp $")
39 #else
40 __RCSID("$NetBSD: file.c,v 1.1.1.1 2009/05/08 16:35:06 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 #else
73 #include "mygetopt.h"
74 #endif
75 #ifndef HAVE_GETOPT_LONG
76 int getopt_long(int argc, char * const *argv, const char *optstring, const struct option *longopts, int *longindex);
77 #endif
78 
79 #include <netinet/in.h>		/* for byte swapping */
80 
81 #include "patchlevel.h"
82 
83 #ifdef S_IFLNK
84 #define SYMLINKFLAG "Lh"
85 #else
86 #define SYMLINKFLAG ""
87 #endif
88 
89 # define USAGE  "Usage: %s [-bcik" SYMLINKFLAG "nNrsvz0] [-e test] [-f namefile] [-F separator] [-m magicfiles] file...\n       %s -C -m magicfiles\n"
90 
91 #ifndef MAXPATHLEN
92 #define	MAXPATHLEN	1024
93 #endif
94 
95 private int 		/* Global command-line options 		*/
96 	bflag = 0,	/* brief output format	 		*/
97 	nopad = 0,	/* Don't pad output			*/
98 	nobuffer = 0,   /* Do not buffer stdout 		*/
99 	nulsep = 0;	/* Append '\0' to the separator		*/
100 
101 private const char *default_magicfile = MAGIC;
102 private const char *separator = ":";	/* Default field separator	*/
103 private	const char hmagic[] = "/.magic";
104 private const struct option long_options[] = {
105 #define OPT(shortname, longname, opt, doc)      \
106     {longname, opt, NULL, shortname},
107 #define OPT_LONGONLY(longname, opt, doc)        \
108     {longname, opt, NULL, 0},
109 #include "file_opts.h"
110 #undef OPT
111 #undef OPT_LONGONLY
112     {0, 0, NULL, 0}
113 };
114 #define OPTSTRING	"bcCde:f:F:hikLm:nNprsvz0"
115 
116 private const struct {
117 	const char *name;
118 	int value;
119 } nv[] = {
120 	{ "apptype",	MAGIC_NO_CHECK_APPTYPE },
121 	{ "ascii",	MAGIC_NO_CHECK_ASCII },
122 	{ "cdf",	MAGIC_NO_CHECK_CDF },
123 	{ "compress",	MAGIC_NO_CHECK_COMPRESS },
124 	{ "elf",	MAGIC_NO_CHECK_ELF },
125 	{ "encoding",	MAGIC_NO_CHECK_ENCODING },
126 	{ "soft",	MAGIC_NO_CHECK_SOFT },
127 	{ "tar",	MAGIC_NO_CHECK_TAR },
128 	{ "tokens",	MAGIC_NO_CHECK_TOKENS },
129 };
130 
131 private char *progname;		/* used throughout 		*/
132 
133 private void usage(void);
134 private void help(void);
135 int main(int, char *[]);
136 
137 private int unwrap(struct magic_set *, const char *);
138 private int process(struct magic_set *ms, const char *, int);
139 private struct magic_set *load(const char *, int);
140 
141 
142 /*
143  * main - parse arguments and handle options
144  */
145 int
146 main(int argc, char *argv[])
147 {
148 	int c;
149 	size_t i;
150 	int action = 0, didsomefiles = 0, errflg = 0;
151 	int flags = 0, e = 0;
152 	char *home, *usermagic;
153 	struct magic_set *magic = NULL;
154 	char magicpath[2 * MAXPATHLEN + 2];
155 	int longindex;
156 	const char *magicfile;		/* where the magic is	*/
157 
158 	/* makes islower etc work for other langs */
159 	(void)setlocale(LC_CTYPE, "");
160 
161 #ifdef __EMX__
162 	/* sh-like wildcard expansion! Shouldn't hurt at least ... */
163 	_wildcard(&argc, &argv);
164 #endif
165 
166 	if ((progname = strrchr(argv[0], '/')) != NULL)
167 		progname++;
168 	else
169 		progname = argv[0];
170 
171 	magicfile = default_magicfile;
172 	if ((usermagic = getenv("MAGIC")) != NULL)
173 		magicfile = usermagic;
174 	else
175 		if ((home = getenv("HOME")) != NULL) {
176 			(void)snprintf(magicpath, sizeof(magicpath), "%s%s",
177 			     home, hmagic);
178 			if (access(magicpath, R_OK) == 0) {
179 				(void)snprintf(magicpath, sizeof(magicpath),
180 				    "%s%s:%s", home, hmagic, magicfile);
181 				magicfile = magicpath;
182 			}
183 		}
184 
185 #ifdef S_IFLNK
186 	flags |= getenv("POSIXLY_CORRECT") ? MAGIC_SYMLINK : 0;
187 #endif
188 	while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
189 	    &longindex)) != -1)
190 		switch (c) {
191 		case 0 :
192 			switch (longindex) {
193 			case 0:
194 				help();
195 				break;
196 			case 10:
197 				flags |= MAGIC_APPLE;
198 				break;
199 			case 11:
200 				flags |= MAGIC_MIME_TYPE;
201 				break;
202 			case 12:
203 				flags |= MAGIC_MIME_ENCODING;
204 				break;
205 			}
206 			break;
207 		case '0':
208 			nulsep = 1;
209 			break;
210 		case 'b':
211 			bflag++;
212 			break;
213 		case 'c':
214 			action = FILE_CHECK;
215 			break;
216 		case 'C':
217 			action = FILE_COMPILE;
218 			break;
219 		case 'd':
220 			flags |= MAGIC_DEBUG|MAGIC_CHECK;
221 			break;
222 		case 'e':
223 			for (i = 0; i < sizeof(nv) / sizeof(nv[0]); i++)
224 				if (strcmp(nv[i].name, optarg) == 0)
225 					break;
226 
227 			if (i == sizeof(nv) / sizeof(nv[0]))
228 				errflg++;
229 			else
230 				flags |= nv[i].value;
231 			break;
232 
233 		case 'f':
234 			if(action)
235 				usage();
236 			if (magic == NULL)
237 				if ((magic = load(magicfile, flags)) == NULL)
238 					return 1;
239 			e |= unwrap(magic, optarg);
240 			++didsomefiles;
241 			break;
242 		case 'F':
243 			separator = optarg;
244 			break;
245 		case 'i':
246 			flags |= MAGIC_MIME;
247 			break;
248 		case 'k':
249 			flags |= MAGIC_CONTINUE;
250 			break;
251 		case 'm':
252 			magicfile = optarg;
253 			break;
254 		case 'n':
255 			++nobuffer;
256 			break;
257 		case 'N':
258 			++nopad;
259 			break;
260 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
261 		case 'p':
262 			flags |= MAGIC_PRESERVE_ATIME;
263 			break;
264 #endif
265 		case 'r':
266 			flags |= MAGIC_RAW;
267 			break;
268 		case 's':
269 			flags |= MAGIC_DEVICES;
270 			break;
271 		case 'v':
272 			(void)fprintf(stderr, "%s-%d.%.2d\n", progname,
273 				       FILE_VERSION_MAJOR, patchlevel);
274 			(void)fprintf(stderr, "magic file from %s\n",
275 				       magicfile);
276 			return 1;
277 		case 'z':
278 			flags |= MAGIC_COMPRESS;
279 			break;
280 #ifdef S_IFLNK
281 		case 'L':
282 			flags |= MAGIC_SYMLINK;
283 			break;
284 		case 'h':
285 			flags &= ~MAGIC_SYMLINK;
286 			break;
287 #endif
288 		case '?':
289 		default:
290 			errflg++;
291 			break;
292 		}
293 
294 	if (errflg) {
295 		usage();
296 	}
297 	if (e)
298 		return e;
299 
300 	switch(action) {
301 	case FILE_CHECK:
302 	case FILE_COMPILE:
303 		/*
304 		 * Don't try to check/compile ~/.magic unless we explicitly
305 		 * ask for it.
306 		 */
307 		if (magicfile == magicpath)
308 			magicfile = default_magicfile;
309 		magic = magic_open(flags|MAGIC_CHECK);
310 		if (magic == NULL) {
311 			(void)fprintf(stderr, "%s: %s\n", progname,
312 			    strerror(errno));
313 			return 1;
314 		}
315 		c = action == FILE_CHECK ? magic_check(magic, magicfile) :
316 		    magic_compile(magic, magicfile);
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 	char buf[MAXPATHLEN];
383 	FILE *f;
384 	int wid = 0, cwid;
385 	int e = 0;
386 
387 	if (strcmp("-", fn) == 0) {
388 		f = stdin;
389 		wid = 1;
390 	} else {
391 		if ((f = fopen(fn, "r")) == NULL) {
392 			(void)fprintf(stderr, "%s: Cannot open `%s' (%s).\n",
393 			    progname, fn, strerror(errno));
394 			return 1;
395 		}
396 
397 		while (fgets(buf, sizeof(buf), f) != NULL) {
398 			buf[strcspn(buf, "\n")] = '\0';
399 			cwid = file_mbswidth(buf);
400 			if (cwid > wid)
401 				wid = cwid;
402 		}
403 
404 		rewind(f);
405 	}
406 
407 	while (fgets(buf, sizeof(buf), f) != NULL) {
408 		buf[strcspn(buf, "\n")] = '\0';
409 		e |= process(ms, buf, wid);
410 		if(nobuffer)
411 			(void)fflush(stdout);
412 	}
413 
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 		else
432 			(void)printf("%s", separator);
433 		(void)printf("%*s ",
434 		    (int) (nopad ? 0 : (wid - file_mbswidth(inname))), "");
435 	}
436 
437 	type = magic_file(ms, std_in ? NULL : inname);
438 	if (type == NULL) {
439 		(void)printf("ERROR: %s\n", magic_error(ms));
440 		return 1;
441 	} else {
442 		(void)printf("%s\n", type);
443 		return 0;
444 	}
445 }
446 
447 size_t
448 file_mbswidth(const char *s)
449 {
450 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH)
451 	size_t bytesconsumed, old_n, n, width = 0;
452 	mbstate_t state;
453 	wchar_t nextchar;
454 	(void)memset(&state, 0, sizeof(mbstate_t));
455 	old_n = n = strlen(s);
456 
457 	while (n > 0) {
458 		bytesconsumed = mbrtowc(&nextchar, s, n, &state);
459 		if (bytesconsumed == (size_t)(-1) ||
460 		    bytesconsumed == (size_t)(-2)) {
461 			/* Something went wrong, return something reasonable */
462 			return old_n;
463 		}
464 		if (s[0] == '\n') {
465 			/*
466 			 * do what strlen() would do, so that caller
467 			 * is always right
468 			 */
469 			width++;
470 		} else
471 			width += wcwidth(nextchar);
472 
473 		s += bytesconsumed, n -= bytesconsumed;
474 	}
475 	return width;
476 #else
477 	return strlen(s);
478 #endif
479 }
480 
481 private void
482 usage(void)
483 {
484 	(void)fprintf(stderr, USAGE, progname, progname);
485 	(void)fputs("Try `file --help' for more information.\n", stderr);
486 	exit(1);
487 }
488 
489 private void
490 help(void)
491 {
492 	(void)fputs(
493 "Usage: file [OPTION...] [FILE...]\n"
494 "Determine type of FILEs.\n"
495 "\n", stderr);
496 #define OPT(shortname, longname, opt, doc)      \
497 	fprintf(stderr, "  -%c, --" longname doc, shortname);
498 #define OPT_LONGONLY(longname, opt, doc)        \
499 	fprintf(stderr, "      --" longname doc);
500 #include "file_opts.h"
501 #undef OPT
502 #undef OPT_LONGONLY
503 	exit(0);
504 }
505