1 /* $NetBSD: gzip.c,v 1.89 2006/11/13 21:57:59 mrg Exp $ */
4 * Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 #include <sys/cdefs.h>
34 __COPYRIGHT("@(#) Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n\
35 All rights reserved.\n");
40 * gzip.c -- GPL free gzip using zlib.
42 * RFC 1950 covers the zlib format
43 * RFC 1951 covers the deflate format
44 * RFC 1952 covers the gzip format
47 * - use mmap where possible
48 * - handle some signals better (remove outfile?)
49 * - make bzip2/compress -v/-t/-l support work as well as possible
52 #include <sys/param.h>
72 #define PRIdOFF PRId64
75 /* what type of file are we dealing with */
78 #ifndef NO_BZIP2_SUPPORT
81 #ifndef NO_COMPRESS_SUPPORT
88 #ifndef NO_BZIP2_SUPPORT
91 #define BZ2_SUFFIX ".bz2"
92 #define BZIP2_MAGIC "\102\132\150"
95 #ifndef NO_COMPRESS_SUPPORT
97 #define Z_MAGIC "\037\235"
100 #define GZ_SUFFIX ".gz"
102 #define BUFLEN (64 * 1024)
104 #define GZIP_MAGIC0 0x1F
105 #define GZIP_MAGIC1 0x8B
106 #define GZIP_OMAGIC1 0x9E
108 #define GZIP_TIMESTAMP (off_t)4
109 #define GZIP_ORIGNAME (off_t)10
111 #define HEAD_CRC 0x02
112 #define EXTRA_FIELD 0x04
113 #define ORIG_NAME 0x08
116 #define OS_CODE 3 /* Unix */
121 const char *normal; /* for unzip - must not be longer than zipped */
123 static suffixes_t suffixes[] = {
124 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
125 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
127 SUFFIX(GZ_SUFFIX, ""),
132 SUFFIX(".taz", ".tar"),
133 SUFFIX(".tgz", ".tar"),
134 #ifndef NO_BZIP2_SUPPORT
135 SUFFIX(BZ2_SUFFIX, ""),
137 #ifndef NO_COMPRESS_SUPPORT
138 SUFFIX(Z_SUFFIX, ""),
140 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
144 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
146 static const char gzip_version[] = "FreeBSD gzip 20070126";
149 static const char gzip_copyright[] = \
150 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
151 " All rights reserved.\n"
153 " Redistribution and use in source and binary forms, with or without\n"
154 " modification, are permitted provided that the following conditions\n"
156 " 1. Redistributions of source code must retain the above copyright\n"
157 " notice, this list of conditions and the following disclaimer.\n"
158 " 2. Redistributions in binary form must reproduce the above copyright\n"
159 " notice, this list of conditions and the following disclaimer in the\n"
160 " documentation and/or other materials provided with the distribution.\n"
161 " 3. The name of the author may not be used to endorse or promote products\n"
162 " derived from this software without specific prior written permission.\n"
164 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
165 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
166 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
167 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
168 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
169 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
170 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
171 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
172 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
173 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
177 static int cflag; /* stdout mode */
178 static int dflag; /* decompress mode */
179 static int lflag; /* list mode */
180 static int numflag = 6; /* gzip -1..-9 value */
183 static int fflag; /* force mode */
184 static int nflag; /* don't save name/timestamp */
185 static int Nflag; /* don't restore name/timestamp */
186 static int qflag; /* quiet mode */
187 static int rflag; /* recursive mode */
188 static int tflag; /* test */
189 static int vflag; /* verbose mode */
195 static int exit_value = 0; /* exit value */
197 static char *infile; /* name of file coming in */
199 static void maybe_err(const char *fmt, ...)
200 __attribute__((__format__(__printf__, 1, 2)));
201 #ifndef NO_BZIP2_SUPPORT
202 static void maybe_errx(const char *fmt, ...)
203 __attribute__((__format__(__printf__, 1, 2)));
205 static void maybe_warn(const char *fmt, ...)
206 __attribute__((__format__(__printf__, 1, 2)));
207 static void maybe_warnx(const char *fmt, ...)
208 __attribute__((__format__(__printf__, 1, 2)));
209 static enum filetype file_gettype(u_char *);
211 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
213 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
214 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
215 static off_t file_compress(char *, char *, size_t);
216 static off_t file_uncompress(char *, char *, size_t);
217 static void handle_pathname(char *);
218 static void handle_file(char *, struct stat *);
219 static void handle_stdin(void);
220 static void handle_stdout(void);
221 static void print_ratio(off_t, off_t, FILE *);
222 static void print_list(int fd, off_t, const char *, time_t);
223 static void usage(void);
224 static void display_version(void);
226 static void display_license(void);
228 static const suffixes_t *check_suffix(char *, int);
229 static ssize_t read_retry(int, void *, size_t);
232 #define unlink_input(f, sb) unlink(f)
234 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
235 static void prepend_gzip(char *, int *, char ***);
236 static void handle_dir(char *);
237 static void print_verbage(const char *, const char *, off_t, off_t);
238 static void print_test(const char *, int);
239 static void copymodes(int fd, const struct stat *, const char *file);
240 static int check_outfile(const char *outfile);
243 #ifndef NO_BZIP2_SUPPORT
244 static off_t unbzip2(int, int, char *, size_t, off_t *);
247 #ifndef NO_COMPRESS_SUPPORT
248 static FILE *zdopen(int);
249 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
252 int main(int, char **p);
255 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
257 static const struct option longopts[] = {
258 { "stdout", no_argument, 0, 'c' },
259 { "to-stdout", no_argument, 0, 'c' },
260 { "decompress", no_argument, 0, 'd' },
261 { "uncompress", no_argument, 0, 'd' },
262 { "force", no_argument, 0, 'f' },
263 { "help", no_argument, 0, 'h' },
264 { "list", no_argument, 0, 'l' },
265 { "no-name", no_argument, 0, 'n' },
266 { "name", no_argument, 0, 'N' },
267 { "quiet", no_argument, 0, 'q' },
268 { "recursive", no_argument, 0, 'r' },
269 { "suffix", required_argument, 0, 'S' },
270 { "test", no_argument, 0, 't' },
271 { "verbose", no_argument, 0, 'v' },
272 { "version", no_argument, 0, 'V' },
273 { "fast", no_argument, 0, '1' },
274 { "best", no_argument, 0, '9' },
275 { "ascii", no_argument, 0, 'a' },
276 { "license", no_argument, 0, 'L' },
277 { NULL, no_argument, 0, 0 },
282 main(int argc, char **argv)
284 const char *progname = getprogname();
291 /* XXX set up signals */
294 if ((gzip = getenv("GZIP")) != NULL)
295 prepend_gzip(gzip, &argc, &argv);
300 * handle being called `gunzip', `zcat' and `gzcat'
302 if (strcmp(progname, "gunzip") == 0)
304 else if (strcmp(progname, "zcat") == 0 ||
305 strcmp(progname, "gzcat") == 0)
309 #define OPT_LIST "123456789cdhltV"
311 #define OPT_LIST "123456789acdfhlLNnqrS:tVv"
314 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
316 case '1': case '2': case '3':
317 case '4': case '5': case '6':
318 case '7': case '8': case '9':
336 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
359 len = strlen(optarg);
361 suffixes[0].zipped = optarg;
362 suffixes[0].ziplen = len;
364 suffixes[NUM_SUFFIXES - 1].zipped = "";
365 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
386 if (dflag) /* stdin mode */
388 else /* stdout mode */
392 handle_pathname(argv[0]);
396 if (qflag == 0 && lflag && argc > 1)
397 print_list(-1, 0, "(totals)", 0);
402 /* maybe print a warning */
404 maybe_warn(const char *fmt, ...)
417 /* ... without an errno. */
419 maybe_warnx(const char *fmt, ...)
432 /* maybe print an error */
434 maybe_err(const char *fmt, ...)
446 #ifndef NO_BZIP2_SUPPORT
447 /* ... without an errno. */
449 maybe_errx(const char *fmt, ...)
463 /* split up $GZIP and prepend it to the argument list */
465 prepend_gzip(char *gzip, int *argc, char ***argv)
467 char *s, **nargv, **ac;
470 /* scan how many arguments there are */
472 while (*s == ' ' || *s == '\t')
477 while (*s != ' ' && *s != '\t')
489 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
493 /* stash this away */
496 /* copy the program name first */
498 nargv[i++] = *(ac++);
500 /* take a copy of $GZIP and add it to the array */
505 /* Skip whitespaces. */
506 while (*s == ' ' || *s == '\t')
511 /* Find the end of this argument. */
512 while (*s != ' ' && *s != '\t')
514 /* Argument followed by NUL. */
516 /* Terminate by overwriting ' ' or '\t' with NUL. */
521 /* copy the original arguments and a NULL */
523 nargv[i++] = *(ac++);
528 /* compress input to output. Return bytes read, -1 on error */
530 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
533 char *outbufp, *inbufp;
534 off_t in_tot = 0, out_tot = 0;
539 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
544 outbufp = malloc(BUFLEN);
545 inbufp = malloc(BUFLEN);
546 if (outbufp == NULL || inbufp == NULL) {
547 maybe_err("malloc failed");
551 memset(&z, 0, sizeof z);
557 memcpy(outbufp, header, sizeof header);
565 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
566 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
567 *origname ? ORIG_NAME : 0,
570 (mtime >> 16) & 0xff,
571 (mtime >> 24) & 0xff,
572 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
575 /* this need PATH_MAX > BUFLEN ... */
576 maybe_err("snprintf");
581 z.next_out = (unsigned char *)outbufp + i;
582 z.avail_out = BUFLEN - i;
584 error = deflateInit2(&z, numflag, Z_DEFLATED,
585 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
587 maybe_warnx("deflateInit2 failed");
592 crc = crc32(0L, Z_NULL, 0);
594 if (z.avail_out == 0) {
595 if (write(out, outbufp, BUFLEN) != BUFLEN) {
602 z.next_out = (unsigned char *)outbufp;
603 z.avail_out = BUFLEN;
606 if (z.avail_in == 0) {
607 in_size = read(in, inbufp, BUFLEN);
616 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
618 z.next_in = (unsigned char *)inbufp;
619 z.avail_in = in_size;
622 error = deflate(&z, Z_NO_FLUSH);
623 if (error != Z_OK && error != Z_STREAM_END) {
624 maybe_warnx("deflate failed");
635 error = deflate(&z, Z_FINISH);
636 if (error != Z_OK && error != Z_STREAM_END) {
637 maybe_warnx("deflate failed");
642 len = (char *)z.next_out - outbufp;
644 w = write(out, outbufp, len);
645 if (w == -1 || (size_t)w != len) {
651 z.next_out = (unsigned char *)outbufp;
652 z.avail_out = BUFLEN;
654 if (error == Z_STREAM_END)
658 if (deflateEnd(&z) != Z_OK) {
659 maybe_warnx("deflateEnd failed");
664 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
666 (int)(crc >> 8) & 0xff,
667 (int)(crc >> 16) & 0xff,
668 (int)(crc >> 24) & 0xff,
670 (int)(in_tot >> 8) & 0xff,
671 (int)(in_tot >> 16) & 0xff,
672 (int)(in_tot >> 24) & 0xff);
674 maybe_err("snprintf");
675 if (write(out, outbufp, i) != i) {
692 * uncompress input to output then close the input. return the
693 * uncompressed size written, and put the compressed sized read
697 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
698 const char *filename)
701 char *outbufp, *inbufp;
702 off_t out_tot = -1, in_tot = 0;
703 uint32_t out_sub_tot = 0;
721 } state = GZSTATE_MAGIC0;
722 int flags = 0, skip_count = 0;
723 int error = Z_STREAM_ERROR, done_reading = 0;
728 #define ADVANCE() { z.next_in++; z.avail_in--; }
730 if ((outbufp = malloc(BUFLEN)) == NULL) {
731 maybe_err("malloc failed");
734 if ((inbufp = malloc(BUFLEN)) == NULL) {
735 maybe_err("malloc failed");
739 memset(&z, 0, sizeof z);
741 z.next_in = (unsigned char *)pre;
742 z.avail_out = BUFLEN;
743 z.next_out = (unsigned char *)outbufp;
752 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
755 if (z.avail_in > 0) {
756 memmove(inbufp, z.next_in, z.avail_in);
758 z.next_in = (unsigned char *)inbufp;
759 in_size = read(in, z.next_in + z.avail_in,
760 BUFLEN - z.avail_in);
763 maybe_warn("failed to read stdin");
765 } else if (in_size == 0) {
769 z.avail_in += in_size;
774 if (z.avail_in == 0) {
775 if (done_reading && state != GZSTATE_MAGIC0) {
776 maybe_warnx("%s: unexpected end of file",
784 if (*z.next_in != GZIP_MAGIC0) {
786 maybe_warnx("%s: trailing garbage "
787 "ignored", filename);
790 maybe_warnx("input not gziped (MAGIC0)");
796 crc = crc32(0L, Z_NULL, 0);
800 if (*z.next_in != GZIP_MAGIC1 &&
801 *z.next_in != GZIP_OMAGIC1) {
802 maybe_warnx("input not gziped (MAGIC1)");
810 if (*z.next_in != Z_DEFLATED) {
811 maybe_warnx("unknown compression method");
825 case GZSTATE_SKIPPING:
826 if (skip_count > 0) {
834 if ((flags & EXTRA_FIELD) == 0) {
835 state = GZSTATE_ORIGNAME;
838 skip_count = *z.next_in;
844 skip_count |= ((*z.next_in) << 8);
850 if (skip_count > 0) {
857 case GZSTATE_ORIGNAME:
858 if ((flags & ORIG_NAME) == 0) {
867 case GZSTATE_COMMENT:
868 if ((flags & COMMENT) == 0) {
877 case GZSTATE_HEAD_CRC1:
878 if (flags & HEAD_CRC)
885 case GZSTATE_HEAD_CRC2:
886 if (skip_count > 0) {
894 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
895 maybe_warnx("failed to inflateInit");
902 error = inflate(&z, Z_FINISH);
904 /* Z_BUF_ERROR goes with Z_FINISH... */
911 maybe_warnx("Z_NEED_DICT error");
914 maybe_warnx("data stream error");
917 maybe_warnx("internal stream error");
920 maybe_warnx("memory allocation error");
924 maybe_warn("unknown error from inflate(): %d",
927 wr = BUFLEN - z.avail_out;
930 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
933 /* don't write anything with -t */
936 write(out, outbufp, wr) != wr) {
937 maybe_warn("error writing to output");
945 if (error == Z_STREAM_END) {
950 z.next_out = (unsigned char *)outbufp;
951 z.avail_out = BUFLEN;
958 if (z.avail_in < 4) {
963 maybe_warnx("truncated input");
966 origcrc = ((unsigned)z.next_in[0] & 0xff) |
967 ((unsigned)z.next_in[1] & 0xff) << 8 |
968 ((unsigned)z.next_in[2] & 0xff) << 16 |
969 ((unsigned)z.next_in[3] & 0xff) << 24;
970 if (origcrc != crc) {
971 maybe_warnx("invalid compressed"
980 if (!z.avail_in && done_reading) {
989 if (z.avail_in < 4) {
994 maybe_warnx("truncated input");
997 origlen = ((unsigned)z.next_in[0] & 0xff) |
998 ((unsigned)z.next_in[1] & 0xff) << 8 |
999 ((unsigned)z.next_in[2] & 0xff) << 16 |
1000 ((unsigned)z.next_in[3] & 0xff) << 24;
1002 if (origlen != out_sub_tot) {
1003 maybe_warnx("invalid compressed"
1004 " data--length error");
1013 maybe_warnx("decompression error");
1016 state = GZSTATE_MAGIC0;
1025 if (state > GZSTATE_INIT)
1039 * set the owner, mode, flags & utimes using the given file descriptor.
1040 * file is only used in possible warning messages.
1043 copymodes(int fd, const struct stat *sbp, const char *file)
1045 struct timeval times[2];
1049 * If we have no info on the input, give this file some
1050 * default values and return..
1053 mode_t mask = umask(022);
1055 (void)fchmod(fd, DEFFILEMODE & ~mask);
1061 /* if the chown fails, remove set-id bits as-per compress(1) */
1062 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1064 maybe_warn("couldn't fchown: %s", file);
1065 sb.st_mode &= ~(S_ISUID|S_ISGID);
1068 /* we only allow set-id and the 9 normal permission bits */
1069 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1070 if (fchmod(fd, sb.st_mode) < 0)
1071 maybe_warn("couldn't fchmod: %s", file);
1073 /* only try flags if they exist already */
1074 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1075 maybe_warn("couldn't fchflags: %s", file);
1077 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atimespec);
1078 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtimespec);
1079 if (futimes(fd, times) < 0)
1080 maybe_warn("couldn't utimes: %s", file);
1084 /* what sort of file is this? */
1085 static enum filetype
1086 file_gettype(u_char *buf)
1089 if (buf[0] == GZIP_MAGIC0 &&
1090 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1093 #ifndef NO_BZIP2_SUPPORT
1094 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1095 buf[3] >= '0' && buf[3] <= '9')
1099 #ifndef NO_COMPRESS_SUPPORT
1100 if (memcmp(buf, Z_MAGIC, 2) == 0)
1108 /* check the outfile is OK. */
1110 check_outfile(const char *outfile)
1115 if (lflag == 0 && stat(outfile, &sb) == 0) {
1118 else if (isatty(STDIN_FILENO)) {
1119 char ans[10] = { 'n', '\0' }; /* default */
1121 fprintf(stderr, "%s already exists -- do you wish to "
1122 "overwrite (y or n)? " , outfile);
1123 (void)fgets(ans, sizeof(ans) - 1, stdin);
1124 if (ans[0] != 'y' && ans[0] != 'Y') {
1125 fprintf(stderr, "\tnot overwritting\n");
1130 maybe_warnx("%s already exists -- skipping", outfile);
1138 unlink_input(const char *file, const struct stat *sb)
1142 if (stat(file, &nsb) != 0)
1143 /* Must be gone alrady */
1145 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1146 /* Definitely a different file */
1152 static const suffixes_t *
1153 check_suffix(char *file, int xlate)
1155 const suffixes_t *s;
1156 int len = strlen(file);
1159 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1160 /* if it doesn't fit in "a.suf", don't bother */
1161 if (s->ziplen >= len)
1163 sp = file + len - s->ziplen;
1164 if (strcmp(s->zipped, sp) != 0)
1167 strcpy(sp, s->normal);
1174 * compress the given file: create a corresponding .gz file and remove the
1178 file_compress(char *file, char *outfile, size_t outsize)
1184 struct stat isb, osb;
1185 const suffixes_t *suff;
1188 in = open(file, O_RDONLY);
1190 maybe_warn("can't open %s", file);
1196 if (fstat(in, &isb) == 0) {
1197 if (isb.st_nlink > 1 && fflag == 0) {
1198 maybe_warnx("%s has %d other link%s -- "
1199 "skipping", file, isb.st_nlink - 1,
1200 isb.st_nlink == 1 ? "" : "s");
1206 if (fflag == 0 && (suff = check_suffix(file, 0))
1207 && suff->zipped[0] != 0) {
1208 maybe_warnx("%s already has %s suffix -- unchanged",
1209 file, suff->zipped);
1215 /* Add (usually) .gz to filename */
1216 if ((size_t)snprintf(outfile, outsize, "%s%s",
1217 file, suffixes[0].zipped) >= outsize)
1218 memcpy(outfile - suffixes[0].ziplen - 1,
1219 suffixes[0].zipped, suffixes[0].ziplen + 1);
1222 if (check_outfile(outfile) == 0) {
1230 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1232 maybe_warn("could not create output: %s", outfile);
1237 out = STDOUT_FILENO;
1239 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1244 * If there was an error, insize will be -1.
1245 * If we compressed to stdout, just return the size.
1246 * Otherwise stat the file and check it is the correct size.
1247 * We only blow away the file if we can stat the output and it
1248 * has the expected size.
1251 return insize == -1 ? -1 : size;
1254 if (fstat(out, &osb) != 0) {
1255 maybe_warn("couldn't stat: %s", outfile);
1259 if (osb.st_size != size) {
1260 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1261 " != %" PRIdOFF "), deleting",
1262 outfile, osb.st_size, size);
1266 copymodes(out, &isb, outfile);
1268 if (close(out) == -1)
1269 maybe_warn("couldn't close output");
1271 /* output is good, ok to delete input */
1272 unlink_input(file, &isb);
1277 if (close(out) == -1)
1278 maybe_warn("couldn't close output");
1280 maybe_warnx("leaving original %s", file);
1286 /* uncompress the given file and remove the original */
1288 file_uncompress(char *file, char *outfile, size_t outsize)
1290 struct stat isb, osb;
1293 unsigned char header1[4];
1294 enum filetype method;
1295 int rv, fd, ofd, zfd = -1;
1297 time_t timestamp = 0;
1298 unsigned char name[PATH_MAX + 1];
1301 /* gather the old name info */
1303 fd = open(file, O_RDONLY);
1305 maybe_warn("can't open %s", file);
1309 strlcpy(outfile, file, outsize);
1310 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1311 maybe_warnx("%s: unknown suffix -- ignored", file);
1315 rbytes = read(fd, header1, sizeof header1);
1316 if (rbytes != sizeof header1) {
1317 /* we don't want to fail here. */
1323 maybe_warn("can't read %s", file);
1325 goto unexpected_EOF;
1329 method = file_gettype(header1);
1332 if (fflag == 0 && method == FT_UNKNOWN) {
1333 maybe_warnx("%s: not in gzip format", file);
1340 if (method == FT_GZIP && Nflag) {
1341 unsigned char ts[4]; /* timestamp */
1343 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1344 if (rv >= 0 && (size_t)rv < sizeof ts)
1345 goto unexpected_EOF;
1348 maybe_warn("can't read %s", file);
1351 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1353 if (header1[3] & ORIG_NAME) {
1354 rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1356 maybe_warn("can't read %s", file);
1360 /* preserve original directory name */
1361 char *dp = strrchr(file, '/');
1366 snprintf(outfile, outsize, "%.*s%.*s",
1368 file, (int) rbytes, name);
1373 lseek(fd, 0, SEEK_SET);
1375 if (cflag == 0 || lflag) {
1376 if (fstat(fd, &isb) != 0)
1379 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1380 maybe_warnx("%s has %d other links -- skipping",
1381 file, isb.st_nlink - 1);
1384 if (nflag == 0 && timestamp)
1385 isb.st_mtime = timestamp;
1386 if (check_outfile(outfile) == 0)
1391 if (cflag == 0 && lflag == 0) {
1392 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1393 if (zfd == STDOUT_FILENO) {
1394 /* We won't close STDOUT_FILENO later... */
1396 close(STDOUT_FILENO);
1399 maybe_warn("can't open %s", outfile);
1403 zfd = STDOUT_FILENO;
1405 #ifndef NO_BZIP2_SUPPORT
1406 if (method == FT_BZIP2) {
1410 maybe_warnx("no -l with bzip2 files");
1414 size = unbzip2(fd, zfd, NULL, 0, NULL);
1418 #ifndef NO_COMPRESS_SUPPORT
1419 if (method == FT_Z) {
1424 maybe_warnx("no -l with Lempel-Ziv files");
1428 if ((in = zdopen(fd)) == NULL) {
1429 maybe_warn("zdopen for read: %s", file);
1433 out = fdopen(dup(zfd), "w");
1435 maybe_warn("fdopen for write: %s", outfile);
1440 size = zuncompress(in, out, NULL, 0, NULL);
1441 /* need to fclose() if ferror() is true... */
1442 if (ferror(in) | fclose(in)) {
1443 maybe_warn("failed infile fclose");
1447 if (fclose(out) != 0) {
1448 maybe_warn("failed outfile fclose");
1456 if (method == FT_UNKNOWN) {
1458 maybe_warnx("no -l for unknown filetypes");
1461 size = cat_fd(NULL, 0, NULL, fd);
1466 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1468 return -1; /* XXX */
1471 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1475 maybe_warn("couldn't close input");
1476 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1477 maybe_warn("couldn't close output");
1482 maybe_warnx("%s: uncompress failed", file);
1486 /* if testing, or we uncompressed to stdout, this is all we need */
1491 /* if we are uncompressing to stdin, don't remove the file. */
1496 * if we create a file...
1499 * if we can't stat the file don't remove the file.
1502 ofd = open(outfile, O_RDWR, 0);
1504 maybe_warn("couldn't open (leaving original): %s",
1508 if (fstat(ofd, &osb) != 0) {
1509 maybe_warn("couldn't stat (leaving original): %s",
1514 if (osb.st_size != size) {
1515 maybe_warnx("stat gave different size: %" PRIdOFF
1516 " != %" PRIdOFF " (leaving original)",
1522 unlink_input(file, &isb);
1524 copymodes(ofd, &isb, outfile);
1530 maybe_warnx("%s: unexpected end of file", file);
1534 if (zfd != -1 && zfd != STDOUT_FILENO)
1541 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1548 w = write(STDOUT_FILENO, prepend, count);
1549 if (w == -1 || (size_t)w != count) {
1550 maybe_warn("write to stdout");
1556 rv = read(fd, buf, sizeof buf);
1560 maybe_warn("read from fd %d", fd);
1564 if (write(STDOUT_FILENO, buf, rv) != rv) {
1565 maybe_warn("write to stdout");
1580 unsigned char header1[4];
1582 enum filetype method;
1584 #ifndef NO_COMPRESS_SUPPORT
1589 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1590 maybe_warnx("standard input is a terminal -- ignoring");
1598 /* XXX could read the whole file, etc. */
1599 if (fstat(STDIN_FILENO, &isb) < 0) {
1600 maybe_warn("fstat");
1603 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1607 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1608 if (bytes_read == -1) {
1609 maybe_warn("can't read stdin");
1611 } else if (bytes_read != sizeof(header1)) {
1612 maybe_warnx("(stdin): unexpected end of file");
1616 method = file_gettype(header1);
1621 maybe_warnx("unknown compression format");
1624 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1628 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1629 (char *)header1, sizeof header1, &gsize, "(stdin)");
1631 #ifndef NO_BZIP2_SUPPORT
1633 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1634 (char *)header1, sizeof header1, &gsize);
1637 #ifndef NO_COMPRESS_SUPPORT
1639 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1640 maybe_warnx("zopen of stdin");
1644 usize = zuncompress(in, stdout, (char *)header1, sizeof header1, &gsize);
1651 if (vflag && !tflag && usize != -1 && gsize != -1)
1652 print_verbage(NULL, NULL, usize, gsize);
1654 print_test("(stdin)", usize != -1);
1669 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1670 maybe_warnx("standard output is a terminal -- ignoring");
1674 /* If stdin is a file use it's mtime, otherwise use current time */
1675 ret = fstat(STDIN_FILENO, &sb);
1679 maybe_warn("Can't stat stdin");
1684 if (S_ISREG(sb.st_mode))
1685 mtime = (uint32_t)sb.st_mtime;
1687 systime = time(NULL);
1689 if (systime == -1) {
1694 mtime = (uint32_t)systime;
1697 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1699 if (vflag && !tflag && usize != -1 && gsize != -1)
1700 print_verbage(NULL, NULL, usize, gsize);
1704 /* do what is asked for, for the path name */
1706 handle_pathname(char *path)
1708 char *opath = path, *s = NULL;
1713 /* check for stdout/stdin */
1714 if (path[0] == '-' && path[1] == '\0') {
1723 if (stat(path, &sb) != 0) {
1724 /* lets try <path>.gz if we're decompressing */
1725 if (dflag && s == NULL && errno == ENOENT) {
1727 slen = suffixes[0].ziplen;
1728 s = malloc(len + slen + 1);
1730 maybe_err("malloc");
1731 memcpy(s, path, len);
1732 memcpy(s + len, suffixes[0].zipped, slen + 1);
1736 maybe_warn("can't stat: %s", opath);
1740 if (S_ISDIR(sb.st_mode)) {
1746 maybe_warnx("%s is a directory", path);
1750 if (S_ISREG(sb.st_mode))
1751 handle_file(path, &sb);
1753 maybe_warnx("%s is not a regular file", path);
1760 /* compress/decompress a file */
1762 handle_file(char *file, struct stat *sbp)
1765 char outfile[PATH_MAX];
1769 usize = file_uncompress(file, outfile, sizeof(outfile));
1772 print_test(file, usize != -1);
1776 gsize = sbp->st_size;
1778 gsize = file_compress(file, outfile, sizeof(outfile));
1781 usize = sbp->st_size;
1786 if (vflag && !tflag)
1787 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1792 /* this is used with -r to recursively descend directories */
1794 handle_dir(char *dir)
1802 fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
1804 warn("couldn't fts_open %s", dir);
1808 while ((entry = fts_read(fts))) {
1809 switch(entry->fts_info) {
1817 maybe_warn("%s", entry->fts_path);
1820 handle_file(entry->fts_name, entry->fts_statp);
1823 (void)fts_close(fts);
1827 /* print a ratio - size reduction as a fraction of uncompressed size */
1829 print_ratio(off_t in, off_t out, FILE *where)
1831 int percent10; /* 10 * percent */
1839 * Output is more than double size of input! print -99.9%
1840 * Quite possibly we've failed to get the original size.
1845 * We only need 12 bits of result from the final division,
1846 * so reduce the values until a 32bit division will suffice.
1848 while (in > 0x100000) {
1853 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1858 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1859 /* Move the '.' to before the last digit */
1860 buff[len - 1] = buff[len - 2];
1861 buff[len - 2] = '.';
1862 fprintf(where, "%5s%%", buff);
1866 /* print compression statistics, and the new name (if there is one!) */
1868 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1871 fprintf(stderr, "%s:%s ", file,
1872 strlen(file) < 7 ? "\t\t" : "\t");
1873 print_ratio(usize, gsize, stderr);
1875 fprintf(stderr, " -- replaced with %s", nfile);
1876 fprintf(stderr, "\n");
1880 /* print test results */
1882 print_test(const char *file, int ok)
1885 if (exit_value == 0 && ok == 0)
1887 fprintf(stderr, "%s:%s %s\n", file,
1888 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1893 /* print a file's info ala --list */
1895 compressed uncompressed ratio uncompressed_name
1896 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1899 print_list(int fd, off_t out, const char *outfile, time_t ts)
1901 static int first = 1;
1903 static off_t in_tot, out_tot;
1911 printf("method crc date time ");
1914 printf(" compressed uncompressed "
1915 "ratio uncompressed_name\n");
1927 /* read the last 4 bytes - this is the uncompressed size */
1928 rv = lseek(fd, (off_t)(-8), SEEK_END);
1930 unsigned char buf[8];
1933 rv = read(fd, (char *)buf, sizeof(buf));
1935 maybe_warn("read of uncompressed size");
1936 else if (rv != sizeof(buf))
1937 maybe_warnx("read of uncompressed size");
1940 usize = buf[4] | buf[5] << 8 |
1941 buf[6] << 16 | buf[7] << 24;
1944 crc = buf[0] | buf[1] << 8 |
1945 buf[2] << 16 | buf[3] << 24;
1952 if (vflag && fd == -1)
1955 char *date = ctime(&ts);
1957 /* skip the day, 1/100th second, and year */
1960 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
1965 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
1966 print_ratio(in, out, stdout);
1967 printf(" %s\n", outfile);
1970 /* display the usage of NetBSD gzip */
1975 fprintf(stderr, "%s\n", gzip_version);
1977 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n"
1979 " -1 --fast fastest (worst) compression\n"
1980 " -2 .. -8 set compression level\n"
1981 " -9 --best best (slowest) compression\n"
1982 " -c --stdout write to stdout, keep original files\n"
1984 " -d --decompress uncompress files\n"
1986 " -f --force force overwriting & compress links\n"
1987 " -h --help display this help\n"
1988 " -l --list list compressed file contents\n"
1989 " -N --name save or restore original file name and time stamp\n"
1990 " -n --no-name don't save original file name or time stamp\n"
1991 " -q --quiet output no warnings\n"
1992 " -r --recursive recursively compress files in directories\n"
1993 " -S .suf use suffix .suf instead of .gz\n"
1995 " -t --test test compressed file\n"
1996 " -V --version display program version\n"
1997 " -v --verbose print extra statistics\n",
2006 /* display the license information of FreeBSD gzip */
2008 display_license(void)
2011 fprintf(stderr, "%s (based on NetBSD gzip 20060927)\n", gzip_version);
2012 fprintf(stderr, "%s\n", gzip_copyright);
2017 /* display the version of NetBSD gzip */
2019 display_version(void)
2022 fprintf(stderr, "%s\n", gzip_version);
2026 #ifndef NO_BZIP2_SUPPORT
2027 #include "unbzip2.c"
2029 #ifndef NO_COMPRESS_SUPPORT
2030 #include "zuncompress.c"
2034 read_retry(int fd, void *buf, size_t sz)
2037 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2042 ret = read(fd, cp, left);
2045 } else if (ret == 0) {