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