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