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