Don't assume that sizeof (long) == 4 when computing statistics.
[debian/gzip] / gzip.c
1 /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
2
3    Copyright (C) 1999, 2001-2002, 2006-2007, 2009-2010 Free Software
4    Foundation, Inc.
5    Copyright (C) 1992-1993 Jean-loup Gailly
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3, or (at your option)
10    any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software Foundation,
19    Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */
20
21 /*
22  * The unzip code was written and put in the public domain by Mark Adler.
23  * Portions of the lzw code are derived from the public domain 'compress'
24  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
25  * Ken Turkowski, Dave Mack and Peter Jannesen.
26  *
27  * See the license_msg below and the file COPYING for the software license.
28  * See the file algorithm.doc for the compression algorithms and file formats.
29  */
30
31 static char const *const license_msg[] = {
32 "Copyright (C) 2007, 2010 Free Software Foundation, Inc.",
33 "Copyright (C) 1993 Jean-loup Gailly.",
34 "This is free software.  You may redistribute copies of it under the terms of",
35 "the GNU General Public License <http://www.gnu.org/licenses/gpl.html>.",
36 "There is NO WARRANTY, to the extent permitted by law.",
37 0};
38
39 /* Compress files with zip algorithm and 'compress' interface.
40  * See help() function below for all options.
41  * Outputs:
42  *        file.gz:   compressed file with same mode, owner, and utimes
43  *     or stdout with -c option or if stdin used as input.
44  * If the output file name had to be truncated, the original name is kept
45  * in the compressed file.
46  * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
47  *
48  * Using gz on MSDOS would create too many file name conflicts. For
49  * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
50  * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
51  * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
52  * too heavily. There is no ideal solution given the MSDOS 8+3 limitation.
53  *
54  * For the meaning of all compilation flags, see comments in Makefile.in.
55  */
56
57 #include <config.h>
58 #include <ctype.h>
59 #include <sys/types.h>
60 #include <signal.h>
61 #include <stdbool.h>
62 #include <sys/stat.h>
63 #include <errno.h>
64
65 #include "closein.h"
66 #include "tailor.h"
67 #include "gzip.h"
68 #include "lzw.h"
69 #include "revision.h"
70 #include "timespec.h"
71
72 #include "fcntl-safer.h"
73 #include "getopt.h"
74 #include "ignore-value.h"
75 #include "stat-time.h"
76 #include "version.h"
77
78                 /* configuration */
79
80 #include <fcntl.h>
81 #include <limits.h>
82 #include <unistd.h>
83 #include <stdlib.h>
84 #include <errno.h>
85
86 #ifndef NO_DIR
87 # define NO_DIR 0
88 #endif
89 #if !NO_DIR
90 # include <dirent.h>
91 # ifndef _D_EXACT_NAMLEN
92 #  define _D_EXACT_NAMLEN(dp) strlen ((dp)->d_name)
93 # endif
94 #endif
95
96 #ifdef CLOSEDIR_VOID
97 # define CLOSEDIR(d) (closedir(d), 0)
98 #else
99 # define CLOSEDIR(d) closedir(d)
100 #endif
101
102 #ifndef NO_UTIME
103 #  include <utimens.h>
104 #endif
105
106 #define RW_USER (S_IRUSR | S_IWUSR)  /* creation mode for open() */
107
108 #ifndef MAX_PATH_LEN
109 #  define MAX_PATH_LEN   1024 /* max pathname length */
110 #endif
111
112 #ifndef SEEK_END
113 #  define SEEK_END 2
114 #endif
115
116 #ifndef CHAR_BIT
117 #  define CHAR_BIT 8
118 #endif
119
120 #ifdef off_t
121   off_t lseek OF((int fd, off_t offset, int whence));
122 #endif
123
124 #ifndef OFF_T_MIN
125 #define OFF_T_MIN (~ (off_t) 0 << (sizeof (off_t) * CHAR_BIT - 1))
126 #endif
127
128 #ifndef OFF_T_MAX
129 #define OFF_T_MAX (~ (off_t) 0 - OFF_T_MIN)
130 #endif
131
132 /* Use SA_NOCLDSTOP as a proxy for whether the sigaction machinery is
133    present.  */
134 #ifndef SA_NOCLDSTOP
135 # define SA_NOCLDSTOP 0
136 # define sigprocmask(how, set, oset) /* empty */
137 # define sigset_t int
138 # if ! HAVE_SIGINTERRUPT
139 #  define siginterrupt(sig, flag) /* empty */
140 # endif
141 #endif
142
143 #ifndef HAVE_WORKING_O_NOFOLLOW
144 # define HAVE_WORKING_O_NOFOLLOW 0
145 #endif
146
147 #ifndef ELOOP
148 # define ELOOP EINVAL
149 #endif
150
151 /* Separator for file name parts (see shorten_name()) */
152 #ifdef NO_MULTIPLE_DOTS
153 #  define PART_SEP "-"
154 #else
155 #  define PART_SEP "."
156 #endif
157
158                 /* global buffers */
159
160 DECLARE(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
161 DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
162 DECLARE(ush, d_buf,  DIST_BUFSIZE);
163 DECLARE(uch, window, 2L*WSIZE);
164 #ifndef MAXSEG_64K
165     DECLARE(ush, tab_prefix, 1L<<BITS);
166 #else
167     DECLARE(ush, tab_prefix0, 1L<<(BITS-1));
168     DECLARE(ush, tab_prefix1, 1L<<(BITS-1));
169 #endif
170
171                 /* local variables */
172
173 /* If true, pretend that standard input is a tty.  This option
174    is deliberately not documented, and only for testing.  */
175 static bool presume_input_tty;
176
177 int ascii = 0;        /* convert end-of-lines to local OS conventions */
178 int to_stdout = 0;    /* output to stdout (-c) */
179 int decompress = 0;   /* decompress (-d) */
180 int force = 0;        /* don't ask questions, compress links (-f) */
181 int no_name = -1;     /* don't save or restore the original file name */
182 int no_time = -1;     /* don't save or restore the original file time */
183 int recursive = 0;    /* recurse through directories (-r) */
184 int list = 0;         /* list the file contents (-l) */
185 int verbose = 0;      /* be verbose (-v) */
186 int quiet = 0;        /* be very quiet (-q) */
187 int do_lzw = 0;       /* generate output compatible with old compress (-Z) */
188 int test = 0;         /* test .gz file integrity */
189 int foreground = 0;   /* set if program run in foreground */
190 char *program_name;   /* program name */
191 int maxbits = BITS;   /* max bits per code for LZW */
192 int method = DEFLATED;/* compression method */
193 int level = 6;        /* compression level */
194 int exit_code = OK;   /* program exit code */
195 int save_orig_name;   /* set if original name must be saved */
196 int last_member;      /* set for .zip and .Z files */
197 int part_nb;          /* number of parts in .gz file */
198 struct timespec time_stamp; /* original time stamp (modification time) */
199 off_t ifile_size;      /* input file size, -1 for devices (debug only) */
200 char *env;            /* contents of GZIP env variable */
201 char **args = NULL;   /* argv pointer if GZIP env variable defined */
202 char const *z_suffix; /* default suffix (can be set with --suffix) */
203 size_t z_len;         /* strlen(z_suffix) */
204
205 /* The set of signals that are caught.  */
206 static sigset_t caught_signals;
207
208 /* If nonzero then exit with status WARNING, rather than with the usual
209    signal status, on receipt of a signal with this value.  This
210    suppresses a "Broken Pipe" message with some shells.  */
211 static int volatile exiting_signal;
212
213 /* If nonnegative, close this file descriptor and unlink ofname on error.  */
214 static int volatile remove_ofname_fd = -1;
215
216 off_t bytes_in;             /* number of input bytes */
217 off_t bytes_out;            /* number of output bytes */
218 off_t total_in;             /* input bytes for all files */
219 off_t total_out;            /* output bytes for all files */
220 char ifname[MAX_PATH_LEN]; /* input file name */
221 char ofname[MAX_PATH_LEN]; /* output file name */
222 struct stat istat;         /* status for input file */
223 int  ifd;                  /* input file descriptor */
224 int  ofd;                  /* output file descriptor */
225 unsigned insize;           /* valid bytes in inbuf */
226 unsigned inptr;            /* index of next byte to be processed in inbuf */
227 unsigned outcnt;           /* bytes in output buffer */
228
229 static int handled_sig[] =
230   {
231     /* SIGINT must be first, as 'foreground' depends on it.  */
232     SIGINT
233
234 #ifdef SIGHUP
235     , SIGHUP
236 #endif
237 #ifdef SIGPIPE
238     , SIGPIPE
239 #else
240 # define SIGPIPE 0
241 #endif
242 #ifdef SIGTERM
243     , SIGTERM
244 #endif
245 #ifdef SIGXCPU
246     , SIGXCPU
247 #endif
248 #ifdef SIGXFSZ
249     , SIGXFSZ
250 #endif
251   };
252
253 /* For long options that have no equivalent short option, use a
254    non-character as a pseudo short option, starting with CHAR_MAX + 1.  */
255 enum
256 {
257   PRESUME_INPUT_TTY_OPTION = CHAR_MAX + 1
258 };
259
260 struct option longopts[] =
261 {
262  /* { name  has_arg  *flag  val } */
263     {"ascii",      0, 0, 'a'}, /* ascii text mode */
264     {"to-stdout",  0, 0, 'c'}, /* write output on standard output */
265     {"stdout",     0, 0, 'c'}, /* write output on standard output */
266     {"decompress", 0, 0, 'd'}, /* decompress */
267     {"uncompress", 0, 0, 'd'}, /* decompress */
268  /* {"encrypt",    0, 0, 'e'},    encrypt */
269     {"force",      0, 0, 'f'}, /* force overwrite of output file */
270     {"help",       0, 0, 'h'}, /* give help */
271  /* {"pkzip",      0, 0, 'k'},    force output in pkzip format */
272     {"list",       0, 0, 'l'}, /* list .gz file contents */
273     {"license",    0, 0, 'L'}, /* display software license */
274     {"no-name",    0, 0, 'n'}, /* don't save or restore original name & time */
275     {"name",       0, 0, 'N'}, /* save or restore original name & time */
276     {"-presume-input-tty", no_argument, NULL, PRESUME_INPUT_TTY_OPTION},
277     {"quiet",      0, 0, 'q'}, /* quiet mode */
278     {"silent",     0, 0, 'q'}, /* quiet mode */
279     {"recursive",  0, 0, 'r'}, /* recurse through directories */
280     {"suffix",     1, 0, 'S'}, /* use given suffix instead of .gz */
281     {"test",       0, 0, 't'}, /* test compressed file integrity */
282     {"no-time",    0, 0, 'T'}, /* don't save or restore the time stamp */
283     {"verbose",    0, 0, 'v'}, /* verbose mode */
284     {"version",    0, 0, 'V'}, /* display version number */
285     {"fast",       0, 0, '1'}, /* compress faster */
286     {"best",       0, 0, '9'}, /* compress better */
287     {"lzw",        0, 0, 'Z'}, /* make output compatible with old compress */
288     {"bits",       1, 0, 'b'}, /* max number of bits per code (implies -Z) */
289
290     { 0, 0, 0, 0 }
291 };
292
293 /* local functions */
294
295 local void try_help     OF((void)) ATTRIBUTE_NORETURN;
296 local void help         OF((void));
297 local void license      OF((void));
298 local void version      OF((void));
299 local int input_eof     OF((void));
300 local void treat_stdin  OF((void));
301 local void treat_file   OF((char *iname));
302 local int create_outfile OF((void));
303 local char *get_suffix  OF((char *name));
304 local int  open_input_file OF((char *iname, struct stat *sbuf));
305 local int  make_ofname  OF((void));
306 local void shorten_name  OF((char *name));
307 local int  get_method   OF((int in));
308 local void do_list      OF((int ifd, int method));
309 local int  check_ofname OF((void));
310 local void copy_stat    OF((struct stat *ifstat));
311 local void install_signal_handlers OF((void));
312 local void remove_output_file OF((void));
313 local RETSIGTYPE abort_gzip_signal OF((int));
314 local void do_exit      OF((int exitcode)) ATTRIBUTE_NORETURN;
315       int main          OF((int argc, char **argv));
316 int (*work) OF((int infile, int outfile)) = zip; /* function to call */
317
318 #if ! NO_DIR
319 local void treat_dir    OF((int fd, char *dir));
320 #endif
321
322 #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
323
324 static void
325 try_help ()
326 {
327   fprintf (stderr, "Try `%s --help' for more information.\n",
328            program_name);
329   do_exit (ERROR);
330 }
331
332 /* ======================================================================== */
333 local void help()
334 {
335     static char const* const help_msg[] = {
336  "Compress or uncompress FILEs (by default, compress FILES in-place).",
337  "",
338  "Mandatory arguments to long options are mandatory for short options too.",
339  "",
340 #if O_BINARY
341  "  -a, --ascii       ascii text; convert end-of-line using local conventions",
342 #endif
343  "  -c, --stdout      write on standard output, keep original files unchanged",
344  "  -d, --decompress  decompress",
345 /*  -e, --encrypt     encrypt */
346  "  -f, --force       force overwrite of output file and compress links",
347  "  -h, --help        give this help",
348 /*  -k, --pkzip       force output in pkzip format */
349  "  -l, --list        list compressed file contents",
350  "  -L, --license     display software license",
351 #ifdef UNDOCUMENTED
352  "  -m, --no-time     do not save or restore the original modification time",
353  "  -M, --time        save or restore the original modification time",
354 #endif
355  "  -n, --no-name     do not save or restore the original name and time stamp",
356  "  -N, --name        save or restore the original name and time stamp",
357  "  -q, --quiet       suppress all warnings",
358 #if ! NO_DIR
359  "  -r, --recursive   operate recursively on directories",
360 #endif
361  "  -S, --suffix=SUF  use suffix SUF on compressed files",
362  "  -t, --test        test compressed file integrity",
363  "  -v, --verbose     verbose mode",
364  "  -V, --version     display version number",
365  "  -1, --fast        compress faster",
366  "  -9, --best        compress better",
367 #ifdef LZW
368  "  -Z, --lzw         produce output compatible with old compress",
369  "  -b, --bits=BITS   max number of bits per code (implies -Z)",
370 #endif
371  "",
372  "With no FILE, or when FILE is -, read standard input.",
373  "",
374  "Report bugs to <bug-gzip@gnu.org>.",
375   0};
376     char const *const *p = help_msg;
377
378     printf ("Usage: %s [OPTION]... [FILE]...\n", program_name);
379     while (*p) printf ("%s\n", *p++);
380 }
381
382 /* ======================================================================== */
383 local void license()
384 {
385     char const *const *p = license_msg;
386
387     printf ("%s %s\n", program_name, Version);
388     while (*p) printf ("%s\n", *p++);
389 }
390
391 /* ======================================================================== */
392 local void version()
393 {
394     license ();
395     printf ("\n");
396     printf ("Written by Jean-loup Gailly.\n");
397 }
398
399 local void progerror (char const *string)
400 {
401     int e = errno;
402     fprintf (stderr, "%s: ", program_name);
403     errno = e;
404     perror(string);
405     exit_code = ERROR;
406 }
407
408 /* ======================================================================== */
409 int main (int argc, char **argv)
410 {
411     int file_count;     /* number of files to process */
412     size_t proglen;     /* length of program_name */
413     int optc;           /* current option */
414
415     EXPAND(argc, argv); /* wild card expansion if necessary */
416
417     program_name = gzip_base_name (argv[0]);
418     proglen = strlen (program_name);
419
420     atexit (close_stdin);
421
422     /* Suppress .exe for MSDOS, OS/2 and VMS: */
423     if (4 < proglen && strequ (program_name + proglen - 4, ".exe"))
424       program_name[proglen - 4] = '\0';
425
426     /* Add options in GZIP environment variable if there is one */
427     env = add_envopt(&argc, &argv, OPTIONS_VAR);
428     if (env != NULL) args = argv;
429
430 #ifndef GNU_STANDARD
431 # define GNU_STANDARD 1
432 #endif
433 #if !GNU_STANDARD
434     /* For compatibility with old compress, use program name as an option.
435      * Unless you compile with -DGNU_STANDARD=0, this program will behave as
436      * gzip even if it is invoked under the name gunzip or zcat.
437      *
438      * Systems which do not support links can still use -d or -dc.
439      * Ignore an .exe extension for MSDOS, OS/2 and VMS.
440      */
441     if (strncmp (program_name, "un",  2) == 0     /* ungzip, uncompress */
442         || strncmp (program_name, "gun", 3) == 0) /* gunzip */
443         decompress = 1;
444     else if (strequ (program_name + 1, "cat")     /* zcat, pcat, gcat */
445              || strequ (program_name, "gzcat"))   /* gzcat */
446         decompress = to_stdout = 1;
447 #endif
448
449     z_suffix = Z_SUFFIX;
450     z_len = strlen(z_suffix);
451
452     while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789",
453                                 longopts, (int *)0)) != -1) {
454         switch (optc) {
455         case 'a':
456             ascii = 1; break;
457         case 'b':
458             maxbits = atoi(optarg);
459             for (; *optarg; optarg++)
460               if (! ('0' <= *optarg && *optarg <= '9'))
461                 {
462                   fprintf (stderr, "%s: -b operand is not an integer\n",
463                            program_name);
464                   try_help ();
465                 }
466             break;
467         case 'c':
468             to_stdout = 1; break;
469         case 'd':
470             decompress = 1; break;
471         case 'f':
472             force++; break;
473         case 'h': case 'H':
474             help(); do_exit(OK); break;
475         case 'l':
476             list = decompress = to_stdout = 1; break;
477         case 'L':
478             license(); do_exit(OK); break;
479         case 'm': /* undocumented, may change later */
480             no_time = 1; break;
481         case 'M': /* undocumented, may change later */
482             no_time = 0; break;
483         case 'n':
484             no_name = no_time = 1; break;
485         case 'N':
486             no_name = no_time = 0; break;
487         case PRESUME_INPUT_TTY_OPTION:
488             presume_input_tty = true; break;
489         case 'q':
490             quiet = 1; verbose = 0; break;
491         case 'r':
492 #if NO_DIR
493             fprintf (stderr, "%s: -r not supported on this system\n",
494                      program_name);
495             try_help ();
496 #else
497             recursive = 1;
498 #endif
499             break;
500         case 'S':
501 #ifdef NO_MULTIPLE_DOTS
502             if (*optarg == '.') optarg++;
503 #endif
504             z_len = strlen(optarg);
505             z_suffix = optarg;
506             break;
507         case 't':
508             test = decompress = to_stdout = 1;
509             break;
510         case 'v':
511             verbose++; quiet = 0; break;
512         case 'V':
513             version(); do_exit(OK); break;
514         case 'Z':
515 #ifdef LZW
516             do_lzw = 1; break;
517 #else
518             fprintf(stderr, "%s: -Z not supported in this version\n",
519                     program_name);
520             try_help ();
521             break;
522 #endif
523         case '1':  case '2':  case '3':  case '4':
524         case '5':  case '6':  case '7':  case '8':  case '9':
525             level = optc - '0';
526             break;
527         default:
528             /* Error message already emitted by getopt_long. */
529             try_help ();
530         }
531     } /* loop on all arguments */
532
533     /* By default, save name and timestamp on compression but do not
534      * restore them on decompression.
535      */
536     if (no_time < 0) no_time = decompress;
537     if (no_name < 0) no_name = decompress;
538
539     file_count = argc - optind;
540
541 #if O_BINARY
542 #else
543     if (ascii && !quiet) {
544         fprintf(stderr, "%s: option --ascii ignored on this system\n",
545                 program_name);
546     }
547 #endif
548     if (z_len == 0 || z_len > MAX_SUFFIX) {
549         fprintf(stderr, "%s: invalid suffix '%s'\n", program_name, z_suffix);
550         do_exit(ERROR);
551     }
552
553     if (do_lzw && !decompress) work = lzw;
554
555     /* Allocate all global buffers (for DYN_ALLOC option) */
556     ALLOC(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
557     ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
558     ALLOC(ush, d_buf,  DIST_BUFSIZE);
559     ALLOC(uch, window, 2L*WSIZE);
560 #ifndef MAXSEG_64K
561     ALLOC(ush, tab_prefix, 1L<<BITS);
562 #else
563     ALLOC(ush, tab_prefix0, 1L<<(BITS-1));
564     ALLOC(ush, tab_prefix1, 1L<<(BITS-1));
565 #endif
566
567     exiting_signal = quiet ? SIGPIPE : 0;
568     install_signal_handlers ();
569
570     /* And get to work */
571     if (file_count != 0) {
572         if (to_stdout && !test && !list && (!decompress || !ascii)) {
573             SET_BINARY_MODE(fileno(stdout));
574         }
575         while (optind < argc) {
576             treat_file(argv[optind++]);
577         }
578     } else {  /* Standard input */
579         treat_stdin();
580     }
581     if (list && !quiet && file_count > 1) {
582         do_list(-1, -1); /* print totals */
583     }
584     do_exit(exit_code);
585     return exit_code; /* just to avoid lint warning */
586 }
587
588 /* Return nonzero when at end of file on input.  */
589 local int
590 input_eof ()
591 {
592   if (!decompress || last_member)
593     return 1;
594
595   if (inptr == insize)
596     {
597       if (insize != INBUFSIZ || fill_inbuf (1) == EOF)
598         return 1;
599
600       /* Unget the char that fill_inbuf got.  */
601       inptr = 0;
602     }
603
604   return 0;
605 }
606
607 /* ========================================================================
608  * Compress or decompress stdin
609  */
610 local void treat_stdin()
611 {
612     if (!force && !list
613         && (presume_input_tty
614             || isatty(fileno((FILE *)(decompress ? stdin : stdout))))) {
615         /* Do not send compressed data to the terminal or read it from
616          * the terminal. We get here when user invoked the program
617          * without parameters, so be helpful. According to the GNU standards:
618          *
619          *   If there is one behavior you think is most useful when the output
620          *   is to a terminal, and another that you think is most useful when
621          *   the output is a file or a pipe, then it is usually best to make
622          *   the default behavior the one that is useful with output to a
623          *   terminal, and have an option for the other behavior.
624          *
625          * Here we use the --force option to get the other behavior.
626          */
627         fprintf(stderr,
628     "%s: compressed data not %s a terminal. Use -f to force %scompression.\n",
629                 program_name, decompress ? "read from" : "written to",
630                 decompress ? "de" : "");
631         fprintf (stderr, "For help, type: %s -h\n", program_name);
632         do_exit(ERROR);
633     }
634
635     if (decompress || !ascii) {
636         SET_BINARY_MODE(fileno(stdin));
637     }
638     if (!test && !list && (!decompress || !ascii)) {
639         SET_BINARY_MODE(fileno(stdout));
640     }
641     strcpy(ifname, "stdin");
642     strcpy(ofname, "stdout");
643
644     /* Get the file's time stamp and size.  */
645     if (fstat (fileno (stdin), &istat) != 0)
646       {
647         progerror ("standard input");
648         do_exit (ERROR);
649       }
650     ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1;
651     time_stamp.tv_nsec = -1;
652     if (!no_time || list)
653       {
654         if (S_ISREG (istat.st_mode))
655           time_stamp = get_stat_mtime (&istat);
656         else
657           gettime (&time_stamp);
658       }
659
660     clear_bufs(); /* clear input and output buffers */
661     to_stdout = 1;
662     part_nb = 0;
663     ifd = fileno(stdin);
664
665     if (decompress) {
666         method = get_method(ifd);
667         if (method < 0) {
668             do_exit(exit_code); /* error message already emitted */
669         }
670     }
671     if (list) {
672         do_list(ifd, method);
673         return;
674     }
675
676     /* Actually do the compression/decompression. Loop over zipped members.
677      */
678     for (;;) {
679         if ((*work)(fileno(stdin), fileno(stdout)) != OK) return;
680
681         if (input_eof ())
682           break;
683
684         method = get_method(ifd);
685         if (method < 0) return; /* error message already emitted */
686         bytes_out = 0;            /* required for length check */
687     }
688
689     if (verbose) {
690         if (test) {
691             fprintf(stderr, " OK\n");
692
693         } else if (!decompress) {
694             display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
695             fprintf(stderr, "\n");
696 #ifdef DISPLAY_STDIN_RATIO
697         } else {
698             display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
699             fprintf(stderr, "\n");
700 #endif
701         }
702     }
703 }
704
705 /* ========================================================================
706  * Compress or decompress the given file
707  */
708 local void treat_file(iname)
709     char *iname;
710 {
711     /* Accept "-" as synonym for stdin */
712     if (strequ(iname, "-")) {
713         int cflag = to_stdout;
714         treat_stdin();
715         to_stdout = cflag;
716         return;
717     }
718
719     /* Check if the input file is present, set ifname and istat: */
720     ifd = open_input_file (iname, &istat);
721     if (ifd < 0)
722       return;
723
724     /* If the input name is that of a directory, recurse or ignore: */
725     if (S_ISDIR(istat.st_mode)) {
726 #if ! NO_DIR
727         if (recursive) {
728             treat_dir (ifd, iname);
729             /* Warning: ifname is now garbage */
730             return;
731         }
732 #endif
733         close (ifd);
734         WARN ((stderr, "%s: %s is a directory -- ignored\n",
735                program_name, ifname));
736         return;
737     }
738
739     if (! to_stdout)
740       {
741         if (! S_ISREG (istat.st_mode))
742           {
743             WARN ((stderr,
744                    "%s: %s is not a directory or a regular file - ignored\n",
745                    program_name, ifname));
746             close (ifd);
747             return;
748           }
749         if (istat.st_mode & S_ISUID)
750           {
751             WARN ((stderr, "%s: %s is set-user-ID on execution - ignored\n",
752                    program_name, ifname));
753             close (ifd);
754             return;
755           }
756         if (istat.st_mode & S_ISGID)
757           {
758             WARN ((stderr, "%s: %s is set-group-ID on execution - ignored\n",
759                    program_name, ifname));
760             close (ifd);
761             return;
762           }
763
764         if (! force)
765           {
766             if (istat.st_mode & S_ISVTX)
767               {
768                 WARN ((stderr,
769                        "%s: %s has the sticky bit set - file ignored\n",
770                        program_name, ifname));
771                 close (ifd);
772                 return;
773               }
774             if (2 <= istat.st_nlink)
775               {
776                 WARN ((stderr, "%s: %s has %lu other link%c -- unchanged\n",
777                        program_name, ifname,
778                        (unsigned long int) istat.st_nlink - 1,
779                        istat.st_nlink == 2 ? ' ' : 's'));
780                 close (ifd);
781                 return;
782               }
783           }
784       }
785
786     ifile_size = S_ISREG (istat.st_mode) ? istat.st_size : -1;
787     time_stamp.tv_nsec = -1;
788     if (!no_time || list)
789       time_stamp = get_stat_mtime (&istat);
790
791     /* Generate output file name. For -r and (-t or -l), skip files
792      * without a valid gzip suffix (check done in make_ofname).
793      */
794     if (to_stdout && !list && !test) {
795         strcpy(ofname, "stdout");
796
797     } else if (make_ofname() != OK) {
798         close (ifd);
799         return;
800     }
801
802     clear_bufs(); /* clear input and output buffers */
803     part_nb = 0;
804
805     if (decompress) {
806         method = get_method(ifd); /* updates ofname if original given */
807         if (method < 0) {
808             close(ifd);
809             return;               /* error message already emitted */
810         }
811     }
812     if (list) {
813         do_list(ifd, method);
814         if (close (ifd) != 0)
815           read_error ();
816         return;
817     }
818
819     /* If compressing to a file, check if ofname is not ambiguous
820      * because the operating system truncates names. Otherwise, generate
821      * a new ofname and save the original name in the compressed file.
822      */
823     if (to_stdout) {
824         ofd = fileno(stdout);
825         /* Keep remove_ofname_fd negative.  */
826     } else {
827         if (create_outfile() != OK) return;
828
829         if (!decompress && save_orig_name && !verbose && !quiet) {
830             fprintf(stderr, "%s: %s compressed to %s\n",
831                     program_name, ifname, ofname);
832         }
833     }
834     /* Keep the name even if not truncated except with --no-name: */
835     if (!save_orig_name) save_orig_name = !no_name;
836
837     if (verbose) {
838         fprintf(stderr, "%s:\t", ifname);
839     }
840
841     /* Actually do the compression/decompression. Loop over zipped members.
842      */
843     for (;;) {
844         if ((*work)(ifd, ofd) != OK) {
845             method = -1; /* force cleanup */
846             break;
847         }
848
849         if (input_eof ())
850           break;
851
852         method = get_method(ifd);
853         if (method < 0) break;    /* error message already emitted */
854         bytes_out = 0;            /* required for length check */
855     }
856
857     if (close (ifd) != 0)
858       read_error ();
859
860     if (!to_stdout)
861       {
862         sigset_t oldset;
863         int unlink_errno;
864
865         copy_stat (&istat);
866         if (close (ofd) != 0)
867           write_error ();
868
869         sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
870         remove_ofname_fd = -1;
871         unlink_errno = xunlink (ifname) == 0 ? 0 : errno;
872         sigprocmask (SIG_SETMASK, &oldset, NULL);
873
874         if (unlink_errno)
875           {
876             WARN ((stderr, "%s: ", program_name));
877             if (!quiet)
878               {
879                 errno = unlink_errno;
880                 perror (ifname);
881               }
882           }
883       }
884
885     if (method == -1) {
886         if (!to_stdout)
887           remove_output_file ();
888         return;
889     }
890
891     /* Display statistics */
892     if(verbose) {
893         if (test) {
894             fprintf(stderr, " OK");
895         } else if (decompress) {
896             display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
897         } else {
898             display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
899         }
900         if (!test && !to_stdout) {
901             fprintf(stderr, " -- replaced with %s", ofname);
902         }
903         fprintf(stderr, "\n");
904     }
905 }
906
907 /* ========================================================================
908  * Create the output file. Return OK or ERROR.
909  * Try several times if necessary to avoid truncating the z_suffix. For
910  * example, do not create a compressed file of name "1234567890123."
911  * Sets save_orig_name to true if the file name has been truncated.
912  * IN assertions: the input file has already been open (ifd is set) and
913  *   ofname has already been updated if there was an original name.
914  * OUT assertions: ifd and ofd are closed in case of error.
915  */
916 local int create_outfile()
917 {
918   int name_shortened = 0;
919   int flags = (O_WRONLY | O_CREAT | O_EXCL
920                | (ascii && decompress ? 0 : O_BINARY));
921
922   for (;;)
923     {
924       int open_errno;
925       sigset_t oldset;
926
927       sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
928       remove_ofname_fd = ofd = OPEN (ofname, flags, RW_USER);
929       open_errno = errno;
930       sigprocmask (SIG_SETMASK, &oldset, NULL);
931
932       if (0 <= ofd)
933         break;
934
935       switch (open_errno)
936         {
937 #ifdef ENAMETOOLONG
938         case ENAMETOOLONG:
939           shorten_name (ofname);
940           name_shortened = 1;
941           break;
942 #endif
943
944         case EEXIST:
945           if (check_ofname () != OK)
946             {
947               close (ifd);
948               return ERROR;
949             }
950           break;
951
952         default:
953           progerror (ofname);
954           close (ifd);
955           return ERROR;
956         }
957     }
958
959   if (name_shortened && decompress)
960     {
961       /* name might be too long if an original name was saved */
962       WARN ((stderr, "%s: %s: warning, name truncated\n",
963              program_name, ofname));
964     }
965
966   return OK;
967 }
968
969 /* ========================================================================
970  * Return a pointer to the 'z' suffix of a file name, or NULL. For all
971  * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are
972  * accepted suffixes, in addition to the value of the --suffix option.
973  * ".tgz" is a useful convention for tar.z files on systems limited
974  * to 3 characters extensions. On such systems, ".?z" and ".??z" are
975  * also accepted suffixes. For Unix, we do not want to accept any
976  * .??z suffix as indicating a compressed file; some people use .xyz
977  * to denote volume data.
978  *   On systems allowing multiple versions of the same file (such as VMS),
979  * this function removes any version suffix in the given name.
980  */
981 local char *get_suffix(name)
982     char *name;
983 {
984     int nlen, slen;
985     char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */
986     static char const *known_suffixes[] =
987        {NULL, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z",
988 #ifdef MAX_EXT_CHARS
989           "z",
990 #endif
991           NULL};
992     char const **suf = known_suffixes;
993
994     *suf = z_suffix;
995     if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */
996
997 #ifdef SUFFIX_SEP
998     /* strip a version number from the file name */
999     {
1000         char *v = strrchr(name, SUFFIX_SEP);
1001         if (v != NULL) *v = '\0';
1002     }
1003 #endif
1004     nlen = strlen(name);
1005     if (nlen <= MAX_SUFFIX+2) {
1006         strcpy(suffix, name);
1007     } else {
1008         strcpy(suffix, name+nlen-MAX_SUFFIX-2);
1009     }
1010     strlwr(suffix);
1011     slen = strlen(suffix);
1012     do {
1013        int s = strlen(*suf);
1014        if (slen > s && suffix[slen-s-1] != PATH_SEP
1015            && strequ(suffix + slen - s, *suf)) {
1016            return name+nlen-s;
1017        }
1018     } while (*++suf != NULL);
1019
1020     return NULL;
1021 }
1022
1023
1024 /* Open file NAME with the given flags and mode and store its status
1025    into *ST.  Return a file descriptor to the newly opened file, or -1
1026    (setting errno) on failure.  */
1027 static int
1028 open_and_stat (char *name, int flags, mode_t mode, struct stat *st)
1029 {
1030   int fd;
1031
1032   /* Refuse to follow symbolic links unless -c or -f.  */
1033   if (!to_stdout && !force)
1034     {
1035       if (HAVE_WORKING_O_NOFOLLOW)
1036         flags |= O_NOFOLLOW;
1037       else
1038         {
1039 #if HAVE_LSTAT || defined lstat
1040           if (lstat (name, st) != 0)
1041             return -1;
1042           else if (S_ISLNK (st->st_mode))
1043             {
1044               errno = ELOOP;
1045               return -1;
1046             }
1047 #endif
1048         }
1049     }
1050
1051   fd = OPEN (name, flags, mode);
1052   if (0 <= fd && fstat (fd, st) != 0)
1053     {
1054       int e = errno;
1055       close (fd);
1056       errno = e;
1057       return -1;
1058     }
1059   return fd;
1060 }
1061
1062
1063 /* ========================================================================
1064  * Set ifname to the input file name (with a suffix appended if necessary)
1065  * and istat to its stats. For decompression, if no file exists with the
1066  * original name, try adding successively z_suffix, .gz, .z, -z and .Z.
1067  * For MSDOS, we try only z_suffix and z.
1068  * Return an open file descriptor or -1.
1069  */
1070 static int
1071 open_input_file (iname, sbuf)
1072     char *iname;
1073     struct stat *sbuf;
1074 {
1075     int ilen;  /* strlen(ifname) */
1076     int z_suffix_errno = 0;
1077     static char const *suffixes[] = {NULL, ".gz", ".z", "-z", ".Z", NULL};
1078     char const **suf = suffixes;
1079     char const *s;
1080 #ifdef NO_MULTIPLE_DOTS
1081     char *dot; /* pointer to ifname extension, or NULL */
1082 #endif
1083     int fd;
1084     int open_flags = (O_RDONLY | O_NONBLOCK | O_NOCTTY
1085                       | (ascii && !decompress ? 0 : O_BINARY));
1086
1087     *suf = z_suffix;
1088
1089     if (sizeof ifname - 1 <= strlen (iname))
1090         goto name_too_long;
1091
1092     strcpy(ifname, iname);
1093
1094     /* If input file exists, return OK. */
1095     fd = open_and_stat (ifname, open_flags, RW_USER, sbuf);
1096     if (0 <= fd)
1097       return fd;
1098
1099     if (!decompress || errno != ENOENT) {
1100         progerror(ifname);
1101         return -1;
1102     }
1103     /* file.ext doesn't exist, try adding a suffix (after removing any
1104      * version number for VMS).
1105      */
1106     s = get_suffix(ifname);
1107     if (s != NULL) {
1108         progerror(ifname); /* ifname already has z suffix and does not exist */
1109         return -1;
1110     }
1111 #ifdef NO_MULTIPLE_DOTS
1112     dot = strrchr(ifname, '.');
1113     if (dot == NULL) {
1114         strcat(ifname, ".");
1115         dot = strrchr(ifname, '.');
1116     }
1117 #endif
1118     ilen = strlen(ifname);
1119     if (strequ(z_suffix, ".gz")) suf++;
1120
1121     /* Search for all suffixes */
1122     do {
1123         char const *s0 = s = *suf;
1124         strcpy (ifname, iname);
1125 #ifdef NO_MULTIPLE_DOTS
1126         if (*s == '.') s++;
1127         if (*dot == '\0') strcpy (dot, ".");
1128 #endif
1129 #ifdef MAX_EXT_CHARS
1130         if (MAX_EXT_CHARS < strlen (s) + strlen (dot + 1))
1131           dot[MAX_EXT_CHARS + 1 - strlen (s)] = '\0';
1132 #endif
1133         if (sizeof ifname <= ilen + strlen (s))
1134           goto name_too_long;
1135         strcat(ifname, s);
1136         fd = open_and_stat (ifname, open_flags, RW_USER, sbuf);
1137         if (0 <= fd)
1138           return fd;
1139         if (errno != ENOENT)
1140           {
1141             progerror (ifname);
1142             return -1;
1143           }
1144         if (strequ (s0, z_suffix))
1145           z_suffix_errno = errno;
1146     } while (*++suf != NULL);
1147
1148     /* No suffix found, complain using z_suffix: */
1149     strcpy(ifname, iname);
1150 #ifdef NO_MULTIPLE_DOTS
1151     if (*dot == '\0') strcpy(dot, ".");
1152 #endif
1153 #ifdef MAX_EXT_CHARS
1154     if (MAX_EXT_CHARS < z_len + strlen (dot + 1))
1155       dot[MAX_EXT_CHARS + 1 - z_len] = '\0';
1156 #endif
1157     strcat(ifname, z_suffix);
1158     errno = z_suffix_errno;
1159     progerror(ifname);
1160     return -1;
1161
1162  name_too_long:
1163     fprintf (stderr, "%s: %s: file name too long\n", program_name, iname);
1164     exit_code = ERROR;
1165     return -1;
1166 }
1167
1168 /* ========================================================================
1169  * Generate ofname given ifname. Return OK, or WARNING if file must be skipped.
1170  * Sets save_orig_name to true if the file name has been truncated.
1171  */
1172 local int make_ofname()
1173 {
1174     char *suff;            /* ofname z suffix */
1175
1176     strcpy(ofname, ifname);
1177     /* strip a version number if any and get the gzip suffix if present: */
1178     suff = get_suffix(ofname);
1179
1180     if (decompress) {
1181         if (suff == NULL) {
1182             /* With -t or -l, try all files (even without .gz suffix)
1183              * except with -r (behave as with just -dr).
1184              */
1185             if (!recursive && (list || test)) return OK;
1186
1187             /* Avoid annoying messages with -r */
1188             if (verbose || (!recursive && !quiet)) {
1189                 WARN((stderr,"%s: %s: unknown suffix -- ignored\n",
1190                       program_name, ifname));
1191             }
1192             return WARNING;
1193         }
1194         /* Make a special case for .tgz and .taz: */
1195         strlwr(suff);
1196         if (strequ(suff, ".tgz") || strequ(suff, ".taz")) {
1197             strcpy(suff, ".tar");
1198         } else {
1199             *suff = '\0'; /* strip the z suffix */
1200         }
1201         /* ofname might be changed later if infile contains an original name */
1202
1203     } else if (suff && ! force) {
1204         /* Avoid annoying messages with -r (see treat_dir()) */
1205         if (verbose || (!recursive && !quiet)) {
1206             /* Don't use WARN, as it affects exit status.  */
1207             fprintf (stderr, "%s: %s already has %s suffix -- unchanged\n",
1208                      program_name, ifname, suff);
1209         }
1210         return WARNING;
1211     } else {
1212         save_orig_name = 0;
1213
1214 #ifdef NO_MULTIPLE_DOTS
1215         suff = strrchr(ofname, '.');
1216         if (suff == NULL) {
1217             if (sizeof ofname <= strlen (ofname) + 1)
1218                 goto name_too_long;
1219             strcat(ofname, ".");
1220 #  ifdef MAX_EXT_CHARS
1221             if (strequ(z_suffix, "z")) {
1222                 if (sizeof ofname <= strlen (ofname) + 2)
1223                     goto name_too_long;
1224                 strcat(ofname, "gz"); /* enough room */
1225                 return OK;
1226             }
1227         /* On the Atari and some versions of MSDOS,
1228          * ENAMETOOLONG does not work correctly.  So we
1229          * must truncate here.
1230          */
1231         } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) {
1232             suff[MAX_SUFFIX+1-z_len] = '\0';
1233             save_orig_name = 1;
1234 #  endif
1235         }
1236 #endif /* NO_MULTIPLE_DOTS */
1237         if (sizeof ofname <= strlen (ofname) + z_len)
1238             goto name_too_long;
1239         strcat(ofname, z_suffix);
1240
1241     } /* decompress ? */
1242     return OK;
1243
1244  name_too_long:
1245     WARN ((stderr, "%s: %s: file name too long\n", program_name, ifname));
1246     return WARNING;
1247 }
1248
1249
1250 /* ========================================================================
1251  * Check the magic number of the input file and update ofname if an
1252  * original name was given and to_stdout is not set.
1253  * Return the compression method, -1 for error, -2 for warning.
1254  * Set inptr to the offset of the next byte to be processed.
1255  * Updates time_stamp if there is one and --no-time is not used.
1256  * This function may be called repeatedly for an input file consisting
1257  * of several contiguous gzip'ed members.
1258  * IN assertions: there is at least one remaining compressed member.
1259  *   If the member is a zip file, it must be the only one.
1260  */
1261 local int get_method(in)
1262     int in;        /* input file descriptor */
1263 {
1264     uch flags;     /* compression flags */
1265     char magic[2]; /* magic header */
1266     int imagic0;   /* first magic byte or EOF */
1267     int imagic1;   /* like magic[1], but can represent EOF */
1268     ulg stamp;     /* time stamp */
1269
1270     /* If --force and --stdout, zcat == cat, so do not complain about
1271      * premature end of file: use try_byte instead of get_byte.
1272      */
1273     if (force && to_stdout) {
1274         imagic0 = try_byte();
1275         magic[0] = (char) imagic0;
1276         imagic1 = try_byte ();
1277         magic[1] = (char) imagic1;
1278         /* If try_byte returned EOF, magic[1] == (char) EOF.  */
1279     } else {
1280         magic[0] = (char)get_byte();
1281         imagic0 = 0;
1282         if (magic[0]) {
1283             magic[1] = (char)get_byte();
1284             imagic1 = 0; /* avoid lint warning */
1285         } else {
1286             imagic1 = try_byte ();
1287             magic[1] = (char) imagic1;
1288         }
1289     }
1290     method = -1;                 /* unknown yet */
1291     part_nb++;                   /* number of parts in gzip file */
1292     header_bytes = 0;
1293     last_member = RECORD_IO;
1294     /* assume multiple members in gzip file except for record oriented I/O */
1295
1296     if (memcmp(magic, GZIP_MAGIC, 2) == 0
1297         || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) {
1298
1299         method = (int)get_byte();
1300         if (method != DEFLATED) {
1301             fprintf(stderr,
1302                     "%s: %s: unknown method %d -- not supported\n",
1303                     program_name, ifname, method);
1304             exit_code = ERROR;
1305             return -1;
1306         }
1307         work = unzip;
1308         flags  = (uch)get_byte();
1309
1310         if ((flags & ENCRYPTED) != 0) {
1311             fprintf(stderr,
1312                     "%s: %s is encrypted -- not supported\n",
1313                     program_name, ifname);
1314             exit_code = ERROR;
1315             return -1;
1316         }
1317         if ((flags & CONTINUATION) != 0) {
1318             fprintf(stderr,
1319                     "%s: %s is a multi-part gzip file -- not supported\n",
1320                     program_name, ifname);
1321             exit_code = ERROR;
1322             if (force <= 1) return -1;
1323         }
1324         if ((flags & RESERVED) != 0) {
1325             fprintf(stderr,
1326                     "%s: %s has flags 0x%x -- not supported\n",
1327                     program_name, ifname, flags);
1328             exit_code = ERROR;
1329             if (force <= 1) return -1;
1330         }
1331         stamp  = (ulg)get_byte();
1332         stamp |= ((ulg)get_byte()) << 8;
1333         stamp |= ((ulg)get_byte()) << 16;
1334         stamp |= ((ulg)get_byte()) << 24;
1335         if (stamp != 0 && !no_time)
1336           {
1337             time_stamp.tv_sec = stamp;
1338             time_stamp.tv_nsec = 0;
1339           }
1340
1341         (void)get_byte();  /* Ignore extra flags for the moment */
1342         (void)get_byte();  /* Ignore OS type for the moment */
1343
1344         if ((flags & CONTINUATION) != 0) {
1345             unsigned part = (unsigned)get_byte();
1346             part |= ((unsigned)get_byte())<<8;
1347             if (verbose) {
1348                 fprintf(stderr,"%s: %s: part number %u\n",
1349                         program_name, ifname, part);
1350             }
1351         }
1352         if ((flags & EXTRA_FIELD) != 0) {
1353             unsigned len = (unsigned)get_byte();
1354             len |= ((unsigned)get_byte())<<8;
1355             if (verbose) {
1356                 fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n",
1357                         program_name, ifname, len);
1358             }
1359             while (len--) (void)get_byte();
1360         }
1361
1362         /* Get original file name if it was truncated */
1363         if ((flags & ORIG_NAME) != 0) {
1364             if (no_name || (to_stdout && !list) || part_nb > 1) {
1365                 /* Discard the old name */
1366                 char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */
1367                 do {c=get_byte();} while (c != 0);
1368             } else {
1369                 /* Copy the base name. Keep a directory prefix intact. */
1370                 char *p = gzip_base_name (ofname);
1371                 char *base = p;
1372                 for (;;) {
1373                     *p = (char)get_char();
1374                     if (*p++ == '\0') break;
1375                     if (p >= ofname+sizeof(ofname)) {
1376                         gzip_error ("corrupted input -- file name too large");
1377                     }
1378                 }
1379                 p = gzip_base_name (base);
1380                 memmove (base, p, strlen (p) + 1);
1381                 /* If necessary, adapt the name to local OS conventions: */
1382                 if (!list) {
1383                    MAKE_LEGAL_NAME(base);
1384                    if (base) list=0; /* avoid warning about unused variable */
1385                 }
1386             } /* no_name || to_stdout */
1387         } /* ORIG_NAME */
1388
1389         /* Discard file comment if any */
1390         if ((flags & COMMENT) != 0) {
1391             while (get_char() != 0) /* null */ ;
1392         }
1393         if (part_nb == 1) {
1394             header_bytes = inptr + 2*4; /* include crc and size */
1395         }
1396
1397     } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2
1398             && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) {
1399         /* To simplify the code, we support a zip file when alone only.
1400          * We are thus guaranteed that the entire local header fits in inbuf.
1401          */
1402         inptr = 0;
1403         work = unzip;
1404         if (check_zipfile(in) != OK) return -1;
1405         /* check_zipfile may get ofname from the local header */
1406         last_member = 1;
1407
1408     } else if (memcmp(magic, PACK_MAGIC, 2) == 0) {
1409         work = unpack;
1410         method = PACKED;
1411
1412     } else if (memcmp(magic, LZW_MAGIC, 2) == 0) {
1413         work = unlzw;
1414         method = COMPRESSED;
1415         last_member = 1;
1416
1417     } else if (memcmp(magic, LZH_MAGIC, 2) == 0) {
1418         work = unlzh;
1419         method = LZHED;
1420         last_member = 1;
1421
1422     } else if (force && to_stdout && !list) { /* pass input unchanged */
1423         method = STORED;
1424         work = copy;
1425         if (imagic1 != EOF)
1426             inptr--;
1427         last_member = 1;
1428         if (imagic0 != EOF) {
1429             write_buf(fileno(stdout), magic, 1);
1430             bytes_out++;
1431         }
1432     }
1433     if (method >= 0) return method;
1434
1435     if (part_nb == 1) {
1436         fprintf (stderr, "\n%s: %s: not in gzip format\n",
1437                  program_name, ifname);
1438         exit_code = ERROR;
1439         return -1;
1440     } else {
1441         if (magic[0] == 0)
1442           {
1443             int inbyte;
1444             for (inbyte = imagic1;  inbyte == 0;  inbyte = try_byte ())
1445               continue;
1446             if (inbyte == EOF)
1447               {
1448                 if (verbose)
1449                   WARN ((stderr, "\n%s: %s: decompression OK, trailing zero bytes ignored\n",
1450                          program_name, ifname));
1451                 return -3;
1452               }
1453           }
1454
1455         WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n",
1456               program_name, ifname));
1457         return -2;
1458     }
1459 }
1460
1461 /* ========================================================================
1462  * Display the characteristics of the compressed file.
1463  * If the given method is < 0, display the accumulated totals.
1464  * IN assertions: time_stamp, header_bytes and ifile_size are initialized.
1465  */
1466 local void do_list(ifd, method)
1467     int ifd;     /* input file descriptor */
1468     int method;  /* compression method */
1469 {
1470     ulg crc;  /* original crc */
1471     static int first_time = 1;
1472     static char const *const methods[MAX_METHODS] = {
1473         "store",  /* 0 */
1474         "compr",  /* 1 */
1475         "pack ",  /* 2 */
1476         "lzh  ",  /* 3 */
1477         "", "", "", "", /* 4 to 7 reserved */
1478         "defla"}; /* 8 */
1479     int positive_off_t_width = 1;
1480     off_t o;
1481
1482     for (o = OFF_T_MAX;  9 < o;  o /= 10) {
1483         positive_off_t_width++;
1484     }
1485
1486     if (first_time && method >= 0) {
1487         first_time = 0;
1488         if (verbose)  {
1489             printf("method  crc     date  time  ");
1490         }
1491         if (!quiet) {
1492             printf("%*.*s %*.*s  ratio uncompressed_name\n",
1493                    positive_off_t_width, positive_off_t_width, "compressed",
1494                    positive_off_t_width, positive_off_t_width, "uncompressed");
1495         }
1496     } else if (method < 0) {
1497         if (total_in <= 0 || total_out <= 0) return;
1498         if (verbose) {
1499             printf("                            ");
1500         }
1501         if (verbose || !quiet) {
1502             fprint_off(stdout, total_in, positive_off_t_width);
1503             printf(" ");
1504             fprint_off(stdout, total_out, positive_off_t_width);
1505             printf(" ");
1506         }
1507         display_ratio(total_out-(total_in-header_bytes), total_out, stdout);
1508         /* header_bytes is not meaningful but used to ensure the same
1509          * ratio if there is a single file.
1510          */
1511         printf(" (totals)\n");
1512         return;
1513     }
1514     crc = (ulg)~0; /* unknown */
1515     bytes_out = -1L;
1516     bytes_in = ifile_size;
1517
1518 #if RECORD_IO == 0
1519     if (method == DEFLATED && !last_member) {
1520         /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files.
1521          * If the lseek fails, we could use read() to get to the end, but
1522          * --list is used to get quick results.
1523          * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if
1524          * you are not concerned about speed.
1525          */
1526         bytes_in = lseek(ifd, (off_t)(-8), SEEK_END);
1527         if (bytes_in != -1L) {
1528             uch buf[8];
1529             bytes_in += 8L;
1530             if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) {
1531                 read_error();
1532             }
1533             crc       = LG(buf);
1534             bytes_out = LG(buf+4);
1535         }
1536     }
1537 #endif /* RECORD_IO */
1538     if (verbose)
1539       {
1540         struct tm *tm = localtime (&time_stamp.tv_sec);
1541         printf ("%5s %08lx ", methods[method], crc);
1542         if (tm)
1543           printf ("%s%3d %02d:%02d ",
1544                   ("Jan\0Feb\0Mar\0Apr\0May\0Jun\0Jul\0Aug\0Sep\0Oct\0Nov\0Dec"
1545                    + 4 * tm->tm_mon),
1546                   tm->tm_mday, tm->tm_hour, tm->tm_min);
1547         else
1548           printf ("??? ?? ??:?? ");
1549       }
1550     fprint_off(stdout, bytes_in, positive_off_t_width);
1551     printf(" ");
1552     fprint_off(stdout, bytes_out, positive_off_t_width);
1553     printf(" ");
1554     if (bytes_in  == -1L) {
1555         total_in = -1L;
1556         bytes_in = bytes_out = header_bytes = 0;
1557     } else if (total_in >= 0) {
1558         total_in  += bytes_in;
1559     }
1560     if (bytes_out == -1L) {
1561         total_out = -1L;
1562         bytes_in = bytes_out = header_bytes = 0;
1563     } else if (total_out >= 0) {
1564         total_out += bytes_out;
1565     }
1566     display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout);
1567     printf(" %s\n", ofname);
1568 }
1569
1570 /* ========================================================================
1571  * Shorten the given name by one character, or replace a .tar extension
1572  * with .tgz. Truncate the last part of the name which is longer than
1573  * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name
1574  * has only parts shorter than MIN_PART truncate the longest part.
1575  * For decompression, just remove the last character of the name.
1576  *
1577  * IN assertion: for compression, the suffix of the given name is z_suffix.
1578  */
1579 local void shorten_name(name)
1580     char *name;
1581 {
1582     int len;                 /* length of name without z_suffix */
1583     char *trunc = NULL;      /* character to be truncated */
1584     int plen;                /* current part length */
1585     int min_part = MIN_PART; /* current minimum part length */
1586     char *p;
1587
1588     len = strlen(name);
1589     if (decompress) {
1590         if (len <= 1)
1591           gzip_error ("name too short");
1592         name[len-1] = '\0';
1593         return;
1594     }
1595     p = get_suffix(name);
1596     if (! p)
1597       gzip_error ("can't recover suffix\n");
1598     *p = '\0';
1599     save_orig_name = 1;
1600
1601     /* compress 1234567890.tar to 1234567890.tgz */
1602     if (len > 4 && strequ(p-4, ".tar")) {
1603         strcpy(p-4, ".tgz");
1604         return;
1605     }
1606     /* Try keeping short extensions intact:
1607      * 1234.678.012.gz -> 123.678.012.gz
1608      */
1609     do {
1610         p = strrchr(name, PATH_SEP);
1611         p = p ? p+1 : name;
1612         while (*p) {
1613             plen = strcspn(p, PART_SEP);
1614             p += plen;
1615             if (plen > min_part) trunc = p-1;
1616             if (*p) p++;
1617         }
1618     } while (trunc == NULL && --min_part != 0);
1619
1620     if (trunc != NULL) {
1621         do {
1622             trunc[0] = trunc[1];
1623         } while (*trunc++);
1624         trunc--;
1625     } else {
1626         trunc = strrchr(name, PART_SEP[0]);
1627         if (!trunc)
1628           gzip_error ("internal error in shorten_name");
1629         if (trunc[1] == '\0') trunc--; /* force truncation */
1630     }
1631     strcpy(trunc, z_suffix);
1632 }
1633
1634 /* ========================================================================
1635  * The compressed file already exists, so ask for confirmation.
1636  * Return ERROR if the file must be skipped.
1637  */
1638 local int check_ofname()
1639 {
1640     /* Ask permission to overwrite the existing file */
1641     if (!force) {
1642         int ok = 0;
1643         fprintf (stderr, "%s: %s already exists;", program_name, ofname);
1644         if (foreground && (presume_input_tty || isatty(fileno(stdin)))) {
1645             fprintf(stderr, " do you wish to overwrite (y or n)? ");
1646             fflush(stderr);
1647             ok = yesno();
1648         }
1649         if (!ok) {
1650             fprintf(stderr, "\tnot overwritten\n");
1651             if (exit_code == OK) exit_code = WARNING;
1652             return ERROR;
1653         }
1654     }
1655     if (xunlink (ofname)) {
1656         progerror(ofname);
1657         return ERROR;
1658     }
1659     return OK;
1660 }
1661
1662
1663 /* ========================================================================
1664  * Copy modes, times, ownership from input file to output file.
1665  * IN assertion: to_stdout is false.
1666  */
1667 local void copy_stat(ifstat)
1668     struct stat *ifstat;
1669 {
1670     mode_t mode = ifstat->st_mode & S_IRWXUGO;
1671     int r;
1672
1673 #ifndef NO_UTIME
1674     struct timespec timespec[2];
1675     timespec[0] = get_stat_atime (ifstat);
1676     timespec[1] = get_stat_mtime (ifstat);
1677
1678     if (decompress && 0 <= time_stamp.tv_nsec
1679         && ! (timespec[1].tv_sec == time_stamp.tv_sec
1680               && timespec[1].tv_nsec == time_stamp.tv_nsec))
1681       {
1682         timespec[1] = time_stamp;
1683         if (verbose > 1) {
1684             fprintf(stderr, "%s: time stamp restored\n", ofname);
1685         }
1686       }
1687
1688     if (gl_futimens (ofd, ofname, timespec) != 0)
1689       {
1690         int e = errno;
1691         WARN ((stderr, "%s: ", program_name));
1692         if (!quiet)
1693           {
1694             errno = e;
1695             perror (ofname);
1696           }
1697       }
1698 #endif
1699
1700 #ifndef NO_CHOWN
1701     /* Copy ownership */
1702 # if HAVE_FCHOWN
1703     ignore_value (fchown (ofd, ifstat->st_uid, ifstat->st_gid));
1704 # elif HAVE_CHOWN
1705     ignore_value (chown (ofname, ifstat->st_uid, ifstat->st_gid));
1706 # endif
1707 #endif
1708
1709     /* Copy the protection modes */
1710 #if HAVE_FCHMOD
1711     r = fchmod (ofd, mode);
1712 #else
1713     r = chmod (ofname, mode);
1714 #endif
1715     if (r != 0) {
1716         int e = errno;
1717         WARN ((stderr, "%s: ", program_name));
1718         if (!quiet) {
1719             errno = e;
1720             perror(ofname);
1721         }
1722     }
1723 }
1724
1725 #if ! NO_DIR
1726
1727 /* ========================================================================
1728  * Recurse through the given directory. This code is taken from ncompress.
1729  */
1730 local void treat_dir (fd, dir)
1731     int fd;
1732     char *dir;
1733 {
1734     struct dirent *dp;
1735     DIR      *dirp;
1736     char     nbuf[MAX_PATH_LEN];
1737     int      len;
1738
1739     dirp = fdopendir (fd);
1740
1741     if (dirp == NULL) {
1742         progerror(dir);
1743         close (fd);
1744         return ;
1745     }
1746     /*
1747      ** WARNING: the following algorithm could occasionally cause
1748      ** compress to produce error warnings of the form "<filename>.gz
1749      ** already has .gz suffix - ignored". This occurs when the
1750      ** .gz output file is inserted into the directory below
1751      ** readdir's current pointer.
1752      ** These warnings are harmless but annoying, so they are suppressed
1753      ** with option -r (except when -v is on). An alternative
1754      ** to allowing this would be to store the entire directory
1755      ** list in memory, then compress the entries in the stored
1756      ** list. Given the depth-first recursive algorithm used here,
1757      ** this could use up a tremendous amount of memory. I don't
1758      ** think it's worth it. -- Dave Mack
1759      ** (An other alternative might be two passes to avoid depth-first.)
1760      */
1761
1762     while ((errno = 0, dp = readdir(dirp)) != NULL) {
1763
1764         if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) {
1765             continue;
1766         }
1767         len = strlen(dir);
1768         if (len + _D_EXACT_NAMLEN (dp) + 1 < MAX_PATH_LEN - 1) {
1769             strcpy(nbuf,dir);
1770             if (len != 0 /* dir = "" means current dir on Amiga */
1771 #ifdef PATH_SEP2
1772                 && dir[len-1] != PATH_SEP2
1773 #endif
1774 #ifdef PATH_SEP3
1775                 && dir[len-1] != PATH_SEP3
1776 #endif
1777             ) {
1778                 nbuf[len++] = PATH_SEP;
1779             }
1780             strcpy(nbuf+len, dp->d_name);
1781             treat_file(nbuf);
1782         } else {
1783             fprintf(stderr,"%s: %s/%s: pathname too long\n",
1784                     program_name, dir, dp->d_name);
1785             exit_code = ERROR;
1786         }
1787     }
1788     if (errno != 0)
1789         progerror(dir);
1790     if (CLOSEDIR(dirp) != 0)
1791         progerror(dir);
1792 }
1793 #endif /* ! NO_DIR */
1794
1795 /* Make sure signals get handled properly.  */
1796
1797 static void
1798 install_signal_handlers ()
1799 {
1800   int nsigs = sizeof handled_sig / sizeof handled_sig[0];
1801   int i;
1802
1803 #if SA_NOCLDSTOP
1804   struct sigaction act;
1805
1806   sigemptyset (&caught_signals);
1807   for (i = 0; i < nsigs; i++)
1808     {
1809       sigaction (handled_sig[i], NULL, &act);
1810       if (act.sa_handler != SIG_IGN)
1811         sigaddset (&caught_signals, handled_sig[i]);
1812     }
1813
1814   act.sa_handler = abort_gzip_signal;
1815   act.sa_mask = caught_signals;
1816   act.sa_flags = 0;
1817
1818   for (i = 0; i < nsigs; i++)
1819     if (sigismember (&caught_signals, handled_sig[i]))
1820       {
1821         if (i == 0)
1822           foreground = 1;
1823         sigaction (handled_sig[i], &act, NULL);
1824       }
1825 #else
1826   for (i = 0; i < nsigs; i++)
1827     if (signal (handled_sig[i], SIG_IGN) != SIG_IGN)
1828       {
1829         if (i == 0)
1830           foreground = 1;
1831         signal (handled_sig[i], abort_gzip_signal);
1832         siginterrupt (handled_sig[i], 1);
1833       }
1834 #endif
1835 }
1836
1837 /* ========================================================================
1838  * Free all dynamically allocated variables and exit with the given code.
1839  */
1840 local void do_exit(exitcode)
1841     int exitcode;
1842 {
1843     static int in_exit = 0;
1844
1845     if (in_exit) exit(exitcode);
1846     in_exit = 1;
1847     free(env);
1848     env  = NULL;
1849     free(args);
1850     args = NULL;
1851     FREE(inbuf);
1852     FREE(outbuf);
1853     FREE(d_buf);
1854     FREE(window);
1855 #ifndef MAXSEG_64K
1856     FREE(tab_prefix);
1857 #else
1858     FREE(tab_prefix0);
1859     FREE(tab_prefix1);
1860 #endif
1861     exit(exitcode);
1862 }
1863
1864 /* ========================================================================
1865  * Close and unlink the output file.
1866  */
1867 static void
1868 remove_output_file ()
1869 {
1870   int fd;
1871   sigset_t oldset;
1872
1873   sigprocmask (SIG_BLOCK, &caught_signals, &oldset);
1874   fd = remove_ofname_fd;
1875   if (0 <= fd)
1876     {
1877       remove_ofname_fd = -1;
1878       close (fd);
1879       xunlink (ofname);
1880     }
1881   sigprocmask (SIG_SETMASK, &oldset, NULL);
1882 }
1883
1884 /* ========================================================================
1885  * Error handler.
1886  */
1887 void
1888 abort_gzip ()
1889 {
1890    remove_output_file ();
1891    do_exit(ERROR);
1892 }
1893
1894 /* ========================================================================
1895  * Signal handler.
1896  */
1897 static RETSIGTYPE
1898 abort_gzip_signal (sig)
1899      int sig;
1900 {
1901   if (! SA_NOCLDSTOP)
1902     signal (sig, SIG_IGN);
1903    remove_output_file ();
1904    if (sig == exiting_signal)
1905      _exit (WARNING);
1906    signal (sig, SIG_DFL);
1907    raise (sig);
1908 }