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