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