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