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.
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.
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.",
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.",
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.",
29 /* Compress files with zip algorithm and 'compress' interface.
30 * See usage() and help() functions below for all options.
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.
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.
44 * For the meaning of all compilation flags, see comments in Makefile.in.
48 static char rcsid[] = "$FreeBSD: src/gnu/usr.bin/gzip/gzip.c,v 1.10 1999/08/27 23:35:50 peter Exp $";
52 #include <sys/types.h>
66 # include <sys/time.h>
79 #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
87 typedef struct dirent dir_type;
88 # define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
89 # define DIR_OPT "DIRENT"
91 # define NLENGTH(dirent) ((dirent)->d_namlen)
94 typedef struct direct dir_type;
95 # define DIR_OPT "SYSDIR"
98 # include <sys/ndir.h>
99 typedef struct direct dir_type;
100 # define DIR_OPT "SYSNDIR"
104 typedef struct direct dir_type;
105 # define DIR_OPT "NDIR"
108 # define DIR_OPT "NO_DIR"
117 # define TIME_OPT "UTIME"
119 # ifdef HAVE_SYS_UTIME_H
120 # include <sys/utime.h>
121 # define TIME_OPT "SYS_UTIME"
131 # define TIME_OPT "NO_UTIME"
134 #if !defined(S_ISDIR) && defined(S_IFDIR)
135 # define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
137 #if !defined(S_ISREG) && defined(S_IFREG)
138 # define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
141 typedef RETSIGTYPE (*sig_type) OF((int));
144 # define O_BINARY 0 /* creation mode for open() */
148 /* Pure BSD system? */
149 # include <sys/file.h>
151 # define O_CREAT FCREAT
154 # define O_EXCL FEXCL
159 # define S_IRUSR 0400
162 # define S_IWUSR 0200
164 #define RW_USER (S_IRUSR | S_IWUSR) /* creation mode for open() */
167 # define MAX_PATH_LEN 1024 /* max pathname length */
176 off_t lseek OF((int fd, off_t offset, int whence));
179 /* Separator for file name parts (see shorten_name()) */
180 #ifdef NO_MULTIPLE_DOTS
181 # define PART_SEP "-"
183 # define PART_SEP "."
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);
193 DECLARE(ush, tab_prefix, 1L<<BITS);
195 DECLARE(ush, tab_prefix0, 1L<<(BITS-1));
196 DECLARE(ush, tab_prefix1, 1L<<(BITS-1));
199 /* local variables */
201 int ascii = 0; /* convert end-of-lines to local OS conventions */
202 int to_stdout = 0; /* output to stdout (-c) */
203 int decompress = 0; /* decompress (-d) */
204 int force = 0; /* don't ask questions, compress links (-f) */
205 int no_name = -1; /* don't save or restore the original file name */
206 int no_time = -1; /* don't save or restore the original file time */
207 int recursive = 0; /* recurse through directories (-r) */
208 int list = 0; /* list the file contents (-l) */
209 int verbose = 0; /* be verbose (-v) */
210 int quiet = 0; /* be very quiet (-q) */
211 int do_lzw = 0; /* generate output compatible with old compress (-Z) */
212 int test = 0; /* test .gz file integrity */
213 int foreground; /* set if program run in foreground */
214 char *progname; /* program name */
215 int maxbits = BITS; /* max bits per code for LZW */
216 int method = DEFLATED;/* compression method */
217 int level = 6; /* compression level */
218 int exit_code = OK; /* program exit code */
219 int save_orig_name; /* set if original name must be saved */
220 int last_member; /* set for .zip and .Z files */
221 int part_nb; /* number of parts in .gz file */
222 long time_stamp; /* original time stamp (modification time) */
223 long ifile_size; /* input file size, -1 for devices (debug only) */
224 char *env; /* contents of GZIP env variable */
225 char **args = NULL; /* argv pointer if GZIP env variable defined */
226 char z_suffix[MAX_SUFFIX+1]; /* default suffix (can be set with --suffix) */
227 int z_len; /* strlen(z_suffix) */
229 long bytes_in; /* number of input bytes */
230 long bytes_out; /* number of output bytes */
231 long total_in = 0; /* input bytes for all files */
232 long total_out = 0; /* output bytes for all files */
233 char ifname[MAX_PATH_LEN]; /* input file name */
234 char ofname[MAX_PATH_LEN]; /* output file name */
235 int remove_ofname = 0; /* remove output file on error */
236 struct stat istat; /* status for input file */
237 int ifd; /* input file descriptor */
238 int ofd; /* output file descriptor */
239 unsigned insize; /* valid bytes in inbuf */
240 unsigned inptr; /* index of next byte to be processed in inbuf */
241 unsigned outcnt; /* bytes in output buffer */
243 struct option longopts[] =
245 /* { name has_arg *flag val } */
246 {"ascii", 0, 0, 'a'}, /* ascii text mode */
247 {"to-stdout", 0, 0, 'c'}, /* write output on standard output */
248 {"stdout", 0, 0, 'c'}, /* write output on standard output */
249 {"decompress", 0, 0, 'd'}, /* decompress */
250 {"uncompress", 0, 0, 'd'}, /* decompress */
251 /* {"encrypt", 0, 0, 'e'}, encrypt */
252 {"force", 0, 0, 'f'}, /* force overwrite of output file */
253 {"help", 0, 0, 'h'}, /* give help */
254 /* {"pkzip", 0, 0, 'k'}, force output in pkzip format */
255 {"list", 0, 0, 'l'}, /* list .gz file contents */
256 {"license", 0, 0, 'L'}, /* display software license */
257 {"no-name", 0, 0, 'n'}, /* don't save or restore original name & time */
258 {"name", 0, 0, 'N'}, /* save or restore original name & time */
259 {"quiet", 0, 0, 'q'}, /* quiet mode */
260 {"silent", 0, 0, 'q'}, /* quiet mode */
261 {"recursive", 0, 0, 'r'}, /* recurse through directories */
262 {"suffix", 1, 0, 'S'}, /* use given suffix instead of .gz */
263 {"test", 0, 0, 't'}, /* test compressed file integrity */
264 {"no-time", 0, 0, 'T'}, /* don't save or restore the time stamp */
265 {"verbose", 0, 0, 'v'}, /* verbose mode */
266 {"version", 0, 0, 'V'}, /* display version number */
267 {"fast", 0, 0, '1'}, /* compress faster */
268 {"best", 0, 0, '9'}, /* compress better */
269 {"lzw", 0, 0, 'Z'}, /* make output compatible with old compress */
270 {"bits", 1, 0, 'b'}, /* max number of bits per code (implies -Z) */
274 /* local functions */
276 local void usage OF((void));
277 local void help OF((void));
278 local void license OF((void));
279 local void version OF((void));
280 local void treat_stdin OF((void));
281 local void treat_file OF((char *iname));
282 local int create_outfile OF((void));
283 local int do_stat OF((char *name, struct stat *sbuf));
284 local char *get_suffix OF((char *name));
285 local int get_istat OF((char *iname, struct stat *sbuf));
286 local int make_ofname OF((void));
287 local int same_file OF((struct stat *stat1, struct stat *stat2));
288 local int name_too_long OF((char *name, struct stat *statb));
289 local void shorten_name OF((char *name));
290 local int get_method OF((int in));
291 local void do_list OF((int ifd, int method));
292 local int check_ofname OF((void));
293 local void copy_stat OF((struct stat *ifstat));
294 local void do_exit OF((int exitcode));
295 int main OF((int argc, char **argv));
296 int (*work) OF((int infile, int outfile)) = zip; /* function to call */
299 local void treat_dir OF((char *dir));
302 local void reset_times OF((char *name, struct stat *statb));
305 #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
307 /* ======================================================================== */
310 fprintf(stderr, "usage: %s [-%scdfhlLnN%stvV19] [-S suffix] [file ...]\n",
325 /* ======================================================================== */
328 static char *help_msg[] = {
330 " -a --ascii ascii text; convert end-of-lines using local conventions",
332 " -c --stdout write on standard output, keep original files unchanged",
333 " -d --decompress decompress",
334 /* -e --encrypt encrypt */
335 " -f --force force overwrite of output file and compress links",
336 " -h --help give this help",
337 /* -k --pkzip force output in pkzip format */
338 " -l --list list compressed file contents",
339 " -L --license display software license",
341 " -m --no-time do not save or restore the original modification time",
342 " -M --time save or restore the original modification time",
344 " -n --no-name do not save or restore the original name and time stamp",
345 " -N --name save or restore the original name and time stamp",
346 " -q --quiet suppress all warnings",
348 " -r --recursive operate recursively on directories",
350 " -S .suf --suffix .suf use suffix .suf on compressed files",
351 " -t --test test compressed file integrity",
352 " -v --verbose verbose mode",
353 " -V --version display version number",
354 " -1 --fast compress faster",
355 " -9 --best compress better",
357 " -Z --lzw produce output compatible with old compress",
358 " -b --bits maxbits max number of bits per code (implies -Z)",
360 " file... files to (de)compress. If none given, use standard input.",
364 fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
366 while (*p) fprintf(stderr, "%s\n", *p++);
369 /* ======================================================================== */
372 char **p = license_msg;
374 fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
375 while (*p) fprintf(stderr, "%s\n", *p++);
378 /* ======================================================================== */
381 fprintf(stderr,"%s %s (%s)\n", progname, VERSION, REVDATE);
383 fprintf(stderr, "Compilation options:\n%s %s ", DIR_OPT, TIME_OPT);
385 fprintf(stderr, "STDC_HEADERS ");
388 fprintf(stderr, "HAVE_UNISTD_H ");
391 fprintf(stderr, "NO_MEMORY_H ");
394 fprintf(stderr, "NO_STRING_H ");
397 fprintf(stderr, "NO_SYMLINK ");
399 #ifdef NO_MULTIPLE_DOTS
400 fprintf(stderr, "NO_MULTIPLE_DOTS ");
403 fprintf(stderr, "NO_CHOWN ");
406 fprintf(stderr, "PROTO ");
409 fprintf(stderr, "ASMV ");
412 fprintf(stderr, "DEBUG ");
415 fprintf(stderr, "DYN_ALLOC ");
418 fprintf(stderr, "MAXSEG_64K");
420 fprintf(stderr, "\n");
423 /* ======================================================================== */
424 int main (argc, argv)
428 int file_count; /* number of files to precess */
429 int proglen; /* length of progname */
430 int optc; /* current option */
432 EXPAND(argc, argv); /* wild card expansion if necessary */
434 progname = basename(argv[0]);
435 proglen = strlen(progname);
437 /* Suppress .exe for MSDOS, OS/2 and VMS: */
438 if (proglen > 4 && strequ(progname+proglen-4, ".exe")) {
439 progname[proglen-4] = '\0';
442 /* Add options in GZIP environment variable if there is one */
443 env = add_envopt(&argc, &argv, OPTIONS_VAR);
444 if (env != NULL) args = argv;
446 foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
448 (void) signal (SIGINT, (sig_type)abort_gzip);
451 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
452 (void) signal(SIGTERM, (sig_type)abort_gzip);
456 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
457 (void) signal(SIGHUP, (sig_type)abort_gzip);
462 /* For compatibility with old compress, use program name as an option.
463 * If you compile with -DGNU_STANDARD, this program will behave as
464 * gzip even if it is invoked under the name gunzip or zcat.
466 * Systems which do not support links can still use -d or -dc.
467 * Ignore an .exe extension for MSDOS, OS/2 and VMS.
469 if ( strncmp(progname, "un", 2) == 0 /* ungzip, uncompress */
470 || strncmp(progname, "gun", 3) == 0) { /* gunzip */
472 } else if (strequ(progname+1, "cat") /* zcat, pcat, gcat */
473 || strequ(progname, "gzcat")) { /* gzcat */
474 decompress = to_stdout = 1;
478 strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix)-1);
479 z_len = strlen(z_suffix);
481 while ((optc = getopt_long (argc, argv, "ab:cdfhH?lLmMnNqrS:tvVZ123456789",
482 longopts, (int *)0)) != EOF) {
487 maxbits = atoi(optarg);
490 to_stdout = 1; break;
492 decompress = 1; break;
495 case 'h': case 'H': case '?':
496 help(); do_exit(OK); break;
498 list = decompress = to_stdout = 1; break;
500 license(); do_exit(OK); break;
501 case 'm': /* undocumented, may change later */
503 case 'M': /* undocumented, may change later */
506 no_name = no_time = 1; break;
508 no_name = no_time = 0; break;
510 quiet = 1; verbose = 0; break;
513 fprintf(stderr, "%s: -r not supported on this system\n", progname);
515 do_exit(ERROR); break;
517 recursive = 1; break;
520 #ifdef NO_MULTIPLE_DOTS
521 if (*optarg == '.') optarg++;
523 z_len = strlen(optarg);
524 if (z_len > sizeof(z_suffix)-1) {
525 fprintf(stderr, "%s: -S suffix too long\n", progname);
529 strncpy(z_suffix, optarg, sizeof z_suffix-1);
530 z_suffix[sizeof z_suffix-1] = '\0';
533 test = decompress = to_stdout = 1;
536 verbose++; quiet = 0; break;
538 version(); do_exit(OK); break;
543 fprintf(stderr, "%s: -Z not supported in this version\n",
546 do_exit(ERROR); break;
548 case '1': case '2': case '3': case '4':
549 case '5': case '6': case '7': case '8': case '9':
553 /* Error message already emitted by getopt_long. */
557 } /* loop on all arguments */
559 /* By default, save name and timestamp on compression but do not
560 * restore them on decompression.
562 if (no_time < 0) no_time = decompress;
563 if (no_name < 0) no_name = decompress;
565 file_count = argc - optind;
569 if (ascii && !quiet) {
570 fprintf(stderr, "%s: option --ascii ignored on this system\n",
574 if ((z_len == 0 && !decompress) || z_len > MAX_SUFFIX) {
575 fprintf(stderr, "%s: incorrect suffix '%s'\n",
579 if (do_lzw && !decompress) work = lzw;
581 /* Allocate all global buffers (for DYN_ALLOC option) */
582 ALLOC(uch, inbuf, INBUFSIZ +INBUF_EXTRA);
583 ALLOC(uch, outbuf, OUTBUFSIZ+OUTBUF_EXTRA);
584 ALLOC(ush, d_buf, DIST_BUFSIZE);
585 ALLOC(uch, window, 2L*WSIZE);
587 ALLOC(ush, tab_prefix, 1L<<BITS);
589 ALLOC(ush, tab_prefix0, 1L<<(BITS-1));
590 ALLOC(ush, tab_prefix1, 1L<<(BITS-1));
593 /* And get to work */
594 if (file_count != 0) {
595 if (to_stdout && !test && !list && (!decompress || !ascii)) {
596 SET_BINARY_MODE(fileno(stdout));
598 while (optind < argc) {
599 treat_file(argv[optind++]);
601 } else { /* Standard input */
604 if (list && !quiet && file_count > 1) {
605 do_list(-1, -1); /* print totals */
608 return exit_code; /* just to avoid lint warning */
611 /* ========================================================================
612 * Compress or decompress stdin
614 local void treat_stdin()
616 if (!force && !list &&
617 isatty(fileno((FILE *)(decompress ? stdin : stdout)))) {
618 /* Do not send compressed data to the terminal or read it from
619 * the terminal. We get here when user invoked the program
620 * without parameters, so be helpful. According to the GNU standards:
622 * If there is one behavior you think is most useful when the output
623 * is to a terminal, and another that you think is most useful when
624 * the output is a file or a pipe, then it is usually best to make
625 * the default behavior the one that is useful with output to a
626 * terminal, and have an option for the other behavior.
628 * Here we use the --force option to get the other behavior.
631 "%s: compressed data not %s a terminal. Use -f to force %scompression.\n",
632 progname, decompress ? "read from" : "written to",
633 decompress ? "de" : "");
634 fprintf(stderr,"For help, type: %s -h\n", progname);
638 if (decompress || !ascii) {
639 SET_BINARY_MODE(fileno(stdin));
641 if (!test && !list && (!decompress || !ascii)) {
642 SET_BINARY_MODE(fileno(stdout));
644 strcpy(ifname, "stdin");
645 strcpy(ofname, "stdout");
647 /* Get the time stamp on the input file. */
648 time_stamp = 0; /* time unknown by default */
650 #ifndef NO_STDIN_FSTAT
651 if (list || !no_time) {
652 if (fstat(fileno(stdin), &istat) != 0) {
653 error("fstat(stdin)");
655 # ifdef NO_PIPE_TIMESTAMP
656 if (S_ISREG(istat.st_mode))
658 time_stamp = istat.st_mtime;
659 #endif /* NO_STDIN_FSTAT */
661 ifile_size = -1L; /* convention for unknown size */
663 clear_bufs(); /* clear input and output buffers */
668 method = get_method(ifd);
670 do_exit(exit_code); /* error message already emitted */
674 do_list(ifd, method);
678 /* Actually do the compression/decompression. Loop over zipped members.
681 if ((*work)(fileno(stdin), fileno(stdout)) != OK) return;
683 if (!decompress || last_member || inptr == insize) break;
686 method = get_method(ifd);
687 if (method < 0) return; /* error message already emitted */
688 bytes_out = 0; /* required for length check */
693 fprintf(stderr, " OK\n");
695 } else if (!decompress) {
696 display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
697 fprintf(stderr, "\n");
698 #ifdef DISPLAY_STDIN_RATIO
700 display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
701 fprintf(stderr, "\n");
707 /* ========================================================================
708 * Compress or decompress the given file
710 local void treat_file(iname)
713 /* Accept "-" as synonym for stdin */
714 if (strequ(iname, "-")) {
715 int cflag = to_stdout;
721 /* Check if the input file is present, set ifname and istat: */
722 if (get_istat(iname, &istat) != OK) return;
724 /* If the input name is that of a directory, recurse or ignore: */
725 if (S_ISDIR(istat.st_mode)) {
731 /* Warning: ifname is now garbage */
733 reset_times (iname, &st);
737 WARN((stderr,"%s: %s is a directory -- ignored\n", progname, ifname));
740 if (!S_ISREG(istat.st_mode)) {
742 "%s: %s is not a directory or a regular file - ignored\n",
746 if (istat.st_nlink > 1 && !to_stdout && !force) {
747 WARN((stderr, "%s: %s has %d other link%c -- unchanged\n",
749 (int)istat.st_nlink - 1, istat.st_nlink > 2 ? 's' : ' '));
753 ifile_size = istat.st_size;
754 time_stamp = no_time && !list ? 0 : istat.st_mtime;
756 /* Generate output file name. For -r and (-t or -l), skip files
757 * without a valid gzip suffix (check done in make_ofname).
759 if (to_stdout && !list && !test) {
760 strcpy(ofname, "stdout");
762 } else if (make_ofname() != OK) {
766 /* Open the input file and determine compression method. The mode
767 * parameter is ignored but required by some systems (VMS) and forbidden
768 * on other systems (MacOS).
770 ifd = OPEN(ifname, ascii && !decompress ? O_RDONLY : O_RDONLY | O_BINARY,
773 fprintf(stderr, "%s: ", progname);
778 clear_bufs(); /* clear input and output buffers */
782 method = get_method(ifd); /* updates ofname if original given */
785 return; /* error message already emitted */
789 do_list(ifd, method);
794 /* If compressing to a file, check if ofname is not ambiguous
795 * because the operating system truncates names. Otherwise, generate
796 * a new ofname and save the original name in the compressed file.
799 ofd = fileno(stdout);
800 /* keep remove_ofname as zero */
802 if (create_outfile() != OK) return;
804 if (!decompress && save_orig_name && !verbose && !quiet) {
805 fprintf(stderr, "%s: %s compressed to %s\n",
806 progname, ifname, ofname);
809 /* Keep the name even if not truncated except with --no-name: */
810 if (!save_orig_name) save_orig_name = !no_name;
813 fprintf(stderr, "%s:\t%s", ifname, (int)strlen(ifname) >= 15 ?
814 "" : ((int)strlen(ifname) >= 7 ? "\t" : "\t\t"));
817 /* Actually do the compression/decompression. Loop over zipped members.
820 if ((*work)(ifd, ofd) != OK) {
821 method = -1; /* force cleanup */
824 if (!decompress || last_member || inptr == insize) break;
827 method = get_method(ifd);
828 if (method < 0) break; /* error message already emitted */
829 bytes_out = 0; /* required for length check */
833 if (!to_stdout && close(ofd)) {
837 if (!to_stdout) unlink (ofname);
840 /* Display statistics */
843 fprintf(stderr, " OK");
844 } else if (decompress) {
845 display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out,stderr);
847 display_ratio(bytes_in-(bytes_out-header_bytes), bytes_in, stderr);
849 if (!test && !to_stdout) {
850 fprintf(stderr, " -- replaced with %s", ofname);
852 fprintf(stderr, "\n");
854 /* Copy modes, times, ownership, and remove the input file */
860 /* ========================================================================
861 * Create the output file. Return OK or ERROR.
862 * Try several times if necessary to avoid truncating the z_suffix. For
863 * example, do not create a compressed file of name "1234567890123."
864 * Sets save_orig_name to true if the file name has been truncated.
865 * IN assertions: the input file has already been open (ifd is set) and
866 * ofname has already been updated if there was an original name.
867 * OUT assertions: ifd and ofd are closed in case of error.
869 local int create_outfile()
871 struct stat ostat; /* stat for ofname */
872 int flags = O_WRONLY | O_CREAT | O_EXCL | O_BINARY;
874 if (ascii && decompress) {
875 flags &= ~O_BINARY; /* force ascii text mode */
878 /* Make sure that ofname is not an existing file */
879 if (check_ofname() != OK) {
883 /* Create the output file */
885 ofd = OPEN(ofname, flags, RW_USER);
893 /* Check for name truncation on new file (1234567890123.gz) */
895 if (stat(ofname, &ostat) != 0) {
897 if (fstat(ofd, &ostat) != 0) {
899 fprintf(stderr, "%s: ", progname);
901 close(ifd); close(ofd);
906 if (!name_too_long(ofname, &ostat)) return OK;
909 /* name might be too long if an original name was saved */
910 WARN((stderr, "%s: %s: warning, name truncated\n",
916 #ifdef NO_MULTIPLE_DOTS
917 /* Should never happen, see check_ofname() */
918 fprintf(stderr, "%s: %s: name too long\n", progname, ofname);
921 shorten_name(ofname);
925 /* ========================================================================
926 * Use lstat if available, except for -c or -f. Use stat otherwise.
927 * This allows links when not removing the original file.
929 local int do_stat(name, sbuf)
934 #if (defined(S_IFLNK) || defined (S_ISLNK)) && !defined(NO_SYMLINK)
935 if (!to_stdout && !force) {
936 return lstat(name, sbuf);
939 return stat(name, sbuf);
942 /* ========================================================================
943 * Return a pointer to the 'z' suffix of a file name, or NULL. For all
944 * systems, ".gz", ".z", ".Z", ".taz", ".tgz", "-gz", "-z" and "_z" are
945 * accepted suffixes, in addition to the value of the --suffix option.
946 * ".tgz" is a useful convention for tar.z files on systems limited
947 * to 3 characters extensions. On such systems, ".?z" and ".??z" are
948 * also accepted suffixes. For Unix, we do not want to accept any
949 * .??z suffix as indicating a compressed file; some people use .xyz
950 * to denote volume data.
951 * On systems allowing multiple versions of the same file (such as VMS),
952 * this function removes any version suffix in the given name.
954 local char *get_suffix(name)
958 char suffix[MAX_SUFFIX+3]; /* last chars of name, forced to lower case */
959 static char *known_suffixes[] =
960 {z_suffix, ".gz", ".z", ".taz", ".tgz", "-gz", "-z", "_z",
965 char **suf = known_suffixes;
967 if (strequ(z_suffix, "z")) suf++; /* check long suffixes first */
970 /* strip a version number from the file name */
972 char *v = strrchr(name, SUFFIX_SEP);
973 if (v != NULL) *v = '\0';
977 if (nlen <= MAX_SUFFIX+2) {
978 strcpy(suffix, name);
980 strcpy(suffix, name+nlen-MAX_SUFFIX-2);
983 slen = strlen(suffix);
985 int s = strlen(*suf);
986 if (slen > s && suffix[slen-s-1] != PATH_SEP
987 && strequ(suffix + slen - s, *suf)) {
990 } while (*++suf != NULL);
996 /* ========================================================================
997 * Set ifname to the input file name (with a suffix appended if necessary)
998 * and istat to its stats. For decompression, if no file exists with the
999 * original name, try adding successively z_suffix, .gz, .z, -z and .Z.
1000 * For MSDOS, we try only z_suffix and z.
1001 * Return OK or ERROR.
1003 local int get_istat(iname, sbuf)
1007 int ilen; /* strlen(ifname) */
1008 static char *suffixes[] = {z_suffix, ".gz", ".z", "-z", ".Z", NULL};
1009 char **suf = suffixes;
1011 #ifdef NO_MULTIPLE_DOTS
1012 char *dot; /* pointer to ifname extension, or NULL */
1015 if (strlen(iname) >= sizeof(ifname) - 3) {
1016 errno = ENAMETOOLONG;
1022 strcpy(ifname, iname);
1024 /* If input file exists, return OK. */
1025 if (do_stat(ifname, sbuf) == 0) return OK;
1027 if (!decompress || errno != ENOENT) {
1032 /* file.ext doesn't exist, try adding a suffix (after removing any
1033 * version number for VMS).
1035 s = get_suffix(ifname);
1037 perror(ifname); /* ifname already has z suffix and does not exist */
1041 #ifdef NO_MULTIPLE_DOTS
1042 dot = strrchr(ifname, '.');
1044 strcat(ifname, ".");
1045 dot = strrchr(ifname, '.');
1048 ilen = strlen(ifname);
1049 if (strequ(z_suffix, ".gz")) suf++;
1051 /* Search for all suffixes */
1054 #ifdef NO_MULTIPLE_DOTS
1057 #ifdef MAX_EXT_CHARS
1058 strcpy(ifname, iname);
1059 /* Needed if the suffixes are not sorted by increasing length */
1061 if (*dot == '\0') strcpy(dot, ".");
1062 dot[MAX_EXT_CHARS+1-strlen(s)] = '\0';
1065 if (do_stat(ifname, sbuf) == 0) return OK;
1066 ifname[ilen] = '\0';
1067 } while (*++suf != NULL);
1069 /* No suffix found, complain using z_suffix: */
1070 #ifdef MAX_EXT_CHARS
1071 strcpy(ifname, iname);
1072 if (*dot == '\0') strcpy(dot, ".");
1073 dot[MAX_EXT_CHARS+1-z_len] = '\0';
1075 strcat(ifname, z_suffix);
1081 /* ========================================================================
1082 * Generate ofname given ifname. Return OK, or WARNING if file must be skipped.
1083 * Sets save_orig_name to true if the file name has been truncated.
1085 local int make_ofname()
1087 char *suff; /* ofname z suffix */
1089 strcpy(ofname, ifname);
1090 /* strip a version number if any and get the gzip suffix if present: */
1091 suff = get_suffix(ofname);
1095 /* Whith -t or -l, try all files (even without .gz suffix)
1096 * except with -r (behave as with just -dr).
1098 if (!recursive && (list || test)) return OK;
1100 /* Avoid annoying messages with -r */
1101 if (verbose || (!recursive && !quiet)) {
1102 WARN((stderr,"%s: %s: unknown suffix -- ignored\n",
1107 /* Make a special case for .tgz and .taz: */
1109 if (strequ(suff, ".tgz") || strequ(suff, ".taz")) {
1110 strcpy(suff, ".tar");
1112 *suff = '\0'; /* strip the z suffix */
1114 /* ofname might be changed later if infile contains an original name */
1116 } else if (suff != NULL) {
1117 /* Avoid annoying messages with -r (see treat_dir()) */
1118 if (verbose || (!recursive && !quiet)) {
1119 fprintf(stderr, "%s: %s already has %s suffix -- unchanged\n",
1120 progname, ifname, suff);
1122 if (exit_code == OK) exit_code = WARNING;
1127 #ifdef NO_MULTIPLE_DOTS
1128 suff = strrchr(ofname, '.');
1130 strcat(ofname, ".");
1131 # ifdef MAX_EXT_CHARS
1132 if (strequ(z_suffix, "z")) {
1133 strcat(ofname, "gz"); /* enough room */
1136 /* On the Atari and some versions of MSDOS, name_too_long()
1137 * does not work correctly because of a bug in stat(). So we
1138 * must truncate here.
1140 } else if (strlen(suff)-1 + z_len > MAX_SUFFIX) {
1141 suff[MAX_SUFFIX+1-z_len] = '\0';
1145 #endif /* NO_MULTIPLE_DOTS */
1146 strcat(ofname, z_suffix);
1148 } /* decompress ? */
1153 /* ========================================================================
1154 * Check the magic number of the input file and update ofname if an
1155 * original name was given and to_stdout is not set.
1156 * Return the compression method, -1 for error, -2 for warning.
1157 * Set inptr to the offset of the next byte to be processed.
1158 * Updates time_stamp if there is one and --no-time is not used.
1159 * This function may be called repeatedly for an input file consisting
1160 * of several contiguous gzip'ed members.
1161 * IN assertions: there is at least one remaining compressed member.
1162 * If the member is a zip file, it must be the only one.
1164 local int get_method(in)
1165 int in; /* input file descriptor */
1167 uch flags; /* compression flags */
1168 char magic[2]; /* magic header */
1169 ulg stamp; /* time stamp */
1171 /* If --force and --stdout, zcat == cat, so do not complain about
1172 * premature end of file: use try_byte instead of get_byte.
1174 if (force && to_stdout) {
1175 magic[0] = (char)try_byte();
1176 magic[1] = (char)try_byte();
1177 /* If try_byte returned EOF, magic[1] == 0xff */
1179 magic[0] = (char)get_byte();
1180 magic[1] = (char)get_byte();
1182 method = -1; /* unknown yet */
1183 part_nb++; /* number of parts in gzip file */
1185 last_member = RECORD_IO;
1186 /* assume multiple members in gzip file except for record oriented I/O */
1188 if (memcmp(magic, GZIP_MAGIC, 2) == 0
1189 || memcmp(magic, OLD_GZIP_MAGIC, 2) == 0) {
1191 method = (int)get_byte();
1192 if (method != DEFLATED) {
1194 "%s: %s: unknown method %d -- get newer version of gzip\n",
1195 progname, ifname, method);
1200 flags = (uch)get_byte();
1202 if ((flags & ENCRYPTED) != 0) {
1204 "%s: %s is encrypted -- get newer version of gzip\n",
1209 if ((flags & CONTINUATION) != 0) {
1211 "%s: %s is a a multi-part gzip file -- get newer version of gzip\n",
1214 if (force <= 1) return -1;
1216 if ((flags & RESERVED) != 0) {
1218 "%s: %s has flags 0x%x -- get newer version of gzip\n",
1219 progname, ifname, flags);
1221 if (force <= 1) return -1;
1223 stamp = (ulg)get_byte();
1224 stamp |= ((ulg)get_byte()) << 8;
1225 stamp |= ((ulg)get_byte()) << 16;
1226 stamp |= ((ulg)get_byte()) << 24;
1227 if (stamp != 0 && !no_time) time_stamp = stamp;
1229 (void)get_byte(); /* Ignore extra flags for the moment */
1230 (void)get_byte(); /* Ignore OS type for the moment */
1232 if ((flags & CONTINUATION) != 0) {
1233 unsigned part = (unsigned)get_byte();
1234 part |= ((unsigned)get_byte())<<8;
1236 fprintf(stderr,"%s: %s: part number %u\n",
1237 progname, ifname, part);
1240 if ((flags & EXTRA_FIELD) != 0) {
1241 unsigned len = (unsigned)get_byte();
1242 len |= ((unsigned)get_byte())<<8;
1244 fprintf(stderr,"%s: %s: extra field of %u bytes ignored\n",
1245 progname, ifname, len);
1247 while (len--) (void)get_byte();
1250 /* Get original file name if it was truncated */
1251 if ((flags & ORIG_NAME) != 0) {
1252 if (no_name || (to_stdout && !list) || part_nb > 1) {
1253 /* Discard the old name */
1254 char c; /* dummy used for NeXTstep 3.0 cc optimizer bug */
1255 do {c=get_byte();} while (c != 0);
1257 /* Copy the base name. Keep a directory prefix intact. */
1258 char *p = basename(ofname);
1261 *p = (char)get_char();
1262 if (*p++ == '\0') break;
1263 if (p >= ofname+sizeof(ofname)) {
1264 error("corrupted input -- file name too large");
1267 /* If necessary, adapt the name to local OS conventions: */
1269 MAKE_LEGAL_NAME(base);
1270 if (base) list=0; /* avoid warning about unused variable */
1272 } /* no_name || to_stdout */
1275 /* Discard file comment if any */
1276 if ((flags & COMMENT) != 0) {
1277 while (get_char() != 0) /* null */ ;
1280 header_bytes = inptr + 2*sizeof(long); /* include crc and size */
1283 } else if (memcmp(magic, PKZIP_MAGIC, 2) == 0 && inptr == 2
1284 && memcmp((char*)inbuf, PKZIP_MAGIC, 4) == 0) {
1285 /* To simplify the code, we support a zip file when alone only.
1286 * We are thus guaranteed that the entire local header fits in inbuf.
1290 if (check_zipfile(in) != OK) return -1;
1291 /* check_zipfile may get ofname from the local header */
1294 } else if (memcmp(magic, PACK_MAGIC, 2) == 0) {
1298 } else if (memcmp(magic, LZW_MAGIC, 2) == 0) {
1300 method = COMPRESSED;
1303 } else if (memcmp(magic, LZH_MAGIC, 2) == 0) {
1308 } else if (force && to_stdout && !list) { /* pass input unchanged */
1314 if (method >= 0) return method;
1317 fprintf(stderr, "\n%s: %s: not in gzip format\n", progname, ifname);
1321 WARN((stderr, "\n%s: %s: decompression OK, trailing garbage ignored\n",
1327 /* ========================================================================
1328 * Display the characteristics of the compressed file.
1329 * If the given method is < 0, display the accumulated totals.
1330 * IN assertions: time_stamp, header_bytes and ifile_size are initialized.
1332 local void do_list(ifd, method)
1333 int ifd; /* input file descriptor */
1334 int method; /* compression method */
1336 ulg crc; /* original crc */
1337 static int first_time = 1;
1338 static char* methods[MAX_METHODS] = {
1343 "", "", "", "", /* 4 to 7 reserved */
1347 if (first_time && method >= 0) {
1350 printf("method crc date time ");
1353 printf("compressed uncompr. ratio uncompressed_name\n");
1355 } else if (method < 0) {
1356 if (total_in <= 0 || total_out <= 0) return;
1358 printf(" %9lu %9lu ",
1359 total_in, total_out);
1360 } else if (!quiet) {
1361 printf("%9ld %9ld ", total_in, total_out);
1363 display_ratio(total_out-(total_in-header_bytes), total_out, stdout);
1364 /* header_bytes is not meaningful but used to ensure the same
1365 * ratio if there is a single file.
1367 printf(" (totals)\n");
1370 crc = (ulg)~0; /* unknown */
1372 bytes_in = ifile_size;
1375 if (method == DEFLATED && !last_member) {
1376 /* Get the crc and uncompressed size for gzip'ed (not zip'ed) files.
1377 * If the lseek fails, we could use read() to get to the end, but
1378 * --list is used to get quick results.
1379 * Use "gunzip < foo.gz | wc -c" to get the uncompressed size if
1380 * you are not concerned about speed.
1382 bytes_in = (long)lseek(ifd, (off_t)(-8), SEEK_END);
1383 if (bytes_in != -1L) {
1386 if (read(ifd, (char*)buf, sizeof(buf)) != sizeof(buf)) {
1390 bytes_out = LG(buf+4);
1393 #endif /* RECORD_IO */
1394 date = ctime((time_t*)&time_stamp) + 4; /* skip the day of the week */
1395 date[12] = '\0'; /* suppress the 1/100sec and the year */
1397 printf("%5s %08lx %11s ", methods[method], crc, date);
1399 printf("%9ld %9ld ", bytes_in, bytes_out);
1400 if (bytes_in == -1L) {
1402 bytes_in = bytes_out = header_bytes = 0;
1403 } else if (total_in >= 0) {
1404 total_in += bytes_in;
1406 if (bytes_out == -1L) {
1408 bytes_in = bytes_out = header_bytes = 0;
1409 } else if (total_out >= 0) {
1410 total_out += bytes_out;
1412 display_ratio(bytes_out-(bytes_in-header_bytes), bytes_out, stdout);
1413 printf(" %s\n", ofname);
1416 /* ========================================================================
1417 * Return true if the two stat structures correspond to the same file.
1419 local int same_file(stat1, stat2)
1423 return stat1->st_ino == stat2->st_ino
1424 && stat1->st_dev == stat2->st_dev
1426 /* Can't rely on st_ino and st_dev, use other fields: */
1427 && stat1->st_mode == stat2->st_mode
1428 && stat1->st_uid == stat2->st_uid
1429 && stat1->st_gid == stat2->st_gid
1430 && stat1->st_size == stat2->st_size
1431 && stat1->st_atime == stat2->st_atime
1432 && stat1->st_mtime == stat2->st_mtime
1433 && stat1->st_ctime == stat2->st_ctime
1438 /* ========================================================================
1439 * Return true if a file name is ambiguous because the operating system
1440 * truncates file names.
1442 local int name_too_long(name, statb)
1443 char *name; /* file name to check */
1444 struct stat *statb; /* stat buf for this file name */
1446 int s = strlen(name);
1448 struct stat tstat; /* stat for truncated name */
1451 tstat = *statb; /* Just in case OS does not fill all fields */
1453 res = stat(name, &tstat) == 0 && same_file(statb, &tstat);
1455 Trace((stderr, " too_long(%s) => %d\n", name, res));
1459 /* ========================================================================
1460 * Shorten the given name by one character, or replace a .tar extension
1461 * with .tgz. Truncate the last part of the name which is longer than
1462 * MIN_PART characters: 1234.678.012.gz -> 123.678.012.gz. If the name
1463 * has only parts shorter than MIN_PART truncate the longest part.
1464 * For decompression, just remove the last character of the name.
1466 * IN assertion: for compression, the suffix of the given name is z_suffix.
1468 local void shorten_name(name)
1471 int len; /* length of name without z_suffix */
1472 char *trunc = NULL; /* character to be truncated */
1473 int plen; /* current part length */
1474 int min_part = MIN_PART; /* current minimum part length */
1479 if (len <= 1) error("name too short");
1483 p = get_suffix(name);
1484 if (p == NULL) error("can't recover suffix\n");
1488 /* compress 1234567890.tar to 1234567890.tgz */
1489 if (len > 4 && strequ(p-4, ".tar")) {
1490 strcpy(p-4, ".tgz");
1493 /* Try keeping short extensions intact:
1494 * 1234.678.012.gz -> 123.678.012.gz
1497 p = strrchr(name, PATH_SEP);
1500 plen = strcspn(p, PART_SEP);
1502 if (plen > min_part) trunc = p-1;
1505 } while (trunc == NULL && --min_part != 0);
1507 if (trunc != NULL) {
1509 trunc[0] = trunc[1];
1513 trunc = strrchr(name, PART_SEP[0]);
1514 if (trunc == NULL) error("internal error in shorten_name");
1515 if (trunc[1] == '\0') trunc--; /* force truncation */
1517 strcpy(trunc, z_suffix);
1520 /* ========================================================================
1521 * If compressing to a file, check if ofname is not ambiguous
1522 * because the operating system truncates names. Otherwise, generate
1523 * a new ofname and save the original name in the compressed file.
1524 * If the compressed file already exists, ask for confirmation.
1525 * The check for name truncation is made dynamically, because different
1526 * file systems on the same OS might use different truncation rules (on SVR4
1527 * s5 truncates to 14 chars and ufs does not truncate).
1528 * This function returns -1 if the file must be skipped, and
1529 * updates save_orig_name if necessary.
1530 * IN assertions: save_orig_name is already set if ofname has been
1531 * already truncated because of NO_MULTIPLE_DOTS. The input file has
1532 * already been open and istat is set.
1534 local int check_ofname()
1536 struct stat ostat; /* stat for ofname */
1539 /* Check for strictly conforming Posix systems (which return ENAMETOOLONG
1540 * instead of silently truncating filenames).
1543 while (stat(ofname, &ostat) != 0) {
1544 if (errno != ENAMETOOLONG) return 0; /* ofname does not exist */
1545 shorten_name(ofname);
1548 if (stat(ofname, &ostat) != 0) return 0;
1550 /* Check for name truncation on existing file. Do this even on systems
1551 * defining ENAMETOOLONG, because on most systems the strict Posix
1552 * behavior is disabled by default (silent name truncation allowed).
1554 if (!decompress && name_too_long(ofname, &ostat)) {
1555 shorten_name(ofname);
1556 if (stat(ofname, &ostat) != 0) return 0;
1559 /* Check that the input and output files are different (could be
1560 * the same by name truncation or links).
1562 if (same_file(&istat, &ostat)) {
1563 if (strequ(ifname, ofname)) {
1564 fprintf(stderr, "%s: %s: cannot %scompress onto itself\n",
1565 progname, ifname, decompress ? "de" : "");
1567 fprintf(stderr, "%s: %s and %s are the same file\n",
1568 progname, ifname, ofname);
1573 /* Ask permission to overwrite the existing file */
1576 strcpy(response,"n");
1577 fprintf(stderr, "%s: %s already exists;", progname, ofname);
1578 if (foreground && isatty(fileno(stdin))) {
1579 fprintf(stderr, " do you wish to overwrite (y or n)? ");
1581 (void)fgets(response, sizeof(response)-1, stdin);
1583 if (tolow(*response) != 'y') {
1584 fprintf(stderr, "\tnot overwritten\n");
1585 if (exit_code == OK) exit_code = WARNING;
1589 if (unlink(ofname)) {
1590 fprintf(stderr, "%s: ", progname);
1600 /* ========================================================================
1601 * Set the access and modification times from the given stat buffer.
1603 local void reset_times (name, statb)
1607 struct utimbuf timep;
1609 /* Copy the time stamp */
1610 timep.actime = statb->st_atime;
1611 timep.modtime = statb->st_mtime;
1613 /* Some systems (at least OS/2) do not support utime on directories */
1614 if (utime(name, &timep) && !S_ISDIR(statb->st_mode)) {
1615 WARN((stderr, "%s: ", progname));
1616 if (!quiet) perror(ofname);
1622 /* ========================================================================
1623 * Copy modes, times, ownership from input file to output file.
1624 * IN assertion: to_stdout is false.
1626 local void copy_stat(ifstat)
1627 struct stat *ifstat;
1630 if (decompress && time_stamp != 0 && ifstat->st_mtime != time_stamp) {
1631 ifstat->st_mtime = time_stamp;
1633 fprintf(stderr, "%s: time stamp restored\n", ofname);
1636 reset_times(ofname, ifstat);
1638 /* Copy the protection modes */
1639 if (chmod(ofname, ifstat->st_mode & 07777)) {
1640 WARN((stderr, "%s: ", progname));
1641 if (!quiet) perror(ofname);
1644 chown(ofname, ifstat->st_uid, ifstat->st_gid); /* Copy ownership */
1647 /* It's now safe to remove the input file: */
1648 if (unlink(ifname)) {
1649 WARN((stderr, "%s: ", progname));
1650 if (!quiet) perror(ifname);
1656 /* ========================================================================
1657 * Recurse through the given directory. This code is taken from ncompress.
1659 local void treat_dir(dir)
1664 char nbuf[MAX_PATH_LEN];
1667 dirp = opendir(dir);
1670 fprintf(stderr, "%s: %s unreadable\n", progname, dir);
1675 ** WARNING: the following algorithm could occasionally cause
1676 ** compress to produce error warnings of the form "<filename>.gz
1677 ** already has .gz suffix - ignored". This occurs when the
1678 ** .gz output file is inserted into the directory below
1679 ** readdir's current pointer.
1680 ** These warnings are harmless but annoying, so they are suppressed
1681 ** with option -r (except when -v is on). An alternative
1682 ** to allowing this would be to store the entire directory
1683 ** list in memory, then compress the entries in the stored
1684 ** list. Given the depth-first recursive algorithm used here,
1685 ** this could use up a tremendous amount of memory. I don't
1686 ** think it's worth it. -- Dave Mack
1687 ** (An other alternative might be two passes to avoid depth-first.)
1690 while ((dp = readdir(dirp)) != NULL) {
1692 if (strequ(dp->d_name,".") || strequ(dp->d_name,"..")) {
1696 if (len + NLENGTH(dp) + 1 < MAX_PATH_LEN - 1) {
1698 if (len != 0 /* dir = "" means current dir on Amiga */
1700 && dir[len-1] != PATH_SEP2
1703 && dir[len-1] != PATH_SEP3
1706 nbuf[len++] = PATH_SEP;
1708 strcpy(nbuf+len, dp->d_name);
1711 fprintf(stderr,"%s: %s/%s: pathname too long\n",
1712 progname, dir, dp->d_name);
1718 #endif /* ? NO_DIR */
1720 /* ========================================================================
1721 * Free all dynamically allocated variables and exit with the given code.
1723 local void do_exit(exitcode)
1726 static int in_exit = 0;
1728 if (in_exit) exit(exitcode);
1730 if (env != NULL) free(env), env = NULL;
1731 if (args != NULL) free((char*)args), args = NULL;
1745 /* ========================================================================
1746 * Signal and error handler.
1748 RETSIGTYPE abort_gzip()
1750 if (remove_ofname) {