xref: /netbsd-src/external/bsd/file/dist/src/file.c (revision ddb176824c39fb0db5ceef3e9e40dcaa273aec38)
1 /*	$NetBSD: file.c,v 1.18 2023/08/18 19:00:11 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.215 2023/05/21 17:08:34 christos Exp $")
39 #else
40 __RCSID("$NetBSD: file.c,v 1.18 2023/08/18 19:00:11 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_WCHAR_H
64 #include <wchar.h>
65 #endif
66 #ifdef HAVE_WCTYPE_H
67 #include <wctype.h>
68 #endif
69 #if defined(HAVE_WCHAR_H) && defined(HAVE_MBRTOWC) && defined(HAVE_WCWIDTH) && \
70    defined(HAVE_WCTYPE_H)
71 #define FILE_WIDE_SUPPORT
72 #else
73 #include <ctype.h>
74 #endif
75 
76 #if defined(HAVE_GETOPT_H) && defined(HAVE_STRUCT_OPTION)
77 # include <getopt.h>
78 # ifndef HAVE_GETOPT_LONG
79 int getopt_long(int, char * const *, const char *,
80     const struct option *, int *);
81 # endif
82 # else
83 #  include "mygetopt.h"
84 #endif
85 
86 #ifdef S_IFLNK
87 # define IFLNK_h "h"
88 # define IFLNK_L "L"
89 #else
90 # define IFLNK_h ""
91 # define IFLNK_L ""
92 #endif
93 
94 #define FILE_FLAGS	"bcCdE" IFLNK_h "ik" IFLNK_L "lNnprsSvzZ0"
95 #define OPTSTRING	"bcCde:Ef:F:hiklLm:nNpP:rsSvzZ0"
96 
97 # define USAGE  \
98     "Usage: %s [-" FILE_FLAGS "] [--apple] [--extension] [--mime-encoding]\n" \
99     "            [--mime-type] [-e <testname>] [-F <separator>] " \
100     " [-f <namefile>]\n" \
101     "            [-m <magicfiles>] [-P <parameter=value>] [--exclude-quiet]\n" \
102     "            <file> ...\n" \
103     "       %s -C [-m <magicfiles>]\n" \
104     "       %s [--help]\n"
105 
106 file_private int 		/* Global command-line options 		*/
107 	bflag = 0,	/* brief output format	 		*/
108 	nopad = 0,	/* Don't pad output			*/
109 	nobuffer = 0,   /* Do not buffer stdout 		*/
110 	nulsep = 0;	/* Append '\0' to the separator		*/
111 
112 file_private const char *separator = ":";	/* Default field separator	*/
113 file_private const struct option long_options[] = {
114 #define OPT_HELP		1
115 #define OPT_APPLE		2
116 #define OPT_EXTENSIONS		3
117 #define OPT_MIME_TYPE		4
118 #define OPT_MIME_ENCODING	5
119 #define OPT_EXCLUDE_QUIET	6
120 #define OPT(shortname, longname, opt, def, doc)		\
121     {longname, opt, NULL, shortname},
122 #define OPT_LONGONLY(longname, opt, def, doc, id)	\
123     {longname, opt, NULL, id},
124 #include "file_opts.h"
125 #undef OPT
126 #undef OPT_LONGONLY
127     {0, 0, NULL, 0}
128     };
129 
130 file_private const struct {
131 	const char *name;
132 	int value;
133 } nv[] = {
134 	{ "apptype",	MAGIC_NO_CHECK_APPTYPE },
135 	{ "ascii",	MAGIC_NO_CHECK_ASCII },
136 	{ "cdf",	MAGIC_NO_CHECK_CDF },
137 	{ "compress",	MAGIC_NO_CHECK_COMPRESS },
138 	{ "csv",	MAGIC_NO_CHECK_CSV },
139 	{ "elf",	MAGIC_NO_CHECK_ELF },
140 	{ "encoding",	MAGIC_NO_CHECK_ENCODING },
141 	{ "soft",	MAGIC_NO_CHECK_SOFT },
142 	{ "tar",	MAGIC_NO_CHECK_TAR },
143 	{ "json",	MAGIC_NO_CHECK_JSON },
144 	{ "simh",	MAGIC_NO_CHECK_SIMH },
145 	{ "text",	MAGIC_NO_CHECK_TEXT },	/* synonym for ascii */
146 	{ "tokens",	MAGIC_NO_CHECK_TOKENS }, /* OBSOLETE: ignored for backwards compatibility */
147 };
148 
149 file_private struct {
150 	const char *name;
151 	size_t value;
152 	size_t def;
153 	const char *desc;
154 	int tag;
155 	int set;
156 } pm[] = {
157 	{ "bytes", 0, FILE_BYTES_MAX, "max bytes to look inside file",
158 	    MAGIC_PARAM_BYTES_MAX, 0 },
159 	{ "elf_notes", 0, FILE_ELF_NOTES_MAX, "max ELF notes processed",
160 	    MAGIC_PARAM_ELF_NOTES_MAX, 0 },
161 	{ "elf_phnum", 0, FILE_ELF_PHNUM_MAX, "max ELF prog sections processed",
162 	    MAGIC_PARAM_ELF_PHNUM_MAX, 0 },
163 	{ "elf_shnum", 0, FILE_ELF_SHNUM_MAX, "max ELF sections processed",
164 	    MAGIC_PARAM_ELF_SHNUM_MAX, 0 },
165 	{ "elf_shsize", 0, FILE_ELF_SHSIZE_MAX, "max ELF section size",
166 	    MAGIC_PARAM_ELF_SHSIZE_MAX, 0 },
167 	{ "encoding", 0, FILE_ENCODING_MAX, "max bytes to scan for encoding",
168 	    MAGIC_PARAM_ENCODING_MAX, 0 },
169 	{ "indir", 0, FILE_INDIR_MAX, "recursion limit for indirection",
170 	    MAGIC_PARAM_INDIR_MAX, 0 },
171 	{ "name", 0, FILE_NAME_MAX, "use limit for name/use magic",
172 	    MAGIC_PARAM_NAME_MAX, 0 },
173 	{ "regex", 0, FILE_REGEX_MAX, "length limit for REGEX searches",
174 	    MAGIC_PARAM_REGEX_MAX, 0 },
175 };
176 
177 file_private int posixly;
178 
179 #ifdef __dead
180 __dead
181 #endif
182 file_private void usage(void);
183 file_private void docprint(const char *, int);
184 #ifdef __dead
185 __dead
186 #endif
187 file_private void help(void);
188 
189 file_private int unwrap(struct magic_set *, const char *);
190 file_private int process(struct magic_set *ms, const char *, int);
191 file_private struct magic_set *load(const char *, int);
192 file_private void setparam(const char *);
193 file_private void applyparam(magic_t);
194 
195 
196 /*
197  * main - parse arguments and handle options
198  */
199 int
main(int argc,char * argv[])200 main(int argc, char *argv[])
201 {
202 	int c;
203 	size_t i, j, wid, nw;
204 	int action = 0, didsomefiles = 0, errflg = 0;
205 	int flags = 0, e = 0;
206 #ifdef HAVE_LIBSECCOMP
207 	int sandbox = 1;
208 #endif
209 	struct magic_set *magic = NULL;
210 	int longindex;
211 	const char *magicfile = NULL;		/* where the magic is	*/
212 	char *progname;
213 
214 	/* makes islower etc work for other langs */
215 	(void)setlocale(LC_CTYPE, "");
216 
217 #ifdef __EMX__
218 	/* sh-like wildcard expansion! Shouldn't hurt at least ... */
219 	_wildcard(&argc, &argv);
220 #endif
221 
222 	if ((progname = strrchr(argv[0], '/')) != NULL)
223 		progname++;
224 	else
225 		progname = argv[0];
226 
227 	file_setprogname(progname);
228 
229 
230 #ifdef S_IFLNK
231 	posixly = getenv("POSIXLY_CORRECT") != NULL;
232 	flags |=  posixly ? MAGIC_SYMLINK : 0;
233 #endif
234 	while ((c = getopt_long(argc, argv, OPTSTRING, long_options,
235 	    &longindex)) != -1)
236 		switch (c) {
237 		case OPT_HELP:
238 			help();
239 			break;
240 		case OPT_APPLE:
241 			flags |= MAGIC_APPLE;
242 			break;
243 		case OPT_EXTENSIONS:
244 			flags |= MAGIC_EXTENSION;
245 			break;
246 		case OPT_MIME_TYPE:
247 			flags |= MAGIC_MIME_TYPE;
248 			break;
249 		case OPT_MIME_ENCODING:
250 			flags |= MAGIC_MIME_ENCODING;
251 			break;
252 		case '0':
253 			nulsep++;
254 			break;
255 		case 'b':
256 			bflag++;
257 			break;
258 		case 'c':
259 			action = FILE_CHECK;
260 			break;
261 		case 'C':
262 			action = FILE_COMPILE;
263 			break;
264 		case 'd':
265 			flags |= MAGIC_DEBUG|MAGIC_CHECK;
266 			break;
267 		case 'E':
268 			flags |= MAGIC_ERROR;
269 			break;
270 		case 'e':
271 		case OPT_EXCLUDE_QUIET:
272 			for (i = 0; i < __arraycount(nv); i++)
273 				if (strcmp(nv[i].name, optarg) == 0)
274 					break;
275 
276 			if (i == __arraycount(nv)) {
277 				if (c != OPT_EXCLUDE_QUIET)
278 					errflg++;
279 			} else
280 				flags |= nv[i].value;
281 			break;
282 
283 		case 'f':
284 			if(action)
285 				usage();
286 			if (magic == NULL)
287 				if ((magic = load(magicfile, flags)) == NULL)
288 					return 1;
289 			applyparam(magic);
290 			e |= unwrap(magic, optarg);
291 			++didsomefiles;
292 			break;
293 		case 'F':
294 			separator = optarg;
295 			break;
296 		case 'i':
297 			flags |= MAGIC_MIME;
298 			break;
299 		case 'k':
300 			flags |= MAGIC_CONTINUE;
301 			break;
302 		case 'l':
303 			action = FILE_LIST;
304 			break;
305 		case 'm':
306 			magicfile = optarg;
307 			break;
308 		case 'n':
309 			++nobuffer;
310 			break;
311 		case 'N':
312 			++nopad;
313 			break;
314 #if defined(HAVE_UTIME) || defined(HAVE_UTIMES)
315 		case 'p':
316 			flags |= MAGIC_PRESERVE_ATIME;
317 			break;
318 #endif
319 		case 'P':
320 			setparam(optarg);
321 			break;
322 		case 'r':
323 			flags |= MAGIC_RAW;
324 			break;
325 		case 's':
326 			flags |= MAGIC_DEVICES;
327 			break;
328 		case 'S':
329 #ifdef HAVE_LIBSECCOMP
330 			sandbox = 0;
331 #endif
332 			break;
333 		case 'v':
334 			if (magicfile == NULL)
335 				magicfile = magic_getpath(magicfile, action);
336 			(void)fprintf(stdout, "%s-%s\n", file_getprogname(),
337 			    VERSION);
338 			(void)fprintf(stdout, "magic file from %s\n",
339 			    magicfile);
340 #ifdef HAVE_LIBSECCOMP
341 			(void)fprintf(stdout, "seccomp support included\n");
342 #endif
343 			return 0;
344 		case 'z':
345 			flags |= MAGIC_COMPRESS;
346 			break;
347 
348 		case 'Z':
349 			flags |= MAGIC_COMPRESS|MAGIC_COMPRESS_TRANSP;
350 			break;
351 #ifdef S_IFLNK
352 		case 'L':
353 			flags |= MAGIC_SYMLINK;
354 			break;
355 		case 'h':
356 			flags &= ~MAGIC_SYMLINK;
357 			break;
358 #endif
359 		case '?':
360 		default:
361 			errflg++;
362 			break;
363 		}
364 
365 	if (errflg) {
366 		usage();
367 	}
368 	if (e)
369 		return e;
370 
371 #ifdef HAVE_LIBSECCOMP
372 #if 0
373 	if (sandbox && enable_sandbox_basic() == -1)
374 #else
375 	if (sandbox && enable_sandbox_full() == -1)
376 #endif
377 		file_err(EXIT_FAILURE, "SECCOMP initialisation failed");
378 	if (sandbox)
379 		flags |= MAGIC_NO_COMPRESS_FORK;
380 #endif /* HAVE_LIBSECCOMP */
381 
382 	if (MAGIC_VERSION != magic_version())
383 		file_warnx("Compiled magic version [%d] "
384 		    "does not match with shared library magic version [%d]\n",
385 		    MAGIC_VERSION, magic_version());
386 
387 	switch(action) {
388 	case FILE_CHECK:
389 	case FILE_COMPILE:
390 	case FILE_LIST:
391 		/*
392 		 * Don't try to check/compile ~/.magic unless we explicitly
393 		 * ask for it.
394 		 */
395 		magic = magic_open(flags|MAGIC_CHECK);
396 		if (magic == NULL) {
397 			file_warn("Can't create magic");
398 			return 1;
399 		}
400 
401 
402 		switch(action) {
403 		case FILE_CHECK:
404 			c = magic_check(magic, magicfile);
405 			break;
406 		case FILE_COMPILE:
407 			c = magic_compile(magic, magicfile);
408 			break;
409 		case FILE_LIST:
410 			c = magic_list(magic, magicfile);
411 			break;
412 		default:
413 			abort();
414 		}
415 		if (c == -1) {
416 			file_warnx("%s", magic_error(magic));
417 			e = 1;
418 			goto out;
419 		}
420 		goto out;
421 	default:
422 		if (magic == NULL)
423 			if ((magic = load(magicfile, flags)) == NULL)
424 				return 1;
425 		applyparam(magic);
426 	}
427 
428 	if (optind == argc) {
429 		if (!didsomefiles)
430 			usage();
431 		goto out;
432 	}
433 
434 	for (wid = 0, j = CAST(size_t, optind); j < CAST(size_t, argc);
435 	    j++) {
436 		nw = file_mbswidth(magic, argv[j]);
437 		if (nw > wid)
438 			wid = nw;
439 	}
440 
441 	/*
442 	 * If bflag is only set twice, set it depending on
443 	 * number of files [this is undocumented, and subject to change]
444 	 */
445 	if (bflag == 2) {
446 		bflag = optind >= argc - 1;
447 	}
448 	for (; optind < argc; optind++)
449 		e |= process(magic, argv[optind], wid);
450 
451 out:
452 	if (!nobuffer)
453 		e |= fflush(stdout) != 0;
454 
455 	if (magic)
456 		magic_close(magic);
457 	return e;
458 }
459 
460 file_private void
applyparam(magic_t magic)461 applyparam(magic_t magic)
462 {
463 	size_t i;
464 
465 	for (i = 0; i < __arraycount(pm); i++) {
466 		if (!pm[i].set)
467 			continue;
468 		if (magic_setparam(magic, pm[i].tag, &pm[i].value) == -1)
469 			file_err(EXIT_FAILURE, "Can't set %s", pm[i].name);
470 	}
471 }
472 
473 file_private void
setparam(const char * p)474 setparam(const char *p)
475 {
476 	size_t i;
477 	char *s;
478 
479 	if ((s = CCAST(char *, strchr(p, '='))) == NULL)
480 		goto badparm;
481 
482 	for (i = 0; i < __arraycount(pm); i++) {
483 		if (strncmp(p, pm[i].name, s - p) != 0)
484 			continue;
485 		pm[i].value = atoi(s + 1);
486 		pm[i].set = 1;
487 		return;
488 	}
489 badparm:
490 	file_errx(EXIT_FAILURE, "Unknown param %s", p);
491 }
492 
493 file_private struct magic_set *
494 /*ARGSUSED*/
load(const char * magicfile,int flags)495 load(const char *magicfile, int flags)
496 {
497 	struct magic_set *magic = magic_open(flags);
498 	const char *e;
499 
500 	if (magic == NULL) {
501 		file_warn("Can't create magic");
502 		return NULL;
503 	}
504 	if (magic_load(magic, magicfile) == -1) {
505 		file_warn("%s", magic_error(magic));
506 		magic_close(magic);
507 		return NULL;
508 	}
509 	if ((e = magic_error(magic)) != NULL)
510 		file_warn("%s", e);
511 	return magic;
512 }
513 
514 /*
515  * unwrap -- read a file of filenames, do each one.
516  */
517 file_private int
unwrap(struct magic_set * ms,const char * fn)518 unwrap(struct magic_set *ms, const char *fn)
519 {
520 	FILE *f;
521 	ssize_t len;
522 	char *line = NULL;
523 	size_t llen = 0;
524 	int wid = 0, cwid;
525 	int e = 0;
526 	size_t fi = 0, fimax = 0;
527 	char **flist = NULL;
528 
529 	if (strcmp("-", fn) == 0)
530 		f = stdin;
531 	else {
532 		if ((f = fopen(fn, "r")) == NULL) {
533 			file_warn("Cannot open `%s'", fn);
534 			return 1;
535 		}
536 	}
537 
538 	while ((len = getline(&line, &llen, f)) > 0) {
539 		if (line[len - 1] == '\n')
540 			line[len - 1] = '\0';
541 		cwid = file_mbswidth(ms, line);
542 		if (nobuffer) {
543 			e |= process(ms, line, cwid);
544 			free(line);
545 			line = NULL;
546 			llen = 0;
547 			continue;
548 		}
549 		if (cwid > wid)
550 			wid = cwid;
551 		if (fi >= fimax) {
552 			fimax += 100;
553 			char **nf = CAST(char **,
554 			    realloc(flist, fimax * sizeof(*flist)));
555 			if (nf == NULL) {
556 				file_err(EXIT_FAILURE,
557 				    "Cannot allocate memory for file list");
558 			}
559 			flist = nf;
560 		}
561 		flist[fi++] = line;
562 		line = NULL;
563 		llen = 0;
564 	}
565 
566 	if (!nobuffer) {
567 		fimax = fi;
568 		for (fi = 0; fi < fimax; fi++) {
569 			e |= process(ms, flist[fi], wid);
570 			free(flist[fi]);
571 		}
572 	}
573 	free(flist);
574 
575 	if (f != stdin)
576 		(void)fclose(f);
577 	return e;
578 }
579 
580 file_private void
file_octal(unsigned char c)581 file_octal(unsigned char c)
582 {
583 	(void)putc('\\', stdout);
584 	(void)putc(((c >> 6) & 7) + '0', stdout);
585 	(void)putc(((c >> 3) & 7) + '0', stdout);
586 	(void)putc(((c >> 0) & 7) + '0', stdout);
587 }
588 
589 file_private void
fname_print(const char * inname)590 fname_print(const char *inname)
591 {
592 	size_t n = strlen(inname);
593 #ifdef FILE_WIDE_SUPPORT
594 	mbstate_t state;
595 	wchar_t nextchar;
596 	size_t bytesconsumed;
597 
598 
599 	(void)memset(&state, 0, sizeof(state));
600 	while (n > 0) {
601 		bytesconsumed = mbrtowc(&nextchar, inname, n, &state);
602 		if (bytesconsumed == CAST(size_t, -1) ||
603 		    bytesconsumed == CAST(size_t, -2))  {
604 			nextchar = *inname++;
605 			n--;
606 			(void)memset(&state, 0, sizeof(state));
607 			file_octal(CAST(unsigned char, nextchar));
608 			continue;
609 		}
610 		inname += bytesconsumed;
611 		n -= bytesconsumed;
612 		if (iswprint(nextchar)) {
613 			printf("%lc", (wint_t)nextchar);
614 			continue;
615 		}
616 		/* XXX: What if it is > 255? */
617 		file_octal(CAST(unsigned char, nextchar));
618 	}
619 #else
620 	size_t i;
621 	for (i = 0; i < n; i++) {
622 		unsigned char c = CAST(unsigned char, inname[i]);
623 		if (isprint(c)) {
624 			(void)putc(c, stdout);
625 			continue;
626 		}
627 		file_octal(c);
628 	}
629 #endif
630 }
631 
632 /*
633  * Called for each input file on the command line (or in a list of files)
634  */
635 file_private int
process(struct magic_set * ms,const char * inname,int wid)636 process(struct magic_set *ms, const char *inname, int wid)
637 {
638 	const char *type, c = nulsep > 1 ? '\0' : '\n';
639 	int std_in = strcmp(inname, "-") == 0;
640 	int haderror = 0;
641 
642 	if (wid > 0 && !bflag) {
643 		const char *pname = std_in ? "/dev/stdin" : inname;
644 		if ((ms->flags & MAGIC_RAW) == 0)
645 			fname_print(pname);
646 		else
647 			(void)printf("%s", pname);
648 		if (nulsep)
649 			(void)putc('\0', stdout);
650 		if (nulsep < 2) {
651 			(void)printf("%s", separator);
652 			(void)printf("%*s ", CAST(int, nopad ? 0
653 			    : (wid - file_mbswidth(ms, inname))), "");
654 		}
655 	}
656 
657 	type = magic_file(ms, std_in ? NULL : inname);
658 
659 	if (type == NULL) {
660 		haderror |= printf("ERROR: %s%c", magic_error(ms), c);
661 	} else {
662 		haderror |= printf("%s%c", type, c) < 0;
663 	}
664 	if (nobuffer)
665 		haderror |= fflush(stdout) != 0;
666 	return haderror || type == NULL;
667 }
668 
669 file_protected size_t
file_mbswidth(struct magic_set * ms,const char * s)670 file_mbswidth(struct magic_set *ms, const char *s)
671 {
672 	size_t width = 0;
673 #ifdef FILE_WIDE_SUPPORT
674 	size_t bytesconsumed, n;
675 	mbstate_t state;
676 	wchar_t nextchar;
677 
678 	(void)memset(&state, 0, sizeof(state));
679 	n = strlen(s);
680 
681 	while (n > 0) {
682 		bytesconsumed = mbrtowc(&nextchar, s, n, &state);
683 		if (bytesconsumed == CAST(size_t, -1) ||
684 		    bytesconsumed == CAST(size_t, -2)) {
685 			nextchar = *s;
686 			bytesconsumed = 1;
687 			(void)memset(&state, 0, sizeof(state));
688 			width += 4;
689 		} else {
690 			int w = wcwidth(nextchar);
691 			width += ((ms->flags & MAGIC_RAW) != 0
692 			    || iswprint(nextchar)) ? (w > 0 ? w : 1) : 4;
693 		}
694 
695 		s += bytesconsumed, n -= bytesconsumed;
696 	}
697 #else
698 	for (; *s; s++) {
699 		width += (ms->flags & MAGIC_RAW) != 0
700 		    || isprint(CAST(unsigned char, *s)) ? 1 : 4;
701 	}
702 #endif
703 	return width;
704 }
705 
706 file_private void
usage(void)707 usage(void)
708 {
709 	const char *pn = file_getprogname();
710 	(void)fprintf(stderr, USAGE, pn, pn, pn);
711 	exit(EXIT_FAILURE);
712 }
713 
714 file_private void
defprint(int def)715 defprint(int def)
716 {
717 	if (!def)
718 		return;
719 	if (((def & 1) && posixly) || ((def & 2) && !posixly))
720 		(void)fprintf(stdout, " (default)");
721 	(void)putc('\n', stdout);
722 }
723 
724 file_private void
docprint(const char * opts,int def)725 docprint(const char *opts, int def)
726 {
727 	size_t i;
728 	int comma, pad;
729 	char *sp, *p;
730 
731 	p = CCAST(char *, strchr(opts, '%'));
732 	if (p == NULL) {
733 		(void)fprintf(stdout, "%s", opts);
734 		defprint(def);
735 		return;
736 	}
737 
738 	for (sp = p - 1; sp > opts && *sp == ' '; sp--)
739 		continue;
740 
741 	(void)printf("%.*s", CAST(int, p - opts), opts);
742 	pad = (int)CAST(int, p - sp - 1);
743 
744 	switch (*++p) {
745 	case 'e':
746 		comma = 0;
747 		for (i = 0; i < __arraycount(nv); i++) {
748 			(void)printf("%s%s", comma++ ? ", " : "", nv[i].name);
749 			if (i && i % 5 == 0 && i != __arraycount(nv) - 1) {
750 				(void)printf(",\n%*s", pad, "");
751 				comma = 0;
752 			}
753 		}
754 		break;
755 	case 'P':
756 		for (i = 0; i < __arraycount(pm); i++) {
757 			(void)printf("%9s %7zu %s", pm[i].name, pm[i].def,
758 			    pm[i].desc);
759 			if (i != __arraycount(pm) - 1)
760 				(void)printf("\n%*s", pad, "");
761 		}
762 		break;
763 	default:
764 		file_errx(EXIT_FAILURE, "Unknown escape `%c' in long options",
765 		   *p);
766 		break;
767 	}
768 	(void)printf("%s", opts + (p - opts) + 1);
769 
770 }
771 
772 file_private void
help(void)773 help(void)
774 {
775 	(void)fputs(
776 "Usage: file [OPTION...] [FILE...]\n"
777 "Determine type of FILEs.\n"
778 "\n", stdout);
779 #define OPT(shortname, longname, opt, def, doc)      \
780 	(void)printf("  -%c, --" longname, shortname), \
781 	docprint(doc, def);
782 #define OPT_LONGONLY(longname, opt, def, doc, id)    	\
783 	(void)printf("      --" longname),	\
784 	docprint(doc, def);
785 #include "file_opts.h"
786 #undef OPT
787 #undef OPT_LONGONLY
788 	(void)printf("\nReport bugs to https://bugs.astron.com/\n");
789 	exit(EXIT_SUCCESS);
790 }
791 
792 file_private const char *file_progname;
793 
794 file_protected void
file_setprogname(const char * progname)795 file_setprogname(const char *progname)
796 {
797 	file_progname = progname;
798 }
799 
800 file_protected const char *
file_getprogname(void)801 file_getprogname(void)
802 {
803 	return file_progname;
804 }
805 
806 file_protected void
file_err(int e,const char * fmt,...)807 file_err(int e, const char *fmt, ...)
808 {
809 	va_list ap;
810 	int se = errno;
811 
812 	va_start(ap, fmt);
813 	(void)fprintf(stderr, "%s: ", file_progname);
814 	(void)vfprintf(stderr, fmt, ap);
815 	va_end(ap);
816 	if (se)
817 		(void)fprintf(stderr, " (%s)\n", strerror(se));
818 	else
819 		fputc('\n', stderr);
820 	exit(e);
821 }
822 
823 file_protected void
file_errx(int e,const char * fmt,...)824 file_errx(int e, const char *fmt, ...)
825 {
826 	va_list ap;
827 
828 	va_start(ap, fmt);
829 	(void)fprintf(stderr, "%s: ", file_progname);
830 	(void)vfprintf(stderr, fmt, ap);
831 	va_end(ap);
832 	(void)fprintf(stderr, "\n");
833 	exit(e);
834 }
835 
836 file_protected void
file_warn(const char * fmt,...)837 file_warn(const char *fmt, ...)
838 {
839 	va_list ap;
840 	int se = errno;
841 
842 	va_start(ap, fmt);
843 	(void)fprintf(stderr, "%s: ", file_progname);
844 	(void)vfprintf(stderr, fmt, ap);
845 	va_end(ap);
846 	if (se)
847 		(void)fprintf(stderr, " (%s)\n", strerror(se));
848 	else
849 		fputc('\n', stderr);
850 	errno = se;
851 }
852 
853 file_protected void
file_warnx(const char * fmt,...)854 file_warnx(const char *fmt, ...)
855 {
856 	va_list ap;
857 	int se = errno;
858 
859 	va_start(ap, fmt);
860 	(void)fprintf(stderr, "%s: ", file_progname);
861 	(void)vfprintf(stderr, fmt, ap);
862 	va_end(ap);
863 	(void)fprintf(stderr, "\n");
864 	errno = se;
865 }
866