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