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