xref: /netbsd-src/usr.bin/gzip/gzip.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: gzip.c,v 1.113 2018/06/12 00:42:17 kamil Exp $	*/
2 
3 /*
4  * Copyright (c) 1997, 1998, 2003, 2004, 2006, 2008, 2009, 2010, 2011, 2015, 2017
5  *    Matthew R. Green
6  * All rights reserved.
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, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #ifndef lint
32 __COPYRIGHT("@(#) Copyright (c) 1997, 1998, 2003, 2004, 2006, 2008,\
33  2009, 2010, 2011, 2015, 2017 Matthew R. Green.  All rights reserved.");
34 __RCSID("$NetBSD: gzip.c,v 1.113 2018/06/12 00:42:17 kamil Exp $");
35 #endif /* not lint */
36 
37 /*
38  * gzip.c -- GPL free gzip using zlib.
39  *
40  * RFC 1950 covers the zlib format
41  * RFC 1951 covers the deflate format
42  * RFC 1952 covers the gzip format
43  *
44  * TODO:
45  *	- use mmap where possible
46  *	- handle some signals better (remove outfile?)
47  *	- make bzip2/compress -v/-t/-l support work as well as possible
48  */
49 
50 #include <sys/param.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53 
54 #include <inttypes.h>
55 #include <unistd.h>
56 #include <stdio.h>
57 #include <string.h>
58 #include <stdlib.h>
59 #include <err.h>
60 #include <errno.h>
61 #include <fcntl.h>
62 #include <zlib.h>
63 #include <fts.h>
64 #include <libgen.h>
65 #include <stdarg.h>
66 #include <getopt.h>
67 #include <time.h>
68 
69 #ifndef PRIdOFF
70 #define PRIdOFF PRId64
71 #endif
72 
73 /* what type of file are we dealing with */
74 enum filetype {
75 	FT_GZIP,
76 #ifndef NO_BZIP2_SUPPORT
77 	FT_BZIP2,
78 #endif
79 #ifndef NO_COMPRESS_SUPPORT
80 	FT_Z,
81 #endif
82 #ifndef NO_PACK_SUPPORT
83 	FT_PACK,
84 #endif
85 #ifndef NO_XZ_SUPPORT
86 	FT_XZ,
87 #endif
88 	FT_LAST,
89 	FT_UNKNOWN
90 };
91 
92 #ifndef NO_BZIP2_SUPPORT
93 #include <bzlib.h>
94 
95 #define BZ2_SUFFIX	".bz2"
96 #define BZIP2_MAGIC	"\102\132\150"
97 #endif
98 
99 #ifndef NO_COMPRESS_SUPPORT
100 #define Z_SUFFIX	".Z"
101 #define Z_MAGIC		"\037\235"
102 #endif
103 
104 #ifndef NO_PACK_SUPPORT
105 #define PACK_MAGIC	"\037\036"
106 #endif
107 
108 #ifndef NO_XZ_SUPPORT
109 #include <lzma.h>
110 #define XZ_SUFFIX	".xz"
111 #define XZ_MAGIC	"\3757zXZ"
112 #endif
113 
114 #define GZ_SUFFIX	".gz"
115 
116 #define BUFLEN		(64 * 1024)
117 
118 #define GZIP_MAGIC0	0x1F
119 #define GZIP_MAGIC1	0x8B
120 #define GZIP_OMAGIC1	0x9E
121 
122 #define GZIP_TIMESTAMP	(off_t)4
123 #define GZIP_ORIGNAME	(off_t)10
124 
125 #define HEAD_CRC	0x02
126 #define EXTRA_FIELD	0x04
127 #define ORIG_NAME	0x08
128 #define COMMENT		0x10
129 
130 #define OS_CODE		3	/* Unix */
131 
132 typedef struct {
133     const char	*zipped;
134     int		ziplen;
135     const char	*normal;	/* for unzip - must not be longer than zipped */
136 } suffixes_t;
137 static suffixes_t suffixes[] = {
138 #define	SUFFIX(Z, N) {Z, sizeof Z - 1, N}
139 	SUFFIX(GZ_SUFFIX,	""),	/* Overwritten by -S .xxx */
140 #ifndef SMALL
141 	SUFFIX(GZ_SUFFIX,	""),
142 	SUFFIX(".z",		""),
143 	SUFFIX("-gz",		""),
144 	SUFFIX("-z",		""),
145 	SUFFIX("_z",		""),
146 	SUFFIX(".taz",		".tar"),
147 	SUFFIX(".tgz",		".tar"),
148 #ifndef NO_BZIP2_SUPPORT
149 	SUFFIX(BZ2_SUFFIX,	""),
150 #endif
151 #ifndef NO_COMPRESS_SUPPORT
152 	SUFFIX(Z_SUFFIX,	""),
153 #endif
154 #ifndef NO_XZ_SUPPORT
155 	SUFFIX(XZ_SUFFIX,	""),
156 #endif
157 	SUFFIX(GZ_SUFFIX,	""),	/* Overwritten by -S "" */
158 #endif /* SMALL */
159 #undef SUFFIX
160 };
161 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
162 #define SUFFIX_MAXLEN	30
163 
164 static	const char	gzip_version[] = "NetBSD gzip 20170803";
165 
166 static	int	cflag;			/* stdout mode */
167 static	int	dflag;			/* decompress mode */
168 static	int	lflag;			/* list mode */
169 static	int	numflag = 6;		/* gzip -1..-9 value */
170 
171 #ifndef SMALL
172 static	int	fflag;			/* force mode */
173 static	int	kflag;			/* don't delete input files */
174 static	int	nflag;			/* don't save name/timestamp */
175 static	int	Nflag;			/* don't restore name/timestamp */
176 static	int	qflag;			/* quiet mode */
177 static	int	rflag;			/* recursive mode */
178 static	int	tflag;			/* test */
179 static	int	vflag;			/* verbose mode */
180 static	sig_atomic_t print_info = 0;
181 #else
182 #define		qflag	0
183 #define		tflag	0
184 #endif
185 
186 static	int	exit_value = 0;		/* exit value */
187 
188 static	const char *infile;		/* name of file coming in */
189 
190 static	void	maybe_err(const char *fmt, ...) __printflike(1, 2) __dead;
191 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) ||	\
192     !defined(NO_XZ_SUPPORT)
193 static	void	maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead;
194 #endif
195 static	void	maybe_warn(const char *fmt, ...) __printflike(1, 2);
196 static	void	maybe_warnx(const char *fmt, ...) __printflike(1, 2);
197 static	enum filetype file_gettype(u_char *);
198 #ifdef SMALL
199 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
200 #endif
201 static	off_t	gz_compress(int, int, off_t *, const char *, uint32_t);
202 static	off_t	gz_uncompress(int, int, char *, size_t, off_t *, const char *);
203 static	off_t	file_compress(char *, char *, size_t);
204 static	off_t	file_uncompress(char *, char *, size_t);
205 static	void	handle_pathname(char *);
206 static	void	handle_file(char *, struct stat *);
207 static	void	handle_stdin(void);
208 static	void	handle_stdout(void);
209 static	void	print_ratio(off_t, off_t, FILE *);
210 static	void	print_list(int fd, off_t, const char *, time_t);
211 __dead static	void	usage(void);
212 __dead static	void	display_version(void);
213 static	const suffixes_t *check_suffix(char *, int);
214 static	ssize_t	read_retry(int, void *, size_t);
215 static	ssize_t	write_retry(int, const void *, size_t);
216 
217 #ifdef SMALL
218 #define infile_set(f,t) infile_set(f)
219 #endif
220 static	void	infile_set(const char *newinfile, off_t total);
221 
222 #ifdef SMALL
223 #define unlink_input(f, sb) unlink(f)
224 #define check_siginfo() /* nothing */
225 #define setup_signals() /* nothing */
226 #define infile_newdata(t) /* nothing */
227 #else
228 static	off_t	infile_total;		/* total expected to read/write */
229 static	off_t	infile_current;		/* current read/write */
230 
231 static	void	check_siginfo(void);
232 static	off_t	cat_fd(unsigned char *, size_t, off_t *, int fd);
233 static	void	prepend_gzip(char *, int *, char ***);
234 static	void	handle_dir(char *);
235 static	void	print_verbage(const char *, const char *, off_t, off_t);
236 static	void	print_test(const char *, int);
237 static	void	copymodes(int fd, const struct stat *, const char *file);
238 static	int	check_outfile(const char *outfile);
239 static	void	setup_signals(void);
240 static	void	infile_newdata(size_t newdata);
241 static	void	infile_clear(void);
242 #endif
243 
244 #ifndef NO_BZIP2_SUPPORT
245 static	off_t	unbzip2(int, int, char *, size_t, off_t *);
246 #endif
247 
248 #ifndef NO_COMPRESS_SUPPORT
249 static	FILE 	*zdopen(int);
250 static	off_t	zuncompress(FILE *, FILE *, char *, size_t, off_t *);
251 #endif
252 
253 #ifndef NO_PACK_SUPPORT
254 static	off_t	unpack(int, int, char *, size_t, off_t *);
255 #endif
256 
257 #ifndef NO_XZ_SUPPORT
258 static	off_t	unxz(int, int, char *, size_t, off_t *);
259 #endif
260 
261 #ifdef SMALL
262 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
263 #else
264 static const struct option longopts[] = {
265 	{ "stdout",		no_argument,		0,	'c' },
266 	{ "to-stdout",		no_argument,		0,	'c' },
267 	{ "decompress",		no_argument,		0,	'd' },
268 	{ "uncompress",		no_argument,		0,	'd' },
269 	{ "force",		no_argument,		0,	'f' },
270 	{ "help",		no_argument,		0,	'h' },
271 	{ "keep",		no_argument,		0,	'k' },
272 	{ "list",		no_argument,		0,	'l' },
273 	{ "no-name",		no_argument,		0,	'n' },
274 	{ "name",		no_argument,		0,	'N' },
275 	{ "quiet",		no_argument,		0,	'q' },
276 	{ "recursive",		no_argument,		0,	'r' },
277 	{ "suffix",		required_argument,	0,	'S' },
278 	{ "test",		no_argument,		0,	't' },
279 	{ "verbose",		no_argument,		0,	'v' },
280 	{ "version",		no_argument,		0,	'V' },
281 	{ "fast",		no_argument,		0,	'1' },
282 	{ "best",		no_argument,		0,	'9' },
283 #if 0
284 	/*
285 	 * This is what else GNU gzip implements.  --ascii isn't useful
286 	 * on NetBSD, and I don't care to have a --license.
287 	 */
288 	{ "ascii",		no_argument,		0,	'a' },
289 	{ "license",		no_argument,		0,	'L' },
290 #endif
291 	{ NULL,			no_argument,		0,	0 },
292 };
293 #endif
294 
295 int
296 main(int argc, char **argv)
297 {
298 	const char *progname = getprogname();
299 #ifndef SMALL
300 	char *gzip;
301 	int len;
302 #endif
303 	int ch;
304 
305 	setup_signals();
306 
307 #ifndef SMALL
308 	if ((gzip = getenv("GZIP")) != NULL)
309 		prepend_gzip(gzip, &argc, &argv);
310 #endif
311 
312 	/*
313 	 * XXX
314 	 * handle being called `gunzip', `zcat' and `gzcat'
315 	 */
316 	if (strcmp(progname, "gunzip") == 0)
317 		dflag = 1;
318 	else if (strcmp(progname, "zcat") == 0 ||
319 		 strcmp(progname, "gzcat") == 0)
320 		dflag = cflag = 1;
321 
322 #ifdef SMALL
323 #define OPT_LIST "123456789cdhlV"
324 #else
325 #define OPT_LIST "123456789cdfhklNnqrS:tVv"
326 #endif
327 
328 	while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
329 		switch (ch) {
330 		case '1': case '2': case '3':
331 		case '4': case '5': case '6':
332 		case '7': case '8': case '9':
333 			numflag = ch - '0';
334 			break;
335 		case 'c':
336 			cflag = 1;
337 			break;
338 		case 'd':
339 			dflag = 1;
340 			break;
341 		case 'l':
342 			lflag = 1;
343 			dflag = 1;
344 			break;
345 		case 'V':
346 			display_version();
347 			/* NOTREACHED */
348 #ifndef SMALL
349 		case 'f':
350 			fflag = 1;
351 			break;
352 		case 'k':
353 			kflag = 1;
354 			break;
355 		case 'N':
356 			nflag = 0;
357 			Nflag = 1;
358 			break;
359 		case 'n':
360 			nflag = 1;
361 			Nflag = 0;
362 			break;
363 		case 'q':
364 			qflag = 1;
365 			break;
366 		case 'r':
367 			rflag = 1;
368 			break;
369 		case 'S':
370 			len = strlen(optarg);
371 			if (len != 0) {
372 				if (len > SUFFIX_MAXLEN)
373 					errx(1, "incorrect suffix: '%s'", optarg);
374 				suffixes[0].zipped = optarg;
375 				suffixes[0].ziplen = len;
376 			} else {
377 				suffixes[NUM_SUFFIXES - 1].zipped = "";
378 				suffixes[NUM_SUFFIXES - 1].ziplen = 0;
379 			}
380 			break;
381 		case 't':
382 			cflag = 1;
383 			tflag = 1;
384 			dflag = 1;
385 			break;
386 		case 'v':
387 			vflag = 1;
388 			break;
389 #endif
390 		default:
391 			usage();
392 			/* NOTREACHED */
393 		}
394 	}
395 	argv += optind;
396 	argc -= optind;
397 
398 	if (argc == 0) {
399 		if (dflag)	/* stdin mode */
400 			handle_stdin();
401 		else		/* stdout mode */
402 			handle_stdout();
403 	} else {
404 		do {
405 			handle_pathname(argv[0]);
406 		} while (*++argv);
407 	}
408 #ifndef SMALL
409 	if (qflag == 0 && lflag && argc > 1)
410 		print_list(-1, 0, "(totals)", 0);
411 #endif
412 	exit(exit_value);
413 }
414 
415 /* maybe print a warning */
416 void
417 maybe_warn(const char *fmt, ...)
418 {
419 	va_list ap;
420 
421 	if (qflag == 0) {
422 		va_start(ap, fmt);
423 		vwarn(fmt, ap);
424 		va_end(ap);
425 	}
426 	if (exit_value == 0)
427 		exit_value = 1;
428 }
429 
430 /* ... without an errno. */
431 void
432 maybe_warnx(const char *fmt, ...)
433 {
434 	va_list ap;
435 
436 	if (qflag == 0) {
437 		va_start(ap, fmt);
438 		vwarnx(fmt, ap);
439 		va_end(ap);
440 	}
441 	if (exit_value == 0)
442 		exit_value = 1;
443 }
444 
445 /* maybe print an error */
446 void
447 maybe_err(const char *fmt, ...)
448 {
449 	va_list ap;
450 
451 	if (qflag == 0) {
452 		va_start(ap, fmt);
453 		vwarn(fmt, ap);
454 		va_end(ap);
455 	}
456 	exit(2);
457 }
458 
459 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) ||	\
460     !defined(NO_XZ_SUPPORT)
461 /* ... without an errno. */
462 void
463 maybe_errx(const char *fmt, ...)
464 {
465 	va_list ap;
466 
467 	if (qflag == 0) {
468 		va_start(ap, fmt);
469 		vwarnx(fmt, ap);
470 		va_end(ap);
471 	}
472 	exit(2);
473 }
474 #endif
475 
476 #ifndef SMALL
477 /* split up $GZIP and prepend it to the argument list */
478 static void
479 prepend_gzip(char *gzip, int *argc, char ***argv)
480 {
481 	char *s, **nargv, **ac;
482 	int nenvarg = 0, i;
483 
484 	/* scan how many arguments there are */
485 	for (s = gzip;;) {
486 		while (*s == ' ' || *s == '\t')
487 			s++;
488 		if (*s == 0)
489 			goto count_done;
490 		nenvarg++;
491 		while (*s != ' ' && *s != '\t')
492 			if (*s++ == 0)
493 				goto count_done;
494 	}
495 count_done:
496 	/* punt early */
497 	if (nenvarg == 0)
498 		return;
499 
500 	*argc += nenvarg;
501 	ac = *argv;
502 
503 	nargv = (char **)malloc((*argc + 1) * sizeof(char *));
504 	if (nargv == NULL)
505 		maybe_err("malloc");
506 
507 	/* stash this away */
508 	*argv = nargv;
509 
510 	/* copy the program name first */
511 	i = 0;
512 	nargv[i++] = *(ac++);
513 
514 	/* take a copy of $GZIP and add it to the array */
515 	s = strdup(gzip);
516 	if (s == NULL)
517 		maybe_err("strdup");
518 	for (;;) {
519 		/* Skip whitespaces. */
520 		while (*s == ' ' || *s == '\t')
521 			s++;
522 		if (*s == 0)
523 			goto copy_done;
524 		nargv[i++] = s;
525 		/* Find the end of this argument. */
526 		while (*s != ' ' && *s != '\t')
527 			if (*s++ == 0)
528 				/* Argument followed by NUL. */
529 				goto copy_done;
530 		/* Terminate by overwriting ' ' or '\t' with NUL. */
531 		*s++ = 0;
532 	}
533 copy_done:
534 
535 	/* copy the original arguments and a NULL */
536 	while (*ac)
537 		nargv[i++] = *(ac++);
538 	nargv[i] = NULL;
539 }
540 #endif
541 
542 /* compress input to output. Return bytes read, -1 on error */
543 static off_t
544 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
545 {
546 	z_stream z;
547 	char *outbufp, *inbufp;
548 	off_t in_tot = 0, out_tot = 0;
549 	ssize_t in_size;
550 	int i, error;
551 	uLong crc;
552 #ifdef SMALL
553 	static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
554 				 0, 0, 0, 0,
555 				 0, OS_CODE };
556 #endif
557 
558 	outbufp = malloc(BUFLEN);
559 	inbufp = malloc(BUFLEN);
560 	if (outbufp == NULL || inbufp == NULL) {
561 		maybe_err("malloc failed");
562 		goto out;
563 	}
564 
565 	memset(&z, 0, sizeof z);
566 	z.zalloc = Z_NULL;
567 	z.zfree = Z_NULL;
568 	z.opaque = 0;
569 
570 #ifdef SMALL
571 	memcpy(outbufp, header, sizeof header);
572 	i = sizeof header;
573 #else
574 	if (nflag != 0) {
575 		mtime = 0;
576 		origname = "";
577 	}
578 
579 	i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
580 		     GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
581 		     *origname ? ORIG_NAME : 0,
582 		     mtime & 0xff,
583 		     (mtime >> 8) & 0xff,
584 		     (mtime >> 16) & 0xff,
585 		     (mtime >> 24) & 0xff,
586 		     numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
587 		     OS_CODE, origname);
588 	if (i >= BUFLEN)
589 		/* this need PATH_MAX > BUFLEN ... */
590 		maybe_err("snprintf");
591 	if (*origname)
592 		i++;
593 #endif
594 
595 	z.next_out = (unsigned char *)outbufp + i;
596 	z.avail_out = BUFLEN - i;
597 
598 	error = deflateInit2(&z, numflag, Z_DEFLATED,
599 			     (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
600 	if (error != Z_OK) {
601 		maybe_warnx("deflateInit2 failed");
602 		in_tot = -1;
603 		goto out;
604 	}
605 
606 	crc = crc32(0L, Z_NULL, 0);
607 	for (;;) {
608 		if (z.avail_out == 0) {
609 			if (write_retry(out, outbufp, BUFLEN) != BUFLEN) {
610 				maybe_warn("write");
611 				out_tot = -1;
612 				goto out;
613 			}
614 
615 			out_tot += BUFLEN;
616 			z.next_out = (unsigned char *)outbufp;
617 			z.avail_out = BUFLEN;
618 		}
619 
620 		if (z.avail_in == 0) {
621 			in_size = read(in, inbufp, BUFLEN);
622 			if (in_size < 0) {
623 				maybe_warn("read");
624 				in_tot = -1;
625 				goto out;
626 			}
627 			if (in_size == 0)
628 				break;
629 			infile_newdata(in_size);
630 
631 			crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
632 			in_tot += in_size;
633 			z.next_in = (unsigned char *)inbufp;
634 			z.avail_in = in_size;
635 		}
636 
637 		error = deflate(&z, Z_NO_FLUSH);
638 		if (error != Z_OK && error != Z_STREAM_END) {
639 			maybe_warnx("deflate failed");
640 			in_tot = -1;
641 			goto out;
642 		}
643 	}
644 
645 	/* clean up */
646 	for (;;) {
647 		size_t len;
648 		ssize_t w;
649 
650 		error = deflate(&z, Z_FINISH);
651 		if (error != Z_OK && error != Z_STREAM_END) {
652 			maybe_warnx("deflate failed");
653 			in_tot = -1;
654 			goto out;
655 		}
656 
657 		len = (char *)z.next_out - outbufp;
658 
659 		w = write_retry(out, outbufp, len);
660 		if (w == -1 || (size_t)w != len) {
661 			maybe_warn("write");
662 			out_tot = -1;
663 			goto out;
664 		}
665 		out_tot += len;
666 		z.next_out = (unsigned char *)outbufp;
667 		z.avail_out = BUFLEN;
668 
669 		if (error == Z_STREAM_END)
670 			break;
671 	}
672 
673 	if (deflateEnd(&z) != Z_OK) {
674 		maybe_warnx("deflateEnd failed");
675 		in_tot = -1;
676 		goto out;
677 	}
678 
679 	i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
680 		 (int)crc & 0xff,
681 		 (int)(crc >> 8) & 0xff,
682 		 (int)(crc >> 16) & 0xff,
683 		 (int)(crc >> 24) & 0xff,
684 		 (int)in_tot & 0xff,
685 		 (int)(in_tot >> 8) & 0xff,
686 		 (int)(in_tot >> 16) & 0xff,
687 		 (int)(in_tot >> 24) & 0xff);
688 	if (i != 8)
689 		maybe_err("snprintf");
690 #if 0
691 	if (in_tot > 0xffffffff)
692 		maybe_warn("input file size >= 4GB cannot be saved");
693 #endif
694 	if (write_retry(out, outbufp, i) != i) {
695 		maybe_warn("write");
696 		in_tot = -1;
697 	} else
698 		out_tot += i;
699 
700 out:
701 	if (inbufp != NULL)
702 		free(inbufp);
703 	if (outbufp != NULL)
704 		free(outbufp);
705 	if (gsizep)
706 		*gsizep = out_tot;
707 	return in_tot;
708 }
709 
710 /*
711  * uncompress input to output then close the input.  return the
712  * uncompressed size written, and put the compressed sized read
713  * into `*gsizep'.
714  */
715 static off_t
716 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
717 	      const char *filename)
718 {
719 	z_stream z;
720 	char *outbufp, *inbufp;
721 	off_t out_tot = -1, in_tot = 0;
722 	uint32_t out_sub_tot = 0;
723 	enum {
724 		GZSTATE_MAGIC0,
725 		GZSTATE_MAGIC1,
726 		GZSTATE_METHOD,
727 		GZSTATE_FLAGS,
728 		GZSTATE_SKIPPING,
729 		GZSTATE_EXTRA,
730 		GZSTATE_EXTRA2,
731 		GZSTATE_EXTRA3,
732 		GZSTATE_ORIGNAME,
733 		GZSTATE_COMMENT,
734 		GZSTATE_HEAD_CRC1,
735 		GZSTATE_HEAD_CRC2,
736 		GZSTATE_INIT,
737 		GZSTATE_READ,
738 		GZSTATE_CRC,
739 		GZSTATE_LEN,
740 	} state = GZSTATE_MAGIC0;
741 	int flags = 0, skip_count = 0;
742 	int error = Z_STREAM_ERROR, done_reading = 0;
743 	uLong crc = 0;
744 	ssize_t wr;
745 	int needmore = 0;
746 
747 #define ADVANCE()       { z.next_in++; z.avail_in--; }
748 
749 	if ((outbufp = malloc(BUFLEN)) == NULL) {
750 		maybe_err("malloc failed");
751 		goto out2;
752 	}
753 	if ((inbufp = malloc(BUFLEN)) == NULL) {
754 		maybe_err("malloc failed");
755 		goto out1;
756 	}
757 
758 	memset(&z, 0, sizeof z);
759 	z.avail_in = prelen;
760 	z.next_in = (unsigned char *)pre;
761 	z.avail_out = BUFLEN;
762 	z.next_out = (unsigned char *)outbufp;
763 	z.zalloc = NULL;
764 	z.zfree = NULL;
765 	z.opaque = 0;
766 
767 	in_tot = prelen;
768 	out_tot = 0;
769 
770 	for (;;) {
771 		check_siginfo();
772 		if ((z.avail_in == 0 || needmore) && done_reading == 0) {
773 			ssize_t in_size;
774 
775 			if (z.avail_in > 0) {
776 				memmove(inbufp, z.next_in, z.avail_in);
777 			}
778 			z.next_in = (unsigned char *)inbufp;
779 			in_size = read(in, z.next_in + z.avail_in,
780 			    BUFLEN - z.avail_in);
781 
782 			if (in_size == -1) {
783 				maybe_warn("failed to read stdin");
784 				goto stop_and_fail;
785 			} else if (in_size == 0) {
786 				done_reading = 1;
787 			}
788 			infile_newdata(in_size);
789 
790 			z.avail_in += in_size;
791 			needmore = 0;
792 
793 			in_tot += in_size;
794 		}
795 		if (z.avail_in == 0) {
796 			if (done_reading && state != GZSTATE_MAGIC0) {
797 				maybe_warnx("%s: unexpected end of file",
798 					    filename);
799 				goto stop_and_fail;
800 			}
801 			goto stop;
802 		}
803 		switch (state) {
804 		case GZSTATE_MAGIC0:
805 			if (*z.next_in != GZIP_MAGIC0) {
806 				if (in_tot > 0) {
807 					maybe_warnx("%s: trailing garbage "
808 						    "ignored", filename);
809 					goto stop;
810 				}
811 				maybe_warnx("input not gziped (MAGIC0)");
812 				exit_value = 2;
813 				goto stop_and_fail;
814 			}
815 			ADVANCE();
816 			state++;
817 			out_sub_tot = 0;
818 			crc = crc32(0L, Z_NULL, 0);
819 			break;
820 
821 		case GZSTATE_MAGIC1:
822 			if (*z.next_in != GZIP_MAGIC1 &&
823 			    *z.next_in != GZIP_OMAGIC1) {
824 				maybe_warnx("input not gziped (MAGIC1)");
825 				goto stop_and_fail;
826 			}
827 			ADVANCE();
828 			state++;
829 			break;
830 
831 		case GZSTATE_METHOD:
832 			if (*z.next_in != Z_DEFLATED) {
833 				maybe_warnx("unknown compression method");
834 				goto stop_and_fail;
835 			}
836 			ADVANCE();
837 			state++;
838 			break;
839 
840 		case GZSTATE_FLAGS:
841 			flags = *z.next_in;
842 			ADVANCE();
843 			skip_count = 6;
844 			state++;
845 			break;
846 
847 		case GZSTATE_SKIPPING:
848 			if (skip_count > 0) {
849 				skip_count--;
850 				ADVANCE();
851 			} else
852 				state++;
853 			break;
854 
855 		case GZSTATE_EXTRA:
856 			if ((flags & EXTRA_FIELD) == 0) {
857 				state = GZSTATE_ORIGNAME;
858 				break;
859 			}
860 			skip_count = *z.next_in;
861 			ADVANCE();
862 			state++;
863 			break;
864 
865 		case GZSTATE_EXTRA2:
866 			skip_count |= ((*z.next_in) << 8);
867 			ADVANCE();
868 			state++;
869 			break;
870 
871 		case GZSTATE_EXTRA3:
872 			if (skip_count > 0) {
873 				skip_count--;
874 				ADVANCE();
875 			} else
876 				state++;
877 			break;
878 
879 		case GZSTATE_ORIGNAME:
880 			if ((flags & ORIG_NAME) == 0) {
881 				state++;
882 				break;
883 			}
884 			if (*z.next_in == 0)
885 				state++;
886 			ADVANCE();
887 			break;
888 
889 		case GZSTATE_COMMENT:
890 			if ((flags & COMMENT) == 0) {
891 				state++;
892 				break;
893 			}
894 			if (*z.next_in == 0)
895 				state++;
896 			ADVANCE();
897 			break;
898 
899 		case GZSTATE_HEAD_CRC1:
900 			if (flags & HEAD_CRC)
901 				skip_count = 2;
902 			else
903 				skip_count = 0;
904 			state++;
905 			break;
906 
907 		case GZSTATE_HEAD_CRC2:
908 			if (skip_count > 0) {
909 				skip_count--;
910 				ADVANCE();
911 			} else
912 				state++;
913 			break;
914 
915 		case GZSTATE_INIT:
916 			if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
917 				maybe_warnx("failed to inflateInit");
918 				goto stop_and_fail;
919 			}
920 			state++;
921 			break;
922 
923 		case GZSTATE_READ:
924 			error = inflate(&z, Z_FINISH);
925 			switch (error) {
926 			/* Z_BUF_ERROR goes with Z_FINISH... */
927 			case Z_BUF_ERROR:
928 				if (z.avail_out > 0 && !done_reading)
929 					continue;
930 
931 			case Z_STREAM_END:
932 			case Z_OK:
933 				break;
934 
935 			case Z_NEED_DICT:
936 				maybe_warnx("Z_NEED_DICT error");
937 				goto stop_and_fail;
938 			case Z_DATA_ERROR:
939 				maybe_warnx("data stream error");
940 				goto stop_and_fail;
941 			case Z_STREAM_ERROR:
942 				maybe_warnx("internal stream error");
943 				goto stop_and_fail;
944 			case Z_MEM_ERROR:
945 				maybe_warnx("memory allocation error");
946 				goto stop_and_fail;
947 
948 			default:
949 				maybe_warn("unknown error from inflate(): %d",
950 				    error);
951 			}
952 			wr = BUFLEN - z.avail_out;
953 
954 			if (wr != 0) {
955 				crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
956 				if (
957 #ifndef SMALL
958 				    /* don't write anything with -t */
959 				    tflag == 0 &&
960 #endif
961 				    write_retry(out, outbufp, wr) != wr) {
962 					maybe_warn("error writing to output");
963 					goto stop_and_fail;
964 				}
965 
966 				out_tot += wr;
967 				out_sub_tot += wr;
968 			}
969 
970 			if (error == Z_STREAM_END) {
971 				inflateEnd(&z);
972 				state++;
973 			}
974 
975 			z.next_out = (unsigned char *)outbufp;
976 			z.avail_out = BUFLEN;
977 
978 			break;
979 		case GZSTATE_CRC:
980 			{
981 				uLong origcrc;
982 
983 				if (z.avail_in < 4) {
984 					if (!done_reading) {
985 						needmore = 1;
986 						continue;
987 					}
988 					maybe_warnx("truncated input");
989 					goto stop_and_fail;
990 				}
991 				origcrc = ((unsigned)z.next_in[0] & 0xff) |
992 					((unsigned)z.next_in[1] & 0xff) << 8 |
993 					((unsigned)z.next_in[2] & 0xff) << 16 |
994 					((unsigned)z.next_in[3] & 0xff) << 24;
995 				if (origcrc != crc) {
996 					maybe_warnx("invalid compressed"
997 					     " data--crc error");
998 					goto stop_and_fail;
999 				}
1000 			}
1001 
1002 			z.avail_in -= 4;
1003 			z.next_in += 4;
1004 
1005 			if (!z.avail_in && done_reading) {
1006 				goto stop;
1007 			}
1008 			state++;
1009 			break;
1010 		case GZSTATE_LEN:
1011 			{
1012 				uLong origlen;
1013 
1014 				if (z.avail_in < 4) {
1015 					if (!done_reading) {
1016 						needmore = 1;
1017 						continue;
1018 					}
1019 					maybe_warnx("truncated input");
1020 					goto stop_and_fail;
1021 				}
1022 				origlen = ((unsigned)z.next_in[0] & 0xff) |
1023 					((unsigned)z.next_in[1] & 0xff) << 8 |
1024 					((unsigned)z.next_in[2] & 0xff) << 16 |
1025 					((unsigned)z.next_in[3] & 0xff) << 24;
1026 
1027 				if (origlen != out_sub_tot) {
1028 					maybe_warnx("invalid compressed"
1029 					     " data--length error");
1030 					goto stop_and_fail;
1031 				}
1032 			}
1033 
1034 			z.avail_in -= 4;
1035 			z.next_in += 4;
1036 
1037 			if (error < 0) {
1038 				maybe_warnx("decompression error");
1039 				goto stop_and_fail;
1040 			}
1041 			state = GZSTATE_MAGIC0;
1042 			break;
1043 		}
1044 		continue;
1045 stop_and_fail:
1046 		out_tot = -1;
1047 stop:
1048 		break;
1049 	}
1050 	if (state > GZSTATE_INIT)
1051 		inflateEnd(&z);
1052 
1053 	free(inbufp);
1054 out1:
1055 	free(outbufp);
1056 out2:
1057 	if (gsizep)
1058 		*gsizep = in_tot;
1059 	return (out_tot);
1060 }
1061 
1062 #ifndef SMALL
1063 /*
1064  * set the owner, mode, flags & utimes using the given file descriptor.
1065  * file is only used in possible warning messages.
1066  */
1067 static void
1068 copymodes(int fd, const struct stat *sbp, const char *file)
1069 {
1070 	struct timeval times[2];
1071 	struct stat sb;
1072 
1073 	/*
1074 	 * If we have no info on the input, give this file some
1075 	 * default values and return..
1076 	 */
1077 	if (sbp == NULL) {
1078 		mode_t mask = umask(022);
1079 
1080 		(void)fchmod(fd, DEFFILEMODE & ~mask);
1081 		(void)umask(mask);
1082 		return;
1083 	}
1084 	sb = *sbp;
1085 
1086 	/* if the chown fails, remove set-id bits as-per compress(1) */
1087 	if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1088 		if (errno != EPERM)
1089 			maybe_warn("couldn't fchown: %s", file);
1090 		sb.st_mode &= ~(S_ISUID|S_ISGID);
1091 	}
1092 
1093 	/* we only allow set-id and the 9 normal permission bits */
1094 	sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1095 	if (fchmod(fd, sb.st_mode) < 0)
1096 		maybe_warn("couldn't fchmod: %s", file);
1097 
1098 	/* only try flags if they exist already */
1099         if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1100 		maybe_warn("couldn't fchflags: %s", file);
1101 
1102 	TIMESPEC_TO_TIMEVAL(&times[0], &sb.st_atimespec);
1103 	TIMESPEC_TO_TIMEVAL(&times[1], &sb.st_mtimespec);
1104 	if (futimes(fd, times) < 0)
1105 		maybe_warn("couldn't utimes: %s", file);
1106 }
1107 #endif
1108 
1109 /* what sort of file is this? */
1110 static enum filetype
1111 file_gettype(u_char *buf)
1112 {
1113 
1114 	if (buf[0] == GZIP_MAGIC0 &&
1115 	    (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1116 		return FT_GZIP;
1117 	else
1118 #ifndef NO_BZIP2_SUPPORT
1119 	if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1120 	    buf[3] >= '0' && buf[3] <= '9')
1121 		return FT_BZIP2;
1122 	else
1123 #endif
1124 #ifndef NO_COMPRESS_SUPPORT
1125 	if (memcmp(buf, Z_MAGIC, 2) == 0)
1126 		return FT_Z;
1127 	else
1128 #endif
1129 #ifndef NO_PACK_SUPPORT
1130 	if (memcmp(buf, PACK_MAGIC, 2) == 0)
1131 		return FT_PACK;
1132 	else
1133 #endif
1134 #ifndef NO_XZ_SUPPORT
1135 	if (memcmp(buf, XZ_MAGIC, 4) == 0)	/* XXX: We only have 4 bytes */
1136 		return FT_XZ;
1137 	else
1138 #endif
1139 		return FT_UNKNOWN;
1140 }
1141 
1142 #ifndef SMALL
1143 /* check the outfile is OK. */
1144 static int
1145 check_outfile(const char *outfile)
1146 {
1147 	struct stat sb;
1148 	int ok = 1;
1149 
1150 	if (lflag == 0 && stat(outfile, &sb) == 0) {
1151 		if (fflag)
1152 			unlink(outfile);
1153 		else if (isatty(STDIN_FILENO)) {
1154 			char ans[10] = { 'n', '\0' };	/* default */
1155 
1156 			fprintf(stderr, "%s already exists -- do you wish to "
1157 					"overwrite (y or n)? " , outfile);
1158 			(void)fgets(ans, sizeof(ans) - 1, stdin);
1159 			if (ans[0] != 'y' && ans[0] != 'Y') {
1160 				fprintf(stderr, "\tnot overwriting\n");
1161 				ok = 0;
1162 			} else
1163 				unlink(outfile);
1164 		} else {
1165 			maybe_warnx("%s already exists -- skipping", outfile);
1166 			ok = 0;
1167 		}
1168 	}
1169 	return ok;
1170 }
1171 
1172 static void
1173 unlink_input(const char *file, const struct stat *sb)
1174 {
1175 	struct stat nsb;
1176 
1177 	if (kflag)
1178 		return;
1179 	if (stat(file, &nsb) != 0)
1180 		/* Must be gone already */
1181 		return;
1182 	if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1183 		/* Definitely a different file */
1184 		return;
1185 	unlink(file);
1186 }
1187 
1188 static void
1189 got_siginfo(int signo)
1190 {
1191 
1192 	print_info = 1;
1193 }
1194 
1195 static void
1196 setup_signals(void)
1197 {
1198 
1199 	signal(SIGINFO, got_siginfo);
1200 }
1201 
1202 static	void
1203 infile_newdata(size_t newdata)
1204 {
1205 
1206 	infile_current += newdata;
1207 }
1208 #endif
1209 
1210 static	void
1211 infile_set(const char *newinfile, off_t total)
1212 {
1213 
1214 	if (newinfile)
1215 		infile = newinfile;
1216 #ifndef SMALL
1217 	infile_total = total;
1218 #endif
1219 }
1220 
1221 static	void
1222 infile_clear(void)
1223 {
1224 
1225 	infile = NULL;
1226 #ifndef SMALL
1227 	infile_total = infile_current = 0;
1228 #endif
1229 }
1230 
1231 static const suffixes_t *
1232 check_suffix(char *file, int xlate)
1233 {
1234 	const suffixes_t *s;
1235 	int len = strlen(file);
1236 	char *sp;
1237 
1238 	for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1239 		/* if it doesn't fit in "a.suf", don't bother */
1240 		if (s->ziplen >= len)
1241 			continue;
1242 		sp = file + len - s->ziplen;
1243 		if (strcmp(s->zipped, sp) != 0)
1244 			continue;
1245 		if (xlate)
1246 			strcpy(sp, s->normal);
1247 		return s;
1248 	}
1249 	return NULL;
1250 }
1251 
1252 /*
1253  * compress the given file: create a corresponding .gz file and remove the
1254  * original.
1255  */
1256 static off_t
1257 file_compress(char *file, char *outfile, size_t outsize)
1258 {
1259 	int in;
1260 	int out;
1261 	off_t size, in_size;
1262 #ifndef SMALL
1263 	struct stat isb, osb;
1264 	const suffixes_t *suff;
1265 #endif
1266 
1267 	in = open(file, O_RDONLY);
1268 	if (in == -1) {
1269 		maybe_warn("can't open %s", file);
1270 		return -1;
1271 	}
1272 
1273 #ifndef SMALL
1274 	if (fstat(in, &isb) != 0) {
1275 		close(in);
1276 		maybe_warn("can't stat %s", file);
1277 		return -1;
1278 	}
1279 	infile_set(file, isb.st_size);
1280 #endif
1281 
1282 	if (cflag == 0) {
1283 #ifndef SMALL
1284 		if (isb.st_nlink > 1 && fflag == 0) {
1285 			maybe_warnx("%s has %d other link%s -- "
1286 				    "skipping", file, isb.st_nlink - 1,
1287 				    isb.st_nlink == 1 ? "" : "s");
1288 			close(in);
1289 			return -1;
1290 		}
1291 
1292 		if (fflag == 0 && (suff = check_suffix(file, 0))
1293 		    && suff->zipped[0] != 0) {
1294 			maybe_warnx("%s already has %s suffix -- unchanged",
1295 				    file, suff->zipped);
1296 			close(in);
1297 			return -1;
1298 		}
1299 #endif
1300 
1301 		/* Add (usually) .gz to filename */
1302 		if ((size_t)snprintf(outfile, outsize, "%s%s",
1303 					file, suffixes[0].zipped) >= outsize)
1304 			memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1305 				suffixes[0].zipped, suffixes[0].ziplen + 1);
1306 
1307 #ifndef SMALL
1308 		if (check_outfile(outfile) == 0) {
1309 			close(in);
1310 			return -1;
1311 		}
1312 #endif
1313 	}
1314 
1315 	if (cflag == 0) {
1316 		out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1317 		if (out == -1) {
1318 			maybe_warn("could not create output: %s", outfile);
1319 			fclose(stdin);
1320 			return -1;
1321 		}
1322 	} else
1323 		out = STDOUT_FILENO;
1324 
1325 	in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1326 
1327 	(void)close(in);
1328 
1329 	/*
1330 	 * If there was an error, in_size will be -1.
1331 	 * If we compressed to stdout, just return the size.
1332 	 * Otherwise stat the file and check it is the correct size.
1333 	 * We only blow away the file if we can stat the output and it
1334 	 * has the expected size.
1335 	 */
1336 	if (cflag != 0)
1337 		return in_size == -1 ? -1 : size;
1338 
1339 #ifndef SMALL
1340 	if (fstat(out, &osb) != 0) {
1341 		maybe_warn("couldn't stat: %s", outfile);
1342 		goto bad_outfile;
1343 	}
1344 
1345 	if (osb.st_size != size) {
1346 		maybe_warnx("output file: %s wrong size (%" PRIdOFF
1347 				" != %" PRIdOFF "), deleting",
1348 				outfile, osb.st_size, size);
1349 		goto bad_outfile;
1350 	}
1351 
1352 	copymodes(out, &isb, outfile);
1353 #endif
1354 	if (close(out) == -1)
1355 		maybe_warn("couldn't close output");
1356 
1357 	/* output is good, ok to delete input */
1358 	unlink_input(file, &isb);
1359 	return size;
1360 
1361 #ifndef SMALL
1362     bad_outfile:
1363 	if (close(out) == -1)
1364 		maybe_warn("couldn't close output");
1365 
1366 	maybe_warnx("leaving original %s", file);
1367 	unlink(outfile);
1368 	return size;
1369 #endif
1370 }
1371 
1372 /* uncompress the given file and remove the original */
1373 static off_t
1374 file_uncompress(char *file, char *outfile, size_t outsize)
1375 {
1376 	struct stat isb, osb;
1377 	off_t size;
1378 	ssize_t rbytes;
1379 	unsigned char header1[4];
1380 	enum filetype method;
1381 	int fd, ofd, zfd = -1;
1382 	size_t in_size;
1383 #ifndef SMALL
1384 	ssize_t rv;
1385 	time_t timestamp = 0;
1386 	char name[PATH_MAX + 1];
1387 #endif
1388 
1389 	/* gather the old name info */
1390 
1391 	fd = open(file, O_RDONLY);
1392 	if (fd < 0) {
1393 		maybe_warn("can't open %s", file);
1394 		goto lose;
1395 	}
1396 	if (fstat(fd, &isb) != 0) {
1397 		close(fd);
1398 		maybe_warn("can't stat %s", file);
1399 		goto lose;
1400 	}
1401 	if (S_ISREG(isb.st_mode))
1402 		in_size = isb.st_size;
1403 	else
1404 		in_size = 0;
1405 	infile_set(file, in_size);
1406 
1407 	strlcpy(outfile, file, outsize);
1408 	if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1409 		maybe_warnx("%s: unknown suffix -- ignored", file);
1410 		goto lose;
1411 	}
1412 
1413 	rbytes = read(fd, header1, sizeof header1);
1414 	if (rbytes != sizeof header1) {
1415 		/* we don't want to fail here. */
1416 #ifndef SMALL
1417 		if (fflag)
1418 			goto lose;
1419 #endif
1420 		if (rbytes == -1)
1421 			maybe_warn("can't read %s", file);
1422 		else
1423 			goto unexpected_EOF;
1424 		goto lose;
1425 	}
1426 	infile_newdata(rbytes);
1427 
1428 	method = file_gettype(header1);
1429 #ifndef SMALL
1430 	if (fflag == 0 && method == FT_UNKNOWN) {
1431 		maybe_warnx("%s: not in gzip format", file);
1432 		goto lose;
1433 	}
1434 
1435 #endif
1436 
1437 #ifndef SMALL
1438 	if (method == FT_GZIP && Nflag) {
1439 		unsigned char ts[4];	/* timestamp */
1440 
1441 		rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1442 		if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1443 			goto unexpected_EOF;
1444 		if (rv == -1) {
1445 			if (!fflag)
1446 				maybe_warn("can't read %s", file);
1447 			goto lose;
1448 		}
1449 		infile_newdata(rv);
1450 		timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1451 
1452 		if (header1[3] & ORIG_NAME) {
1453 			rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1454 			if (rbytes < 0) {
1455 				maybe_warn("can't read %s", file);
1456 				goto lose;
1457 			}
1458 			if (name[0] != '\0') {
1459 				char *dp, *nf;
1460 
1461 				/* Make sure that name is NUL-terminated */
1462 				name[rbytes] = '\0';
1463 
1464 				/* strip saved directory name */
1465 				nf = strrchr(name, '/');
1466 				if (nf == NULL)
1467 					nf = name;
1468 				else
1469 					nf++;
1470 
1471 				/* preserve original directory name */
1472 				dp = strrchr(file, '/');
1473 				if (dp == NULL)
1474 					dp = file;
1475 				else
1476 					dp++;
1477 				snprintf(outfile, outsize, "%.*s%.*s",
1478 						(int) (dp - file),
1479 						file, (int) rbytes, nf);
1480 			}
1481 		}
1482 	}
1483 #endif
1484 	lseek(fd, 0, SEEK_SET);
1485 
1486 	if (cflag == 0 || lflag) {
1487 #ifndef SMALL
1488 		if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1489 			maybe_warnx("%s has %d other links -- skipping",
1490 			    file, isb.st_nlink - 1);
1491 			goto lose;
1492 		}
1493 		if (nflag == 0 && timestamp)
1494 			isb.st_mtime = timestamp;
1495 		if (check_outfile(outfile) == 0)
1496 			goto lose;
1497 #endif
1498 	}
1499 
1500 	if (cflag)
1501 		zfd = STDOUT_FILENO;
1502 	else if (lflag)
1503 		zfd = -1;
1504 	else {
1505 		zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1506 		if (zfd == STDOUT_FILENO) {
1507 			/* We won't close STDOUT_FILENO later... */
1508 			zfd = dup(zfd);
1509 			close(STDOUT_FILENO);
1510 		}
1511 		if (zfd == -1) {
1512 			maybe_warn("can't open %s", outfile);
1513 			goto lose;
1514 		}
1515 	}
1516 
1517 	switch (method) {
1518 #ifndef NO_BZIP2_SUPPORT
1519 	case FT_BZIP2:
1520 		/* XXX */
1521 		if (lflag) {
1522 			maybe_warnx("no -l with bzip2 files");
1523 			goto lose;
1524 		}
1525 
1526 		size = unbzip2(fd, zfd, NULL, 0, NULL);
1527 		break;
1528 #endif
1529 
1530 #ifndef NO_COMPRESS_SUPPORT
1531 	case FT_Z: {
1532 		FILE *in, *out;
1533 
1534 		/* XXX */
1535 		if (lflag) {
1536 			maybe_warnx("no -l with Lempel-Ziv files");
1537 			goto lose;
1538 		}
1539 
1540 		if ((in = zdopen(fd)) == NULL) {
1541 			maybe_warn("zdopen for read: %s", file);
1542 			goto lose;
1543 		}
1544 
1545 		out = fdopen(dup(zfd), "w");
1546 		if (out == NULL) {
1547 			maybe_warn("fdopen for write: %s", outfile);
1548 			fclose(in);
1549 			goto lose;
1550 		}
1551 
1552 		size = zuncompress(in, out, NULL, 0, NULL);
1553 		/* need to fclose() if ferror() is true... */
1554 		if (ferror(in) | fclose(in)) {
1555 			maybe_warn("failed infile fclose");
1556 			unlink(outfile);
1557 			(void)fclose(out);
1558 		}
1559 		if (fclose(out) != 0) {
1560 			maybe_warn("failed outfile fclose");
1561 			unlink(outfile);
1562 			goto lose;
1563 		}
1564 		break;
1565 	}
1566 #endif
1567 
1568 #ifndef NO_PACK_SUPPORT
1569 	case FT_PACK:
1570 		if (lflag) {
1571 			maybe_warnx("no -l with packed files");
1572 			goto lose;
1573 		}
1574 
1575 		size = unpack(fd, zfd, NULL, 0, NULL);
1576 		break;
1577 #endif
1578 
1579 #ifndef NO_XZ_SUPPORT
1580 	case FT_XZ:
1581 		if (lflag) {
1582 			maybe_warnx("no -l with xz files");
1583 			goto lose;
1584 		}
1585 
1586 		size = unxz(fd, zfd, NULL, 0, NULL);
1587 		break;
1588 #endif
1589 
1590 #ifndef SMALL
1591 	case FT_UNKNOWN:
1592 		if (lflag) {
1593 			maybe_warnx("no -l for unknown filetypes");
1594 			goto lose;
1595 		}
1596 		size = cat_fd(NULL, 0, NULL, fd);
1597 		break;
1598 #endif
1599 	default:
1600 		if (lflag) {
1601 			print_list(fd, in_size, outfile, isb.st_mtime);
1602 			close(fd);
1603 			return -1;	/* XXX */
1604 		}
1605 
1606 		size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1607 		break;
1608 	}
1609 
1610 	if (close(fd) != 0)
1611 		maybe_warn("couldn't close input");
1612 	if (zfd != STDOUT_FILENO && close(zfd) != 0)
1613 		maybe_warn("couldn't close output");
1614 
1615 	if (size == -1) {
1616 		if (cflag == 0)
1617 			unlink(outfile);
1618 		maybe_warnx("%s: uncompress failed", file);
1619 		return -1;
1620 	}
1621 
1622 	/* if testing, or we uncompressed to stdout, this is all we need */
1623 #ifndef SMALL
1624 	if (tflag)
1625 		return size;
1626 #endif
1627 	/* if we are uncompressing to stdin, don't remove the file. */
1628 	if (cflag)
1629 		return size;
1630 
1631 	/*
1632 	 * if we create a file...
1633 	 */
1634 	/*
1635 	 * if we can't stat the file don't remove the file.
1636 	 */
1637 
1638 	ofd = open(outfile, O_RDWR, 0);
1639 	if (ofd == -1) {
1640 		maybe_warn("couldn't open (leaving original): %s",
1641 			   outfile);
1642 		return -1;
1643 	}
1644 	if (fstat(ofd, &osb) != 0) {
1645 		maybe_warn("couldn't stat (leaving original): %s",
1646 			   outfile);
1647 		close(ofd);
1648 		return -1;
1649 	}
1650 	if (osb.st_size != size) {
1651 		maybe_warnx("stat gave different size: %" PRIdOFF
1652 				" != %" PRIdOFF " (leaving original)",
1653 				size, osb.st_size);
1654 		close(ofd);
1655 		unlink(outfile);
1656 		return -1;
1657 	}
1658 	unlink_input(file, &isb);
1659 #ifndef SMALL
1660 	copymodes(ofd, &isb, outfile);
1661 #endif
1662 	close(ofd);
1663 	return size;
1664 
1665     unexpected_EOF:
1666 	maybe_warnx("%s: unexpected end of file", file);
1667     lose:
1668 	if (fd != -1)
1669 		close(fd);
1670 	if (zfd != -1 && zfd != STDOUT_FILENO)
1671 		close(fd);
1672 	return -1;
1673 }
1674 
1675 #ifndef SMALL
1676 static void
1677 check_siginfo(void)
1678 {
1679 	if (print_info == 0)
1680 		return;
1681 	if (infile) {
1682 		if (infile_total) {
1683 			int pcent = (int)((100.0 * infile_current) / infile_total);
1684 
1685 			fprintf(stderr, "%s: done %llu/%llu bytes %d%%\n",
1686 				infile, (unsigned long long)infile_current,
1687 				(unsigned long long)infile_total, pcent);
1688 		} else
1689 			fprintf(stderr, "%s: done %llu bytes\n",
1690 				infile, (unsigned long long)infile_current);
1691 	}
1692 	print_info = 0;
1693 }
1694 
1695 static off_t
1696 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1697 {
1698 	char buf[BUFLEN];
1699 	off_t in_tot;
1700 	ssize_t w;
1701 
1702 	in_tot = count;
1703 	w = write_retry(STDOUT_FILENO, prepend, count);
1704 	if (w == -1 || (size_t)w != count) {
1705 		maybe_warn("write to stdout");
1706 		return -1;
1707 	}
1708 	for (;;) {
1709 		ssize_t rv;
1710 
1711 		rv = read(fd, buf, sizeof buf);
1712 		if (rv == 0)
1713 			break;
1714 		if (rv < 0) {
1715 			maybe_warn("read from fd %d", fd);
1716 			break;
1717 		}
1718 		infile_newdata(rv);
1719 
1720 		if (write_retry(STDOUT_FILENO, buf, rv) != rv) {
1721 			maybe_warn("write to stdout");
1722 			break;
1723 		}
1724 		in_tot += rv;
1725 	}
1726 
1727 	if (gsizep)
1728 		*gsizep = in_tot;
1729 	return (in_tot);
1730 }
1731 #endif
1732 
1733 static void
1734 handle_stdin(void)
1735 {
1736 	struct stat isb;
1737 	unsigned char header1[4];
1738 	size_t in_size;
1739 	off_t usize, gsize;
1740 	enum filetype method;
1741 	ssize_t bytes_read;
1742 #ifndef NO_COMPRESS_SUPPORT
1743 	FILE *in;
1744 #endif
1745 
1746 #ifndef SMALL
1747 	if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1748 		maybe_warnx("standard input is a terminal -- ignoring");
1749 		goto out;
1750 	}
1751 #endif
1752 
1753 	if (fstat(STDIN_FILENO, &isb) < 0) {
1754 		maybe_warn("fstat");
1755 		goto out;
1756 	}
1757 	if (S_ISREG(isb.st_mode))
1758 		in_size = isb.st_size;
1759 	else
1760 		in_size = 0;
1761 	infile_set("(stdin)", in_size);
1762 
1763 	if (lflag) {
1764 		print_list(STDIN_FILENO, in_size, infile, isb.st_mtime);
1765 		goto out;
1766 	}
1767 
1768 	bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1769 	if (bytes_read == -1) {
1770 		maybe_warn("can't read stdin");
1771 		goto out;
1772 	} else if (bytes_read != sizeof(header1)) {
1773 		maybe_warnx("(stdin): unexpected end of file");
1774 		goto out;
1775 	}
1776 
1777 	method = file_gettype(header1);
1778 	switch (method) {
1779 	default:
1780 #ifndef SMALL
1781 		if (fflag == 0) {
1782 			maybe_warnx("unknown compression format");
1783 			goto out;
1784 		}
1785 		usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1786 		break;
1787 #endif
1788 	case FT_GZIP:
1789 		usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1790 			      (char *)header1, sizeof header1, &gsize, "(stdin)");
1791 		break;
1792 #ifndef NO_BZIP2_SUPPORT
1793 	case FT_BZIP2:
1794 		usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1795 				(char *)header1, sizeof header1, &gsize);
1796 		break;
1797 #endif
1798 #ifndef NO_COMPRESS_SUPPORT
1799 	case FT_Z:
1800 		if ((in = zdopen(STDIN_FILENO)) == NULL) {
1801 			maybe_warnx("zopen of stdin");
1802 			goto out;
1803 		}
1804 
1805 		usize = zuncompress(in, stdout, (char *)header1,
1806 		    sizeof header1, &gsize);
1807 		fclose(in);
1808 		break;
1809 #endif
1810 #ifndef NO_PACK_SUPPORT
1811 	case FT_PACK:
1812 		usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1813 			       (char *)header1, sizeof header1, &gsize);
1814 		break;
1815 #endif
1816 #ifndef NO_XZ_SUPPORT
1817 	case FT_XZ:
1818 		usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1819 			     (char *)header1, sizeof header1, &gsize);
1820 		break;
1821 #endif
1822 	}
1823 
1824 #ifndef SMALL
1825         if (vflag && !tflag && usize != -1 && gsize != -1)
1826 		print_verbage(NULL, NULL, usize, gsize);
1827 	if (vflag && tflag)
1828 		print_test("(stdin)", usize != -1);
1829 #else
1830 	(void)&usize;
1831 #endif
1832 
1833 out:
1834 	infile_clear();
1835 }
1836 
1837 static void
1838 handle_stdout(void)
1839 {
1840 	off_t gsize;
1841 #ifndef SMALL
1842 	off_t usize;
1843 	struct stat sb;
1844 	time_t systime;
1845 	uint32_t mtime;
1846 	int ret;
1847 
1848 	infile_set("(stdout)", 0);
1849 
1850 	if (fflag == 0 && isatty(STDOUT_FILENO)) {
1851 		maybe_warnx("standard output is a terminal -- ignoring");
1852 		return;
1853 	}
1854 
1855 	/* If stdin is a file use its mtime, otherwise use current time */
1856 	ret = fstat(STDIN_FILENO, &sb);
1857 	if (ret < 0) {
1858 		maybe_warn("Can't stat stdin");
1859 		return;
1860 	}
1861 
1862 	if (S_ISREG(sb.st_mode)) {
1863 		infile_set("(stdout)", sb.st_size);
1864 		mtime = (uint32_t)sb.st_mtime;
1865 	} else {
1866 		systime = time(NULL);
1867 		if (systime == -1) {
1868 			maybe_warn("time");
1869 			return;
1870 		}
1871 		mtime = (uint32_t)systime;
1872 	}
1873 
1874 	usize =
1875 #endif
1876 		gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1877 #ifndef SMALL
1878         if (vflag && !tflag && usize != -1 && gsize != -1)
1879 		print_verbage(NULL, NULL, usize, gsize);
1880 #endif
1881 }
1882 
1883 /* do what is asked for, for the path name */
1884 static void
1885 handle_pathname(char *path)
1886 {
1887 	char *opath = path, *s = NULL;
1888 	ssize_t len;
1889 	int slen;
1890 	struct stat sb;
1891 
1892 	/* check for stdout/stdin */
1893 	if (path[0] == '-' && path[1] == '\0') {
1894 		if (dflag)
1895 			handle_stdin();
1896 		else
1897 			handle_stdout();
1898 		return;
1899 	}
1900 
1901 retry:
1902 	if (stat(path, &sb) != 0) {
1903 		/* lets try <path>.gz if we're decompressing */
1904 		if (dflag && s == NULL && errno == ENOENT) {
1905 			len = strlen(path);
1906 			slen = suffixes[0].ziplen;
1907 			s = malloc(len + slen + 1);
1908 			if (s == NULL)
1909 				maybe_err("malloc");
1910 			memcpy(s, path, len);
1911 			memcpy(s + len, suffixes[0].zipped, slen + 1);
1912 			path = s;
1913 			goto retry;
1914 		}
1915 		maybe_warn("can't stat: %s", opath);
1916 		goto out;
1917 	}
1918 
1919 	if (S_ISDIR(sb.st_mode)) {
1920 #ifndef SMALL
1921 		if (rflag)
1922 			handle_dir(path);
1923 		else
1924 #endif
1925 			maybe_warnx("%s is a directory", path);
1926 		goto out;
1927 	}
1928 
1929 	if (S_ISREG(sb.st_mode))
1930 		handle_file(path, &sb);
1931 	else
1932 		maybe_warnx("%s is not a regular file", path);
1933 
1934 out:
1935 	if (s)
1936 		free(s);
1937 }
1938 
1939 /* compress/decompress a file */
1940 static void
1941 handle_file(char *file, struct stat *sbp)
1942 {
1943 	off_t usize, gsize;
1944 	char	outfile[PATH_MAX];
1945 
1946 	infile_set(file, sbp->st_size);
1947 	if (dflag) {
1948 		usize = file_uncompress(file, outfile, sizeof(outfile));
1949 #ifndef SMALL
1950 		if (vflag && tflag)
1951 			print_test(file, usize != -1);
1952 #endif
1953 		if (usize == -1)
1954 			return;
1955 		gsize = sbp->st_size;
1956 	} else {
1957 		gsize = file_compress(file, outfile, sizeof(outfile));
1958 		if (gsize == -1)
1959 			return;
1960 		usize = sbp->st_size;
1961 	}
1962 	infile_clear();
1963 
1964 #ifndef SMALL
1965 	if (vflag && !tflag)
1966 		print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1967 #endif
1968 }
1969 
1970 #ifndef SMALL
1971 /* this is used with -r to recursively descend directories */
1972 static void
1973 handle_dir(char *dir)
1974 {
1975 	char *path_argv[2];
1976 	FTS *fts;
1977 	FTSENT *entry;
1978 
1979 	path_argv[0] = dir;
1980 	path_argv[1] = 0;
1981 	fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
1982 	if (fts == NULL) {
1983 		warn("couldn't fts_open %s", dir);
1984 		return;
1985 	}
1986 
1987 	while ((entry = fts_read(fts))) {
1988 		switch(entry->fts_info) {
1989 		case FTS_D:
1990 		case FTS_DP:
1991 			continue;
1992 
1993 		case FTS_DNR:
1994 		case FTS_ERR:
1995 		case FTS_NS:
1996 			maybe_warn("%s", entry->fts_path);
1997 			continue;
1998 		case FTS_F:
1999 			handle_file(entry->fts_name, entry->fts_statp);
2000 		}
2001 	}
2002 	(void)fts_close(fts);
2003 }
2004 #endif
2005 
2006 /* print a ratio - size reduction as a fraction of uncompressed size */
2007 static void
2008 print_ratio(off_t in, off_t out, FILE *where)
2009 {
2010 	int percent10;	/* 10 * percent */
2011 	off_t diff;
2012 	char buff[8];
2013 	int len;
2014 
2015 	diff = in - out/2;
2016 	if (in == 0 && out == 0)
2017 		percent10 = 0;
2018 	else if (diff < 0)
2019 		/*
2020 		 * Output is more than double size of input! print -99.9%
2021 		 * Quite possibly we've failed to get the original size.
2022 		 */
2023 		percent10 = -999;
2024 	else {
2025 		/*
2026 		 * We only need 12 bits of result from the final division,
2027 		 * so reduce the values until a 32bit division will suffice.
2028 		 */
2029 		while (in > 0x100000) {
2030 			diff >>= 1;
2031 			in >>= 1;
2032 		}
2033 		if (in != 0)
2034 			percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
2035 		else
2036 			percent10 = 0;
2037 	}
2038 
2039 	len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
2040 	/* Move the '.' to before the last digit */
2041 	buff[len - 1] = buff[len - 2];
2042 	buff[len - 2] = '.';
2043 	fprintf(where, "%5s%%", buff);
2044 }
2045 
2046 #ifndef SMALL
2047 /* print compression statistics, and the new name (if there is one!) */
2048 static void
2049 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
2050 {
2051 	if (file)
2052 		fprintf(stderr, "%s:%s  ", file,
2053 		    strlen(file) < 7 ? "\t\t" : "\t");
2054 	print_ratio(usize, gsize, stderr);
2055 	if (nfile)
2056 		fprintf(stderr, " -- replaced with %s", nfile);
2057 	fprintf(stderr, "\n");
2058 	fflush(stderr);
2059 }
2060 
2061 /* print test results */
2062 static void
2063 print_test(const char *file, int ok)
2064 {
2065 
2066 	if (exit_value == 0 && ok == 0)
2067 		exit_value = 1;
2068 	fprintf(stderr, "%s:%s  %s\n", file,
2069 	    strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2070 	fflush(stderr);
2071 }
2072 #endif
2073 
2074 /* print a file's info ala --list */
2075 /* eg:
2076   compressed uncompressed  ratio uncompressed_name
2077       354841      1679360  78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2078 */
2079 static void
2080 print_list(int fd, off_t out, const char *outfile, time_t ts)
2081 {
2082 	static int first = 1;
2083 #ifndef SMALL
2084 	static off_t in_tot, out_tot;
2085 	uint32_t crc = 0;
2086 #endif
2087 	off_t in = 0, rv;
2088 
2089 	if (first) {
2090 #ifndef SMALL
2091 		if (vflag)
2092 			printf("method  crc     date  time  ");
2093 #endif
2094 		if (qflag == 0)
2095 			printf("  compressed uncompressed  "
2096 			       "ratio uncompressed_name\n");
2097 	}
2098 	first = 0;
2099 
2100 	/* print totals? */
2101 #ifndef SMALL
2102 	if (fd == -1) {
2103 		in = in_tot;
2104 		out = out_tot;
2105 	} else
2106 #endif
2107 	{
2108 		/* read the last 4 bytes - this is the uncompressed size */
2109 		rv = lseek(fd, (off_t)(-8), SEEK_END);
2110 		if (rv != -1) {
2111 			unsigned char buf[8];
2112 			uint32_t usize;
2113 
2114 			rv = read(fd, (char *)buf, sizeof(buf));
2115 			if (rv == -1)
2116 				maybe_warn("read of uncompressed size");
2117 			else if (rv != sizeof(buf))
2118 				maybe_warnx("read of uncompressed size");
2119 
2120 			else {
2121 				usize = buf[4];
2122 				usize |= (unsigned int)buf[5] << 8;
2123 				usize |= (unsigned int)buf[6] << 16;
2124 				usize |= (unsigned int)buf[7] << 24;
2125 				in = (off_t)usize;
2126 #ifndef SMALL
2127 				crc = buf[0];
2128 				crc |= (unsigned int)buf[1] << 8;
2129 				crc |= (unsigned int)buf[2] << 16;
2130 				crc |= (unsigned int)buf[3] << 24;
2131 #endif
2132 			}
2133 		}
2134 	}
2135 
2136 #ifndef SMALL
2137 	if (vflag && fd == -1)
2138 		printf("                            ");
2139 	else if (vflag) {
2140 		char *date = ctime(&ts);
2141 
2142 		/* skip the day, 1/100th second, and year */
2143 		date += 4;
2144 		date[12] = 0;
2145 		printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2146 	}
2147 	in_tot += in;
2148 	out_tot += out;
2149 #endif
2150 	printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2151 	print_ratio(in, out, stdout);
2152 	printf(" %s\n", outfile);
2153 }
2154 
2155 /* display the usage of NetBSD gzip */
2156 static void
2157 usage(void)
2158 {
2159 
2160 	fprintf(stderr, "%s\n", gzip_version);
2161 	fprintf(stderr,
2162     "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n"
2163 #ifndef SMALL
2164     " -1 --fast            fastest (worst) compression\n"
2165     " -2 .. -8             set compression level\n"
2166     " -9 --best            best (slowest) compression\n"
2167     " -c --stdout          write to stdout, keep original files\n"
2168     "    --to-stdout\n"
2169     " -d --decompress      uncompress files\n"
2170     "    --uncompress\n"
2171     " -f --force           force overwriting & compress links\n"
2172     " -h --help            display this help\n"
2173     " -k --keep            don't delete input files during operation\n"
2174     " -l --list            list compressed file contents\n"
2175     " -N --name            save or restore original file name and time stamp\n"
2176     " -n --no-name         don't save original file name or time stamp\n"
2177     " -q --quiet           output no warnings\n"
2178     " -r --recursive       recursively compress files in directories\n"
2179     " -S .suf              use suffix .suf instead of .gz\n"
2180     "    --suffix .suf\n"
2181     " -t --test            test compressed file\n"
2182     " -V --version         display program version\n"
2183     " -v --verbose         print extra statistics\n",
2184 #else
2185     ,
2186 #endif
2187 	    getprogname());
2188 	exit(0);
2189 }
2190 
2191 /* display the version of NetBSD gzip */
2192 static void
2193 display_version(void)
2194 {
2195 
2196 	fprintf(stderr, "%s\n", gzip_version);
2197 	exit(0);
2198 }
2199 
2200 #ifndef NO_BZIP2_SUPPORT
2201 #include "unbzip2.c"
2202 #endif
2203 #ifndef NO_COMPRESS_SUPPORT
2204 #include "zuncompress.c"
2205 #endif
2206 #ifndef NO_PACK_SUPPORT
2207 #include "unpack.c"
2208 #endif
2209 #ifndef NO_XZ_SUPPORT
2210 #include "unxz.c"
2211 #endif
2212 
2213 static ssize_t
2214 read_retry(int fd, void *buf, size_t sz)
2215 {
2216 	char *cp = buf;
2217 	size_t left = MIN(sz, (size_t) SSIZE_MAX);
2218 
2219 	while (left > 0) {
2220 		ssize_t ret;
2221 
2222 		ret = read(fd, cp, left);
2223 		if (ret == -1) {
2224 			return ret;
2225 		} else if (ret == 0) {
2226 			break; /* EOF */
2227 		}
2228 		cp += ret;
2229 		left -= ret;
2230 	}
2231 
2232 	return sz - left;
2233 }
2234 
2235 static ssize_t
2236 write_retry(int fd, const void *buf, size_t sz)
2237 {
2238 	const char *cp = buf;
2239 	size_t left = MIN(sz, (size_t) SSIZE_MAX);
2240 
2241 	while (left > 0) {
2242 		ssize_t ret;
2243 
2244 		ret = write(fd, cp, left);
2245 		if (ret == -1) {
2246 			return ret;
2247 		} else if (ret == 0) {
2248 			abort();	/* Can't happen */
2249 		}
2250 		cp += ret;
2251 		left -= ret;
2252 	}
2253 
2254 	return sz - left;
2255 }
2256