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