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