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