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