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