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