Home | History | Annotate | Line # | Download | only in gzip
gzip.c revision 1.13
      1 /*	$NetBSD: gzip.c,v 1.13 2004/01/02 01:34:01 mrg Exp $	*/
      2 
      3 /*
      4  * Copyright (c) 1997, 1998, 2003 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 Matthew R. Green\n\
     34      All rights reserved.\n");
     35 __RCSID("$NetBSD: gzip.c,v 1.13 2004/01/02 01:34:01 mrg Exp $");
     36 #endif /* not lint */
     37 
     38 /*
     39  * gzip.c -- GPL free gzip using zlib.
     40  *
     41  * very minor portions of this code are (very loosely) derived from
     42  * the minigzip.c in the zlib distribution.
     43  *
     44  * TODO:
     45  *	- handle .taz/.tgz files?
     46  *	- use mmap where possible
     47  */
     48 
     49 #include <sys/param.h>
     50 #include <sys/stat.h>
     51 #include <sys/time.h>
     52 
     53 #include <unistd.h>
     54 #include <stdio.h>
     55 #include <string.h>
     56 #include <stdlib.h>
     57 #include <err.h>
     58 #include <errno.h>
     59 #include <fcntl.h>
     60 #include <zlib.h>
     61 #include <fts.h>
     62 #include <libgen.h>
     63 #include <stdarg.h>
     64 #include <getopt.h>
     65 
     66 /* what type of file are we dealing with */
     67 enum filetype {
     68 	FT_GZIP,
     69 	FT_BZIP2,
     70 	FT_LAST,
     71 	FT_UNKNOWN
     72 };
     73 
     74 #define BZ_NO_STDIO
     75 #include <bzlib.h>
     76 
     77 #define BZ2_SUFFIX	".bz2"
     78 #define BZIP2_MAGIC	"\102\132\150"
     79 
     80 #define GZ_SUFFIX	".gz"
     81 
     82 #define BUFLEN		(32 * 1024)
     83 
     84 #define GZIP_MAGIC0	0x1F
     85 #define GZIP_MAGIC1	0x8B
     86 #define GZIP_OMAGIC1	0x9E
     87 
     88 #define ORIG_NAME 	0x08
     89 
     90 /* Define this if you have the NetBSD gzopenfull(3) extension to zlib(3) */
     91 #ifndef HAVE_ZLIB_GZOPENFULL
     92 #define HAVE_ZLIB_GZOPENFULL 0
     93 #endif
     94 
     95 static	const char	gzip_version[] = "NetBSD gzip 2.1";
     96 
     97 static	char	gzipflags[3];		/* `w' or `r', possible with [1-9] */
     98 static	int	cflag;			/* stdout mode */
     99 static	int	dflag;			/* decompress mode */
    100 static	int	fflag;			/* force mode */
    101 static	int	lflag;			/* list mode */
    102 static	int	nflag;			/* don't save name/timestamp */
    103 static	int	Nflag;			/* don't restore name/timestamp */
    104 static	int	qflag;			/* quiet mode */
    105 static	int	rflag;			/* recursive mode */
    106 static	int	tflag;			/* test */
    107 static	int	vflag;			/* verbose mode */
    108 static	char	*Sflag;
    109 static	char	*suffix;
    110 
    111 #define suffix_len	(strlen(suffix) + 1)	/* len + nul */
    112 static	char	*newfile;		/* name of newly created file */
    113 static	char	*infile;		/* name of file coming in */
    114 
    115 static	void	maybe_err(int rv, const char *fmt, ...);
    116 static	void	maybe_errx(int rv, const char *fmt, ...);
    117 static	void	maybe_warn(const char *fmt, ...);
    118 static	void	maybe_warnx(const char *fmt, ...);
    119 static	void	gz_compress(FILE *, gzFile);
    120 static	off_t	gz_uncompress(gzFile, FILE *);
    121 static	void	copymodes(const char *, struct stat *);
    122 static	ssize_t	file_compress(char *);
    123 static	ssize_t	file_uncompress(char *);
    124 static	void	handle_pathname(char *);
    125 static	void	handle_file(char *, struct stat *);
    126 static	void	handle_dir(char *, struct stat *);
    127 static	void	handle_stdin(void);
    128 static	void	handle_stdout(void);
    129 static	void	print_ratio(off_t, off_t, FILE *);
    130 static	void	print_verbage(char *, char *, ssize_t, ssize_t);
    131 static	void	print_test(char *, int);
    132 static	void	print_list(int fd, off_t, const char *, time_t);
    133 static	void	usage(void);
    134 static	void	display_version(void);
    135 static	off_t	unbzip2(int, int);
    136 
    137 int main(int, char *p[]);
    138 
    139 #ifdef SMALL
    140 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
    141 #else
    142 static const struct option longopts[] = {
    143 	{ "stdout",		no_argument,		0,	'c' },
    144 	{ "to-stdout",		no_argument,		0,	'c' },
    145 	{ "decompress",		no_argument,		0,	'd' },
    146 	{ "uncompress",		no_argument,		0,	'd' },
    147 	{ "force",		no_argument,		0,	'f' },
    148 	{ "help",		no_argument,		0,	'h' },
    149 	{ "list",		no_argument,		0,	'l' },
    150 	{ "no-name",		no_argument,		0,	'n' },
    151 	{ "name",		no_argument,		0,	'N' },
    152 	{ "quiet",		no_argument,		0,	'q' },
    153 	{ "recursive",		no_argument,		0,	'r' },
    154 	{ "suffix",		required_argument,	0,	'S' },
    155 	{ "test",		no_argument,		0,	't' },
    156 	{ "verbose",		no_argument,		0,	'v' },
    157 	{ "version",		no_argument,		0,	'V' },
    158 	{ "fast",		no_argument,		0,	'1' },
    159 	{ "best",		no_argument,		0,	'9' },
    160 #if 0
    161 	/*
    162 	 * This is what else GNU gzip implements.  --ascii isn't useful
    163 	 * on NetBSD, and I don't care to have a --license.
    164 	 */
    165 	{ "ascii",		no_argument,		0,	'a' },
    166 	{ "license",		no_argument,		0,	'L' },
    167 #endif
    168 	{ NULL,			no_argument,		0,	0 },
    169 };
    170 #endif
    171 
    172 int
    173 main(int argc, char **argv)
    174 {
    175 	const char *progname = getprogname();
    176 	int ch;
    177 
    178 	gzipflags[0] = 'w';
    179 	gzipflags[1] = '\0';
    180 
    181 	suffix = GZ_SUFFIX;;
    182 
    183 	/*
    184 	 * XXX
    185 	 * handle being called `gunzip', `zcat' and `gzcat'
    186 	 */
    187 	if (strcmp(progname, "gunzip") == 0)
    188 		dflag = 1;
    189 	else if (strcmp(progname, "zcat") == 0 ||
    190 		 strcmp(progname, "gzcat") == 0)
    191 		dflag = cflag = 1;
    192 
    193 	while ((ch = getopt_long(argc, argv, "cdfhHlnNqrS:tvV123456789",
    194 				 longopts, NULL)) != -1)
    195 		switch (ch) {
    196 		case 'c':
    197 			cflag = 1;
    198 			break;
    199 		case 'd':
    200 			dflag = 1;
    201 			break;
    202 		case 'f':
    203 			fflag = 1;
    204 			break;
    205 		case 'l':
    206 			lflag = 1;
    207 			tflag = 1;
    208 			dflag = 1;
    209 			break;
    210 		case 'n':
    211 			nflag = 1;
    212 			Nflag = 0;
    213 			break;
    214 		case 'N':
    215 			nflag = 0;
    216 			Nflag = 1;
    217 			break;
    218 		case 'q':
    219 			qflag = 1;
    220 			break;
    221 		case 'r':
    222 			rflag = 1;
    223 			break;
    224 		case 'S':
    225 			Sflag = optarg;
    226 			break;
    227 		case 't':
    228 			cflag = 1;
    229 			tflag = 1;
    230 			dflag = 1;
    231 			break;
    232 		case 'v':
    233 			vflag = 1;
    234 			break;
    235 		case 'V':
    236 			display_version();
    237 			/* NOTREACHED */
    238 		case '1': case '2': case '3':
    239 		case '4': case '5': case '6':
    240 		case '7': case '8': case '9':
    241 			gzipflags[1] = (char)ch;
    242 			gzipflags[2] = '\0';
    243 			break;
    244 		default:
    245 			usage();
    246 			/* NOTREACHED */
    247 		}
    248 	argv += optind;
    249 	argc -= optind;
    250 	if (dflag)
    251 		gzipflags[0] = 'r';
    252 
    253 	if (argc == 0) {
    254 		if (dflag)	/* stdin mode */
    255 			handle_stdin();
    256 		else		/* stdout mode */
    257 			handle_stdout();
    258 	} else {
    259 		do {
    260 			handle_pathname(argv[0]);
    261 		} while (*++argv);
    262 	}
    263 	if (qflag == 0 && lflag && argc > 1)
    264 		print_list(-1, 0, "(totals)", 0);
    265 	exit(0);
    266 }
    267 
    268 /* maybe print a warning */
    269 void
    270 maybe_warn(const char *fmt, ...)
    271 {
    272 	va_list ap;
    273 
    274 	if (qflag == 0) {
    275 		va_start(ap, fmt);
    276 		vwarn(fmt, ap);
    277 		va_end(ap);
    278 	}
    279 }
    280 
    281 void
    282 maybe_warnx(const char *fmt, ...)
    283 {
    284 	va_list ap;
    285 
    286 	if (qflag == 0) {
    287 		va_start(ap, fmt);
    288 		vwarnx(fmt, ap);
    289 		va_end(ap);
    290 	}
    291 }
    292 
    293 /* maybe print a warning */
    294 void
    295 maybe_err(int rv, const char *fmt, ...)
    296 {
    297 	va_list ap;
    298 
    299 	if (qflag == 0) {
    300 		va_start(ap, fmt);
    301 		vwarn(fmt, ap);
    302 		va_end(ap);
    303 	}
    304 	exit(rv);
    305 }
    306 
    307 /* maybe print a warning */
    308 void
    309 maybe_errx(int rv, const char *fmt, ...)
    310 {
    311 	va_list ap;
    312 
    313 	if (qflag == 0) {
    314 		va_start(ap, fmt);
    315 		vwarnx(fmt, ap);
    316 		va_end(ap);
    317 	}
    318 	exit(rv);
    319 }
    320 
    321 /* compress input to output then close both files */
    322 static void
    323 gz_compress(FILE *in, gzFile out)
    324 {
    325 	char buf[BUFLEN];
    326 	ssize_t len;
    327 	int i;
    328 
    329 	for (;;) {
    330 		len = fread(buf, 1, sizeof(buf), in);
    331 		if (ferror(in))
    332 			maybe_err(1, "fread");
    333 		if (len == 0)
    334 			break;
    335 
    336 		if ((ssize_t)gzwrite(out, buf, len) != len)
    337 			maybe_err(1, gzerror(out, &i));
    338 	}
    339 	if (fclose(in) < 0)
    340 		maybe_err(1, "failed fclose");
    341 	if (gzclose(out) != Z_OK)
    342 		maybe_err(1, "failed gzclose");
    343 }
    344 
    345 /* uncompress input to output then close the input */
    346 static off_t
    347 gz_uncompress(gzFile in, FILE *out)
    348 {
    349 	char buf[BUFLEN];
    350 	off_t size;
    351 	ssize_t len;
    352 	int i;
    353 
    354 	for (size = 0;;) {
    355 		len = gzread(in, buf, sizeof(buf));
    356 
    357 		if (len < 0) {
    358 			if (tflag) {
    359 				print_test(infile, 0);
    360 				return (0);
    361 			} else
    362 				maybe_errx(1, gzerror(in, &i));
    363 		} else if (len == 0) {
    364 			if (tflag)
    365 				print_test(infile, 1);
    366 			break;
    367 		}
    368 
    369 		size += len;
    370 
    371 		/* don't write anything with -t */
    372 		if (tflag)
    373 			continue;
    374 
    375 		if (fwrite(buf, 1, (unsigned)len, out) != (ssize_t)len)
    376 			maybe_err(1, "failed fwrite");
    377 	}
    378 	if (gzclose(in) != Z_OK)
    379 		maybe_errx(1, "failed gzclose");
    380 
    381 	return (size);
    382 }
    383 
    384 /*
    385  * set the owner, mode, flags & utimes for a file
    386  */
    387 static void
    388 copymodes(const char *file, struct stat *sbp)
    389 {
    390 	struct timeval times[2];
    391 
    392 	/*
    393 	 * If we have no info on the input, give this file some
    394 	 * default values and return..
    395 	 */
    396 	if (sbp == NULL) {
    397 		mode_t mask = umask(022);
    398 
    399 		(void)chmod(file, DEFFILEMODE & ~mask);
    400 		(void)umask(mask);
    401 		return;
    402 	}
    403 
    404 	/* if the chown fails, remove set-id bits as-per compress(1) */
    405 	if (chown(file, sbp->st_uid, sbp->st_gid) < 0) {
    406 		if (errno != EPERM)
    407 			maybe_warn("couldn't chown: %s", file);
    408 		sbp->st_mode &= ~(S_ISUID|S_ISGID);
    409 	}
    410 
    411 	/* we only allow set-id and the 9 normal permission bits */
    412 	sbp->st_mode &= S_ISUID|S_ISGID|S_IRWXU|S_IRWXG|S_IRWXO;
    413 	if (chmod(file, sbp->st_mode) < 0)
    414 		maybe_warn("couldn't chmod: %s", file);
    415 
    416 	/* only try flags if they exist already */
    417         if (sbp->st_flags != 0 && chflags(file, sbp->st_flags) < 0)
    418 		maybe_warn("couldn't chflags: %s", file);
    419 
    420 	TIMESPEC_TO_TIMEVAL(&times[0], &sbp->st_atimespec);
    421 	TIMESPEC_TO_TIMEVAL(&times[1], &sbp->st_mtimespec);
    422 	if (utimes(file, times) < 0)
    423 		maybe_warn("couldn't utimes: %s", file);
    424 }
    425 
    426 /*
    427  * compress the given file: create a corresponding .gz file and remove the
    428  * original.
    429  */
    430 static ssize_t
    431 file_compress(char *file)
    432 {
    433 	FILE *in;
    434 	gzFile out;
    435 	struct stat isb, osb;
    436 	char outfile[MAXPATHLEN];
    437 	ssize_t size;
    438 	u_int32_t mtime = 0;
    439 
    440 	if (cflag == 0) {
    441 		(void)strncpy(outfile, file, MAXPATHLEN - suffix_len);
    442 		outfile[MAXPATHLEN - suffix_len] = '\0';
    443 		(void)strlcat(outfile, suffix, sizeof(outfile));
    444 
    445 		if (fflag == 0) {
    446 			if (stat(outfile, &osb) == 0) {
    447 				maybe_warnx("%s already exists -- skipping",
    448 					      outfile);
    449 				goto lose;
    450 			}
    451 		}
    452 		if (stat(file, &isb) == 0) {
    453 			if (isb.st_nlink > 1) {
    454 				maybe_warnx("%s has %d other link%s -- "
    455 					    "skipping", file, isb.st_nlink-1,
    456 					    isb.st_nlink == 1 ? "" : "s");
    457 				goto lose;
    458 			}
    459 			if (nflag == 0)
    460 				mtime = (u_int32_t)isb.st_mtime;
    461 		}
    462 	}
    463 	in = fopen(file, "r");
    464 	if (in == 0)
    465 		maybe_err(1, "can't fopen %s", file);
    466 
    467 	if (cflag == 0) {
    468 #if HAVE_ZLIB_GZOPENFULL
    469 		char *savename;
    470 
    471 		if (nflag == 0)
    472 			savename = basename(file);
    473 		else
    474 			savename = NULL;
    475 		out = gzopenfull(outfile, gzipflags, savename, mtime);
    476 #else
    477 		out = gzopen(outfile, gzipflags);
    478 #endif
    479 	} else
    480 		out = gzdopen(STDOUT_FILENO, gzipflags);
    481 
    482 	if (out == 0)
    483 		maybe_err(1, "can't gz%sopen %s",
    484 		    cflag ? "d"         : "",
    485 		    cflag ? "stdout"    : outfile);
    486 
    487 	gz_compress(in, out);
    488 
    489 	/*
    490 	 * if we compressed to stdout, we don't know the size and
    491 	 * we don't know the new file name, punt.  if we can't stat
    492 	 * the file, whine, otherwise set the size from the stat
    493 	 * buffer.  we only blow away the file if we can stat the
    494 	 * output, just in case.
    495 	 */
    496 	if (cflag == 0) {
    497 		if (stat(outfile, &osb) < 0) {
    498 			maybe_warn("couldn't stat: %s", outfile);
    499 			maybe_warnx("leaving original %s", file);
    500 			size = 0;
    501 		} else {
    502 			unlink(file);
    503 			size = osb.st_size;
    504 		}
    505 		newfile = outfile;
    506 		copymodes(outfile, &isb);
    507 	} else {
    508 lose:
    509 		size = 0;
    510 		newfile = 0;
    511 	}
    512 
    513 	return (size);
    514 }
    515 
    516 /* uncompress the given file and remove the original */
    517 static ssize_t
    518 file_uncompress(char *file)
    519 {
    520 	struct stat isb, osb;
    521 	char buf[PATH_MAX];
    522 	char *outfile = buf, *s;
    523 	FILE *out;
    524 	gzFile in;
    525 	off_t size;
    526 	ssize_t len = strlen(file);
    527 	int fd;
    528 	unsigned char header1[10], name[PATH_MAX + 1];
    529 	enum filetype method;
    530 
    531 	/* gather the old name info */
    532 
    533 	fd = open(file, O_RDONLY);
    534 	if (fd < 0)
    535 		maybe_err(1, "can't open %s", file);
    536 	if (read(fd, header1, 10) != 10) {
    537 		/* we don't want to fail here. */
    538 		if (fflag)
    539 			goto close_it;
    540 		maybe_err(1, "can't read %s", file);
    541 	}
    542 
    543 	if (header1[0] == GZIP_MAGIC0 &&
    544 	    (header1[1] == GZIP_MAGIC1 || header1[1] == GZIP_OMAGIC1))
    545 		method = FT_GZIP;
    546 	else if (memcmp(header1, BZIP2_MAGIC, 3) == 0 &&
    547 	    header1[3] >= '0' && header1[3] <= '9') {
    548 		if (Sflag == NULL)
    549 			suffix = BZ2_SUFFIX;
    550 		method = FT_BZIP2;
    551 	} else
    552 		method = FT_UNKNOWN;
    553 
    554 	if (fflag == 0 && method == FT_UNKNOWN)
    555 		maybe_errx(1, "%s: not in gzip format", file);
    556 
    557 	if (cflag == 0 || lflag) {
    558 		s = &file[len - suffix_len + 1];
    559 		if (strncmp(s, suffix, suffix_len) == 0) {
    560 			(void)strncpy(outfile, file, len - suffix_len + 1);
    561 			outfile[len - suffix_len + 1] = '\0';
    562 		} else if (lflag == 0)
    563 			maybe_errx(1, "unknown suffix %s", s);
    564 	}
    565 
    566 	if (method == FT_GZIP && (Nflag || lflag)) {
    567 		if (header1[3] & ORIG_NAME) {
    568 			size_t rbytes;
    569 			int i;
    570 
    571 			rbytes = read(fd, name, PATH_MAX + 1);
    572 			if (rbytes < 0)
    573 				maybe_err(1, "can't read %s", file);
    574 			for (i = 0; i < rbytes && name[i]; i++)
    575 				;
    576 			if (i < rbytes) {
    577 				name[i] = 0;
    578 				/* now maybe merge old dirname */
    579 				if (strchr(outfile, '/') == 0)
    580 					outfile = name;
    581 				else {
    582 					char *dir = dirname(outfile);
    583 					if (asprintf(&outfile, "%s/%s", dir,
    584 					    name) == -1)
    585 						maybe_err(1, "malloc");
    586 				}
    587 			}
    588 		}
    589 	}
    590 close_it:
    591 	close(fd);
    592 
    593 	if ((cflag == 0 || lflag) && fflag == 0) {
    594 		if (lflag == 0 && stat(outfile, &osb) == 0) {
    595 			maybe_warnx("%s already exists -- skipping", outfile);
    596 			goto lose;
    597 		}
    598 		if (stat(file, &isb) == 0) {
    599 			if (isb.st_nlink > 1 && lflag == 0) {
    600 				maybe_warnx("%s has %d other links -- skipping",
    601 				    file, isb.st_nlink - 1);
    602 				goto lose;
    603 			}
    604 		} else
    605 			goto lose;
    606 	}
    607 
    608 	if (method == FT_BZIP2) {
    609 		int in, out;
    610 
    611 		if ((in = open(file, O_RDONLY)) == -1)
    612 			maybe_err(1, "open for read: %s", file);
    613 		if (cflag == 1)
    614 			out = STDOUT_FILENO;
    615 		else
    616 			out = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
    617 		if (out == -1)
    618 			maybe_err(1, "open for write: %s", outfile);
    619 
    620 		if ((size = unbzip2(in, out)) == 0) {
    621 			unlink(outfile);
    622 			goto lose;
    623 		}
    624 	} else {
    625 		if (lflag) {
    626 			int fd;
    627 
    628 			if ((fd = open(file, O_RDONLY)) == -1)
    629 				maybe_err(1, "open");
    630 			print_list(fd, isb.st_size, outfile, isb.st_mtime);
    631 			return 0;	/* XXX */
    632 		}
    633 
    634 		in = gzopen(file, gzipflags);
    635 		if (in == NULL)
    636 			maybe_err(1, "can't gzopen %s", file);
    637 
    638 		if (cflag == 0) {
    639 			int fd;
    640 
    641 			/* Use open(2) directly to get a safe file.  */
    642 			fd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
    643 			if (fd < 0)
    644 				maybe_err(1, "can't open %s", outfile);
    645 			out = fdopen(fd, "w");
    646 			if (out == NULL)
    647 				maybe_err(1, "can't fdopen %s", outfile);
    648 		} else
    649 			out = stdout;
    650 
    651 		if ((size = gz_uncompress(in, out)) == 0) {
    652 			unlink(outfile);
    653 			goto lose;
    654 		}
    655 
    656 		/* close the file */
    657 		if (fclose(out))
    658 			maybe_err(1, "failed fclose");
    659 	}
    660 
    661 	/* if testing, or we uncompressed to stdout, this is all we need */
    662 	if (tflag || cflag)
    663 		return (size);
    664 
    665 	/*
    666 	 * if we create a file...
    667 	 */
    668 	if (cflag == 0) {
    669 		/*
    670 		 * if we can't stat the file, or we are uncompressing to
    671 		 * stdin, don't remove the file.
    672 		 */
    673 		if (stat(outfile, &osb) < 0) {
    674 			maybe_warn("couldn't stat (leaving original): %s",
    675 				   outfile);
    676 			goto lose;
    677 		}
    678 		if (osb.st_size != size) {
    679 			maybe_warn("stat gave different size: %llu != %llu "
    680 			    "(leaving original)",
    681 			    (unsigned long long)size,
    682 			    (unsigned long long)osb.st_size);
    683 			goto lose;
    684 		}
    685 		newfile = outfile;
    686 		unlink(file);
    687 		size = osb.st_size;
    688 		copymodes(outfile, &isb);
    689 	}
    690 	return (size);
    691 
    692 lose:
    693 	newfile = 0;
    694 	return (0);
    695 }
    696 
    697 static void
    698 handle_stdin(void)
    699 {
    700 	gzFile *file;
    701 
    702 	if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
    703 		maybe_warnx("standard input is a terminal -- ignoring");
    704 		return;
    705 	}
    706 
    707 	if (lflag) {
    708 		struct stat isb;
    709 
    710 		if (fstat(STDIN_FILENO, &isb) < 0)
    711 			maybe_err(1, "fstat");
    712 		print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
    713 		return;
    714 	}
    715 
    716 	file = gzdopen(STDIN_FILENO, gzipflags);
    717 	if (file == NULL)
    718 		maybe_err(1, "can't gzdopen stdin");
    719 	gz_uncompress(file, stdout);
    720 }
    721 
    722 static void
    723 handle_stdout(void)
    724 {
    725 	gzFile *file;
    726 
    727 	if (fflag == 0 && isatty(STDOUT_FILENO)) {
    728 		maybe_warnx("standard output is a terminal -- ignoring");
    729 		return;
    730 	}
    731 	file = gzdopen(STDOUT_FILENO, gzipflags);
    732 	if (file == NULL)
    733 		maybe_err(1, "can't gzdopen stdout");
    734 	gz_compress(stdin, file);
    735 }
    736 
    737 /* do what is asked for, for the path name */
    738 static void
    739 handle_pathname(char *path)
    740 {
    741 	char *opath = path, *s = 0;
    742 	ssize_t len;
    743 	struct stat sb;
    744 
    745 	/* check for stdout/stdin */
    746 	if (path[0] == '-' && path[1] == '\0') {
    747 		if (dflag)
    748 			handle_stdin();
    749 		else
    750 			handle_stdout();
    751 	}
    752 
    753 retry:
    754 	if (stat(path, &sb) < 0) {
    755 		/* lets try <path>.gz if we're decompressing */
    756 		if (dflag && s == 0 && errno == ENOENT) {
    757 			len = strlen(path);
    758 			s = malloc(len + suffix_len);
    759 			if (s == 0)
    760 				maybe_err(1, "malloc");
    761 			memmove(s, path, len);
    762 			memmove(&s[len], suffix, suffix_len);
    763 			path = s;
    764 			goto retry;
    765 		}
    766 		maybe_warn("can't stat: %s", opath);
    767 		goto out;
    768 	}
    769 
    770 	if (S_ISDIR(sb.st_mode)) {
    771 		if (rflag)
    772 			handle_dir(path, &sb);
    773 		else
    774 			maybe_warn("%s is a directory", path);
    775 		goto out;
    776 	}
    777 
    778 	if (S_ISREG(sb.st_mode))
    779 		handle_file(path, &sb);
    780 
    781 out:
    782 	if (s)
    783 		free(s);
    784 	return;
    785 }
    786 
    787 /* compress/decompress a file */
    788 static void
    789 handle_file(char *file, struct stat *sbp)
    790 {
    791 	ssize_t usize, gsize;
    792 
    793 	infile = file;
    794 	if (dflag) {
    795 		usize = file_uncompress(file);
    796 		if (usize == 0)
    797 			return;
    798 		gsize = sbp->st_size;
    799 	} else {
    800 		gsize = file_compress(file);
    801 		if (gsize == 0)
    802 			return;
    803 		usize = sbp->st_size;
    804 	}
    805 
    806 	if (vflag && !tflag)
    807 		print_verbage(file, cflag == 0 ? newfile : 0, usize, gsize);
    808 }
    809 
    810 /* this is used with -r to recursively decend directories */
    811 static void
    812 handle_dir(char *dir, struct stat *sbp)
    813 {
    814 	char *path_argv[2];
    815 	FTS *fts;
    816 	FTSENT *entry;
    817 
    818 	path_argv[0] = dir;
    819 	path_argv[1] = 0;
    820 	fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
    821 	if (fts == NULL) {
    822 		warn("couldn't fts_open %s", dir);
    823 		return;
    824 	}
    825 
    826 	while ((entry = fts_read(fts))) {
    827 		switch(entry->fts_info) {
    828 		case FTS_D:
    829 		case FTS_DP:
    830 			continue;
    831 
    832 		case FTS_DNR:
    833 		case FTS_ERR:
    834 		case FTS_NS:
    835 			maybe_warn("%s", entry->fts_path);
    836 			continue;
    837 		case FTS_F:
    838 			handle_file(entry->fts_name, entry->fts_statp);
    839 		}
    840 	}
    841 	(void)fts_close(fts);
    842 }
    843 
    844 /* print a ratio */
    845 static void
    846 print_ratio(off_t in, off_t out, FILE *where)
    847 {
    848 	u_int64_t percent;
    849 
    850 	if (out == 0)
    851 		percent = 0;
    852 	else
    853 		percent = 1000 - ((1000 * out) / in);
    854 	fprintf(where, "%3lu.%1lu%%", (unsigned long)percent / 10UL,
    855 	    (unsigned long)percent % 10);
    856 }
    857 
    858 /* print compression statistics, and the new name (if there is one!) */
    859 static void
    860 print_verbage(char *file, char *nfile, ssize_t usize, ssize_t gsize)
    861 {
    862 	fprintf(stderr, "%s:%s  ", file,
    863 	    strlen(file) < 7 ? "\t\t" : "\t");
    864 	print_ratio(usize, gsize, stderr);
    865 	if (nfile)
    866 		fprintf(stderr, " -- replaced with %s", nfile);
    867 	fprintf(stderr, "\n");
    868 	fflush(stderr);
    869 }
    870 
    871 /* print test results */
    872 static void
    873 print_test(char *file, int ok)
    874 {
    875 
    876 	fprintf(stderr, "%s:%s  %s\n", file,
    877 	    strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
    878 	fflush(stderr);
    879 }
    880 
    881 /* print a file's info ala --list */
    882 /* eg:
    883   compressed uncompressed  ratio uncompressed_name
    884       354841      1679360  78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
    885 */
    886 static void
    887 print_list(int fd, off_t in, const char *outfile, time_t ts)
    888 {
    889 	static int first = 1;
    890 	static off_t in_tot, out_tot;
    891 	off_t out;
    892 	u_int32_t crc;
    893 	int rv;
    894 
    895 	if (first) {
    896 		if (vflag)
    897 			printf("method  crc     date  time  ");
    898 		if (qflag == 0)
    899 			printf("  compressed uncompressed  "
    900 			       "ratio uncompressed_name\n");
    901 	}
    902 	first = 0;
    903 
    904 	/* print totals? */
    905 	if (fd == -1) {
    906 		in = in_tot;
    907 		out = out_tot;
    908 	} else {
    909 		/* read the last 4 bytes - this is the uncompressed size */
    910 		rv = lseek(fd, (off_t)(-8), SEEK_END);
    911 		if (rv != -1) {
    912 			unsigned char buf[8];
    913 			u_int32_t usize;
    914 
    915 			if (read(fd, (char *)buf, sizeof(buf)) != sizeof(buf))
    916 				maybe_err(1, "read of uncompressed size");
    917 			crc = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;
    918 			usize = buf[4] | buf[5] << 8 | buf[6] << 16 | buf[7] << 24;
    919 			out = (off_t)usize;
    920 		}
    921 	}
    922 
    923 	if (vflag && fd == -1)
    924 		printf("                            ");
    925 	else if (vflag) {
    926 		char *date = ctime(&ts);
    927 
    928 		/* skip the day, 1/100th second, and year */
    929 		date += 4;
    930 		date[12] = 0;
    931 		printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
    932 	}
    933 	printf("%12llu %12llu ", (unsigned long long)in, (unsigned long long)out);
    934 	print_ratio(in, out, stdout);
    935 	printf(" %s\n", outfile);
    936 	in_tot += in;
    937 	out_tot += out;
    938 }
    939 
    940 /* display the usage of NetBSD gzip */
    941 static void
    942 usage(void)
    943 {
    944 
    945 	fprintf(stderr, "%s\n", gzip_version);
    946 	fprintf(stderr,
    947     "Usage: %s [-cdfhnNqrStvV123456789] [<file> [<file> ...]]\n"
    948 #ifndef SMALL
    949     " -c --stdout          write to stdout, keep original files\n"
    950     "    --to-stdout\n"
    951     " -d --decompress      uncompress files\n"
    952     "    --uncompress\n"
    953     " -f --force           force overwriting & compress links\n"
    954     " -h --help            display this help\n"
    955     " -n --no-name         don't save original file name or time stamp\n"
    956     " -N --name            save or restore original file name and time stamp\n"
    957     " -q --quiet           output no warnings\n"
    958     " -r --recursive       recursively compress files in directories\n"
    959     " -S .suf              use suffix .suf instead of .gz\n"
    960     "    --suffix .suf\n"
    961     " -t --test            test compressed file\n"
    962     " -v --verbose         print extra statistics\n"
    963     " -V --version         display program version\n"
    964     " -1 --fast            fastest (worst) compression\n"
    965     " -2 .. -8             set compression level\n"
    966     " -9 --best            best (slowest) compression\n",
    967 #else
    968     ,
    969 #endif
    970 	    getprogname());
    971 	fflush(stderr);
    972 	exit(0);
    973 }
    974 
    975 /* display the version of NetBSD gzip */
    976 static void
    977 display_version(void)
    978 {
    979 
    980 	fprintf(stderr, "%s\n", gzip_version);
    981 	fflush(stderr);
    982 	exit(0);
    983 }
    984 
    985 #include "unbzip2.c"
    986