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