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