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