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