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, ""),
136 SUFFIX(".tbz", ".tar"),
137 SUFFIX(".tbz2", ".tar"),
139 #ifndef NO_COMPRESS_SUPPORT
140 SUFFIX(Z_SUFFIX, ""),
142 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
146 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
148 static const char gzip_version[] = "FreeBSD gzip 20070711";
151 static const char gzip_copyright[] = \
152 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
153 " All rights reserved.\n"
155 " Redistribution and use in source and binary forms, with or without\n"
156 " modification, are permitted provided that the following conditions\n"
158 " 1. Redistributions of source code must retain the above copyright\n"
159 " notice, this list of conditions and the following disclaimer.\n"
160 " 2. Redistributions in binary form must reproduce the above copyright\n"
161 " notice, this list of conditions and the following disclaimer in the\n"
162 " documentation and/or other materials provided with the distribution.\n"
163 " 3. The name of the author may not be used to endorse or promote products\n"
164 " derived from this software without specific prior written permission.\n"
166 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
167 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
168 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
169 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
170 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
171 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
172 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
173 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
174 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
175 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
179 static int cflag; /* stdout mode */
180 static int dflag; /* decompress mode */
181 static int lflag; /* list mode */
182 static int numflag = 6; /* gzip -1..-9 value */
185 static int fflag; /* force mode */
186 static int kflag; /* don't delete input files */
187 static int nflag; /* don't save name/timestamp */
188 static int Nflag; /* don't restore name/timestamp */
189 static int qflag; /* quiet mode */
190 static int rflag; /* recursive mode */
191 static int tflag; /* test */
192 static int vflag; /* verbose mode */
198 static int exit_value = 0; /* exit value */
200 static char *infile; /* name of file coming in */
202 static void maybe_err(const char *fmt, ...)
203 __attribute__((__format__(__printf__, 1, 2)));
204 #ifndef NO_BZIP2_SUPPORT
205 static void maybe_errx(const char *fmt, ...)
206 __attribute__((__format__(__printf__, 1, 2)));
208 static void maybe_warn(const char *fmt, ...)
209 __attribute__((__format__(__printf__, 1, 2)));
210 static void maybe_warnx(const char *fmt, ...)
211 __attribute__((__format__(__printf__, 1, 2)));
212 static enum filetype file_gettype(u_char *);
214 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
216 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
217 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
218 static off_t file_compress(char *, char *, size_t);
219 static off_t file_uncompress(char *, char *, size_t);
220 static void handle_pathname(char *);
221 static void handle_file(char *, struct stat *);
222 static void handle_stdin(void);
223 static void handle_stdout(void);
224 static void print_ratio(off_t, off_t, FILE *);
225 static void print_list(int fd, off_t, const char *, time_t);
226 static void usage(void);
227 static void display_version(void);
229 static void display_license(void);
231 static const suffixes_t *check_suffix(char *, int);
232 static ssize_t read_retry(int, void *, size_t);
235 #define unlink_input(f, sb) unlink(f)
237 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
238 static void prepend_gzip(char *, int *, char ***);
239 static void handle_dir(char *);
240 static void print_verbage(const char *, const char *, off_t, off_t);
241 static void print_test(const char *, int);
242 static void copymodes(int fd, const struct stat *, const char *file);
243 static int check_outfile(const char *outfile);
246 #ifndef NO_BZIP2_SUPPORT
247 static off_t unbzip2(int, int, char *, size_t, off_t *);
250 #ifndef NO_COMPRESS_SUPPORT
251 static FILE *zdopen(int);
252 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
255 int main(int, char **p);
258 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
260 static const struct option longopts[] = {
261 { "stdout", no_argument, 0, 'c' },
262 { "to-stdout", no_argument, 0, 'c' },
263 { "decompress", no_argument, 0, 'd' },
264 { "uncompress", no_argument, 0, 'd' },
265 { "force", no_argument, 0, 'f' },
266 { "help", no_argument, 0, 'h' },
267 { "keep", no_argument, 0, 'k' },
268 { "list", no_argument, 0, 'l' },
269 { "no-name", no_argument, 0, 'n' },
270 { "name", no_argument, 0, 'N' },
271 { "quiet", no_argument, 0, 'q' },
272 { "recursive", no_argument, 0, 'r' },
273 { "suffix", required_argument, 0, 'S' },
274 { "test", no_argument, 0, 't' },
275 { "verbose", no_argument, 0, 'v' },
276 { "version", no_argument, 0, 'V' },
277 { "fast", no_argument, 0, '1' },
278 { "best", no_argument, 0, '9' },
279 { "ascii", no_argument, 0, 'a' },
280 { "license", no_argument, 0, 'L' },
281 { NULL, no_argument, 0, 0 },
286 main(int argc, char **argv)
288 const char *progname = getprogname();
295 /* XXX set up signals */
298 if ((gzip = getenv("GZIP")) != NULL)
299 prepend_gzip(gzip, &argc, &argv);
304 * handle being called `gunzip', `zcat' and `gzcat'
306 if (strcmp(progname, "gunzip") == 0)
308 else if (strcmp(progname, "zcat") == 0 ||
309 strcmp(progname, "gzcat") == 0)
313 #define OPT_LIST "123456789cdhltV"
315 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
318 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
320 case '1': case '2': case '3':
321 case '4': case '5': case '6':
322 case '7': case '8': case '9':
340 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
366 len = strlen(optarg);
368 suffixes[0].zipped = optarg;
369 suffixes[0].ziplen = len;
371 suffixes[NUM_SUFFIXES - 1].zipped = "";
372 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
393 if (dflag) /* stdin mode */
395 else /* stdout mode */
399 handle_pathname(argv[0]);
403 if (qflag == 0 && lflag && argc > 1)
404 print_list(-1, 0, "(totals)", 0);
409 /* maybe print a warning */
411 maybe_warn(const char *fmt, ...)
424 /* ... without an errno. */
426 maybe_warnx(const char *fmt, ...)
439 /* maybe print an error */
441 maybe_err(const char *fmt, ...)
453 #ifndef NO_BZIP2_SUPPORT
454 /* ... without an errno. */
456 maybe_errx(const char *fmt, ...)
470 /* split up $GZIP and prepend it to the argument list */
472 prepend_gzip(char *gzip, int *argc, char ***argv)
474 char *s, **nargv, **ac;
477 /* scan how many arguments there are */
479 while (*s == ' ' || *s == '\t')
484 while (*s != ' ' && *s != '\t')
496 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
500 /* stash this away */
503 /* copy the program name first */
505 nargv[i++] = *(ac++);
507 /* take a copy of $GZIP and add it to the array */
512 /* Skip whitespaces. */
513 while (*s == ' ' || *s == '\t')
518 /* Find the end of this argument. */
519 while (*s != ' ' && *s != '\t')
521 /* Argument followed by NUL. */
523 /* Terminate by overwriting ' ' or '\t' with NUL. */
528 /* copy the original arguments and a NULL */
530 nargv[i++] = *(ac++);
535 /* compress input to output. Return bytes read, -1 on error */
537 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
540 char *outbufp, *inbufp;
541 off_t in_tot = 0, out_tot = 0;
546 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
551 outbufp = malloc(BUFLEN);
552 inbufp = malloc(BUFLEN);
553 if (outbufp == NULL || inbufp == NULL) {
554 maybe_err("malloc failed");
558 memset(&z, 0, sizeof z);
564 memcpy(outbufp, header, sizeof header);
572 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
573 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
574 *origname ? ORIG_NAME : 0,
577 (mtime >> 16) & 0xff,
578 (mtime >> 24) & 0xff,
579 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
582 /* this need PATH_MAX > BUFLEN ... */
583 maybe_err("snprintf");
588 z.next_out = (unsigned char *)outbufp + i;
589 z.avail_out = BUFLEN - i;
591 error = deflateInit2(&z, numflag, Z_DEFLATED,
592 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
594 maybe_warnx("deflateInit2 failed");
599 crc = crc32(0L, Z_NULL, 0);
601 if (z.avail_out == 0) {
602 if (write(out, outbufp, BUFLEN) != BUFLEN) {
609 z.next_out = (unsigned char *)outbufp;
610 z.avail_out = BUFLEN;
613 if (z.avail_in == 0) {
614 in_size = read(in, inbufp, BUFLEN);
623 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
625 z.next_in = (unsigned char *)inbufp;
626 z.avail_in = in_size;
629 error = deflate(&z, Z_NO_FLUSH);
630 if (error != Z_OK && error != Z_STREAM_END) {
631 maybe_warnx("deflate failed");
642 error = deflate(&z, Z_FINISH);
643 if (error != Z_OK && error != Z_STREAM_END) {
644 maybe_warnx("deflate failed");
649 len = (char *)z.next_out - outbufp;
651 w = write(out, outbufp, len);
652 if (w == -1 || (size_t)w != len) {
658 z.next_out = (unsigned char *)outbufp;
659 z.avail_out = BUFLEN;
661 if (error == Z_STREAM_END)
665 if (deflateEnd(&z) != Z_OK) {
666 maybe_warnx("deflateEnd failed");
671 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
673 (int)(crc >> 8) & 0xff,
674 (int)(crc >> 16) & 0xff,
675 (int)(crc >> 24) & 0xff,
677 (int)(in_tot >> 8) & 0xff,
678 (int)(in_tot >> 16) & 0xff,
679 (int)(in_tot >> 24) & 0xff);
681 maybe_err("snprintf");
682 if (write(out, outbufp, i) != i) {
699 * uncompress input to output then close the input. return the
700 * uncompressed size written, and put the compressed sized read
704 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
705 const char *filename)
708 char *outbufp, *inbufp;
709 off_t out_tot = -1, in_tot = 0;
710 uint32_t out_sub_tot = 0;
728 } state = GZSTATE_MAGIC0;
729 int flags = 0, skip_count = 0;
730 int error = Z_STREAM_ERROR, done_reading = 0;
735 #define ADVANCE() { z.next_in++; z.avail_in--; }
737 if ((outbufp = malloc(BUFLEN)) == NULL) {
738 maybe_err("malloc failed");
741 if ((inbufp = malloc(BUFLEN)) == NULL) {
742 maybe_err("malloc failed");
746 memset(&z, 0, sizeof z);
748 z.next_in = (unsigned char *)pre;
749 z.avail_out = BUFLEN;
750 z.next_out = (unsigned char *)outbufp;
759 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
762 if (z.avail_in > 0) {
763 memmove(inbufp, z.next_in, z.avail_in);
765 z.next_in = (unsigned char *)inbufp;
766 in_size = read(in, z.next_in + z.avail_in,
767 BUFLEN - z.avail_in);
770 maybe_warn("failed to read stdin");
772 } else if (in_size == 0) {
776 z.avail_in += in_size;
781 if (z.avail_in == 0) {
782 if (done_reading && state != GZSTATE_MAGIC0) {
783 maybe_warnx("%s: unexpected end of file",
791 if (*z.next_in != GZIP_MAGIC0) {
793 maybe_warnx("%s: trailing garbage "
794 "ignored", filename);
797 maybe_warnx("input not gziped (MAGIC0)");
803 crc = crc32(0L, Z_NULL, 0);
807 if (*z.next_in != GZIP_MAGIC1 &&
808 *z.next_in != GZIP_OMAGIC1) {
809 maybe_warnx("input not gziped (MAGIC1)");
817 if (*z.next_in != Z_DEFLATED) {
818 maybe_warnx("unknown compression method");
832 case GZSTATE_SKIPPING:
833 if (skip_count > 0) {
841 if ((flags & EXTRA_FIELD) == 0) {
842 state = GZSTATE_ORIGNAME;
845 skip_count = *z.next_in;
851 skip_count |= ((*z.next_in) << 8);
857 if (skip_count > 0) {
864 case GZSTATE_ORIGNAME:
865 if ((flags & ORIG_NAME) == 0) {
874 case GZSTATE_COMMENT:
875 if ((flags & COMMENT) == 0) {
884 case GZSTATE_HEAD_CRC1:
885 if (flags & HEAD_CRC)
892 case GZSTATE_HEAD_CRC2:
893 if (skip_count > 0) {
901 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
902 maybe_warnx("failed to inflateInit");
909 error = inflate(&z, Z_FINISH);
911 /* Z_BUF_ERROR goes with Z_FINISH... */
918 maybe_warnx("Z_NEED_DICT error");
921 maybe_warnx("data stream error");
924 maybe_warnx("internal stream error");
927 maybe_warnx("memory allocation error");
931 maybe_warn("unknown error from inflate(): %d",
934 wr = BUFLEN - z.avail_out;
937 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
940 /* don't write anything with -t */
943 write(out, outbufp, wr) != wr) {
944 maybe_warn("error writing to output");
952 if (error == Z_STREAM_END) {
957 z.next_out = (unsigned char *)outbufp;
958 z.avail_out = BUFLEN;
965 if (z.avail_in < 4) {
970 maybe_warnx("truncated input");
973 origcrc = ((unsigned)z.next_in[0] & 0xff) |
974 ((unsigned)z.next_in[1] & 0xff) << 8 |
975 ((unsigned)z.next_in[2] & 0xff) << 16 |
976 ((unsigned)z.next_in[3] & 0xff) << 24;
977 if (origcrc != crc) {
978 maybe_warnx("invalid compressed"
987 if (!z.avail_in && done_reading) {
996 if (z.avail_in < 4) {
1001 maybe_warnx("truncated input");
1004 origlen = ((unsigned)z.next_in[0] & 0xff) |
1005 ((unsigned)z.next_in[1] & 0xff) << 8 |
1006 ((unsigned)z.next_in[2] & 0xff) << 16 |
1007 ((unsigned)z.next_in[3] & 0xff) << 24;
1009 if (origlen != out_sub_tot) {
1010 maybe_warnx("invalid compressed"
1011 " data--length error");
1020 maybe_warnx("decompression error");
1023 state = GZSTATE_MAGIC0;
1032 if (state > GZSTATE_INIT)
1046 * set the owner, mode, flags & utimes using the given file descriptor.
1047 * file is only used in possible warning messages.
1050 copymodes(int fd, const struct stat *sbp, const char *file)
1052 struct timeval times[2];
1056 * If we have no info on the input, give this file some
1057 * default values and return..
1060 mode_t mask = umask(022);
1062 (void)fchmod(fd, DEFFILEMODE & ~mask);
1068 /* if the chown fails, remove set-id bits as-per compress(1) */
1069 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1071 maybe_warn("couldn't fchown: %s", file);
1072 sb.st_mode &= ~(S_ISUID|S_ISGID);
1075 /* we only allow set-id and the 9 normal permission bits */
1076 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1077 if (fchmod(fd, sb.st_mode) < 0)
1078 maybe_warn("couldn't fchmod: %s", file);
1080 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atimespec);
1081 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtimespec);
1082 if (futimes(fd, times) < 0)
1083 maybe_warn("couldn't utimes: %s", file);
1085 /* only try flags if they exist already */
1086 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1087 maybe_warn("couldn't fchflags: %s", file);
1091 /* what sort of file is this? */
1092 static enum filetype
1093 file_gettype(u_char *buf)
1096 if (buf[0] == GZIP_MAGIC0 &&
1097 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1100 #ifndef NO_BZIP2_SUPPORT
1101 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1102 buf[3] >= '0' && buf[3] <= '9')
1106 #ifndef NO_COMPRESS_SUPPORT
1107 if (memcmp(buf, Z_MAGIC, 2) == 0)
1115 /* check the outfile is OK. */
1117 check_outfile(const char *outfile)
1122 if (lflag == 0 && stat(outfile, &sb) == 0) {
1125 else if (isatty(STDIN_FILENO)) {
1126 char ans[10] = { 'n', '\0' }; /* default */
1128 fprintf(stderr, "%s already exists -- do you wish to "
1129 "overwrite (y or n)? " , outfile);
1130 (void)fgets(ans, sizeof(ans) - 1, stdin);
1131 if (ans[0] != 'y' && ans[0] != 'Y') {
1132 fprintf(stderr, "\tnot overwriting\n");
1137 maybe_warnx("%s already exists -- skipping", outfile);
1145 unlink_input(const char *file, const struct stat *sb)
1151 if (stat(file, &nsb) != 0)
1152 /* Must be gone alrady */
1154 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1155 /* Definitely a different file */
1161 static const suffixes_t *
1162 check_suffix(char *file, int xlate)
1164 const suffixes_t *s;
1165 int len = strlen(file);
1168 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1169 /* if it doesn't fit in "a.suf", don't bother */
1170 if (s->ziplen >= len)
1172 sp = file + len - s->ziplen;
1173 if (strcmp(s->zipped, sp) != 0)
1176 strcpy(sp, s->normal);
1183 * compress the given file: create a corresponding .gz file and remove the
1187 file_compress(char *file, char *outfile, size_t outsize)
1193 struct stat isb, osb;
1194 const suffixes_t *suff;
1197 in = open(file, O_RDONLY);
1199 maybe_warn("can't open %s", file);
1205 if (fstat(in, &isb) == 0) {
1206 if (isb.st_nlink > 1 && fflag == 0) {
1207 maybe_warnx("%s has %d other link%s -- "
1208 "skipping", file, isb.st_nlink - 1,
1209 isb.st_nlink == 1 ? "" : "s");
1215 if (fflag == 0 && (suff = check_suffix(file, 0))
1216 && suff->zipped[0] != 0) {
1217 maybe_warnx("%s already has %s suffix -- unchanged",
1218 file, suff->zipped);
1224 /* Add (usually) .gz to filename */
1225 if ((size_t)snprintf(outfile, outsize, "%s%s",
1226 file, suffixes[0].zipped) >= outsize)
1227 memcpy(outfile - suffixes[0].ziplen - 1,
1228 suffixes[0].zipped, suffixes[0].ziplen + 1);
1231 if (check_outfile(outfile) == 0) {
1239 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1241 maybe_warn("could not create output: %s", outfile);
1246 out = STDOUT_FILENO;
1248 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1253 * If there was an error, insize will be -1.
1254 * If we compressed to stdout, just return the size.
1255 * Otherwise stat the file and check it is the correct size.
1256 * We only blow away the file if we can stat the output and it
1257 * has the expected size.
1260 return insize == -1 ? -1 : size;
1263 if (fstat(out, &osb) != 0) {
1264 maybe_warn("couldn't stat: %s", outfile);
1268 if (osb.st_size != size) {
1269 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1270 " != %" PRIdOFF "), deleting",
1271 outfile, osb.st_size, size);
1275 copymodes(out, &isb, outfile);
1277 if (close(out) == -1)
1278 maybe_warn("couldn't close output");
1280 /* output is good, ok to delete input */
1281 unlink_input(file, &isb);
1286 if (close(out) == -1)
1287 maybe_warn("couldn't close output");
1289 maybe_warnx("leaving original %s", file);
1295 /* uncompress the given file and remove the original */
1297 file_uncompress(char *file, char *outfile, size_t outsize)
1299 struct stat isb, osb;
1302 unsigned char header1[4];
1303 enum filetype method;
1304 int rv, fd, ofd, zfd = -1;
1306 time_t timestamp = 0;
1307 unsigned char name[PATH_MAX + 1];
1310 /* gather the old name info */
1312 fd = open(file, O_RDONLY);
1314 maybe_warn("can't open %s", file);
1318 strlcpy(outfile, file, outsize);
1319 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1320 maybe_warnx("%s: unknown suffix -- ignored", file);
1324 rbytes = read(fd, header1, sizeof header1);
1325 if (rbytes != sizeof header1) {
1326 /* we don't want to fail here. */
1332 maybe_warn("can't read %s", file);
1334 goto unexpected_EOF;
1338 method = file_gettype(header1);
1341 if (fflag == 0 && method == FT_UNKNOWN) {
1342 maybe_warnx("%s: not in gzip format", file);
1349 if (method == FT_GZIP && Nflag) {
1350 unsigned char ts[4]; /* timestamp */
1352 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1353 if (rv >= 0 && (size_t)rv < sizeof ts)
1354 goto unexpected_EOF;
1357 maybe_warn("can't read %s", file);
1360 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1362 if (header1[3] & ORIG_NAME) {
1363 rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1365 maybe_warn("can't read %s", file);
1369 /* preserve original directory name */
1370 char *dp = strrchr(file, '/');
1375 snprintf(outfile, outsize, "%.*s%.*s",
1377 file, (int) rbytes, name);
1382 lseek(fd, 0, SEEK_SET);
1384 if (cflag == 0 || lflag) {
1385 if (fstat(fd, &isb) != 0)
1388 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1389 maybe_warnx("%s has %d other links -- skipping",
1390 file, isb.st_nlink - 1);
1393 if (nflag == 0 && timestamp)
1394 isb.st_mtime = timestamp;
1395 if (check_outfile(outfile) == 0)
1400 if (cflag == 0 && lflag == 0) {
1401 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1402 if (zfd == STDOUT_FILENO) {
1403 /* We won't close STDOUT_FILENO later... */
1405 close(STDOUT_FILENO);
1408 maybe_warn("can't open %s", outfile);
1412 zfd = STDOUT_FILENO;
1414 #ifndef NO_BZIP2_SUPPORT
1415 if (method == FT_BZIP2) {
1419 maybe_warnx("no -l with bzip2 files");
1423 size = unbzip2(fd, zfd, NULL, 0, NULL);
1427 #ifndef NO_COMPRESS_SUPPORT
1428 if (method == FT_Z) {
1433 maybe_warnx("no -l with Lempel-Ziv files");
1437 if ((in = zdopen(fd)) == NULL) {
1438 maybe_warn("zdopen for read: %s", file);
1442 out = fdopen(dup(zfd), "w");
1444 maybe_warn("fdopen for write: %s", outfile);
1449 size = zuncompress(in, out, NULL, 0, NULL);
1450 /* need to fclose() if ferror() is true... */
1451 if (ferror(in) | fclose(in)) {
1452 maybe_warn("failed infile fclose");
1456 if (fclose(out) != 0) {
1457 maybe_warn("failed outfile fclose");
1465 if (method == FT_UNKNOWN) {
1467 maybe_warnx("no -l for unknown filetypes");
1470 size = cat_fd(NULL, 0, NULL, fd);
1475 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1477 return -1; /* XXX */
1480 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1484 maybe_warn("couldn't close input");
1485 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1486 maybe_warn("couldn't close output");
1491 maybe_warnx("%s: uncompress failed", file);
1495 /* if testing, or we uncompressed to stdout, this is all we need */
1500 /* if we are uncompressing to stdin, don't remove the file. */
1505 * if we create a file...
1508 * if we can't stat the file don't remove the file.
1511 ofd = open(outfile, O_RDWR, 0);
1513 maybe_warn("couldn't open (leaving original): %s",
1517 if (fstat(ofd, &osb) != 0) {
1518 maybe_warn("couldn't stat (leaving original): %s",
1523 if (osb.st_size != size) {
1524 maybe_warnx("stat gave different size: %" PRIdOFF
1525 " != %" PRIdOFF " (leaving original)",
1531 unlink_input(file, &isb);
1533 copymodes(ofd, &isb, outfile);
1539 maybe_warnx("%s: unexpected end of file", file);
1543 if (zfd != -1 && zfd != STDOUT_FILENO)
1550 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1557 w = write(STDOUT_FILENO, prepend, count);
1558 if (w == -1 || (size_t)w != count) {
1559 maybe_warn("write to stdout");
1565 rv = read(fd, buf, sizeof buf);
1569 maybe_warn("read from fd %d", fd);
1573 if (write(STDOUT_FILENO, buf, rv) != rv) {
1574 maybe_warn("write to stdout");
1589 unsigned char header1[4];
1591 enum filetype method;
1593 #ifndef NO_COMPRESS_SUPPORT
1598 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1599 maybe_warnx("standard input is a terminal -- ignoring");
1607 /* XXX could read the whole file, etc. */
1608 if (fstat(STDIN_FILENO, &isb) < 0) {
1609 maybe_warn("fstat");
1612 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1616 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1617 if (bytes_read == -1) {
1618 maybe_warn("can't read stdin");
1620 } else if (bytes_read != sizeof(header1)) {
1621 maybe_warnx("(stdin): unexpected end of file");
1625 method = file_gettype(header1);
1630 maybe_warnx("unknown compression format");
1633 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1637 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1638 (char *)header1, sizeof header1, &gsize, "(stdin)");
1640 #ifndef NO_BZIP2_SUPPORT
1642 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1643 (char *)header1, sizeof header1, &gsize);
1646 #ifndef NO_COMPRESS_SUPPORT
1648 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1649 maybe_warnx("zopen of stdin");
1653 usize = zuncompress(in, stdout, (char *)header1, sizeof header1, &gsize);
1660 if (vflag && !tflag && usize != -1 && gsize != -1)
1661 print_verbage(NULL, NULL, usize, gsize);
1663 print_test("(stdin)", usize != -1);
1678 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1679 maybe_warnx("standard output is a terminal -- ignoring");
1683 /* If stdin is a file use it's mtime, otherwise use current time */
1684 ret = fstat(STDIN_FILENO, &sb);
1688 maybe_warn("Can't stat stdin");
1693 if (S_ISREG(sb.st_mode))
1694 mtime = (uint32_t)sb.st_mtime;
1696 systime = time(NULL);
1698 if (systime == -1) {
1703 mtime = (uint32_t)systime;
1706 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1708 if (vflag && !tflag && usize != -1 && gsize != -1)
1709 print_verbage(NULL, NULL, usize, gsize);
1713 /* do what is asked for, for the path name */
1715 handle_pathname(char *path)
1717 char *opath = path, *s = NULL;
1722 /* check for stdout/stdin */
1723 if (path[0] == '-' && path[1] == '\0') {
1732 if (stat(path, &sb) != 0) {
1733 /* lets try <path>.gz if we're decompressing */
1734 if (dflag && s == NULL && errno == ENOENT) {
1736 slen = suffixes[0].ziplen;
1737 s = malloc(len + slen + 1);
1739 maybe_err("malloc");
1740 memcpy(s, path, len);
1741 memcpy(s + len, suffixes[0].zipped, slen + 1);
1745 maybe_warn("can't stat: %s", opath);
1749 if (S_ISDIR(sb.st_mode)) {
1755 maybe_warnx("%s is a directory", path);
1759 if (S_ISREG(sb.st_mode))
1760 handle_file(path, &sb);
1762 maybe_warnx("%s is not a regular file", path);
1769 /* compress/decompress a file */
1771 handle_file(char *file, struct stat *sbp)
1774 char outfile[PATH_MAX];
1778 usize = file_uncompress(file, outfile, sizeof(outfile));
1781 print_test(file, usize != -1);
1785 gsize = sbp->st_size;
1787 gsize = file_compress(file, outfile, sizeof(outfile));
1790 usize = sbp->st_size;
1795 if (vflag && !tflag)
1796 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1801 /* this is used with -r to recursively descend directories */
1803 handle_dir(char *dir)
1811 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1813 warn("couldn't fts_open %s", dir);
1817 while ((entry = fts_read(fts))) {
1818 switch(entry->fts_info) {
1826 maybe_warn("%s", entry->fts_path);
1829 handle_file(entry->fts_path, entry->fts_statp);
1832 (void)fts_close(fts);
1836 /* print a ratio - size reduction as a fraction of uncompressed size */
1838 print_ratio(off_t in, off_t out, FILE *where)
1840 int percent10; /* 10 * percent */
1848 * Output is more than double size of input! print -99.9%
1849 * Quite possibly we've failed to get the original size.
1854 * We only need 12 bits of result from the final division,
1855 * so reduce the values until a 32bit division will suffice.
1857 while (in > 0x100000) {
1862 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1867 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1868 /* Move the '.' to before the last digit */
1869 buff[len - 1] = buff[len - 2];
1870 buff[len - 2] = '.';
1871 fprintf(where, "%5s%%", buff);
1875 /* print compression statistics, and the new name (if there is one!) */
1877 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1880 fprintf(stderr, "%s:%s ", file,
1881 strlen(file) < 7 ? "\t\t" : "\t");
1882 print_ratio(usize, gsize, stderr);
1884 fprintf(stderr, " -- replaced with %s", nfile);
1885 fprintf(stderr, "\n");
1889 /* print test results */
1891 print_test(const char *file, int ok)
1894 if (exit_value == 0 && ok == 0)
1896 fprintf(stderr, "%s:%s %s\n", file,
1897 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1902 /* print a file's info ala --list */
1904 compressed uncompressed ratio uncompressed_name
1905 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1908 print_list(int fd, off_t out, const char *outfile, time_t ts)
1910 static int first = 1;
1912 static off_t in_tot, out_tot;
1920 printf("method crc date time ");
1923 printf(" compressed uncompressed "
1924 "ratio uncompressed_name\n");
1936 /* read the last 4 bytes - this is the uncompressed size */
1937 rv = lseek(fd, (off_t)(-8), SEEK_END);
1939 unsigned char buf[8];
1942 rv = read(fd, (char *)buf, sizeof(buf));
1944 maybe_warn("read of uncompressed size");
1945 else if (rv != sizeof(buf))
1946 maybe_warnx("read of uncompressed size");
1949 usize = buf[4] | buf[5] << 8 |
1950 buf[6] << 16 | buf[7] << 24;
1953 crc = buf[0] | buf[1] << 8 |
1954 buf[2] << 16 | buf[3] << 24;
1961 if (vflag && fd == -1)
1964 char *date = ctime(&ts);
1966 /* skip the day, 1/100th second, and year */
1969 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
1974 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
1975 print_ratio(in, out, stdout);
1976 printf(" %s\n", outfile);
1979 /* display the usage of NetBSD gzip */
1984 fprintf(stderr, "%s\n", gzip_version);
1987 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
1989 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
1990 " -1 --fast fastest (worst) compression\n"
1991 " -2 .. -8 set compression level\n"
1992 " -9 --best best (slowest) compression\n"
1993 " -c --stdout write to stdout, keep original files\n"
1995 " -d --decompress uncompress files\n"
1997 " -f --force force overwriting & compress links\n"
1998 " -h --help display this help\n"
1999 " -k --keep don't delete input files during operation\n"
2000 " -l --list list compressed file contents\n"
2001 " -N --name save or restore original file name and time stamp\n"
2002 " -n --no-name don't save original file name or time stamp\n"
2003 " -q --quiet output no warnings\n"
2004 " -r --recursive recursively compress files in directories\n"
2005 " -S .suf use suffix .suf instead of .gz\n"
2007 " -t --test test compressed file\n"
2008 " -V --version display program version\n"
2009 " -v --verbose print extra statistics\n",
2016 /* display the license information of FreeBSD gzip */
2018 display_license(void)
2021 fprintf(stderr, "%s (based on NetBSD gzip 20060927)\n", gzip_version);
2022 fprintf(stderr, "%s\n", gzip_copyright);
2027 /* display the version of NetBSD gzip */
2029 display_version(void)
2032 fprintf(stderr, "%s\n", gzip_version);
2036 #ifndef NO_BZIP2_SUPPORT
2037 #include "unbzip2.c"
2039 #ifndef NO_COMPRESS_SUPPORT
2040 #include "zuncompress.c"
2044 read_retry(int fd, void *buf, size_t sz)
2047 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2052 ret = read(fd, cp, left);
2055 } else if (ret == 0) {