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