home *** CD-ROM | disk | FTP | other *** search
/ Meeting Pearls 1 / Meeting Pearls Vol 1 (1994).iso / installed_progs / linux / tools / amiga / gzip-1.1.2.lha / gzip-1.1.2 / gzip.c < prev    next >
Encoding:
C/C++ Source or Header  |  1993-06-04  |  42.6 KB  |  1,467 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 OS does not support file names with multiple dots (MSDOS, VMS) or
  35.  * if the output file name had to be truncated, the original name is kept
  36.  * in the compressed file.
  37.  * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
  38.  *
  39.  * For the meaning of all compilation flags, see comments in Makefile.in.
  40.  */
  41.  
  42. #ifndef lint
  43. static char rcsid[] = "$Id: gzip.c,v 0.19 1993/06/01 14:21:46 jloup Exp $";
  44. #endif
  45.  
  46. #include <stdio.h>
  47. #include <ctype.h>
  48. #include <sys/types.h>
  49. #include <signal.h>
  50. #include <sys/stat.h>
  51. #include <errno.h>
  52.  
  53. #include "tailor.h"
  54. #include "gzip.h"
  55. #include "lzw.h"
  56. #include "revision.h"
  57. #include "getopt.h"
  58.  
  59.         /* configuration */
  60.  
  61. #ifndef NO_FCNTL_H
  62. #  include <fcntl.h>
  63. #endif
  64.  
  65. #ifdef HAVE_UNISTD_H
  66. #  include <unistd.h>
  67. #endif
  68.  
  69. #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
  70. #  include <stdlib.h>
  71. #else
  72.    extern int errno;
  73. #endif
  74.  
  75. #if defined(DIRENT)
  76. #  include <dirent.h>
  77.    typedef struct dirent dir_type;
  78. #  define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
  79. #  define DIR_OPT "DIRENT"
  80. #else
  81. #  define NLENGTH(dirent) ((dirent)->d_namlen)
  82. #  ifdef SYSDIR
  83. #    include <sys/dir.h>
  84.      typedef struct direct dir_type;
  85. #    define DIR_OPT "SYSDIR"
  86. #  else
  87. #    ifdef SYSNDIR
  88. #      include <sys/ndir.h>
  89.        typedef struct direct dir_type;
  90. #      define DIR_OPT "SYSNDIR"
  91. #    else
  92. #      ifdef NDIR
  93. #        include <ndir.h>
  94.          typedef struct direct dir_type;
  95. #        define DIR_OPT "NDIR"
  96. #      else
  97. #        define NO_DIR
  98. #        define DIR_OPT "NO_DIR"
  99. #      endif
  100. #    endif
  101. #  endif
  102. #endif
  103.  
  104. #ifndef NO_UTIME
  105. #  ifndef NO_UTIME_H
  106. #    include <utime.h>
  107. #    define TIME_OPT "UTIME"
  108. #  else
  109. #    ifdef HAVE_SYS_UTIME_H
  110. #      include <sys/utime.h>
  111. #      define TIME_OPT "SYS_UTIME"
  112. #    else
  113.        struct utimbuf {
  114.          time_t actime;
  115.          time_t modtime;
  116.        };
  117. #      define TIME_OPT ""
  118. #    endif
  119. #  endif
  120. #else
  121. #  define TIME_OPT "NO_UTIME"
  122. #endif
  123.  
  124. #if !defined(S_ISDIR) && defined(S_IFDIR)
  125. #  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
  126. #endif
  127. #if !defined(S_ISREG) && defined(S_IFREG)
  128. #  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
  129. #endif
  130.  
  131. typedef RETSIGTYPE (*sig_type) OF((int));
  132.  
  133. #ifndef    O_BINARY
  134. #  define  O_BINARY  0  /* creation mode for open() */
  135. #endif
  136.  
  137. #ifndef O_CREAT
  138.    /* Pure BSD system? */
  139. #  include <sys/file.h>
  140. #  ifndef O_CREAT
  141. #    define O_CREAT FCREAT
  142. #  endif
  143. #  ifndef O_EXCL
  144. #    define O_EXCL FEXCL
  145. #  endif
  146. #endif
  147.  
  148. #ifndef S_IRUSR
  149. #  define S_IRUSR 0400
  150. #endif
  151. #ifndef S_IWUSR
  152. #  define S_IWUSR 0200
  153. #endif
  154. #define RW_USER (S_IRUSR | S_IWUSR)  /* creation mode for open() */
  155.  
  156. #ifndef MAX_PATH_LEN
  157. #  define MAX_PATH_LEN   1024 /* max pathname length */
  158. #endif
  159.  
  160. #define MAX_HEADER_LEN   16
  161. /* max length of a compressed file header, fixed part only */
  162.  
  163.         /* global buffers */
  164.  
  165. DECLARE(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  166. DECLARE(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  167. DECLARE(ush, d_buf,  DIST_BUFSIZE);
  168. DECLARE(uch, window, 2L*WSIZE);
  169. #ifndef MAXSEG_64K
  170.     DECLARE(ush, tab_prefix, 1L<<BITS);
  171. #else
  172.     DECLARE(ush, tab_prefix0, 1L<<(BITS-1));
  173.     DECLARE(ush, tab_prefix1, 1L<<(BITS-1));
  174. #endif
  175.  
  176.         /* local variables */
  177.  
  178. int ascii = 0;        /* convert end-of-lines to local OS conventions */
  179. int to_stdout = 0;    /* output to stdout (-c) */
  180. int decompress = 0;   /* decompress (-d) */
  181. int force = 0;        /* don't ask questions, compress links (-f) */
  182. int recursive = 0;    /* recurse through directories (-r) */
  183. int verbose = 0;      /* be verbose (-v) */
  184. int quiet = 0;        /* be very quiet (-q) */
  185. int do_lzw = 0;       /* generate output compatible with old compress (-Z) */
  186. int test = 0;         /* test .gz file integrity */
  187. int foreground;       /* set if program run in foreground */
  188. char *progname;       /* program name */
  189. int maxbits = BITS;   /* max bits per code for LZW */
  190. int method = DEFLATED;/* compression method */
  191. int level = 5;        /* compression level */
  192. int exit_code = OK;   /* program exit code */
  193. int save_orig_name;   /* set if original name must be saved */
  194. int last_member;      /* set for .zip and .Z files */
  195. int part_nb;          /* number of parts in .gz file */
  196. ulg time_stamp;       /* original time stamp (modification time) */
  197. long ifile_size;      /* input file size, -1 for devices (debug only) */
  198. char *env;            /* contents of GZIP env variable */
  199. char **args = NULL;   /* argv pointer if GZIP env variable defined */
  200. char z_suffix[MAX_SUFFIX+1]; /* default suffix (can be set with --suffix) */
  201. int  z_len;           /* strlen(z_suffix) */
  202.  
  203. long bytes_in;             /* number of input bytes */
  204. long bytes_out;            /* number of output bytes */
  205. char ifname[MAX_PATH_LEN]; /* input file name */
  206. char ofname[MAX_PATH_LEN]; /* output file name */
  207. int  remove_ofname = 0;       /* remove output file on error */
  208. struct stat istat;         /* status for input file */
  209. int  ifd;                  /* input file descriptor */
  210. int  ofd;                  /* output file descriptor */
  211. unsigned insize;           /* valid bytes in inbuf */
  212. unsigned inptr;            /* index of next byte to be processed in inbuf */
  213. unsigned outcnt;           /* bytes in output buffer */
  214.  
  215. struct option longopts[] =
  216. {
  217.  /* { name  has_arg  *flag  val } */
  218.     {"ascii",      0, 0, 'a'}, /* ascii text mode */
  219.     {"to-stdout",  0, 0, 'c'}, /* write output on standard output */
  220.     {"stdout",     0, 0, 'c'}, /* write output on standard output */
  221.     {"decompress", 0, 0, 'd'}, /* decompress */
  222.     {"uncompress", 0, 0, 'd'}, /* decompress */
  223.  /* {"encrypt",    0, 0, 'e'},    encrypt */
  224.     {"force",      0, 0, 'f'}, /* force overwrite of output file */
  225.     {"help",       0, 0, 'h'}, /* give help */
  226.  /* {"pkzip",      0, 0, 'k'},    force output in pkzip format */
  227.  /* {"list",       0, 0, 'l'},    list .gz file contents */
  228.     {"license",    0, 0, 'L'}, /* display software license */
  229.     {"quiet",      0, 0, 'q'}, /* quiet mode */
  230.     {"silent",     0, 0, 'q'}, /* quiet mode */
  231.     {"recurse",    0, 0, 'r'}, /* recurse through directories */
  232.     {"suffix",     1, 0, 'S'}, /* use given suffix instead of .gz */
  233.     {"test",       0, 0, 't'}, /* test compressed file integrity */
  234.     {"verbose",    0, 0, 'v'}, /* verbose mode */
  235.     {"version",    0, 0, 'V'}, /* display version number */
  236.     {"fast",       0, 0, '1'}, /* compress faster */
  237.     {"best",       0, 0, '9'}, /* compress better */
  238.     {"lzw",        0, 0, 'Z'}, /* make output compatible with old compress */
  239.     {"bits",       1, 0, 'b'}, /* max number of bits per code (implies -Z) */
  240.     { 0, 0, 0, 0 }
  241. };
  242.  
  243. /* local functions */
  244.  
  245. local void usage        OF((void));
  246. local void help         OF((void));
  247. local void license      OF((void));
  248. local void version      OF((void));
  249. local void treat_stdin  OF((void));
  250. local void treat_file   OF((char *iname));
  251. local int create_outfile OF((void));
  252. local int  do_stat      OF((char *name, struct stat *sbuf));
  253. local char *get_suffix  OF((char *name));
  254. local int  get_istat    OF((char *iname, struct stat *sbuf));
  255. local int  make_ofname  OF((void));
  256. local int  same_file    OF((struct stat *stat1, struct stat *stat2));
  257. local int name_too_long OF((char *name, struct stat *statb));
  258. local int  get_method   OF((int in));
  259. local int  check_ofname OF((void));
  260. local void reset_times  OF((char *name, struct stat *statb));
  261. local void copy_stat    OF((struct stat *ifstat));
  262. local void treat_dir    OF((char *dir));
  263. local void do_exit      OF((int exitcode));
  264.       int main          OF((int argc, char **argv));
  265.  
  266. int (*work) OF((int infile, int outfile)) = zip; /* function to call */
  267.  
  268. #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
  269.  
  270. /* ======================================================================== */
  271. local void usage()
  272. {
  273.     fprintf(stderr, "usage: %s [-%scdfhL%stvV19] [-S suffix] [file ...]\n",
  274.         progname,
  275. #if O_BINARY
  276.         "a",
  277. #else
  278.         "",
  279. #endif
  280. #ifdef NO_DIR
  281.         ""
  282. #else
  283.         "r"
  284. #endif
  285.         );
  286. }
  287.  
  288. /* ======================================================================== */
  289. local void help()
  290. {
  291.     static char  *help_msg[] = {
  292. #if O_BINARY
  293.  " -a --ascii       ascii text; convert end-of-lines using local conventions",
  294. #endif
  295.  " -c --stdout      write on standard output, keep original files unchanged",
  296.  " -d --decompress  decompress",
  297. /* -e --encrypt     encrypt */
  298.  " -f --force       force overwrite of output file and compress links",
  299.  " -h --help        give this help",
  300. /* -k --pkzip       force output in pkzip format */
  301. /* -l --list        list .gz file contents */
  302.  " -L --license     display software license",
  303.  " -q --quiet       suppress all warnings",
  304. #ifndef NO_DIR
  305.  " -r --recurse     recurse through directories",
  306. #endif
  307. #ifdef MAX_EXT_CHARS
  308.  " -S .suf  --suffix .suf     use suffix .suf instead of .z",
  309. #else
  310.  " -S .suf  --suffix .suf     use suffix .suf instead of .gz",
  311. #endif
  312.  " -t --test        test compressed file integrity",
  313.  " -v --verbose     verbose mode",
  314.  " -V --version     display version number",
  315.  " -1 --fast        compress faster",
  316.  " -9 --best        compress better",
  317. #ifdef LZW
  318.  " -Z --lzw         produce output compatible with old compress",
  319.  " -b --bits maxbits   max number of bits per code (implies -Z)",
  320. #endif
  321.  " file...          files to (de)compress. If none given, use standard input.",
  322.   0};
  323.     char **p = help_msg;
  324.  
  325.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  326.     usage();
  327.     while (*p) fprintf(stderr, "%s\n", *p++);
  328. }
  329.  
  330. /* ======================================================================== */
  331. local void license()
  332. {
  333.     char **p = license_msg;
  334.  
  335.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  336.     while (*p) fprintf(stderr, "%s\n", *p++);
  337. }
  338.  
  339. /* ======================================================================== */
  340. local void version()
  341. {
  342.     fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
  343.  
  344.     fprintf(stderr, "Compilation options:\n%s %s ", DIR_OPT, TIME_OPT);
  345. #ifdef STDC_HEADERS
  346.     fprintf(stderr, "STDC_HEADERS ");
  347. #endif
  348. #ifdef HAVE_UNISTD_H
  349.     fprintf(stderr, "HAVE_UNISTD_H ");
  350. #endif
  351. #ifdef NO_MEMORY_H
  352.     fprintf(stderr, "NO_MEMORY_H ");
  353. #endif
  354. #ifdef NO_STRING_H
  355.     fprintf(stderr, "NO_STRING_H ");
  356. #endif
  357. #ifdef NO_SYMLINK
  358.     fprintf(stderr, "NO_SYMLINK ");
  359. #endif
  360. #ifdef NO_MULTIPLE_DOTS
  361.     fprintf(stderr, "NO_MULTIPLE_DOTS ");
  362. #endif
  363. #ifdef NO_CHOWN
  364.     fprintf(stderr, "NO_CHOWN ");
  365. #endif
  366. #ifdef PROTO
  367.     fprintf(stderr, "PROTO ");
  368. #endif
  369. #ifdef ASMV
  370.     fprintf(stderr, "ASMV ");
  371. #endif
  372. #ifdef DEBUG
  373.     fprintf(stderr, "DEBUG ");
  374. #endif
  375. #ifdef DYN_ALLOC
  376.     fprintf(stderr, "DYN_ALLOC ");
  377. #endif
  378. #ifdef MAXSEG_64K
  379.     fprintf(stderr, "MAXSEG_64K");
  380. #endif
  381.     fprintf(stderr, "\n");
  382. }
  383.  
  384. /* ======================================================================== */
  385. int main (argc, argv)
  386.     int argc;
  387.     char **argv;
  388. {
  389.     int file_count = 0; /* number of files to precess */
  390.     int proglen;        /* length of progname */
  391.     int optc;           /* current option */
  392.  
  393.     EXPAND(argc, argv); /* wild card expansion if necessary */
  394.  
  395.     progname = basename(argv[0]);
  396.     proglen = strlen(progname);
  397.  
  398.     /* Suppress .exe for MSDOS, OS/2 and VMS: */
  399.     if (proglen > 4 && strequ(progname+proglen-4, ".exe")) {
  400.         progname[proglen-4] = '\0';
  401.     }
  402.  
  403.     /* Add options in GZIP environment variable if there is one */
  404.     env = add_envopt(&argc, &argv, OPTIONS_VAR);
  405.     if (env != NULL) args = argv;
  406.  
  407.     foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
  408.     if (foreground) {
  409.     signal (SIGINT, (sig_type)abort_gzip);
  410.     }
  411. #ifdef SIGTERM
  412.     signal(SIGTERM, (sig_type)abort_gzip);
  413. #endif
  414. #ifdef SIGHUP
  415.     signal(SIGHUP,  (sig_type)abort_gzip);
  416. #endif
  417.  
  418. #ifndef GNU_STANDARD
  419.     /* For compatibility with old compress, use program name as an option.
  420.      * If you compile with -DGNU_STANDARD, this program will behave as
  421.      * gzip even if it is invoked under the name gunzip or zcat.
  422.      *
  423.      * Systems which do not support links can still use -d or -dc.
  424.      * Ignore an .exe extension for MSDOS, OS/2 and VMS.
  425.      */
  426.     if (  strncmp(progname, "un",  2) == 0     /* ungzip, uncompress */
  427.        || strncmp(progname, "gun", 3) == 0) {  /* gunzip */
  428.     decompress = 1;
  429.     } else if (strequ(progname+1, "cat")       /* zcat, pcat, gcat */
  430.         || strequ(progname, "gzcat")) {    /* gzcat */
  431.     decompress = to_stdout = 1;
  432.     }
  433. #endif
  434.  
  435.     strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix)-1);
  436.     z_len = strlen(z_suffix);
  437.  
  438.     while ((optc = getopt_long (argc, argv, "ab:cdfhLqrS:tvVZ123456789",
  439.                 longopts, (int *)0)) != EOF) {
  440.     switch (optc) {
  441.         case 'a':
  442.             ascii = 1; break;
  443.     case 'b':
  444.         maxbits = atoi(optarg);
  445.         break;
  446.     case 'c':
  447.         to_stdout = 1; break;
  448.     case 'd':
  449.         decompress = 1; break;
  450.     case 'f':
  451.         force++; break;
  452.     case 'h': case 'H': case '?':
  453.         help(); do_exit(OK); break;
  454.     case 'L':
  455.         license(); do_exit(OK); break;
  456.     case 'q':
  457.         quiet = 1; verbose = 0; break;
  458.     case 'r':
  459. #ifdef NO_DIR
  460.         fprintf(stderr, "%s: -r not supported on this system\n", progname);
  461.         usage();
  462.         do_exit(ERROR); break;
  463. #else
  464.         recursive = 1; break;
  465. #endif
  466.     case 'S':
  467. #ifdef NO_MULTIPLE_DOTS
  468.             if (*optarg == '.') optarg++;
  469. #endif
  470.             z_len = strlen(optarg);
  471.             if (z_len == 0 || z_len > MAX_SUFFIX) {
  472.                 fprintf(stderr, "%s: incorrect suffix '%s'\n",
  473.                         progname, optarg);
  474.                 do_exit(ERROR);
  475.             }
  476.             strcpy(z_suffix, optarg);
  477.             break;
  478.     case 't':
  479.         test = decompress = to_stdout = 1;
  480.         break;
  481.     case 'v':
  482.         verbose++; quiet = 0; break;
  483.     case 'V':
  484.         version(); do_exit(OK); break;
  485.     case 'Z':
  486. #ifdef LZW
  487.         do_lzw = 1; break;
  488. #else
  489.         fprintf(stderr, "%s: -Z not supported in this version\n",
  490.             progname);
  491.         usage();
  492.         do_exit(ERROR); break;
  493. #endif
  494.     case '1':  case '2':  case '3':  case '4':
  495.     case '5':  case '6':  case '7':  case '8':  case '9':
  496.         level = optc - '0';
  497.         break;
  498.     default:
  499.         /* Error message already emitted by getopt_long. */
  500.         usage();
  501.         do_exit(ERROR);
  502.     }
  503.     } /* loop on all arguments */
  504.  
  505.     file_count = argc - optind;
  506.  
  507. #if O_BINARY
  508. #else
  509.     if (ascii && !quiet) {
  510.     fprintf(stderr, "%s: option --ascii ignored on this system\n",
  511.         progname);
  512.     }
  513. #endif
  514.     if (do_lzw && !decompress) work = lzw;
  515.  
  516.     /* Allocate all global buffers (for DYN_ALLOC option) */
  517.     ALLOC(uch, inbuf,  INBUFSIZ +INBUF_EXTRA);
  518.     ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
  519.     ALLOC(ush, d_buf,  DIST_BUFSIZE);
  520.     ALLOC(uch, window, 2L*WSIZE);
  521. #ifndef MAXSEG_64K
  522.     ALLOC(ush, tab_prefix, 1L<<BITS);
  523. #else
  524.     ALLOC(ush, tab_prefix0, 1L<<(BITS-1));
  525.     ALLOC(ush, tab_prefix1, 1L<<(BITS-1));
  526. #endif
  527.  
  528.     /* And get to work */
  529.     if (file_count != 0) {
  530.     if (to_stdout && !test && (!decompress || !ascii)) {
  531.         SET_BINARY_MODE(fileno(stdout));
  532.     }
  533.         while (optind < argc) {
  534.         treat_file(argv[optind++]);
  535.     }
  536.     } else {  /* Standard input */
  537.     treat_stdin();
  538.     }
  539.     do_exit(exit_code);
  540.     return exit_code; /* just to avoid lint warning */
  541. }
  542.  
  543. /* ========================================================================
  544.  * Compress or decompress stdin
  545.  */
  546. local void treat_stdin()
  547. {
  548.     if (!force && isatty(fileno((FILE *)(decompress ? stdin : stdout)))) {
  549.     /* Do not send compressed data to the terminal or read it from
  550.      * the terminal. We get here when user invoked the program
  551.      * without parameters, so be helpful. According to the GNU standards:
  552.      *
  553.      *   If there is one behavior you think is most useful when the output
  554.      *   is to a terminal, and another that you think is most useful when
  555.      *   the output is a file or a pipe, then it is usually best to make
  556.      *   the default behavior the one that is useful with output to a
  557.      *   terminal, and have an option for the other behavior.
  558.      *
  559.      * Here we use the --force option to get the other behavior.
  560.      */
  561.     fprintf(stderr,
  562.     "%s: compressed data not %s a terminal. Use -f to force %scompression.\n",
  563.         progname, decompress ? "read from" : "written to",
  564.         decompress ? "de" : "");
  565.     fprintf(stderr,"For help, type: %s -h\n", progname);
  566.     do_exit(ERROR);
  567.     }
  568.  
  569.     if (decompress || !ascii) {
  570.     SET_BINARY_MODE(fileno(stdin));
  571.     }
  572.     if (!test && (!decompress || !ascii)) {
  573.     SET_BINARY_MODE(fileno(stdout));
  574.     }
  575.     strcpy(ifname, "stdin");
  576.     strcpy(ofname, "stdout");
  577.  
  578.     /* Get the time stamp on the input file. */
  579. #ifdef NO_STDIN_FSTAT
  580.     time_stamp = 0; /* time unknown */
  581. #else
  582.     if (fstat(fileno(stdin), &istat) != 0) {
  583.     error("fstat(stdin)");
  584.     }
  585.     /* If you do not wish to save the time stamp when input comes from a pipe,
  586.      * compile with -DNO_PIPE_TIMESTAMP.
  587.      */
  588. #ifdef NO_PIPE_TIMESTAMP
  589.     if (!S_ISREG(istat.st_mode))
  590.     time_stamp = 0;
  591.     else
  592. #endif
  593.     time_stamp = istat.st_mtime;
  594. #endif
  595.     ifile_size = -1L; /* convention for unknown size */
  596.  
  597.     clear_bufs(); /* clear input and output buffers */
  598.     to_stdout = 1;
  599.     part_nb = 0;
  600.  
  601.     if (decompress) {
  602.     method = get_method(ifd);
  603.     if (method < 0) {
  604.         do_exit(exit_code); /* error message already emitted */
  605.     }
  606.     }
  607.  
  608.     /* Actually do the compression/decompression. Loop over zipped members.
  609.      */
  610.     for (;;) {
  611.     if ((*work)(fileno(stdin), fileno(stdout)) != OK) return;
  612.  
  613.     if (!decompress || last_member || inptr == insize) break;
  614.     /* end of file */
  615.  
  616.     method = get_method(ifd);
  617.     if (method < 0) return; /* error message already emitted */
  618.     bytes_out = 0;            /* required for length check */
  619.     }
  620.  
  621.     if (verbose) {
  622.     if (test) {
  623.         fprintf(stderr, " OK");
  624.  
  625.     } else if (!decompress) {
  626.         display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in);
  627. #ifdef DISPLAY_STDIN_RATIO
  628.     } else {
  629.         display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out);
  630. #endif
  631.     }
  632.     fprintf(stderr, "\n");
  633.     }
  634. }
  635.  
  636. /* ========================================================================
  637.  * Compress or decompress the given file
  638.  */
  639. local void treat_file(iname)
  640.     char *iname;
  641. {
  642.     /* Check if the input file is present, set ifname and istat: */
  643.     if (get_istat(iname, &istat) != OK) return;
  644.  
  645.     /* If the input name is that of a directory, recurse or ignore: */
  646.     if (S_ISDIR(istat.st_mode)) {
  647. #ifndef NO_DIR
  648.     if (recursive) {
  649.         struct stat st;
  650.         st = istat;
  651.         treat_dir(iname);
  652.         /* Warning: ifname is now garbage */
  653.         reset_times (iname, &st);
  654.     } else
  655. #endif
  656.     WARN((stderr,"%s: %s is a directory -- ignored\n", progname, ifname));
  657.     return;
  658.     }
  659.     if (!S_ISREG(istat.st_mode)) {
  660.     WARN((stderr,
  661.           "%s: %s is not a directory or a regular file - ignored\n",
  662.           progname, ifname));
  663.     return;
  664.     }
  665.     if (istat.st_nlink > 1 && !to_stdout && !force) {
  666.     WARN((stderr, "%s: %s has %d other link%c -- unchanged\n",
  667.           progname, ifname,
  668.           (int)istat.st_nlink - 1, istat.st_nlink > 2 ? 's' : ' '));
  669.     return;
  670.     }
  671.  
  672.     ifile_size = istat.st_size;
  673.     time_stamp = istat.st_mtime;
  674.  
  675.     /* Generate output file name */
  676.     if (to_stdout) {
  677.     strcpy(ofname, "stdout");
  678.  
  679.     } else if (make_ofname() != OK) {
  680.     return;
  681.     }
  682.  
  683.     /* Open the input file and determine compression method. The mode
  684.      * parameter is ignored but required by some systems (VMS) and forbidden
  685.      * on other systems (MacOS).
  686.      */
  687.     ifd = OPEN(ifname, ascii && !decompress ? O_RDONLY : O_RDONLY | O_BINARY,
  688.            RW_USER);
  689.     if (ifd == -1) {
  690.     fprintf(stderr, "%s: ", progname);
  691.     perror(ifname);
  692.     exit_code = ERROR;
  693.     return;
  694.     }
  695.     clear_bufs(); /* clear input and output buffers */
  696.     part_nb = 0;
  697.  
  698.     if (decompress) {
  699.     method = get_method(ifd); /* updates ofname if original given */
  700.     if (method < 0) {
  701.         close(ifd);
  702.         return;               /* error message already emitted */
  703.     }
  704.     }
  705.  
  706.     /* If compressing to a file, check if ofname is not ambiguous
  707.      * because the operating system truncates names. Otherwise, generate
  708.      * a new ofname and save the original name in the compressed file.
  709.      */
  710.     if (to_stdout) {
  711.     ofd = fileno(stdout);
  712.     /* keep remove_ofname as zero */
  713.     } else {
  714.     if (create_outfile() != OK) return;
  715.  
  716.     if (save_orig_name && !verbose && !quiet) {
  717.         fprintf(stderr, "%s: %s compressed to %s\n",
  718.             progname, ifname, ofname);
  719.     }
  720.     }
  721.     if (verbose) {
  722.     fprintf(stderr, "%s:\t%s", ifname, (int)strlen(ifname) >= 15 ? 
  723.         "" : ((int)strlen(ifname) >= 7 ? "\t" : "\t\t"));
  724.     }
  725.  
  726.     /* Actually do the compression/decompression. Loop over zipped members.
  727.      */
  728.     for (;;) {
  729.     if ((*work)(ifd, ofd) != OK) {
  730.         method = -1; /* force cleanup */
  731.         break;
  732.     }
  733.     if (!decompress || last_member || inptr == insize) break;
  734.     /* end of file */
  735.  
  736.     method = get_method(ifd);
  737.     if (method < 0) break;    /* error message already emitted */
  738.     bytes_out = 0;            /* required for length check */
  739.     }
  740.  
  741.     close(ifd);
  742.     if (!to_stdout && close(ofd)) {
  743.     write_error();
  744.     }
  745.     if (method == -1) {
  746.     if (!to_stdout) unlink (ofname);
  747.     return;
  748.     }
  749.     /* Display statistics */
  750.     if(verbose) {
  751.     if (test) {
  752.         fprintf(stderr, " OK");
  753.     } else if (decompress) {
  754.         display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out);
  755.     } else {
  756.         display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in);
  757.     }
  758.     if (!test && !to_stdout) {
  759.         fprintf(stderr, " -- replaced with %s", ofname);
  760.     }
  761.     fprintf(stderr, "\n");
  762.     }
  763.     /* Copy modes, times, ownership, and remove the input file */
  764.     if (!to_stdout) {
  765.     copy_stat(&istat);
  766.     }
  767. }
  768.  
  769. /* ========================================================================
  770.  * Create the output file. Return OK or ERROR.
  771.  * Try several times if necessary to avoid truncating the z_suffix. For
  772.  * example, do not create a compressed file of name "1234567890123."
  773.  * IN assertions: the input file has already been open (ifd is set) and
  774.  *   ofname has already been updated if there was an original name.
  775.  * OUT assertions: ifd and ofd are closed in case of error.
  776.  */
  777. local int create_outfile()
  778. {
  779.     struct stat    ostat; /* stat for ofname */
  780.     int len;
  781.     int flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
  782.  
  783.     if (ascii && decompress) {
  784.     flags &= ~O_BINARY; /* force ascii text mode */
  785.     }
  786.     for (;;) {
  787.         len = strlen(ofname);
  788.         if (len == 0 || ofname[len] == PATH_SEP) break;
  789.     if (check_ofname() != OK) {
  790.         close(ifd);
  791.         return ERROR;
  792.     }
  793.     /* Create the output file */
  794.     remove_ofname = 1;
  795.     ofd = OPEN(ofname, flags, RW_USER);
  796.     if (ofd == -1) {
  797.         perror(ofname);
  798.         close(ifd);
  799.         exit_code = ERROR;
  800.         return ERROR;
  801.     }
  802.  
  803.     /* Check for name truncation on new file (1234567890123.gz) */
  804.     if (fstat(ofd, &ostat) != 0) {
  805.         fprintf(stderr, "%s: ", progname);
  806.         perror(ofname);
  807.         close(ifd); close(ofd);
  808.         unlink(ofname);
  809.         exit_code = ERROR;
  810.         return ERROR;
  811.     }
  812.     if (!name_too_long(ofname, &ostat)) return OK;
  813.  
  814.     if (decompress) {
  815.         /* name might be too long if an original name was saved */
  816.         WARN((stderr, "%s: %s: warning, name truncated\n",
  817.           progname, ofname));
  818.         return OK;
  819.     } else {
  820. #ifdef NO_MULTIPLE_DOTS
  821.         /* Should never happen, see check_ofname() */
  822.         fprintf(stderr, "%s: %s: name too long\n", progname, ofname);
  823.         do_exit(ERROR);
  824. #else
  825.         close(ofd);
  826.         unlink(ofname);
  827.         save_orig_name = 1;
  828.         strcpy(ofname+strlen(ofname)-z_len-1, z_suffix);
  829.             /* 123456789012.gz -> 12345678901.gz */
  830. #endif
  831.     } /* decompress ? */
  832.     } /* while non null name */
  833.  
  834.     close(ifd);
  835.     fprintf(stderr, "%s: %s: name too long\n", progname, ofname);
  836.     exit_code = ERROR;
  837.     return ERROR;
  838. }
  839.  
  840. /* ========================================================================
  841.  * Use lstat if available, except for -c or -f. Use stat otherwise.
  842.  * This allows links when not removing the original file.
  843.  */
  844. local int do_stat(name, sbuf)
  845.     char *name;
  846.     struct stat *sbuf;
  847. {
  848.     errno = 0;
  849. #if (defined(S_IFLNK) || defined (S_ISLNK)) && !defined(NO_SYMLINK)
  850.     if (!to_stdout && !force) {
  851.     return lstat(name, sbuf);
  852.     }
  853. #endif
  854.     return stat(name, sbuf);
  855. }
  856.  
  857. /* ========================================================================
  858.  * Return a pointer to the 'z' suffix of a file name, or NULL. For all
  859.  * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are
  860.  * accepted suffixes, in addition to the value of the --suffix option.
  861.  * ".tgz" is a useful convention for tar.z files on systems limited
  862.  * to 3 characters extensions. On such systems, ".?z" and ".??z" are
  863.  * also accepted suffixes. For Unix, we do not want to accept any
  864.  * .??z suffix as indicating a compressed file; some people use .xyz
  865.  * to denote volume data.
  866.  */
  867. local char *get_suffix(name)
  868.     char *name;
  869. {
  870.     int nlen, slen;
  871.     char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */
  872.     static char *known_suffixes[] =
  873.        {z_suffix, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z",
  874. #ifdef MAX_EXT_CHARS
  875.           "z",
  876. #endif
  877.           NULL};
  878.     char **suf = known_suffixes;
  879.  
  880.     if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */
  881.  
  882.     nlen = strlen(name);
  883.     if (nlen <= MAX_SUFFIX+2) {
  884.         strcpy(suffix, name);
  885.     } else {
  886.         strcpy(suffix, name+nlen-MAX_SUFFIX-2);
  887.     }
  888. #ifdef SUFFIX_SEP
  889.     /* strip a version number from the file name */
  890.     {
  891.     char *v = strrchr(suffix, SUFFIX_SEP);
  892.     if (v != NULL) *v = '\0', nlen = v - name;
  893.     }
  894. #endif
  895.     strlwr(suffix);
  896.     slen = strlen(suffix);
  897.     do {
  898.        int s = strlen(*suf);
  899.        if (slen > s && suffix[slen-s-1] != PATH_SEP
  900.            && strequ(suffix + slen - s, *suf)) {
  901.            return name+nlen-s;
  902.        }
  903.     } while (*++suf != NULL);
  904.  
  905.     return NULL;
  906. }
  907.  
  908.  
  909. /* ========================================================================
  910.  * Set ifname to the input file name (with a suffix appended if necessary)
  911.  * and istat to its stats. For decompression, if no file exists with the
  912.  * original name, try adding successively z_suffix, .gz, .z, -z and .Z.
  913.  * For MSDOS, we try only z_suffix and z.
  914.  * Return OK or ERROR.
  915.  */
  916. local int get_istat(iname, sbuf)
  917.     char *iname;
  918.     struct stat *sbuf;
  919. {
  920.     int ilen;  /* strlen(ifname) */
  921.     static char *suffixes[] = {z_suffix, ".gz", ".z", "-z", ".Z", NULL};
  922.     char **suf = suffixes;
  923.     char *s;
  924. #ifdef NO_MULTIPLE_DOTS
  925.     char *dot; /* pointer to ifname extension, or NULL */
  926. #endif
  927.  
  928.     strcpy(ifname, iname);
  929.  
  930.     /* If input file exists, return OK. */
  931.     if (do_stat(ifname, sbuf) == 0) return OK;
  932.  
  933.     if (!decompress || errno != ENOENT) {
  934.     perror(ifname);
  935.     exit_code = ERROR;
  936.     return ERROR;
  937.     }
  938.     /* file.ext doesn't exist, try adding a suffix.
  939.      */
  940.     s = get_suffix(ifname);
  941.     if (s != NULL) {
  942.     perror(ifname); /* ifname already has z suffix and does not exist */
  943.     exit_code = ERROR;
  944.     return ERROR;
  945.     }
  946. #ifdef SUFFIX_SEP
  947.     /* strip a version number from the input file name */
  948.     if ((s = strrchr(ifname, SUFFIX_SEP)) != NULL) *s = '\0';
  949. #endif
  950. #ifdef NO_MULTIPLE_DOTS
  951.     dot = strrchr(ifname, '.');
  952.     if (dot == NULL) {
  953.         strcat(ifname, ".");
  954.         dot = strrchr(ifname, '.');
  955.     }
  956. #endif
  957.     ilen = strlen(ifname);
  958.     if (strequ(z_suffix, ".gz")) suf++;
  959.  
  960.     /* Search for all suffixes */
  961.     do {
  962.         s = *suf;
  963. #ifdef NO_MULTIPLE_DOTS
  964.         if (*s == '.') s++;
  965. #endif
  966. #ifdef MAX_EXT_CHARS
  967.         strcpy(ifname, iname);
  968.         /* Needed if the suffixes are not sorted by increasing length */
  969.  
  970.         if (*dot == '\0') strcpy(dot, ".");
  971.         dot[MAX_EXT_CHARS+1-strlen(s)] = '\0';
  972. #endif
  973.         strcat(ifname, s);
  974.         if (do_stat(ifname, sbuf) == 0) return OK;
  975.     ifname[ilen] = '\0';
  976.     } while (*++suf != NULL);
  977.  
  978.     /* No suffix found, complain using z_suffix: */
  979. #ifdef MAX_EXT_CHARS
  980.     strcpy(ifname, iname);
  981.     if (*dot == '\0') strcpy(dot, ".");
  982.     dot[MAX_EXT_CHARS+1-z_len] = '\0';
  983. #endif
  984.     strcat(ifname, z_suffix);
  985.     perror(ifname);
  986.     exit_code = ERROR;
  987.     return ERROR;
  988. }
  989.  
  990. /* ========================================================================
  991.  * Generate ofname given ifname. Return OK, or WARNING if file must be skipped.
  992.  * Initializes save_orig_name.
  993.  * IN assertion: this function is not called if to_stdout is true.
  994.  */
  995. local int make_ofname()
  996. {
  997.     char *suff;            /* ofname z suffix */
  998.  
  999.     strcpy(ofname, ifname);
  1000. #ifdef SUFFIX_SEP
  1001.     /* strip a version number from the output file name */
  1002.     if ((suff = strrchr(ofname, SUFFIX_SEP)) != NULL) *suff = '\0';
  1003. #endif
  1004.     suff = get_suffix(ofname);
  1005.  
  1006.     if (decompress) {
  1007.     if (suff == NULL) {
  1008.         WARN((stderr,"%s: %s: unknown suffix -- ignored\n",
  1009.           progname, ifname));
  1010.         return WARNING;
  1011.     }
  1012.     /* Make a special case for .tgz and .taz: */
  1013.     strlwr(suff);
  1014.     if (strequ(suff, ".tgz") || strequ(suff, ".taz")) {
  1015.         strcpy(suff, ".tar");
  1016.     } else {
  1017.         *suff = '\0'; /* strip z suffix and optional version number */
  1018.     }
  1019.         /* ofname might be changed later if infile contains an original name */
  1020.  
  1021.     } else if (suff != NULL) {
  1022.     /* Avoid annoying messages with -r (see treat_dir()) */
  1023.     if (verbose || (!recursive && !quiet)) {
  1024.         fprintf(stderr, "%s: %s already has %s suffix -- unchanged\n",
  1025.             progname, ifname, suff);
  1026.     }
  1027.     if (exit_code == OK) exit_code = WARNING;
  1028.     return WARNING;
  1029.     } else {
  1030.         save_orig_name = 0;
  1031.  
  1032. #ifdef NO_MULTIPLE_DOTS
  1033.     suff = strrchr(ofname, '.');
  1034.     if (suff == NULL) {
  1035.             strcat(ofname, ".");
  1036. #  ifdef MAX_EXT_CHARS
  1037.         /* On the Atari and some versions of MSDOS, name_too_long()
  1038.          * does not work correctly because of a bug in stat(). So we
  1039.          * must truncate here.
  1040.          */
  1041.         } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) {
  1042.             suff[MAX_SUFFIX+1-z_len] = '\0';
  1043.             save_orig_name = 1;
  1044. #  endif
  1045.         }
  1046. #endif /* NO_MULTIPLE_DOTS */
  1047.     strcat(ofname, z_suffix);
  1048.  
  1049.     } /* decompress ? */
  1050.     return OK;
  1051. }
  1052.  
  1053.  
  1054. /* ========================================================================
  1055.  * Check the magic number of the input file and update ofname if an
  1056.  * original name was given and to_stdout is not set.
  1057.  * Return the compression method, -1 for error, -2 for warning.
  1058.  * Set inptr to the offset of the next byte to be processed.
  1059.  * This function may be called repeatedly for an input file consisting
  1060.  * of several contiguous gzip'ed members.
  1061.  * IN assertions: there is at least one remaining compressed member.
  1062.  *   If the member is a zip file, it must be the only one.
  1063.  */
  1064. local int get_method(in)
  1065.     int in;        /* input file descriptor */
  1066. {
  1067.     uch flags;
  1068.     char magic[2]; /* magic header */
  1069.  
  1070.     magic[0] = (char)get_byte();
  1071.     magic[1] = (char)get_byte();
  1072.  
  1073.     time_stamp = istat.st_mtime; /* may be modified later for some methods */
  1074.     method = -1;                 /* unknown yet */
  1075.     part_nb++;                   /* number of parts in gzip file */
  1076.     header_bytes = 0;
  1077.     last_member = RECORD_IO;
  1078.     /* assume multiple members in gzip file except for record oriented I/O */
  1079.  
  1080.     if (memcmp(magic, GZIP_MAGIC, 2) == 0
  1081.         || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) {
  1082.  
  1083.     method = (int)get_byte();
  1084.     if (method != DEFLATED) {
  1085.         fprintf(stderr,
  1086.             "%s: %s: unknown method %d -- get newer version of gzip\n",
  1087.             progname, ifname, method);
  1088.         exit_code = ERROR;
  1089.         return -1;
  1090.     }
  1091.     work = unzip;
  1092.     flags  = (uch)get_byte();
  1093.  
  1094.     if ((flags & ENCRYPTED) != 0) {
  1095.         fprintf(stderr,
  1096.             "%s: %s is encrypted -- get newer version of gzip\n",
  1097.             progname, ifname);
  1098.         exit_code = ERROR;
  1099.         return -1;
  1100.     }
  1101.     if ((flags & CONTINUATION) != 0) {
  1102.         fprintf(stderr,
  1103.        "%s: %s is a a multi-part gzip file -- get newer version of gzip\n",
  1104.             progname, ifname);
  1105.         exit_code = ERROR;
  1106.         if (force <= 1) return -1;
  1107.     }
  1108.     if ((flags & RESERVED) != 0) {
  1109.         fprintf(stderr,
  1110.             "%s: %s has flags 0x%x -- get newer version of gzip\n",
  1111.             progname, ifname, flags);
  1112.         exit_code = ERROR;
  1113.         if (force <= 1) return -1;
  1114.     }
  1115.     time_stamp  = (ulg)get_byte();
  1116.     time_stamp |= ((ulg)get_byte()) << 8;
  1117.     time_stamp |= ((ulg)get_byte()) << 16;
  1118.     time_stamp |= ((ulg)get_byte()) << 24;
  1119.  
  1120.     (void)get_byte();  /* Ignore extra flags for the moment */
  1121.     (void)get_byte();  /* Ignore OS type for the moment */
  1122.  
  1123.     if ((flags & CONTINUATION) != 0) {
  1124.         unsigned part = (unsigned)get_byte();
  1125.         part |= ((unsigned)get_byte())<<8;
  1126.         if (verbose) {
  1127.         fprintf(stderr,"%s: %s: part number %u\n",
  1128.             progname, ifname, part);
  1129.         }
  1130.     }
  1131.     if ((flags & EXTRA_FIELD) != 0) {
  1132.         unsigned len = (unsigned)get_byte();
  1133.         len |= ((unsigned)get_byte())<<8;
  1134.         if (verbose) {
  1135.         fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n",
  1136.             progname, ifname, len);
  1137.         }
  1138.         while (len--) (void)get_byte();
  1139.     }
  1140.  
  1141.     /* Get original file name if it was truncated */
  1142.     if ((flags & ORIG_NAME) != 0) {
  1143.         if (to_stdout || part_nb > 1) {
  1144.         /* Discard the old name */
  1145.         char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */
  1146.         while ((c=get_byte()) != 0) c++;
  1147.         } else {
  1148.         /* Copy the base name. Keep a directory prefix intact. */
  1149.         char *p = basename(ofname);
  1150.         for (;;) {
  1151.             *p = (char)get_char();
  1152.             if (*p++ == '\0') break;
  1153.             if (p >= ofname+sizeof(ofname)) {
  1154.             error("corrupted input -- file name too large");
  1155.             }
  1156.         }
  1157.         } /* to_stdout */
  1158.     } /* orig_name */
  1159.  
  1160.     /* Discard file comment if any */
  1161.     if ((flags & COMMENT) != 0) {
  1162.         while (get_char() != 0) /* null */ ;
  1163.     }
  1164.     if (part_nb == 1) {
  1165.         header_bytes = inptr + 2*sizeof(long); /* include crc and size */
  1166.     }
  1167.  
  1168.     } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2
  1169.         && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) {
  1170.     /* To simplify the code, we support a zip file when alone only.
  1171.          * We are thus guaranteed that the entire local header fits in inbuf.
  1172.          */
  1173.         inptr = 0;
  1174.     work = unzip;
  1175.     if (check_zipfile(in) != OK) return -1;
  1176.     /* check_zipfile may get ofname from the local header */
  1177.     last_member = 1;
  1178.  
  1179.     } else if (memcmp(magic, PACK_MAGIC, 2) == 0) {
  1180.     work = unpack;
  1181.     method = PACKED;
  1182.     } else if (memcmp(magic, LZW_MAGIC, 2) == 0) {
  1183.     work = unlzw;
  1184.     method = COMPRESSED;
  1185.     last_member = 1;
  1186.     }
  1187.     if (method >= 0) return method;
  1188.     if (part_nb == 1) {
  1189.     fprintf(stderr, "\n%s: %s: not in gzip format\n", progname, ifname);
  1190.     exit_code = ERROR;
  1191.     return -1;
  1192.     } else {
  1193.     WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n",
  1194.           progname, ifname));
  1195.     return -2;
  1196.     }
  1197. }
  1198.  
  1199. /* ========================================================================
  1200.  * Return true if the two stat structures correspond to the same file.
  1201.  */
  1202. local int same_file(stat1, stat2)
  1203.     struct stat *stat1;
  1204.     struct stat *stat2;
  1205. {
  1206.     return stat1->st_ino   == stat2->st_ino
  1207.     && stat1->st_dev   == stat2->st_dev
  1208. #ifdef NO_ST_INO
  1209.         /* Can't rely on st_ino and st_dev, use other fields: */
  1210.     && stat1->st_mode  == stat2->st_mode
  1211.     && stat1->st_uid   == stat2->st_uid
  1212.     && stat1->st_gid   == stat2->st_gid
  1213.     && stat1->st_size  == stat2->st_size
  1214.     && stat1->st_atime == stat2->st_atime
  1215.     && stat1->st_mtime == stat2->st_mtime
  1216.     && stat1->st_ctime == stat2->st_ctime
  1217. #endif
  1218.         ;
  1219. }
  1220.  
  1221. /* ========================================================================
  1222.  * Return true if a file name is ambiguous because the operating system
  1223.  * truncates file names.
  1224.  */
  1225. local int name_too_long(name, statb)
  1226.     char *name;           /* file name to check */
  1227.     struct stat *statb;   /* stat buf for this file name */
  1228. {
  1229.     int s = strlen(name);
  1230.     char c = name[s-1];
  1231.     struct stat    tstat; /* stat for truncated name */
  1232.     int res;
  1233.  
  1234.     tstat = *statb;      /* Just in case OS does not fill all fields */
  1235.     name[s-1] = '\0';
  1236.     res = stat(name, &tstat) == 0 && same_file(statb, &tstat);
  1237.     name[s-1] = c;
  1238.     Trace((stderr, " too_long(%s) => %d\n", name, res));
  1239.     return res;
  1240. }
  1241.  
  1242. /* ========================================================================
  1243.  * If compressing to a file, check if ofname is not ambiguous
  1244.  * because the operating system truncates names. Otherwise, generate
  1245.  * a new ofname and save the original name in the compressed file.
  1246.  * If the compressed file already exists, ask for confirmation.
  1247.  *    The check for name truncation is made dynamically, because different
  1248.  * file systems on the same OS might use different truncation rules (on SVR4
  1249.  * s5 truncates to 14 chars and ufs does not truncate).
  1250.  *    This function returns -1 if the file must be skipped, and
  1251.  * updates save_orig_name if necessary.
  1252.  * IN assertions: save_orig_name is already set if ofname has been
  1253.  * already truncated because of NO_MULTIPLE_DOTS. The input file has
  1254.  * already been open and istat is set.
  1255.  */
  1256. local int check_ofname()
  1257. {
  1258.     int s = strlen(ofname);
  1259.     struct stat    ostat; /* stat for ofname */
  1260.  
  1261.     if (stat(ofname, &ostat) != 0) return 0;
  1262.  
  1263.     /* Check for name truncation on existing file: */
  1264. #ifdef NO_MULTIPLE_DOTS
  1265.     if (!decompress && name_too_long(ofname, &ostat)) {
  1266. #else
  1267.     if (!decompress && s > 8 && name_too_long(ofname, &ostat)) {
  1268. #endif
  1269.     save_orig_name = 1;
  1270.     strcpy(ofname+s-z_len-1, z_suffix);  /* f.ext.gz -> f.ex.gz  */
  1271.  
  1272.     if (stat(ofname, &ostat) != 0) return 0;
  1273.     } /* !decompress && name_too_long */
  1274.  
  1275.     /* Check that the input and output files are different (could be
  1276.      * the same by name truncation or links).
  1277.      */
  1278.     if (same_file(&istat, &ostat)) {
  1279.     fprintf(stderr, "%s: %s and %s are the same file\n",
  1280.         progname, ifname, ofname);
  1281.     exit_code = ERROR;
  1282.     return ERROR;
  1283.     }
  1284.     /* Ask permission to overwrite the existing file */
  1285.     if (!force) {
  1286.     char response[80];
  1287.     strcpy(response,"n");
  1288.     fprintf(stderr, "%s: %s already exists;", progname, ofname);
  1289.     if (foreground && isatty(fileno(stdin))) {
  1290.         fprintf(stderr, " do you wish to overwrite (y or n)? ");
  1291.         fflush(stderr);
  1292.         (void)fgets(response, sizeof(response)-1, stdin);
  1293.     }
  1294.     if (tolow(*response) != 'y') {
  1295.         fprintf(stderr, "\tnot overwritten\n");
  1296.         if (exit_code == OK) exit_code = WARNING;
  1297.         return ERROR;
  1298.     }
  1299.     }
  1300.     (void) chmod(ofname, 0777);
  1301.     if (unlink(ofname)) {
  1302.     fprintf(stderr, "%s: ", progname);
  1303.     perror(ofname);
  1304.     exit_code = ERROR;
  1305.     return ERROR;
  1306.     }
  1307.     return OK;
  1308. }
  1309.  
  1310.  
  1311. /* ========================================================================
  1312.  * Set the access and modification times from the given stat buffer.
  1313.  */
  1314. local void reset_times (name, statb)
  1315.     char *name;
  1316.     struct stat *statb;
  1317. {
  1318. #ifndef NO_UTIME
  1319.     struct utimbuf    timep;
  1320.  
  1321.     /* Copy the time stamp */
  1322.     timep.actime  = statb->st_atime;
  1323.     timep.modtime = statb->st_mtime;
  1324.  
  1325.     /* Some systems (at least OS/2) do not support utime on directories */
  1326.     if (utime(name, &timep) && !S_ISDIR(statb->st_mode)) {
  1327.     WARN((stderr, "%s: ", progname));
  1328.     if (!quiet) perror(ofname);
  1329.     }
  1330. #else
  1331.     name = name; statb = statb; /* avoid warnings */
  1332. #endif
  1333. }
  1334.  
  1335.  
  1336. /* ========================================================================
  1337.  * Copy modes, times, ownership from input file to output file.
  1338.  * IN assertion: to_stdout is false.
  1339.  */
  1340. local void copy_stat(ifstat)
  1341.     struct stat *ifstat;
  1342. {
  1343. #ifndef NO_UTIME
  1344.     if (decompress && time_stamp != 0 && ifstat->st_mtime != time_stamp) {
  1345.     ifstat->st_mtime = time_stamp;
  1346.     if (verbose) {
  1347.         fprintf(stderr, "%s: time stamp restored\n", ofname);
  1348.     }
  1349.     }
  1350.     reset_times(ofname, ifstat);
  1351. #endif
  1352.     /* Copy the protection modes */
  1353.     if (chmod(ofname, ifstat->st_mode & 07777)) {
  1354.     WARN((stderr, "%s: ", progname));
  1355.     if (!quiet) perror(ofname);
  1356.     }
  1357. #ifndef NO_CHOWN
  1358.     chown(ofname, ifstat->st_uid, ifstat->st_gid);  /* Copy ownership */
  1359. #endif
  1360.     remove_ofname = 0;
  1361.     /* It's now safe to remove the input file: */
  1362.     (void) chmod(ifname, 0777);
  1363.     if (unlink(ifname)) {
  1364.     WARN((stderr, "%s: ", progname));
  1365.     if (!quiet) perror(ifname);
  1366.     }
  1367. }
  1368.  
  1369. #ifndef NO_DIR
  1370.  
  1371. /* ========================================================================
  1372.  * Recurse through the given directory. This code is taken from ncompress.
  1373.  */
  1374. local void treat_dir(dir)
  1375.     char *dir;
  1376. {
  1377.     dir_type *dp;
  1378.     DIR      *dirp;
  1379.     char     nbuf[MAX_PATH_LEN];
  1380.     int      len;
  1381.  
  1382.     dirp = opendir(dir);
  1383.     
  1384.     if (dirp == NULL) {
  1385.     fprintf(stderr, "%s: %s unreadable\n", progname, dir);
  1386.     exit_code = ERROR;
  1387.     return ;
  1388.     }
  1389.     /*
  1390.      ** WARNING: the following algorithm could occasionally cause
  1391.      ** compress to produce error warnings of the form "<filename>.gz
  1392.      ** already has .gz suffix - ignored". This occurs when the
  1393.      ** .gz output file is inserted into the directory below
  1394.      ** readdir's current pointer.
  1395.      ** These warnings are harmless but annoying, so they are suppressed
  1396.      ** with option -r (except when -v is on). An alternative
  1397.      ** to allowing this would be to store the entire directory
  1398.      ** list in memory, then compress the entries in the stored
  1399.      ** list. Given the depth-first recursive algorithm used here,
  1400.      ** this could use up a tremendous amount of memory. I don't
  1401.      ** think it's worth it. -- Dave Mack
  1402.      ** (An other alternative might be two passes to avoid depth-first.)
  1403.      */
  1404.     
  1405.     while ((dp = readdir(dirp)) != NULL) {
  1406.  
  1407.     if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) {
  1408.         continue;
  1409.     }
  1410.     len = strlen(dir);
  1411.     if (len + NLENGTH(dp) + 1 < MAX_PATH_LEN - 1) {
  1412.         strcpy(nbuf,dir);
  1413.         if (len != 0 /* dir = "" means current dir on Amiga */
  1414. #ifdef PATH_SEP2
  1415.         && dir[len-1] != PATH_SEP2
  1416. #endif
  1417. #ifdef PATH_SEP3
  1418.         && dir[len-1] != PATH_SEP3
  1419. #endif
  1420.         ) {
  1421.         nbuf[len++] = PATH_SEP;
  1422.         }
  1423.         strcpy(nbuf+len, dp->d_name);
  1424.         treat_file(nbuf);
  1425.     } else {
  1426.         fprintf(stderr,"%s: %s/%s: pathname too long\n",
  1427.             progname, dir, dp->d_name);
  1428.         exit_code = ERROR;
  1429.     }
  1430.     }
  1431.     closedir(dirp);
  1432. }
  1433. #endif /* ? NO_DIR */
  1434.  
  1435. /* ========================================================================
  1436.  * Free all dynamically allocated variables and exit with the given code.
  1437.  */
  1438. local void do_exit(exitcode)
  1439.     int exitcode;
  1440. {
  1441.     if (env != NULL)  free(env),  env  = NULL;
  1442.     if (args != NULL) free((char*)args), args = NULL;
  1443.     FREE(inbuf);
  1444.     FREE(outbuf);
  1445.     FREE(d_buf);
  1446.     FREE(window);
  1447. #ifndef MAXSEG_64K
  1448.     FREE(tab_prefix);
  1449. #else
  1450.     FREE(tab_prefix0);
  1451.     FREE(tab_prefix1);
  1452. #endif
  1453.     exit(exitcode);
  1454. }
  1455.  
  1456. /* ========================================================================
  1457.  * Signal and error handler.
  1458.  */
  1459. RETSIGTYPE abort_gzip()
  1460. {
  1461.    if (remove_ofname) {
  1462.        close(ofd);
  1463.        unlink (ofname);
  1464.    }
  1465.    do_exit(ERROR);
  1466. }
  1467.