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