Home | History | Annotate | Line # | Download | only in gzip
gzip.c revision 1.34
      1 /*	$NetBSD: gzip.c,v 1.34 2004/03/31 15:46:25 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.34 2004/03/31 15:46:25 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 #include <bzlib.h>
     82 
     83 #define BZ2_SUFFIX	".bz2"
     84 #define BZIP2_MAGIC	"\102\132\150"
     85 #endif
     86 
     87 #ifndef NO_COMPRESS_SUPPORT
     88 #define Z_SUFFIX	".Z"
     89 #define Z_MAGIC		"\037\235"
     90 #endif
     91 
     92 #define GZ_SUFFIX	".gz"
     93 
     94 #define BUFLEN		(32 * 1024)
     95 
     96 #define GZIP_MAGIC0	0x1F
     97 #define GZIP_MAGIC1	0x8B
     98 #define GZIP_OMAGIC1	0x9E
     99 
    100 #define ORIG_NAME 	0x08
    101 
    102 /* Define this if you have the NetBSD gzopenfull(3) extension to zlib(3) */
    103 #ifndef HAVE_ZLIB_GZOPENFULL
    104 #define HAVE_ZLIB_GZOPENFULL 1
    105 #endif
    106 
    107 static	const char	gzip_version[] = "NetBSD gzip 2.2";
    108 
    109 static	char	gzipflags[3];		/* `w' or `r', possible with [1-9] */
    110 static	int	cflag;			/* stdout mode */
    111 static	int	dflag;			/* decompress mode */
    112 static	int	lflag;			/* list mode */
    113 
    114 #ifndef SMALL
    115 static	int	fflag;			/* force mode */
    116 static	int	nflag;			/* don't save name/timestamp */
    117 static	int	Nflag;			/* don't restore name/timestamp */
    118 static	int	qflag;			/* quiet mode */
    119 static	int	rflag;			/* recursive mode */
    120 static	int	tflag;			/* test */
    121 static	char	*Sflag;
    122 static	int	vflag;			/* verbose mode */
    123 #else
    124 #define		qflag	0
    125 #endif
    126 
    127 static	char	*suffix;
    128 #define suffix_len	(strlen(suffix) + 1)	/* len + nul */
    129 static	char	*newfile;		/* name of newly created file */
    130 static	char	*infile;		/* name of file coming in */
    131 
    132 static	void	maybe_err(int rv, const char *fmt, ...);
    133 static	void	maybe_errx(int rv, const char *fmt, ...);
    134 static	void	maybe_warn(const char *fmt, ...);
    135 static	void	maybe_warnx(const char *fmt, ...);
    136 static	enum filetype file_gettype(u_char *);
    137 static	void	gz_compress(FILE *, gzFile);
    138 static	off_t	gz_uncompress(gzFile, FILE *);
    139 static	off_t	file_compress(char *);
    140 static	off_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 *, off_t, off_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 "cdhHltV123456789"
    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 /* what sort of file is this? */
    542 static enum filetype
    543 file_gettype(u_char *buf)
    544 {
    545 
    546 	if (buf[0] == GZIP_MAGIC0 &&
    547 	    (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
    548 		return FT_GZIP;
    549 	else
    550 #ifndef NO_BZIP2_SUPPORT
    551 	if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
    552 	    buf[3] >= '0' && buf[3] <= '9')
    553 		return FT_BZIP2;
    554 	else
    555 #endif
    556 #ifndef NO_COMPRESS_SUPPORT
    557 	if (memcmp(buf, Z_MAGIC, 2) == 0)
    558 		return FT_Z;
    559 	else
    560 #endif
    561 		return FT_UNKNOWN;
    562 }
    563 
    564 /*
    565  * compress the given file: create a corresponding .gz file and remove the
    566  * original.
    567  */
    568 static off_t
    569 file_compress(char *file)
    570 {
    571 	FILE *in;
    572 	gzFile out;
    573 	struct stat isb, osb;
    574 	char outfile[MAXPATHLEN];
    575 	off_t size;
    576 #ifndef SMALL
    577 	u_int32_t mtime = 0;
    578 #endif
    579 
    580 	if (cflag == 0) {
    581 		(void)strncpy(outfile, file, MAXPATHLEN - suffix_len);
    582 		outfile[MAXPATHLEN - suffix_len] = '\0';
    583 		(void)strlcat(outfile, suffix, sizeof(outfile));
    584 
    585 #ifndef SMALL
    586 		if (fflag == 0) {
    587 			if (stat(outfile, &osb) == 0) {
    588 				maybe_warnx("%s already exists -- skipping",
    589 					      outfile);
    590 				goto lose;
    591 			}
    592 		}
    593 		if (stat(file, &isb) == 0) {
    594 			if (isb.st_nlink > 1 && fflag == 0) {
    595 				maybe_warnx("%s has %d other link%s -- "
    596 					    "skipping", file, isb.st_nlink - 1,
    597 					    isb.st_nlink == 1 ? "" : "s");
    598 				goto lose;
    599 			}
    600 			if (nflag == 0)
    601 				mtime = (u_int32_t)isb.st_mtime;
    602 		}
    603 #endif
    604 	}
    605 	in = fopen(file, "r");
    606 	if (in == 0)
    607 		maybe_err(1, "can't fopen %s", file);
    608 
    609 	if (cflag == 0) {
    610 #if HAVE_ZLIB_GZOPENFULL && !defined(SMALL)
    611 		char *savename;
    612 
    613 		if (nflag == 0)
    614 			savename = basename(file);
    615 		else
    616 			savename = NULL;
    617 		out = gzopenfull(outfile, gzipflags, savename, mtime);
    618 #else
    619 		out = gzopen(outfile, gzipflags);
    620 #endif
    621 	} else
    622 		out = gzdopen(STDOUT_FILENO, gzipflags);
    623 
    624 	if (out == 0)
    625 		maybe_err(1, "can't gz%sopen %s",
    626 		    cflag ? "d"         : "",
    627 		    cflag ? "stdout"    : outfile);
    628 
    629 	gz_compress(in, out);
    630 
    631 	/*
    632 	 * if we compressed to stdout, we don't know the size and
    633 	 * we don't know the new file name, punt.  if we can't stat
    634 	 * the file, whine, otherwise set the size from the stat
    635 	 * buffer.  we only blow away the file if we can stat the
    636 	 * output, just in case.
    637 	 */
    638 	if (cflag == 0) {
    639 		if (stat(outfile, &osb) < 0) {
    640 			maybe_warn("couldn't stat: %s", outfile);
    641 			maybe_warnx("leaving original %s", file);
    642 			size = 0;
    643 		} else {
    644 			unlink(file);
    645 			size = osb.st_size;
    646 		}
    647 		newfile = outfile;
    648 #ifndef SMALL
    649 		copymodes(outfile, &isb);
    650 #endif
    651 	} else {
    652 lose:
    653 		size = 0;
    654 		newfile = 0;
    655 	}
    656 
    657 	return (size);
    658 }
    659 
    660 /* uncompress the given file and remove the original */
    661 static off_t
    662 file_uncompress(char *file)
    663 {
    664 	struct stat isb, osb;
    665 	char buf[PATH_MAX];
    666 	char *outfile = buf, *s;
    667 	FILE *out;
    668 	gzFile in;
    669 	off_t size;
    670 	ssize_t len = strlen(file);
    671 	int fd;
    672 	unsigned char header1[10], name[PATH_MAX + 1];
    673 	enum filetype method;
    674 
    675 	/* gather the old name info */
    676 
    677 	fd = open(file, O_RDONLY);
    678 	if (fd < 0)
    679 		maybe_err(1, "can't open %s", file);
    680 	if (read(fd, header1, 10) != 10) {
    681 		/* we don't want to fail here. */
    682 #ifndef SMALL
    683 		if (fflag)
    684 			goto close_it;
    685 #endif
    686 		maybe_err(1, "can't read %s", file);
    687 	}
    688 
    689 	method = file_gettype(header1);
    690 
    691 #ifndef SMALL
    692 	if (Sflag == NULL) {
    693 # ifndef NO_BZIP2_SUPPORT
    694 		if (method == FT_BZIP2)
    695 			suffix = BZ2_SUFFIX;
    696 		else
    697 # endif
    698 # ifndef NO_COMPRESS_SUPPORT
    699 		if (method == FT_Z)
    700 			suffix = Z_SUFFIX;
    701 # endif
    702 	}
    703 
    704 	if (fflag == 0 && method == FT_UNKNOWN)
    705 		maybe_errx(1, "%s: not in gzip format", file);
    706 #endif
    707 
    708 	if (cflag == 0 || lflag) {
    709 		s = &file[len - suffix_len + 1];
    710 		if (strncmp(s, suffix, suffix_len) == 0) {
    711 			(void)strncpy(outfile, file, len - suffix_len + 1);
    712 			outfile[len - suffix_len + 1] = '\0';
    713 		} else if (lflag == 0)
    714 			maybe_errx(1, "unknown suffix %s", s);
    715 	}
    716 
    717 #ifdef SMALL
    718 	if (method == FT_GZIP && lflag)
    719 #else
    720 	if (method == FT_GZIP && (Nflag || lflag))
    721 #endif
    722 	{
    723 		if (header1[3] & ORIG_NAME) {
    724 			size_t rbytes;
    725 			int i;
    726 
    727 			rbytes = read(fd, name, PATH_MAX + 1);
    728 			if (rbytes < 0)
    729 				maybe_err(1, "can't read %s", file);
    730 			for (i = 0; i < rbytes && name[i]; i++)
    731 				;
    732 			if (i < rbytes) {
    733 				name[i] = 0;
    734 				/* now maybe merge old dirname */
    735 				if (strchr(outfile, '/') == 0)
    736 					outfile = name;
    737 				else {
    738 					char *dir = dirname(outfile);
    739 					if (asprintf(&outfile, "%s/%s", dir,
    740 					    name) == -1)
    741 						maybe_err(1, "malloc");
    742 				}
    743 			}
    744 		}
    745 	}
    746 #ifndef SMALL
    747 close_it:
    748 #endif
    749 	close(fd);
    750 
    751 	if (cflag == 0 || lflag) {
    752 #ifndef SMALL
    753 		if (fflag == 0 && lflag == 0 && stat(outfile, &osb) == 0) {
    754 			maybe_warnx("%s already exists -- skipping", outfile);
    755 			goto lose;
    756 		}
    757 #endif
    758 		if (stat(file, &isb) == 0) {
    759 #ifndef SMALL
    760 			if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
    761 				maybe_warnx("%s has %d other links -- skipping",
    762 				    file, isb.st_nlink - 1);
    763 				goto lose;
    764 			}
    765 #endif
    766 		} else
    767 			goto lose;
    768 	}
    769 
    770 #ifndef NO_BZIP2_SUPPORT
    771 	if (method == FT_BZIP2) {
    772 		int in, out;
    773 
    774 		/* XXX */
    775 		if (lflag)
    776 			maybe_errx(1, "no -l with bzip2 files");
    777 
    778 		if ((in = open(file, O_RDONLY)) == -1)
    779 			maybe_err(1, "open for read: %s", file);
    780 		if (cflag == 1)
    781 			out = STDOUT_FILENO;
    782 		else
    783 			out = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
    784 		if (out == -1)
    785 			maybe_err(1, "open for write: %s", outfile);
    786 
    787 		if ((size = unbzip2(in, out)) == 0) {
    788 			unlink(outfile);
    789 			goto lose;
    790 		}
    791 	} else
    792 #endif
    793 
    794 #ifndef NO_COMPRESS_SUPPORT
    795 	if (method == FT_Z) {
    796 		FILE *in, *out;
    797 		int fd;
    798 
    799 		/* XXX */
    800 		if (lflag)
    801 			maybe_errx(1, "no -l with Lempel-Ziv files");
    802 
    803 		if ((in = zopen(file)) == NULL)
    804 			maybe_err(1, "open for read: %s", file);
    805 
    806 		if (cflag == 1)
    807 			fd = STDOUT_FILENO;
    808 		else {
    809 			fd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
    810 			if (fd == -1)
    811 				maybe_err(1, "open for write: %s", outfile);
    812 		}
    813 		out = fdopen(fd, "w");
    814 		if (out == NULL)
    815 			maybe_err(1, "open for write: %s", outfile);
    816 
    817 		if ((size = zuncompress(in, out)) == 0) {
    818 			unlink(outfile);
    819 			goto lose;
    820 		}
    821 		if (ferror(in) || fclose(in)) {
    822 			unlink(outfile);
    823 			maybe_err(1, "failed infile fclose");
    824 		}
    825 		if (fclose(out)) {
    826 			unlink(outfile);
    827 			maybe_err(1, "failed outfile close");
    828 		}
    829 	} else
    830 #endif
    831 	{
    832 		if (lflag) {
    833 			int fd;
    834 
    835 			if ((fd = open(file, O_RDONLY)) == -1)
    836 				maybe_err(1, "open");
    837 			print_list(fd, isb.st_size, outfile, isb.st_mtime);
    838 			return 0;	/* XXX */
    839 		}
    840 
    841 		in = gzopen(file, gzipflags);
    842 		if (in == NULL)
    843 			maybe_err(1, "can't gzopen %s", file);
    844 
    845 		if (cflag == 0) {
    846 			int fd;
    847 
    848 			/* Use open(2) directly to get a safe file.  */
    849 			fd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
    850 			if (fd < 0)
    851 				maybe_err(1, "can't open %s", outfile);
    852 			out = fdopen(fd, "w");
    853 			if (out == NULL)
    854 				maybe_err(1, "can't fdopen %s", outfile);
    855 		} else
    856 			out = stdout;
    857 
    858 		if ((size = gz_uncompress(in, out)) == 0) {
    859 			unlink(outfile);
    860 			goto lose;
    861 		}
    862 		if (fclose(out))
    863 			maybe_err(1, "failed fclose");
    864 	}
    865 
    866 	/* if testing, or we uncompressed to stdout, this is all we need */
    867 #ifndef SMALL
    868 	if (tflag)
    869 		return (size);
    870 #endif
    871 	if (cflag)
    872 		return (size);
    873 
    874 	/*
    875 	 * if we create a file...
    876 	 */
    877 	if (cflag == 0) {
    878 		/*
    879 		 * if we can't stat the file, or we are uncompressing to
    880 		 * stdin, don't remove the file.
    881 		 */
    882 		if (stat(outfile, &osb) < 0) {
    883 			maybe_warn("couldn't stat (leaving original): %s",
    884 				   outfile);
    885 			goto lose;
    886 		}
    887 		if (osb.st_size != size) {
    888 			maybe_warn("stat gave different size: %llu != %llu "
    889 			    "(leaving original)",
    890 			    (unsigned long long)size,
    891 			    (unsigned long long)osb.st_size);
    892 			goto lose;
    893 		}
    894 		newfile = outfile;
    895 		unlink(file);
    896 		size = osb.st_size;
    897 #ifndef SMALL
    898 		copymodes(outfile, &isb);
    899 #endif
    900 	}
    901 	return (size);
    902 
    903 lose:
    904 	newfile = 0;
    905 	return 0;
    906 }
    907 
    908 static void
    909 handle_stdin(void)
    910 {
    911 	gzFile *file;
    912 
    913 #ifndef SMALL
    914 	if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
    915 		maybe_warnx("standard input is a terminal -- ignoring");
    916 		return;
    917 	}
    918 #endif
    919 
    920 	if (lflag) {
    921 		struct stat isb;
    922 
    923 		if (fstat(STDIN_FILENO, &isb) < 0)
    924 			maybe_err(1, "fstat");
    925 		print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
    926 		return;
    927 	}
    928 
    929 	file = gzdopen(STDIN_FILENO, gzipflags);
    930 	if (file == NULL)
    931 		maybe_err(1, "can't gzdopen stdin");
    932 	gz_uncompress(file, stdout);
    933 }
    934 
    935 static void
    936 handle_stdout(void)
    937 {
    938 	gzFile *file;
    939 
    940 #ifndef SMALL
    941 	if (fflag == 0 && isatty(STDOUT_FILENO)) {
    942 		maybe_warnx("standard output is a terminal -- ignoring");
    943 		return;
    944 	}
    945 #endif
    946 	file = gzdopen(STDOUT_FILENO, gzipflags);
    947 	if (file == NULL)
    948 		maybe_err(1, "can't gzdopen stdout");
    949 	gz_compress(stdin, file);
    950 }
    951 
    952 /* do what is asked for, for the path name */
    953 static void
    954 handle_pathname(char *path)
    955 {
    956 	char *opath = path, *s = 0;
    957 	ssize_t len;
    958 	struct stat sb;
    959 
    960 	/* check for stdout/stdin */
    961 	if (path[0] == '-' && path[1] == '\0') {
    962 		if (dflag)
    963 			handle_stdin();
    964 		else
    965 			handle_stdout();
    966 	}
    967 
    968 retry:
    969 	if (stat(path, &sb) < 0) {
    970 		/* lets try <path>.gz if we're decompressing */
    971 		if (dflag && s == 0 && errno == ENOENT) {
    972 			len = strlen(path);
    973 			s = malloc(len + suffix_len);
    974 			if (s == 0)
    975 				maybe_err(1, "malloc");
    976 			memmove(s, path, len);
    977 			memmove(&s[len], suffix, suffix_len);
    978 			path = s;
    979 			goto retry;
    980 		}
    981 		maybe_warn("can't stat: %s", opath);
    982 		goto out;
    983 	}
    984 
    985 	if (S_ISDIR(sb.st_mode)) {
    986 #ifndef SMALL
    987 		if (rflag)
    988 			handle_dir(path, &sb);
    989 		else
    990 #endif
    991 			maybe_warn("%s is a directory", path);
    992 		goto out;
    993 	}
    994 
    995 	if (S_ISREG(sb.st_mode))
    996 		handle_file(path, &sb);
    997 
    998 out:
    999 	if (s)
   1000 		free(s);
   1001 }
   1002 
   1003 /* compress/decompress a file */
   1004 static void
   1005 handle_file(char *file, struct stat *sbp)
   1006 {
   1007 	off_t usize, gsize;
   1008 
   1009 	infile = file;
   1010 	if (dflag) {
   1011 		usize = file_uncompress(file);
   1012 		if (usize == 0)
   1013 			return;
   1014 		gsize = sbp->st_size;
   1015 	} else {
   1016 		gsize = file_compress(file);
   1017 		if (gsize == 0)
   1018 			return;
   1019 		usize = sbp->st_size;
   1020 	}
   1021 
   1022 
   1023 #ifndef SMALL
   1024 	if (vflag && !tflag)
   1025 		print_verbage(file, cflag == 0 ? newfile : 0, usize, gsize);
   1026 #endif
   1027 }
   1028 
   1029 #ifndef SMALL
   1030 /* this is used with -r to recursively decend directories */
   1031 static void
   1032 handle_dir(char *dir, struct stat *sbp)
   1033 {
   1034 	char *path_argv[2];
   1035 	FTS *fts;
   1036 	FTSENT *entry;
   1037 
   1038 	path_argv[0] = dir;
   1039 	path_argv[1] = 0;
   1040 	fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
   1041 	if (fts == NULL) {
   1042 		warn("couldn't fts_open %s", dir);
   1043 		return;
   1044 	}
   1045 
   1046 	while ((entry = fts_read(fts))) {
   1047 		switch(entry->fts_info) {
   1048 		case FTS_D:
   1049 		case FTS_DP:
   1050 			continue;
   1051 
   1052 		case FTS_DNR:
   1053 		case FTS_ERR:
   1054 		case FTS_NS:
   1055 			maybe_warn("%s", entry->fts_path);
   1056 			continue;
   1057 		case FTS_F:
   1058 			handle_file(entry->fts_name, entry->fts_statp);
   1059 		}
   1060 	}
   1061 	(void)fts_close(fts);
   1062 }
   1063 #endif
   1064 
   1065 /* print a ratio */
   1066 static void
   1067 print_ratio(off_t in, off_t out, FILE *where)
   1068 {
   1069 	u_int64_t percent;
   1070 
   1071 	if (out == 0)
   1072 		percent = 0;
   1073 	else
   1074 		percent = 1000 - ((in * 1000ULL) / out);
   1075 	fprintf(where, "%3lu.%1lu%%", (unsigned long)percent / 10UL,
   1076 	    (unsigned long)percent % 10);
   1077 }
   1078 
   1079 #ifndef SMALL
   1080 /* print compression statistics, and the new name (if there is one!) */
   1081 static void
   1082 print_verbage(char *file, char *nfile, off_t usize, off_t gsize)
   1083 {
   1084 	fprintf(stderr, "%s:%s  ", file,
   1085 	    strlen(file) < 7 ? "\t\t" : "\t");
   1086 	print_ratio((off_t)usize, (off_t)gsize, stderr);
   1087 	if (nfile)
   1088 		fprintf(stderr, " -- replaced with %s", nfile);
   1089 	fprintf(stderr, "\n");
   1090 	fflush(stderr);
   1091 }
   1092 
   1093 /* print test results */
   1094 static void
   1095 print_test(char *file, int ok)
   1096 {
   1097 
   1098 	fprintf(stderr, "%s:%s  %s\n", file,
   1099 	    strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
   1100 	fflush(stderr);
   1101 }
   1102 #endif
   1103 
   1104 /* print a file's info ala --list */
   1105 /* eg:
   1106   compressed uncompressed  ratio uncompressed_name
   1107       354841      1679360  78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
   1108 */
   1109 static void
   1110 print_list(int fd, off_t in, const char *outfile, time_t ts)
   1111 {
   1112 	static int first = 1;
   1113 #ifndef SMALL
   1114 	static off_t in_tot, out_tot;
   1115 	u_int32_t crc;
   1116 #endif
   1117 	off_t out;
   1118 	int rv;
   1119 
   1120 	if (first) {
   1121 #ifndef SMALL
   1122 		if (vflag)
   1123 			printf("method  crc     date  time  ");
   1124 #endif
   1125 		if (qflag == 0)
   1126 			printf("  compressed uncompressed  "
   1127 			       "ratio uncompressed_name\n");
   1128 	}
   1129 	first = 0;
   1130 
   1131 	/* print totals? */
   1132 #ifndef SMALL
   1133 	if (fd == -1) {
   1134 		in = in_tot;
   1135 		out = out_tot;
   1136 	} else
   1137 #endif
   1138 	{
   1139 		/* read the last 4 bytes - this is the uncompressed size */
   1140 		rv = lseek(fd, (off_t)(-8), SEEK_END);
   1141 		if (rv != -1) {
   1142 			unsigned char buf[8];
   1143 			u_int32_t usize;
   1144 
   1145 			if (read(fd, (char *)buf, sizeof(buf)) != sizeof(buf))
   1146 				maybe_err(1, "read of uncompressed size");
   1147 			usize = buf[4] | buf[5] << 8 | buf[6] << 16 | buf[7] << 24;
   1148 			out = (off_t)usize;
   1149 #ifndef SMALL
   1150 			crc = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;
   1151 #endif
   1152 		}
   1153 	}
   1154 
   1155 #ifndef SMALL
   1156 	if (vflag && fd == -1)
   1157 		printf("                            ");
   1158 	else if (vflag) {
   1159 		char *date = ctime(&ts);
   1160 
   1161 		/* skip the day, 1/100th second, and year */
   1162 		date += 4;
   1163 		date[12] = 0;
   1164 		printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
   1165 	}
   1166 	in_tot += in;
   1167 	out_tot += out;
   1168 #endif
   1169 	printf("%12llu %12llu ", (unsigned long long)in, (unsigned long long)out);
   1170 	print_ratio(in, out, stdout);
   1171 	printf(" %s\n", outfile);
   1172 }
   1173 
   1174 /* display the usage of NetBSD gzip */
   1175 static void
   1176 usage(void)
   1177 {
   1178 
   1179 	fprintf(stderr, "%s\n", gzip_version);
   1180 	fprintf(stderr,
   1181     "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n"
   1182 #ifndef SMALL
   1183     " -c --stdout          write to stdout, keep original files\n"
   1184     "    --to-stdout\n"
   1185     " -d --decompress      uncompress files\n"
   1186     "    --uncompress\n"
   1187     " -f --force           force overwriting & compress links\n"
   1188     " -h --help            display this help\n"
   1189     " -n --no-name         don't save original file name or time stamp\n"
   1190     " -N --name            save or restore original file name and time stamp\n"
   1191     " -q --quiet           output no warnings\n"
   1192     " -r --recursive       recursively compress files in directories\n"
   1193     " -S .suf              use suffix .suf instead of .gz\n"
   1194     "    --suffix .suf\n"
   1195     " -t --test            test compressed file\n"
   1196     " -v --verbose         print extra statistics\n"
   1197     " -V --version         display program version\n"
   1198     " -1 --fast            fastest (worst) compression\n"
   1199     " -2 .. -8             set compression level\n"
   1200     " -9 --best            best (slowest) compression\n",
   1201 #else
   1202     ,
   1203 #endif
   1204 	    getprogname());
   1205 	exit(0);
   1206 }
   1207 
   1208 /* display the version of NetBSD gzip */
   1209 static void
   1210 display_version(void)
   1211 {
   1212 
   1213 	fprintf(stderr, "%s\n", gzip_version);
   1214 	exit(0);
   1215 }
   1216 
   1217 #ifndef NO_BZIP2_SUPPORT
   1218 #include "unbzip2.c"
   1219 #endif
   1220 #ifndef NO_COMPRESS_SUPPORT
   1221 #include "zuncompress.c"
   1222 #endif
   1223