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