xref: /netbsd-src/usr.bin/gzip/gzip.c (revision 5b84b3983f71fd20a534cfa5d1556623a8aaa717)
1 /*	$NetBSD: gzip.c,v 1.73 2005/08/28 10:17:50 mrg 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.73 2005/08/28 10:17:50 mrg 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 (in_tot > 0xffffffff)
641 		maybe_warn("input file size >= 4GB cannot be saved");
642 	if (write(out, outbufp, i) != i) {
643 		maybe_warn("write");
644 		in_tot = -1;
645 	} else
646 		out_tot += i;
647 
648 out:
649 	if (inbufp != NULL)
650 		free(inbufp);
651 	if (outbufp != NULL)
652 		free(outbufp);
653 	if (gsizep)
654 		*gsizep = out_tot;
655 	return in_tot;
656 }
657 
658 /*
659  * uncompress input to output then close the input.  return the
660  * uncompressed size written, and put the compressed sized read
661  * into `*gsizep'.
662  */
663 static off_t
664 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
665 	      const char *filename)
666 {
667 	z_stream z;
668 	char *outbufp, *inbufp;
669 	off_t out_tot = -1, in_tot = 0;
670 	uint32_t out_sub_tot = 0;
671 	enum {
672 		GZSTATE_MAGIC0,
673 		GZSTATE_MAGIC1,
674 		GZSTATE_METHOD,
675 		GZSTATE_FLAGS,
676 		GZSTATE_SKIPPING,
677 		GZSTATE_EXTRA,
678 		GZSTATE_EXTRA2,
679 		GZSTATE_EXTRA3,
680 		GZSTATE_ORIGNAME,
681 		GZSTATE_COMMENT,
682 		GZSTATE_HEAD_CRC1,
683 		GZSTATE_HEAD_CRC2,
684 		GZSTATE_INIT,
685 		GZSTATE_READ,
686 		GZSTATE_CRC,
687 		GZSTATE_LEN,
688 	} state = GZSTATE_MAGIC0;
689 	int flags = 0, skip_count = 0;
690 	int error = Z_STREAM_ERROR, done_reading = 0;
691 	uLong crc = 0;
692 	ssize_t wr;
693 	int needmore = 0;
694 
695 #define ADVANCE()       { z.next_in++; z.avail_in--; }
696 
697 	if ((outbufp = malloc(BUFLEN)) == NULL) {
698 		maybe_err("malloc failed");
699 		goto out2;
700 	}
701 	if ((inbufp = malloc(BUFLEN)) == NULL) {
702 		maybe_err("malloc failed");
703 		goto out1;
704 	}
705 
706 	memset(&z, 0, sizeof z);
707 	z.avail_in = prelen;
708 	z.next_in = pre;
709 	z.avail_out = BUFLEN;
710 	z.next_out = outbufp;
711 	z.zalloc = NULL;
712 	z.zfree = NULL;
713 	z.opaque = 0;
714 
715 	in_tot = prelen;
716 	out_tot = 0;
717 
718 	for (;;) {
719 		if ((z.avail_in == 0 || needmore) && done_reading == 0) {
720 			size_t in_size;
721 
722 			if (z.avail_in > 0) {
723 				memmove(inbufp, z.next_in, z.avail_in);
724 			}
725 			z.next_in = inbufp;
726 			in_size = read(in, z.next_in + z.avail_in,
727 			    BUFLEN - z.avail_in);
728 
729 			if (in_size == -1) {
730 #ifndef SMALL
731 				if (tflag && vflag)
732 					print_test(filename, 0);
733 #endif
734 				maybe_warn("failed to read stdin");
735 				goto stop_and_fail;
736 			} else if (in_size == 0) {
737 				done_reading = 1;
738 			}
739 
740 			z.avail_in += in_size;
741 			needmore = 0;
742 
743 			in_tot += in_size;
744 		}
745 		if (z.avail_in == 0) {
746 			if (done_reading && state != GZSTATE_MAGIC0)
747 				maybe_warnx("%s: unexpected end of file",
748 					    filename);
749 			goto stop;
750 		}
751 		switch (state) {
752 		case GZSTATE_MAGIC0:
753 			if (*z.next_in != GZIP_MAGIC0) {
754 				maybe_warnx("input not gziped (MAGIC0)");
755 				goto stop_and_fail;
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 				goto stop_and_fail;
768 			}
769 			ADVANCE();
770 			state++;
771 			break;
772 
773 		case GZSTATE_METHOD:
774 			if (*z.next_in != Z_DEFLATED) {
775 				maybe_warnx("unknown compression method");
776 				goto stop_and_fail;
777 			}
778 			ADVANCE();
779 			state++;
780 			break;
781 
782 		case GZSTATE_FLAGS:
783 			flags = *z.next_in;
784 			ADVANCE();
785 			skip_count = 6;
786 			state++;
787 			break;
788 
789 		case GZSTATE_SKIPPING:
790 			if (skip_count > 0) {
791 				skip_count--;
792 				ADVANCE();
793 			} else
794 				state++;
795 			break;
796 
797 		case GZSTATE_EXTRA:
798 			if ((flags & EXTRA_FIELD) == 0) {
799 				state = GZSTATE_ORIGNAME;
800 				break;
801 			}
802 			skip_count = *z.next_in;
803 			ADVANCE();
804 			state++;
805 			break;
806 
807 		case GZSTATE_EXTRA2:
808 			skip_count |= ((*z.next_in) << 8);
809 			ADVANCE();
810 			state++;
811 			break;
812 
813 		case GZSTATE_EXTRA3:
814 			if (skip_count > 0) {
815 				skip_count--;
816 				ADVANCE();
817 			} else
818 				state++;
819 			break;
820 
821 		case GZSTATE_ORIGNAME:
822 			if ((flags & ORIG_NAME) == 0) {
823 				state++;
824 				break;
825 			}
826 			if (*z.next_in == 0)
827 				state++;
828 			ADVANCE();
829 			break;
830 
831 		case GZSTATE_COMMENT:
832 			if ((flags & COMMENT) == 0) {
833 				state++;
834 				break;
835 			}
836 			if (*z.next_in == 0)
837 				state++;
838 			ADVANCE();
839 			break;
840 
841 		case GZSTATE_HEAD_CRC1:
842 			if (flags & HEAD_CRC)
843 				skip_count = 2;
844 			else
845 				skip_count = 0;
846 			state++;
847 			break;
848 
849 		case GZSTATE_HEAD_CRC2:
850 			if (skip_count > 0) {
851 				skip_count--;
852 				ADVANCE();
853 			} else
854 				state++;
855 			break;
856 
857 		case GZSTATE_INIT:
858 			if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
859 				maybe_warnx("failed to inflateInit");
860 				goto stop_and_fail;
861 			}
862 			state++;
863 			break;
864 
865 		case GZSTATE_READ:
866 			error = inflate(&z, Z_FINISH);
867 			switch (error) {
868 			/* Z_BUF_ERROR goes with Z_FINISH... */
869 			case Z_BUF_ERROR:
870 			case Z_STREAM_END:
871 			case Z_OK:
872 				break;
873 
874 			case Z_NEED_DICT:
875 				maybe_warnx("Z_NEED_DICT error");
876 				goto stop_and_fail;
877 			case Z_DATA_ERROR:
878 				maybe_warnx("data stream error");
879 				goto stop_and_fail;
880 			case Z_STREAM_ERROR:
881 				maybe_warnx("internal stream error");
882 				goto stop_and_fail;
883 			case Z_MEM_ERROR:
884 				maybe_warnx("memory allocation error");
885 				goto stop_and_fail;
886 
887 			default:
888 				maybe_warn("unknown error from inflate(): %d",
889 				    error);
890 			}
891 			wr = BUFLEN - z.avail_out;
892 
893 			if (wr != 0) {
894 				crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
895 				if (
896 #ifndef SMALL
897 				    /* don't write anything with -t */
898 				    tflag == 0 &&
899 #endif
900 				    write(out, outbufp, wr) != wr) {
901 					maybe_warn("error writing to output");
902 					goto stop_and_fail;
903 				}
904 
905 				out_tot += wr;
906 				out_sub_tot += wr;
907 			}
908 
909 			if (error == Z_STREAM_END) {
910 				inflateEnd(&z);
911 				state++;
912 			}
913 
914 			z.next_out = outbufp;
915 			z.avail_out = BUFLEN;
916 
917 			break;
918 		case GZSTATE_CRC:
919 			{
920 				uLong origcrc;
921 
922 				if (z.avail_in < 4) {
923 					if (!done_reading) {
924 						needmore = 1;
925 						continue;
926 					}
927 					maybe_warnx("truncated input");
928 					goto stop_and_fail;
929 				}
930 				origcrc = ((unsigned)z.next_in[0] & 0xff) |
931 					((unsigned)z.next_in[1] & 0xff) << 8 |
932 					((unsigned)z.next_in[2] & 0xff) << 16 |
933 					((unsigned)z.next_in[3] & 0xff) << 24;
934 				if (origcrc != crc) {
935 					maybe_warnx("invalid compressed"
936 					     " data--crc error");
937 					goto stop_and_fail;
938 				}
939 			}
940 
941 			z.avail_in -= 4;
942 			z.next_in += 4;
943 
944 			if (!z.avail_in && done_reading) {
945 				goto stop;
946 			}
947 			state++;
948 			break;
949 		case GZSTATE_LEN:
950 			{
951 				uLong origlen;
952 
953 				if (z.avail_in < 4) {
954 					if (!done_reading) {
955 						needmore = 1;
956 						continue;
957 					}
958 					maybe_warnx("truncated input");
959 					goto stop_and_fail;
960 				}
961 				origlen = ((unsigned)z.next_in[0] & 0xff) |
962 					((unsigned)z.next_in[1] & 0xff) << 8 |
963 					((unsigned)z.next_in[2] & 0xff) << 16 |
964 					((unsigned)z.next_in[3] & 0xff) << 24;
965 
966 				if (origlen != out_sub_tot) {
967 					maybe_warnx("invalid compressed"
968 					     " data--length error");
969 					goto stop_and_fail;
970 				}
971 			}
972 
973 			z.avail_in -= 4;
974 			z.next_in += 4;
975 
976 			if (error < 0) {
977 				maybe_warnx("decompression error");
978 				goto stop_and_fail;
979 			}
980 			state = GZSTATE_MAGIC0;
981 			break;
982 		}
983 		continue;
984 stop_and_fail:
985 		out_tot = 1;
986 stop:
987 		break;
988 	}
989 	if (state > GZSTATE_INIT)
990 		inflateEnd(&z);
991 
992 #ifndef SMALL
993 	if (tflag && vflag)
994 		print_test(filename, out_tot != -1);
995 #endif
996 
997 	free(inbufp);
998 out1:
999 	free(outbufp);
1000 out2:
1001 	if (gsizep)
1002 		*gsizep = in_tot;
1003 	return (out_tot);
1004 }
1005 
1006 #ifndef SMALL
1007 /*
1008  * set the owner, mode, flags & utimes for a file
1009  */
1010 static void
1011 copymodes(const char *file, struct stat *sbp)
1012 {
1013 	struct timeval times[2];
1014 
1015 	/*
1016 	 * If we have no info on the input, give this file some
1017 	 * default values and return..
1018 	 */
1019 	if (sbp == NULL) {
1020 		mode_t mask = umask(022);
1021 
1022 		(void)chmod(file, DEFFILEMODE & ~mask);
1023 		(void)umask(mask);
1024 		return;
1025 	}
1026 
1027 	/* if the chown fails, remove set-id bits as-per compress(1) */
1028 	if (chown(file, sbp->st_uid, sbp->st_gid) < 0) {
1029 		if (errno != EPERM)
1030 			maybe_warn("couldn't chown: %s", file);
1031 		sbp->st_mode &= ~(S_ISUID|S_ISGID);
1032 	}
1033 
1034 	/* we only allow set-id and the 9 normal permission bits */
1035 	sbp->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1036 	if (chmod(file, sbp->st_mode) < 0)
1037 		maybe_warn("couldn't chmod: %s", file);
1038 
1039 	/* only try flags if they exist already */
1040         if (sbp->st_flags != 0 && chflags(file, sbp->st_flags) < 0)
1041 		maybe_warn("couldn't chflags: %s", file);
1042 
1043 	TIMESPEC_TO_TIMEVAL(&times[0], &sbp->st_atimespec);
1044 	TIMESPEC_TO_TIMEVAL(&times[1], &sbp->st_mtimespec);
1045 	if (utimes(file, times) < 0)
1046 		maybe_warn("couldn't utimes: %s", file);
1047 }
1048 #endif
1049 
1050 /* what sort of file is this? */
1051 static enum filetype
1052 file_gettype(u_char *buf)
1053 {
1054 
1055 	if (buf[0] == GZIP_MAGIC0 &&
1056 	    (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1057 		return FT_GZIP;
1058 	else
1059 #ifndef NO_BZIP2_SUPPORT
1060 	if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1061 	    buf[3] >= '0' && buf[3] <= '9')
1062 		return FT_BZIP2;
1063 	else
1064 #endif
1065 #ifndef NO_COMPRESS_SUPPORT
1066 	if (memcmp(buf, Z_MAGIC, 2) == 0)
1067 		return FT_Z;
1068 	else
1069 #endif
1070 		return FT_UNKNOWN;
1071 }
1072 
1073 #ifndef SMALL
1074 /* check the outfile is OK. */
1075 static int
1076 check_outfile(const char *outfile, struct stat *sb)
1077 {
1078 	int ok = 1;
1079 
1080 	if (lflag == 0 && stat(outfile, sb) == 0) {
1081 		if (fflag)
1082 			unlink(outfile);
1083 		else if (isatty(STDIN_FILENO)) {
1084 			char ans[10] = { 'n', '\0' };	/* default */
1085 
1086 			fprintf(stderr, "%s already exists -- do you wish to "
1087 					"overwrite (y or n)? " , outfile);
1088 			(void)fgets(ans, sizeof(ans) - 1, stdin);
1089 			if (ans[0] != 'y' && ans[0] != 'Y') {
1090 				fprintf(stderr, "\tnot overwritting\n");
1091 				ok = 0;
1092 			} else
1093 				unlink(outfile);
1094 		} else {
1095 			maybe_warnx("%s already exists -- skipping", outfile);
1096 			ok = 0;
1097 		}
1098 	}
1099 	return ok;
1100 }
1101 
1102 static void
1103 unlink_input(const char *file, struct stat *sb)
1104 {
1105 	struct stat nsb;
1106 
1107 	if (stat(file, &nsb) != 0)
1108 		/* Must be gone alrady */
1109 		return;
1110 	if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1111 		/* Definitely a different file */
1112 		return;
1113 	unlink(file);
1114 }
1115 #endif
1116 
1117 static const suffixes_t *
1118 check_suffix(char *file, int xlate)
1119 {
1120 	const suffixes_t *s;
1121 	int len = strlen(file);
1122 	char *sp;
1123 
1124 	for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1125 		/* if it doesn't fit in "a.suf", don't bother */
1126 		if (s->ziplen >= len)
1127 			continue;
1128 		sp = file + len - s->ziplen;
1129 		if (strcmp(s->zipped, sp) != 0)
1130 			continue;
1131 		if (xlate)
1132 			strcpy(sp, s->normal);
1133 		return s;
1134 	}
1135 	return NULL;
1136 }
1137 
1138 /*
1139  * compress the given file: create a corresponding .gz file and remove the
1140  * original.
1141  */
1142 static off_t
1143 file_compress(char *file, char *outfile, size_t outsize)
1144 {
1145 	int in;
1146 	int out;
1147 	off_t size, insize;
1148 #ifndef SMALL
1149 	struct stat isb, osb;
1150 	const suffixes_t *suff;
1151 #endif
1152 
1153 	in = open(file, O_RDONLY);
1154 	if (in == -1) {
1155 		maybe_warn("can't open %s", file);
1156 		return -1;
1157 	}
1158 
1159 	if (cflag == 0) {
1160 #ifndef SMALL
1161 		if (stat(file, &isb) == 0) {
1162 			if (isb.st_nlink > 1 && fflag == 0) {
1163 				maybe_warnx("%s has %d other link%s -- "
1164 					    "skipping", file, isb.st_nlink - 1,
1165 					    isb.st_nlink == 1 ? "" : "s");
1166 				close(in);
1167 				return -1;
1168 			}
1169 		}
1170 
1171 		if (fflag == 0 && (suff = check_suffix(file, 0))
1172 		    && suff->zipped[0] != 0) {
1173 			maybe_warnx("%s already has %s suffix -- unchanged",
1174 				    file, suff->zipped);
1175 			close(in);
1176 			return -1;
1177 		}
1178 #endif
1179 
1180 		/* Add (usually) .gz to filename */
1181 		if (snprintf(outfile, outsize, "%s%s",
1182 					file, suffixes[0].zipped) >= outsize)
1183 			memcpy(outfile - suffixes[0].ziplen - 1,
1184 				suffixes[0].zipped, suffixes[0].ziplen + 1);
1185 
1186 #ifndef SMALL
1187 		if (check_outfile(outfile, &osb) == 0) {
1188 			close(in);
1189 			return -1;
1190 		}
1191 #endif
1192 	}
1193 
1194 	if (cflag == 0) {
1195 		out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1196 		if (out == -1) {
1197 			maybe_warn("could not create output: %s", outfile);
1198 			fclose(stdin);
1199 			return -1;
1200 		}
1201 	} else
1202 		out = STDOUT_FILENO;
1203 
1204 	insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1205 
1206 	(void)close(in);
1207 
1208 	/*
1209 	 * If there was an error, insize will be -1.
1210 	 * If we compressed to stdout, just return the size.
1211 	 * Otherwise stat the file and check it is the correct size.
1212 	 * We only blow away the file if we can stat the output and it
1213 	 * has the expected size.
1214 	 */
1215 	if (cflag != 0)
1216 		return insize == -1 ? -1 : size;
1217 
1218 	if (close(out) == -1)
1219 		maybe_warn("couldn't close ouput");
1220 
1221 #ifndef SMALL
1222 	if (stat(outfile, &osb) != 0) {
1223 		maybe_warn("couldn't stat: %s", outfile);
1224 		goto bad_outfile;
1225 	}
1226 
1227 	if (osb.st_size != size) {
1228 		maybe_warnx("output file: %s wrong size (%" PRIdOFF
1229 				" != %" PRIdOFF "), deleting",
1230 				outfile, osb.st_size, size);
1231 		goto bad_outfile;
1232 	}
1233 
1234 	copymodes(outfile, &isb);
1235 #endif
1236 
1237 	/* output is good, ok to delete input */
1238 	unlink_input(file, &isb);
1239 	return size;
1240 
1241 #ifndef SMALL
1242     bad_outfile:
1243 	maybe_warnx("leaving original %s", file);
1244 	unlink(outfile);
1245 	return size;
1246 #endif
1247 }
1248 
1249 /* uncompress the given file and remove the original */
1250 static off_t
1251 file_uncompress(char *file, char *outfile, size_t outsize)
1252 {
1253 	struct stat isb, osb;
1254 	off_t size;
1255 	ssize_t rbytes;
1256 	unsigned char header1[4];
1257 	enum filetype method;
1258 	int fd, zfd = -1;
1259 #ifndef SMALL
1260 	time_t timestamp = 0;
1261 	unsigned char name[PATH_MAX + 1];
1262 #endif
1263 
1264 	/* gather the old name info */
1265 
1266 	fd = open(file, O_RDONLY);
1267 	if (fd < 0) {
1268 		maybe_warn("can't open %s", file);
1269 		goto lose;
1270 	}
1271 
1272 	strlcpy(outfile, file, outsize);
1273 	if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1274 		maybe_warnx("%s: unknown suffix -- ignored", file);
1275 		goto lose;
1276 	}
1277 
1278 	rbytes = read(fd, header1, sizeof header1);
1279 	if (rbytes != sizeof header1) {
1280 		/* we don't want to fail here. */
1281 #ifndef SMALL
1282 		if (fflag)
1283 			goto lose;
1284 #endif
1285 		if (rbytes == -1)
1286 			maybe_warn("can't read %s", file);
1287 		else
1288 			maybe_warnx("%s: unexpected end of file", file);
1289 		goto lose;
1290 	}
1291 
1292 	method = file_gettype(header1);
1293 
1294 #ifndef SMALL
1295 	if (fflag == 0 && method == FT_UNKNOWN) {
1296 		maybe_warnx("%s: not in gzip format", file);
1297 		goto lose;
1298 	}
1299 
1300 #endif
1301 
1302 #ifndef SMALL
1303 	if (method == FT_GZIP && Nflag) {
1304 		unsigned char ts[4];	/* timestamp */
1305 
1306 		if (pread(fd, ts, sizeof ts, GZIP_TIMESTAMP) != sizeof ts) {
1307 			if (!fflag)
1308 				maybe_warn("can't read %s", file);
1309 			goto lose;
1310 		}
1311 		timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1312 
1313 		if (header1[3] & ORIG_NAME) {
1314 			rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1315 			if (rbytes < 0) {
1316 				maybe_warn("can't read %s", file);
1317 				goto lose;
1318 			}
1319 			if (name[0] != 0) {
1320 				/* preserve original directory name */
1321 				char *dp = strrchr(file, '/');
1322 				if (dp == NULL)
1323 					dp = file;
1324 				else
1325 					dp++;
1326 				snprintf(outfile, outsize, "%.*s%.*s",
1327 						(int) (dp - file),
1328 						file, (int) rbytes, name);
1329 			}
1330 		}
1331 	}
1332 #endif
1333 	lseek(fd, 0, SEEK_SET);
1334 
1335 	if (cflag == 0 || lflag) {
1336 		if (fstat(fd, &isb) != 0)
1337 			goto lose;
1338 #ifndef SMALL
1339 		if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1340 			maybe_warnx("%s has %d other links -- skipping",
1341 			    file, isb.st_nlink - 1);
1342 			goto lose;
1343 		}
1344 		if (nflag == 0 && timestamp)
1345 			isb.st_mtime = timestamp;
1346 		if (check_outfile(outfile, &osb) == 0)
1347 			goto lose;
1348 #endif
1349 	}
1350 
1351 	if (cflag == 0 && lflag == 0) {
1352 		zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1353 		if (zfd == STDOUT_FILENO) {
1354 			/* We won't close STDOUT_FILENO later... */
1355 			zfd = dup(zfd);
1356 			close(STDOUT_FILENO);
1357 		}
1358 		if (zfd == -1) {
1359 			maybe_warn("can't open %s", outfile);
1360 			goto lose;
1361 		}
1362 	} else
1363 		zfd = STDOUT_FILENO;
1364 
1365 #ifndef NO_BZIP2_SUPPORT
1366 	if (method == FT_BZIP2) {
1367 
1368 		/* XXX */
1369 		if (lflag) {
1370 			maybe_warnx("no -l with bzip2 files");
1371 			goto lose;
1372 		}
1373 
1374 		size = unbzip2(fd, zfd, NULL, 0, NULL);
1375 	} else
1376 #endif
1377 
1378 #ifndef NO_COMPRESS_SUPPORT
1379 	if (method == FT_Z) {
1380 		FILE *in, *out;
1381 
1382 		/* XXX */
1383 		if (lflag) {
1384 			maybe_warnx("no -l with Lempel-Ziv files");
1385 			goto lose;
1386 		}
1387 
1388 		if ((in = zdopen(fd)) == NULL) {
1389 			maybe_warn("zdopen for read: %s", file);
1390 			goto lose;
1391 		}
1392 
1393 		out = fdopen(dup(zfd), "w");
1394 		if (out == NULL) {
1395 			maybe_warn("fdopen for write: %s", outfile);
1396 			fclose(in);
1397 			goto lose;
1398 		}
1399 
1400 		size = zuncompress(in, out, NULL, 0, NULL);
1401 		/* need to fclose() if ferror() is true... */
1402 		if (ferror(in) | fclose(in)) {
1403 			maybe_warn("failed infile fclose");
1404 			unlink(outfile);
1405 			(void)fclose(out);
1406 		}
1407 		if (fclose(out) != 0) {
1408 			maybe_warn("failed outfile fclose");
1409 			unlink(outfile);
1410 			goto lose;
1411 		}
1412 	} else
1413 #endif
1414 
1415 #ifndef SMALL
1416 	if (method == FT_UNKNOWN) {
1417 		if (lflag) {
1418 			maybe_warnx("no -l for unknown filetypes");
1419 			goto lose;
1420 		}
1421 		size = cat_fd(NULL, 0, NULL, fd);
1422 	} else
1423 #endif
1424 	{
1425 		if (lflag) {
1426 			print_list(fd, isb.st_size, outfile, isb.st_mtime);
1427 			close(fd);
1428 			return -1;	/* XXX */
1429 		}
1430 
1431 		size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1432 	}
1433 
1434 	if (close(fd) != 0)
1435 		maybe_warn("couldn't close input");
1436 	if (zfd != STDOUT_FILENO && close(zfd) != 0)
1437 		maybe_warn("couldn't close output");
1438 
1439 	if (size == -1) {
1440 		if (cflag == 0)
1441 			unlink(outfile);
1442 		maybe_warnx("%s: uncompress failed", file);
1443 		return -1;
1444 	}
1445 
1446 	/* if testing, or we uncompressed to stdout, this is all we need */
1447 #ifndef SMALL
1448 	if (tflag)
1449 		return size;
1450 #endif
1451 	/* if we are uncompressing to stdin, don't remove the file. */
1452 	if (cflag)
1453 		return size;
1454 
1455 	/*
1456 	 * if we create a file...
1457 	 */
1458 	/*
1459 	 * if we can't stat the file don't remove the file.
1460 	 */
1461 	if (stat(outfile, &osb) != 0) {
1462 		maybe_warn("couldn't stat (leaving original): %s",
1463 			   outfile);
1464 		return -1;
1465 	}
1466 	if (osb.st_size != size) {
1467 		maybe_warnx("stat gave different size: %" PRIdOFF
1468 				" != %" PRIdOFF " (leaving original)",
1469 				size, osb.st_size);
1470 		unlink(outfile);
1471 		return -1;
1472 	}
1473 	unlink_input(file, &isb);
1474 #ifndef SMALL
1475 	copymodes(outfile, &isb);
1476 #endif
1477 	return size;
1478 
1479     lose:
1480 	if (fd != -1)
1481 		close(fd);
1482 	if (zfd != -1 && zfd != STDOUT_FILENO)
1483 		close(fd);
1484 	return -1;
1485 }
1486 
1487 #ifndef SMALL
1488 static off_t
1489 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1490 {
1491 	char buf[BUFLEN];
1492 	size_t rv;
1493 	off_t in_tot;
1494 
1495 	in_tot = count;
1496 	if (write(STDOUT_FILENO, prepend, count) != count) {
1497 		maybe_warn("write to stdout");
1498 		return -1;
1499 	}
1500 	for (;;) {
1501 		rv = read(fd, buf, sizeof buf);
1502 		if (rv == 0)
1503 			break;
1504 		if (rv < 0) {
1505 			maybe_warn("read from fd %d", fd);
1506 			break;
1507 		}
1508 
1509 		if (write(STDOUT_FILENO, buf, rv) != rv) {
1510 			maybe_warn("write to stdout");
1511 			break;
1512 		}
1513 		in_tot += rv;
1514 	}
1515 
1516 	if (gsizep)
1517 		*gsizep = in_tot;
1518 	return (in_tot);
1519 }
1520 #endif
1521 
1522 static void
1523 handle_stdin(void)
1524 {
1525 	unsigned char header1[4];
1526 	off_t usize, gsize;
1527 	enum filetype method;
1528 	ssize_t bytes_read;
1529 #ifndef NO_COMPRESS_SUPPORT
1530 	FILE *in;
1531 #endif
1532 
1533 #ifndef SMALL
1534 	if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1535 		maybe_warnx("standard input is a terminal -- ignoring");
1536 		return;
1537 	}
1538 #endif
1539 
1540 	if (lflag) {
1541 		struct stat isb;
1542 
1543 		/* XXX could read the whole file, etc. */
1544 		if (fstat(STDIN_FILENO, &isb) < 0) {
1545 			maybe_warn("fstat");
1546 			return;
1547 		}
1548 		print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1549 		return;
1550 	}
1551 
1552 	bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1553 	if (bytes_read == -1) {
1554 		maybe_warn("can't read stdin");
1555 		return;
1556 	} else if (bytes_read != sizeof(header1)) {
1557 		maybe_warnx("unexpected EOF");
1558 		return;
1559 	}
1560 
1561 	method = file_gettype(header1);
1562 	switch (method) {
1563 	default:
1564 #ifndef SMALL
1565 		if (fflag == 0) {
1566 			maybe_warnx("unknown compression format");
1567 			return;
1568 		}
1569 		usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1570 		break;
1571 #endif
1572 	case FT_GZIP:
1573 		usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1574 			      header1, sizeof header1, &gsize, "(stdin)");
1575 		break;
1576 #ifndef NO_BZIP2_SUPPORT
1577 	case FT_BZIP2:
1578 		usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1579 				header1, sizeof header1, &gsize);
1580 		break;
1581 #endif
1582 #ifndef NO_COMPRESS_SUPPORT
1583 	case FT_Z:
1584 		if ((in = zdopen(STDIN_FILENO)) == NULL) {
1585 			maybe_warnx("zopen of stdin");
1586 			return;
1587 		}
1588 
1589 		usize = zuncompress(in, stdout, header1, sizeof header1, &gsize);
1590 		fclose(in);
1591 		break;
1592 #endif
1593 	}
1594 
1595 #ifndef SMALL
1596         if (vflag && !tflag && usize != -1 && gsize != -1)
1597 		print_verbage(NULL, NULL, usize, gsize);
1598 #endif
1599 
1600 }
1601 
1602 static void
1603 handle_stdout(void)
1604 {
1605 	off_t gsize, usize;
1606 	struct stat sb;
1607 	time_t systime;
1608 	uint32_t mtime;
1609 	int ret;
1610 
1611 #ifndef SMALL
1612 	if (fflag == 0 && isatty(STDOUT_FILENO)) {
1613 		maybe_warnx("standard output is a terminal -- ignoring");
1614 		return;
1615 	}
1616 #endif
1617 	/* If stdin is a file use it's mtime, otherwise use current time */
1618 	ret = fstat(STDIN_FILENO, &sb);
1619 
1620 #ifndef SMALL
1621 	if (ret < 0) {
1622 		maybe_warn("Can't stat stdin");
1623 		return;
1624 	}
1625 #endif
1626 
1627 	if (S_ISREG(sb.st_mode))
1628 		mtime = (uint32_t)sb.st_mtime;
1629 	else {
1630 		systime = time(NULL);
1631 #ifndef SMALL
1632 		if (systime == -1) {
1633 			maybe_warn("time");
1634 			return;
1635 		}
1636 #endif
1637 		mtime = (uint32_t)systime;
1638 	}
1639 
1640 	usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1641 #ifndef SMALL
1642         if (vflag && !tflag && usize != -1 && gsize != -1)
1643 		print_verbage(NULL, NULL, usize, gsize);
1644 #endif
1645 }
1646 
1647 /* do what is asked for, for the path name */
1648 static void
1649 handle_pathname(char *path)
1650 {
1651 	char *opath = path, *s = NULL;
1652 	ssize_t len;
1653 	int slen;
1654 	struct stat sb;
1655 
1656 	/* check for stdout/stdin */
1657 	if (path[0] == '-' && path[1] == '\0') {
1658 		if (dflag)
1659 			handle_stdin();
1660 		else
1661 			handle_stdout();
1662 		return;
1663 	}
1664 
1665 retry:
1666 	if (stat(path, &sb) != 0) {
1667 		/* lets try <path>.gz if we're decompressing */
1668 		if (dflag && s == NULL && errno == ENOENT) {
1669 			len = strlen(path);
1670 			slen = suffixes[0].ziplen;
1671 			s = malloc(len + slen + 1);
1672 			if (s == NULL)
1673 				maybe_err("malloc");
1674 			memcpy(s, path, len);
1675 			memcpy(s + len, suffixes[0].zipped, slen + 1);
1676 			path = s;
1677 			goto retry;
1678 		}
1679 		maybe_warn("can't stat: %s", opath);
1680 		goto out;
1681 	}
1682 
1683 	if (S_ISDIR(sb.st_mode)) {
1684 #ifndef SMALL
1685 		if (rflag)
1686 			handle_dir(path, &sb);
1687 		else
1688 #endif
1689 			maybe_warnx("%s is a directory", path);
1690 		goto out;
1691 	}
1692 
1693 	if (S_ISREG(sb.st_mode))
1694 		handle_file(path, &sb);
1695 	else
1696 		maybe_warnx("%s is not a regular file", path);
1697 
1698 out:
1699 	if (s)
1700 		free(s);
1701 }
1702 
1703 /* compress/decompress a file */
1704 static void
1705 handle_file(char *file, struct stat *sbp)
1706 {
1707 	off_t usize, gsize;
1708 	char	outfile[PATH_MAX];
1709 
1710 	infile = file;
1711 	if (dflag) {
1712 		usize = file_uncompress(file, outfile, sizeof(outfile));
1713 		if (usize == -1)
1714 			return;
1715 		gsize = sbp->st_size;
1716 	} else {
1717 		gsize = file_compress(file, outfile, sizeof(outfile));
1718 		if (gsize == -1)
1719 			return;
1720 		usize = sbp->st_size;
1721 	}
1722 
1723 
1724 #ifndef SMALL
1725 	if (vflag && !tflag)
1726 		print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1727 #endif
1728 }
1729 
1730 #ifndef SMALL
1731 /* this is used with -r to recursively descend directories */
1732 static void
1733 handle_dir(char *dir, struct stat *sbp)
1734 {
1735 	char *path_argv[2];
1736 	FTS *fts;
1737 	FTSENT *entry;
1738 
1739 	path_argv[0] = dir;
1740 	path_argv[1] = 0;
1741 	fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
1742 	if (fts == NULL) {
1743 		warn("couldn't fts_open %s", dir);
1744 		return;
1745 	}
1746 
1747 	while ((entry = fts_read(fts))) {
1748 		switch(entry->fts_info) {
1749 		case FTS_D:
1750 		case FTS_DP:
1751 			continue;
1752 
1753 		case FTS_DNR:
1754 		case FTS_ERR:
1755 		case FTS_NS:
1756 			maybe_warn("%s", entry->fts_path);
1757 			continue;
1758 		case FTS_F:
1759 			handle_file(entry->fts_name, entry->fts_statp);
1760 		}
1761 	}
1762 	(void)fts_close(fts);
1763 }
1764 #endif
1765 
1766 /* print a ratio - size reduction as a fraction of uncompressed size */
1767 static void
1768 print_ratio(off_t in, off_t out, FILE *where)
1769 {
1770 	int percent10;	/* 10 * percent */
1771 	off_t diff;
1772 	char buff[8];
1773 	int len;
1774 
1775 	diff = in - out/2;
1776 	if (diff <= 0)
1777 		/*
1778 		 * Output is more than double size of input! print -99.9%
1779 		 * Quite possibly we've failed to get the original size.
1780 		 */
1781 		percent10 = -999;
1782 	else {
1783 		/*
1784 		 * We only need 12 bits of result from the final division,
1785 		 * so reduce the values until a 32bit division will suffice.
1786 		 */
1787 		while (in > 0x100000) {
1788 			diff >>= 1;
1789 			in >>= 1;
1790 		}
1791 		if (in != 0)
1792 			percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1793 		else
1794 			percent10 = 0;
1795 	}
1796 
1797 	len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1798 	/* Move the '.' to before the last digit */
1799 	buff[len - 1] = buff[len - 2];
1800 	buff[len - 2] = '.';
1801 	fprintf(where, "%5s%%", buff);
1802 }
1803 
1804 #ifndef SMALL
1805 /* print compression statistics, and the new name (if there is one!) */
1806 static void
1807 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1808 {
1809 	if (file)
1810 		fprintf(stderr, "%s:%s  ", file,
1811 		    strlen(file) < 7 ? "\t\t" : "\t");
1812 	print_ratio(usize, gsize, stderr);
1813 	if (nfile)
1814 		fprintf(stderr, " -- replaced with %s", nfile);
1815 	fprintf(stderr, "\n");
1816 	fflush(stderr);
1817 }
1818 
1819 /* print test results */
1820 static void
1821 print_test(const char *file, int ok)
1822 {
1823 
1824 	if (exit_value == 0 && ok == 0)
1825 		exit_value = 1;
1826 	fprintf(stderr, "%s:%s  %s\n", file,
1827 	    strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1828 	fflush(stderr);
1829 }
1830 #endif
1831 
1832 /* print a file's info ala --list */
1833 /* eg:
1834   compressed uncompressed  ratio uncompressed_name
1835       354841      1679360  78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1836 */
1837 static void
1838 print_list(int fd, off_t out, const char *outfile, time_t ts)
1839 {
1840 	static int first = 1;
1841 #ifndef SMALL
1842 	static off_t in_tot, out_tot;
1843 	uint32_t crc = 0;
1844 #endif
1845 	off_t in = 0;
1846 	int rv;
1847 
1848 	if (first) {
1849 #ifndef SMALL
1850 		if (vflag)
1851 			printf("method  crc     date  time  ");
1852 #endif
1853 		if (qflag == 0)
1854 			printf("  compressed uncompressed  "
1855 			       "ratio uncompressed_name\n");
1856 	}
1857 	first = 0;
1858 
1859 	/* print totals? */
1860 #ifndef SMALL
1861 	if (fd == -1) {
1862 		in = in_tot;
1863 		out = out_tot;
1864 	} else
1865 #endif
1866 	{
1867 		/* read the last 4 bytes - this is the uncompressed size */
1868 		rv = lseek(fd, (off_t)(-8), SEEK_END);
1869 		if (rv != -1) {
1870 			unsigned char buf[8];
1871 			uint32_t usize;
1872 
1873 			if (read(fd, (char *)buf, sizeof(buf)) != sizeof(buf))
1874 				maybe_warn("read of uncompressed size");
1875 			usize = buf[4] | buf[5] << 8 | buf[6] << 16 | buf[7] << 24;
1876 			in = (off_t)usize;
1877 #ifndef SMALL
1878 			crc = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;
1879 #endif
1880 		}
1881 	}
1882 
1883 #ifndef SMALL
1884 	if (vflag && fd == -1)
1885 		printf("                            ");
1886 	else if (vflag) {
1887 		char *date = ctime(&ts);
1888 
1889 		/* skip the day, 1/100th second, and year */
1890 		date += 4;
1891 		date[12] = 0;
1892 		printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
1893 	}
1894 	in_tot += in;
1895 	out_tot += out;
1896 #endif
1897 	printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
1898 	print_ratio(in, out, stdout);
1899 	printf(" %s\n", outfile);
1900 }
1901 
1902 /* display the usage of NetBSD gzip */
1903 static void
1904 usage(void)
1905 {
1906 
1907 	fprintf(stderr, "%s\n", gzip_version);
1908 	fprintf(stderr,
1909     "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n"
1910 #ifndef SMALL
1911     " -c --stdout          write to stdout, keep original files\n"
1912     "    --to-stdout\n"
1913     " -d --decompress      uncompress files\n"
1914     "    --uncompress\n"
1915     " -f --force           force overwriting & compress links\n"
1916     " -h --help            display this help\n"
1917     " -n --no-name         don't save original file name or time stamp\n"
1918     " -N --name            save or restore original file name and time stamp\n"
1919     " -q --quiet           output no warnings\n"
1920     " -r --recursive       recursively compress files in directories\n"
1921     " -S .suf              use suffix .suf instead of .gz\n"
1922     "    --suffix .suf\n"
1923     " -t --test            test compressed file\n"
1924     " -v --verbose         print extra statistics\n"
1925     " -V --version         display program version\n"
1926     " -1 --fast            fastest (worst) compression\n"
1927     " -2 .. -8             set compression level\n"
1928     " -9 --best            best (slowest) compression\n",
1929 #else
1930     ,
1931 #endif
1932 	    getprogname());
1933 	exit(0);
1934 }
1935 
1936 /* display the version of NetBSD gzip */
1937 static void
1938 display_version(void)
1939 {
1940 
1941 	fprintf(stderr, "%s\n", gzip_version);
1942 	exit(0);
1943 }
1944 
1945 #ifndef NO_BZIP2_SUPPORT
1946 #include "unbzip2.c"
1947 #endif
1948 #ifndef NO_COMPRESS_SUPPORT
1949 #include "zuncompress.c"
1950 #endif
1951 
1952 static ssize_t
1953 read_retry(int fd, void *buf, size_t sz)
1954 {
1955 	char *cp = buf;
1956 	ssize_t left = sz;
1957 
1958 	while (left > 0) {
1959 		ssize_t ret;
1960 
1961 		ret = read(fd, cp, sz);
1962 		if (ret == -1) {
1963 			return ret;
1964 		} else if (ret == 0) {
1965 			break; /* EOF */
1966 		}
1967 		cp += ret;
1968 		left -= ret;
1969 	}
1970 
1971 	return sz - left;
1972 }
1973