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