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