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