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