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