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