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