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