home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / gzip-1.2.3 / gzip.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-06-23  |  49.1 KB  |  1,684 lines

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