1 /* $NetBSD: gzip.c,v 1.97 2009/10/11 09:17:21 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.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 #include <sys/cdefs.h>
32 __COPYRIGHT("@(#) Copyright (c) 1997, 1998, 2003, 2004, 2006\
33 Matthew R. Green. All rights reserved.");
38 * gzip.c -- GPL free gzip using zlib.
40 * RFC 1950 covers the zlib format
41 * RFC 1951 covers the deflate format
42 * RFC 1952 covers the gzip format
45 * - use mmap where possible
46 * - make bzip2/compress -v/-t/-l support work as well as possible
49 #include <sys/param.h>
68 /* what type of file are we dealing with */
71 #ifndef NO_BZIP2_SUPPORT
74 #ifndef NO_COMPRESS_SUPPORT
77 #ifndef NO_PACK_SUPPORT
84 #ifndef NO_BZIP2_SUPPORT
87 #define BZ2_SUFFIX ".bz2"
88 #define BZIP2_MAGIC "\102\132\150"
91 #ifndef NO_COMPRESS_SUPPORT
93 #define Z_MAGIC "\037\235"
96 #ifndef NO_PACK_SUPPORT
97 #define PACK_MAGIC "\037\036"
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])
147 #define SUFFIX_MAXLEN 30
149 static const char gzip_version[] = "FreeBSD gzip 20100407";
152 static const char gzip_copyright[] = \
153 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
154 " All rights reserved.\n"
156 " Redistribution and use in source and binary forms, with or without\n"
157 " modification, are permitted provided that the following conditions\n"
159 " 1. Redistributions of source code must retain the above copyright\n"
160 " notice, this list of conditions and the following disclaimer.\n"
161 " 2. Redistributions in binary form must reproduce the above copyright\n"
162 " notice, this list of conditions and the following disclaimer in the\n"
163 " documentation and/or other materials provided with the distribution.\n"
165 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
166 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
167 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
168 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
169 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
170 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
171 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
172 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
173 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
174 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
178 static int cflag; /* stdout mode */
179 static int dflag; /* decompress mode */
180 static int lflag; /* list mode */
181 static int numflag = 6; /* gzip -1..-9 value */
184 static int fflag; /* force mode */
185 static int kflag; /* don't delete input files */
186 static int nflag; /* don't save name/timestamp */
187 static int Nflag; /* don't restore name/timestamp */
188 static int qflag; /* quiet mode */
189 static int rflag; /* recursive mode */
190 static int tflag; /* test */
191 static int vflag; /* verbose mode */
192 static const char *remove_file = NULL; /* file to be removed upon SIGINT */
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, ...) __dead2
203 __attribute__((__format__(__printf__, 1, 2)));
204 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT)
205 static void maybe_errx(const char *fmt, ...) __dead2
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);
230 static void sigint_handler(int);
232 static const suffixes_t *check_suffix(char *, int);
233 static ssize_t read_retry(int, void *, size_t);
236 #define unlink_input(f, sb) unlink(f)
238 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
239 static void prepend_gzip(char *, int *, char ***);
240 static void handle_dir(char *);
241 static void print_verbage(const char *, const char *, off_t, off_t);
242 static void print_test(const char *, int);
243 static void copymodes(int fd, const struct stat *, const char *file);
244 static int check_outfile(const char *outfile);
247 #ifndef NO_BZIP2_SUPPORT
248 static off_t unbzip2(int, int, char *, size_t, off_t *);
251 #ifndef NO_COMPRESS_SUPPORT
252 static FILE *zdopen(int);
253 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
256 #ifndef NO_PACK_SUPPORT
257 static off_t unpack(int, int, char *, size_t, off_t *);
260 int main(int, char **p);
263 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
265 static const struct option longopts[] = {
266 { "stdout", no_argument, 0, 'c' },
267 { "to-stdout", no_argument, 0, 'c' },
268 { "decompress", no_argument, 0, 'd' },
269 { "uncompress", no_argument, 0, 'd' },
270 { "force", no_argument, 0, 'f' },
271 { "help", no_argument, 0, 'h' },
272 { "keep", no_argument, 0, 'k' },
273 { "list", no_argument, 0, 'l' },
274 { "no-name", no_argument, 0, 'n' },
275 { "name", no_argument, 0, 'N' },
276 { "quiet", no_argument, 0, 'q' },
277 { "recursive", no_argument, 0, 'r' },
278 { "suffix", required_argument, 0, 'S' },
279 { "test", no_argument, 0, 't' },
280 { "verbose", no_argument, 0, 'v' },
281 { "version", no_argument, 0, 'V' },
282 { "fast", no_argument, 0, '1' },
283 { "best", no_argument, 0, '9' },
284 { "ascii", no_argument, 0, 'a' },
285 { "license", no_argument, 0, 'L' },
286 { NULL, no_argument, 0, 0 },
291 main(int argc, char **argv)
293 const char *progname = getprogname();
301 if ((gzip = getenv("GZIP")) != NULL)
302 prepend_gzip(gzip, &argc, &argv);
303 signal(SIGINT, sigint_handler);
308 * handle being called `gunzip', `zcat' and `gzcat'
310 if (strcmp(progname, "gunzip") == 0)
312 else if (strcmp(progname, "zcat") == 0 ||
313 strcmp(progname, "gzcat") == 0)
317 #define OPT_LIST "123456789cdhltV"
319 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
322 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
324 case '1': case '2': case '3':
325 case '4': case '5': case '6':
326 case '7': case '8': case '9':
344 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
370 len = strlen(optarg);
372 if (len > SUFFIX_MAXLEN)
373 errx(1, "incorrect suffix: '%s': too long", optarg);
374 suffixes[0].zipped = optarg;
375 suffixes[0].ziplen = len;
377 suffixes[NUM_SUFFIXES - 1].zipped = "";
378 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
399 if (dflag) /* stdin mode */
401 else /* stdout mode */
405 handle_pathname(argv[0]);
409 if (qflag == 0 && lflag && argc > 1)
410 print_list(-1, 0, "(totals)", 0);
415 /* maybe print a warning */
417 maybe_warn(const char *fmt, ...)
430 /* ... without an errno. */
432 maybe_warnx(const char *fmt, ...)
445 /* maybe print an error */
447 maybe_err(const char *fmt, ...)
459 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT)
460 /* ... without an errno. */
462 maybe_errx(const char *fmt, ...)
476 /* split up $GZIP and prepend it to the argument list */
478 prepend_gzip(char *gzip, int *argc, char ***argv)
480 char *s, **nargv, **ac;
483 /* scan how many arguments there are */
485 while (*s == ' ' || *s == '\t')
490 while (*s != ' ' && *s != '\t')
502 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
506 /* stash this away */
509 /* copy the program name first */
511 nargv[i++] = *(ac++);
513 /* take a copy of $GZIP and add it to the array */
518 /* Skip whitespaces. */
519 while (*s == ' ' || *s == '\t')
524 /* Find the end of this argument. */
525 while (*s != ' ' && *s != '\t')
527 /* Argument followed by NUL. */
529 /* Terminate by overwriting ' ' or '\t' with NUL. */
534 /* copy the original arguments and a NULL */
536 nargv[i++] = *(ac++);
541 /* compress input to output. Return bytes read, -1 on error */
543 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
546 char *outbufp, *inbufp;
547 off_t in_tot = 0, out_tot = 0;
552 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
557 outbufp = malloc(BUFLEN);
558 inbufp = malloc(BUFLEN);
559 if (outbufp == NULL || inbufp == NULL) {
560 maybe_err("malloc failed");
564 memset(&z, 0, sizeof z);
570 memcpy(outbufp, header, sizeof header);
578 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
579 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
580 *origname ? ORIG_NAME : 0,
583 (mtime >> 16) & 0xff,
584 (mtime >> 24) & 0xff,
585 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
588 /* this need PATH_MAX > BUFLEN ... */
589 maybe_err("snprintf");
594 z.next_out = (unsigned char *)outbufp + i;
595 z.avail_out = BUFLEN - i;
597 error = deflateInit2(&z, numflag, Z_DEFLATED,
598 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
600 maybe_warnx("deflateInit2 failed");
605 crc = crc32(0L, Z_NULL, 0);
607 if (z.avail_out == 0) {
608 if (write(out, outbufp, BUFLEN) != BUFLEN) {
615 z.next_out = (unsigned char *)outbufp;
616 z.avail_out = BUFLEN;
619 if (z.avail_in == 0) {
620 in_size = read(in, inbufp, BUFLEN);
629 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
631 z.next_in = (unsigned char *)inbufp;
632 z.avail_in = in_size;
635 error = deflate(&z, Z_NO_FLUSH);
636 if (error != Z_OK && error != Z_STREAM_END) {
637 maybe_warnx("deflate failed");
648 error = deflate(&z, Z_FINISH);
649 if (error != Z_OK && error != Z_STREAM_END) {
650 maybe_warnx("deflate failed");
655 len = (char *)z.next_out - outbufp;
657 w = write(out, outbufp, len);
658 if (w == -1 || (size_t)w != len) {
664 z.next_out = (unsigned char *)outbufp;
665 z.avail_out = BUFLEN;
667 if (error == Z_STREAM_END)
671 if (deflateEnd(&z) != Z_OK) {
672 maybe_warnx("deflateEnd failed");
677 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
679 (int)(crc >> 8) & 0xff,
680 (int)(crc >> 16) & 0xff,
681 (int)(crc >> 24) & 0xff,
683 (int)(in_tot >> 8) & 0xff,
684 (int)(in_tot >> 16) & 0xff,
685 (int)(in_tot >> 24) & 0xff);
687 maybe_err("snprintf");
688 if (write(out, outbufp, i) != i) {
705 * uncompress input to output then close the input. return the
706 * uncompressed size written, and put the compressed sized read
710 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
711 const char *filename)
714 char *outbufp, *inbufp;
715 off_t out_tot = -1, in_tot = 0;
716 uint32_t out_sub_tot = 0;
734 } state = GZSTATE_MAGIC0;
735 int flags = 0, skip_count = 0;
736 int error = Z_STREAM_ERROR, done_reading = 0;
741 #define ADVANCE() { z.next_in++; z.avail_in--; }
743 if ((outbufp = malloc(BUFLEN)) == NULL) {
744 maybe_err("malloc failed");
747 if ((inbufp = malloc(BUFLEN)) == NULL) {
748 maybe_err("malloc failed");
752 memset(&z, 0, sizeof z);
754 z.next_in = (unsigned char *)pre;
755 z.avail_out = BUFLEN;
756 z.next_out = (unsigned char *)outbufp;
765 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
768 if (z.avail_in > 0) {
769 memmove(inbufp, z.next_in, z.avail_in);
771 z.next_in = (unsigned char *)inbufp;
772 in_size = read(in, z.next_in + z.avail_in,
773 BUFLEN - z.avail_in);
776 maybe_warn("failed to read stdin");
778 } else if (in_size == 0) {
782 z.avail_in += in_size;
787 if (z.avail_in == 0) {
788 if (done_reading && state != GZSTATE_MAGIC0) {
789 maybe_warnx("%s: unexpected end of file",
797 if (*z.next_in != GZIP_MAGIC0) {
799 maybe_warnx("%s: trailing garbage "
800 "ignored", filename);
803 maybe_warnx("input not gziped (MAGIC0)");
809 crc = crc32(0L, Z_NULL, 0);
813 if (*z.next_in != GZIP_MAGIC1 &&
814 *z.next_in != GZIP_OMAGIC1) {
815 maybe_warnx("input not gziped (MAGIC1)");
823 if (*z.next_in != Z_DEFLATED) {
824 maybe_warnx("unknown compression method");
838 case GZSTATE_SKIPPING:
839 if (skip_count > 0) {
847 if ((flags & EXTRA_FIELD) == 0) {
848 state = GZSTATE_ORIGNAME;
851 skip_count = *z.next_in;
857 skip_count |= ((*z.next_in) << 8);
863 if (skip_count > 0) {
870 case GZSTATE_ORIGNAME:
871 if ((flags & ORIG_NAME) == 0) {
880 case GZSTATE_COMMENT:
881 if ((flags & COMMENT) == 0) {
890 case GZSTATE_HEAD_CRC1:
891 if (flags & HEAD_CRC)
898 case GZSTATE_HEAD_CRC2:
899 if (skip_count > 0) {
907 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
908 maybe_warnx("failed to inflateInit");
915 error = inflate(&z, Z_FINISH);
917 /* Z_BUF_ERROR goes with Z_FINISH... */
924 maybe_warnx("Z_NEED_DICT error");
927 maybe_warnx("data stream error");
930 maybe_warnx("internal stream error");
933 maybe_warnx("memory allocation error");
937 maybe_warn("unknown error from inflate(): %d",
940 wr = BUFLEN - z.avail_out;
943 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
946 /* don't write anything with -t */
949 write(out, outbufp, wr) != wr) {
950 maybe_warn("error writing to output");
958 if (error == Z_STREAM_END) {
963 z.next_out = (unsigned char *)outbufp;
964 z.avail_out = BUFLEN;
971 if (z.avail_in < 4) {
976 maybe_warnx("truncated input");
979 origcrc = ((unsigned)z.next_in[0] & 0xff) |
980 ((unsigned)z.next_in[1] & 0xff) << 8 |
981 ((unsigned)z.next_in[2] & 0xff) << 16 |
982 ((unsigned)z.next_in[3] & 0xff) << 24;
983 if (origcrc != crc) {
984 maybe_warnx("invalid compressed"
993 if (!z.avail_in && done_reading) {
1002 if (z.avail_in < 4) {
1003 if (!done_reading) {
1007 maybe_warnx("truncated input");
1010 origlen = ((unsigned)z.next_in[0] & 0xff) |
1011 ((unsigned)z.next_in[1] & 0xff) << 8 |
1012 ((unsigned)z.next_in[2] & 0xff) << 16 |
1013 ((unsigned)z.next_in[3] & 0xff) << 24;
1015 if (origlen != out_sub_tot) {
1016 maybe_warnx("invalid compressed"
1017 " data--length error");
1026 maybe_warnx("decompression error");
1029 state = GZSTATE_MAGIC0;
1038 if (state > GZSTATE_INIT)
1052 * set the owner, mode, flags & utimes using the given file descriptor.
1053 * file is only used in possible warning messages.
1056 copymodes(int fd, const struct stat *sbp, const char *file)
1058 struct timeval times[2];
1062 * If we have no info on the input, give this file some
1063 * default values and return..
1066 mode_t mask = umask(022);
1068 (void)fchmod(fd, DEFFILEMODE & ~mask);
1074 /* if the chown fails, remove set-id bits as-per compress(1) */
1075 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1077 maybe_warn("couldn't fchown: %s", file);
1078 sb.st_mode &= ~(S_ISUID|S_ISGID);
1081 /* we only allow set-id and the 9 normal permission bits */
1082 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1083 if (fchmod(fd, sb.st_mode) < 0)
1084 maybe_warn("couldn't fchmod: %s", file);
1086 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atimespec);
1087 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtimespec);
1088 if (futimes(fd, times) < 0)
1089 maybe_warn("couldn't utimes: %s", file);
1091 /* only try flags if they exist already */
1092 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1093 maybe_warn("couldn't fchflags: %s", file);
1097 /* what sort of file is this? */
1098 static enum filetype
1099 file_gettype(u_char *buf)
1102 if (buf[0] == GZIP_MAGIC0 &&
1103 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1106 #ifndef NO_BZIP2_SUPPORT
1107 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1108 buf[3] >= '0' && buf[3] <= '9')
1112 #ifndef NO_COMPRESS_SUPPORT
1113 if (memcmp(buf, Z_MAGIC, 2) == 0)
1117 #ifndef NO_PACK_SUPPORT
1118 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1126 /* check the outfile is OK. */
1128 check_outfile(const char *outfile)
1133 if (lflag == 0 && stat(outfile, &sb) == 0) {
1136 else if (isatty(STDIN_FILENO)) {
1137 char ans[10] = { 'n', '\0' }; /* default */
1139 fprintf(stderr, "%s already exists -- do you wish to "
1140 "overwrite (y or n)? " , outfile);
1141 (void)fgets(ans, sizeof(ans) - 1, stdin);
1142 if (ans[0] != 'y' && ans[0] != 'Y') {
1143 fprintf(stderr, "\tnot overwriting\n");
1148 maybe_warnx("%s already exists -- skipping", outfile);
1156 unlink_input(const char *file, const struct stat *sb)
1162 if (stat(file, &nsb) != 0)
1163 /* Must be gone alrady */
1165 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1166 /* Definitely a different file */
1172 sigint_handler(int signo __unused)
1175 if (remove_file != NULL)
1176 unlink(remove_file);
1181 static const suffixes_t *
1182 check_suffix(char *file, int xlate)
1184 const suffixes_t *s;
1185 int len = strlen(file);
1188 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1189 /* if it doesn't fit in "a.suf", don't bother */
1190 if (s->ziplen >= len)
1192 sp = file + len - s->ziplen;
1193 if (strcmp(s->zipped, sp) != 0)
1196 strcpy(sp, s->normal);
1203 * compress the given file: create a corresponding .gz file and remove the
1207 file_compress(char *file, char *outfile, size_t outsize)
1213 struct stat isb, osb;
1214 const suffixes_t *suff;
1217 in = open(file, O_RDONLY);
1219 maybe_warn("can't open %s", file);
1224 if (fstat(in, &isb) != 0) {
1225 maybe_warn("couldn't stat: %s", file);
1233 if (isb.st_nlink > 1 && fflag == 0) {
1234 maybe_warnx("%s has %d other link%s -- skipping",
1235 file, isb.st_nlink - 1,
1236 (isb.st_nlink - 1) == 1 ? "" : "s");
1241 if (fflag == 0 && (suff = check_suffix(file, 0)) &&
1242 suff->zipped[0] != 0) {
1243 maybe_warnx("%s already has %s suffix -- unchanged",
1244 file, suff->zipped);
1250 /* Add (usually) .gz to filename */
1251 if ((size_t)snprintf(outfile, outsize, "%s%s",
1252 file, suffixes[0].zipped) >= outsize)
1253 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1254 suffixes[0].zipped, suffixes[0].ziplen + 1);
1257 if (check_outfile(outfile) == 0) {
1265 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1267 maybe_warn("could not create output: %s", outfile);
1272 remove_file = outfile;
1275 out = STDOUT_FILENO;
1277 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1282 * If there was an error, insize will be -1.
1283 * If we compressed to stdout, just return the size.
1284 * Otherwise stat the file and check it is the correct size.
1285 * We only blow away the file if we can stat the output and it
1286 * has the expected size.
1289 return (insize == -1 ? -1 : size);
1292 if (fstat(out, &osb) != 0) {
1293 maybe_warn("couldn't stat: %s", outfile);
1297 if (osb.st_size != size) {
1298 maybe_warnx("output file: %s wrong size (%ju != %ju), deleting",
1299 outfile, (uintmax_t)osb.st_size, (uintmax_t)size);
1303 copymodes(out, &isb, outfile);
1306 if (close(out) == -1)
1307 maybe_warn("couldn't close output");
1309 /* output is good, ok to delete input */
1310 unlink_input(file, &isb);
1315 if (close(out) == -1)
1316 maybe_warn("couldn't close output");
1318 maybe_warnx("leaving original %s", file);
1324 /* uncompress the given file and remove the original */
1326 file_uncompress(char *file, char *outfile, size_t outsize)
1328 struct stat isb, osb;
1331 unsigned char header1[4];
1332 enum filetype method;
1333 int fd, ofd, zfd = -1;
1336 time_t timestamp = 0;
1337 unsigned char name[PATH_MAX + 1];
1340 /* gather the old name info */
1342 fd = open(file, O_RDONLY);
1344 maybe_warn("can't open %s", file);
1348 strlcpy(outfile, file, outsize);
1349 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1350 maybe_warnx("%s: unknown suffix -- ignored", file);
1354 rbytes = read(fd, header1, sizeof header1);
1355 if (rbytes != sizeof header1) {
1356 /* we don't want to fail here. */
1362 maybe_warn("can't read %s", file);
1364 goto unexpected_EOF;
1368 method = file_gettype(header1);
1371 if (fflag == 0 && method == FT_UNKNOWN) {
1372 maybe_warnx("%s: not in gzip format", file);
1379 if (method == FT_GZIP && Nflag) {
1380 unsigned char ts[4]; /* timestamp */
1382 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1383 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1384 goto unexpected_EOF;
1387 maybe_warn("can't read %s", file);
1390 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1392 if (header1[3] & ORIG_NAME) {
1393 rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1395 maybe_warn("can't read %s", file);
1399 /* preserve original directory name */
1400 char *dp = strrchr(file, '/');
1405 snprintf(outfile, outsize, "%.*s%.*s",
1407 file, (int) rbytes, name);
1412 lseek(fd, 0, SEEK_SET);
1414 if (cflag == 0 || lflag) {
1415 if (fstat(fd, &isb) != 0)
1418 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1419 maybe_warnx("%s has %d other links -- skipping",
1420 file, isb.st_nlink - 1);
1423 if (nflag == 0 && timestamp)
1424 isb.st_mtime = timestamp;
1425 if (check_outfile(outfile) == 0)
1430 if (cflag == 0 && lflag == 0) {
1431 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1432 if (zfd == STDOUT_FILENO) {
1433 /* We won't close STDOUT_FILENO later... */
1435 close(STDOUT_FILENO);
1438 maybe_warn("can't open %s", outfile);
1442 remove_file = outfile;
1445 zfd = STDOUT_FILENO;
1447 #ifndef NO_BZIP2_SUPPORT
1448 if (method == FT_BZIP2) {
1452 maybe_warnx("no -l with bzip2 files");
1456 size = unbzip2(fd, zfd, NULL, 0, NULL);
1460 #ifndef NO_COMPRESS_SUPPORT
1461 if (method == FT_Z) {
1466 maybe_warnx("no -l with Lempel-Ziv files");
1470 if ((in = zdopen(fd)) == NULL) {
1471 maybe_warn("zdopen for read: %s", file);
1475 out = fdopen(dup(zfd), "w");
1477 maybe_warn("fdopen for write: %s", outfile);
1482 size = zuncompress(in, out, NULL, 0, NULL);
1483 /* need to fclose() if ferror() is true... */
1484 if (ferror(in) | fclose(in)) {
1485 maybe_warn("failed infile fclose");
1489 if (fclose(out) != 0) {
1490 maybe_warn("failed outfile fclose");
1497 #ifndef NO_PACK_SUPPORT
1498 if (method == FT_PACK) {
1500 maybe_warnx("no -l with packed files");
1504 size = unpack(fd, zfd, NULL, 0, NULL);
1509 if (method == FT_UNKNOWN) {
1511 maybe_warnx("no -l for unknown filetypes");
1514 size = cat_fd(NULL, 0, NULL, fd);
1519 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1521 return -1; /* XXX */
1524 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1528 maybe_warn("couldn't close input");
1529 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1530 maybe_warn("couldn't close output");
1535 maybe_warnx("%s: uncompress failed", file);
1539 /* if testing, or we uncompressed to stdout, this is all we need */
1544 /* if we are uncompressing to stdin, don't remove the file. */
1549 * if we create a file...
1552 * if we can't stat the file don't remove the file.
1555 ofd = open(outfile, O_RDWR, 0);
1557 maybe_warn("couldn't open (leaving original): %s",
1561 if (fstat(ofd, &osb) != 0) {
1562 maybe_warn("couldn't stat (leaving original): %s",
1567 if (osb.st_size != size) {
1568 maybe_warnx("stat gave different size: %ju != %ju (leaving original)",
1569 (uintmax_t)size, (uintmax_t)osb.st_size);
1575 copymodes(ofd, &isb, outfile);
1579 unlink_input(file, &isb);
1583 maybe_warnx("%s: unexpected end of file", file);
1587 if (zfd != -1 && zfd != STDOUT_FILENO)
1594 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1601 w = write(STDOUT_FILENO, prepend, count);
1602 if (w == -1 || (size_t)w != count) {
1603 maybe_warn("write to stdout");
1609 rv = read(fd, buf, sizeof buf);
1613 maybe_warn("read from fd %d", fd);
1617 if (write(STDOUT_FILENO, buf, rv) != rv) {
1618 maybe_warn("write to stdout");
1633 unsigned char header1[4];
1635 enum filetype method;
1637 #ifndef NO_COMPRESS_SUPPORT
1642 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1643 maybe_warnx("standard input is a terminal -- ignoring");
1651 /* XXX could read the whole file, etc. */
1652 if (fstat(STDIN_FILENO, &isb) < 0) {
1653 maybe_warn("fstat");
1656 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1660 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1661 if (bytes_read == -1) {
1662 maybe_warn("can't read stdin");
1664 } else if (bytes_read != sizeof(header1)) {
1665 maybe_warnx("(stdin): unexpected end of file");
1669 method = file_gettype(header1);
1674 maybe_warnx("unknown compression format");
1677 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1681 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1682 (char *)header1, sizeof header1, &gsize, "(stdin)");
1684 #ifndef NO_BZIP2_SUPPORT
1686 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1687 (char *)header1, sizeof header1, &gsize);
1690 #ifndef NO_COMPRESS_SUPPORT
1692 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1693 maybe_warnx("zopen of stdin");
1697 usize = zuncompress(in, stdout, (char *)header1, sizeof header1, &gsize);
1701 #ifndef NO_PACK_SUPPORT
1703 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1704 (char *)header1, sizeof header1, &gsize);
1710 if (vflag && !tflag && usize != -1 && gsize != -1)
1711 print_verbage(NULL, NULL, usize, gsize);
1713 print_test("(stdin)", usize != -1);
1728 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1729 maybe_warnx("standard output is a terminal -- ignoring");
1733 /* If stdin is a file use it's mtime, otherwise use current time */
1734 ret = fstat(STDIN_FILENO, &sb);
1738 maybe_warn("Can't stat stdin");
1743 if (S_ISREG(sb.st_mode))
1744 mtime = (uint32_t)sb.st_mtime;
1746 systime = time(NULL);
1748 if (systime == -1) {
1753 mtime = (uint32_t)systime;
1756 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1758 if (vflag && !tflag && usize != -1 && gsize != -1)
1759 print_verbage(NULL, NULL, usize, gsize);
1763 /* do what is asked for, for the path name */
1765 handle_pathname(char *path)
1767 char *opath = path, *s = NULL;
1772 /* check for stdout/stdin */
1773 if (path[0] == '-' && path[1] == '\0') {
1782 if (stat(path, &sb) != 0) {
1783 /* lets try <path>.gz if we're decompressing */
1784 if (dflag && s == NULL && errno == ENOENT) {
1786 slen = suffixes[0].ziplen;
1787 s = malloc(len + slen + 1);
1789 maybe_err("malloc");
1790 memcpy(s, path, len);
1791 memcpy(s + len, suffixes[0].zipped, slen + 1);
1795 maybe_warn("can't stat: %s", opath);
1799 if (S_ISDIR(sb.st_mode)) {
1805 maybe_warnx("%s is a directory", path);
1809 if (S_ISREG(sb.st_mode))
1810 handle_file(path, &sb);
1812 maybe_warnx("%s is not a regular file", path);
1819 /* compress/decompress a file */
1821 handle_file(char *file, struct stat *sbp)
1824 char outfile[PATH_MAX];
1828 usize = file_uncompress(file, outfile, sizeof(outfile));
1831 print_test(file, usize != -1);
1835 gsize = sbp->st_size;
1837 gsize = file_compress(file, outfile, sizeof(outfile));
1840 usize = sbp->st_size;
1845 if (vflag && !tflag)
1846 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1851 /* this is used with -r to recursively descend directories */
1853 handle_dir(char *dir)
1861 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1863 warn("couldn't fts_open %s", dir);
1867 while ((entry = fts_read(fts))) {
1868 switch(entry->fts_info) {
1876 maybe_warn("%s", entry->fts_path);
1879 handle_file(entry->fts_path, entry->fts_statp);
1882 (void)fts_close(fts);
1886 /* print a ratio - size reduction as a fraction of uncompressed size */
1888 print_ratio(off_t in, off_t out, FILE *where)
1890 int percent10; /* 10 * percent */
1898 * Output is more than double size of input! print -99.9%
1899 * Quite possibly we've failed to get the original size.
1904 * We only need 12 bits of result from the final division,
1905 * so reduce the values until a 32bit division will suffice.
1907 while (in > 0x100000) {
1912 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1917 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1918 /* Move the '.' to before the last digit */
1919 buff[len - 1] = buff[len - 2];
1920 buff[len - 2] = '.';
1921 fprintf(where, "%5s%%", buff);
1925 /* print compression statistics, and the new name (if there is one!) */
1927 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1930 fprintf(stderr, "%s:%s ", file,
1931 strlen(file) < 7 ? "\t\t" : "\t");
1932 print_ratio(usize, gsize, stderr);
1934 fprintf(stderr, " -- replaced with %s", nfile);
1935 fprintf(stderr, "\n");
1939 /* print test results */
1941 print_test(const char *file, int ok)
1944 if (exit_value == 0 && ok == 0)
1946 fprintf(stderr, "%s:%s %s\n", file,
1947 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1952 /* print a file's info ala --list */
1954 compressed uncompressed ratio uncompressed_name
1955 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1958 print_list(int fd, off_t out, const char *outfile, time_t ts)
1960 static int first = 1;
1962 static off_t in_tot, out_tot;
1970 printf("method crc date time ");
1973 printf(" compressed uncompressed "
1974 "ratio uncompressed_name\n");
1986 /* read the last 4 bytes - this is the uncompressed size */
1987 rv = lseek(fd, (off_t)(-8), SEEK_END);
1989 unsigned char buf[8];
1992 rv = read(fd, (char *)buf, sizeof(buf));
1994 maybe_warn("read of uncompressed size");
1995 else if (rv != sizeof(buf))
1996 maybe_warnx("read of uncompressed size");
1999 usize = buf[4] | buf[5] << 8 |
2000 buf[6] << 16 | buf[7] << 24;
2003 crc = buf[0] | buf[1] << 8 |
2004 buf[2] << 16 | buf[3] << 24;
2011 if (vflag && fd == -1)
2014 char *date = ctime(&ts);
2016 /* skip the day, 1/100th second, and year */
2019 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2024 (void)&ts; /* XXX */
2026 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2027 print_ratio(in, out, stdout);
2028 printf(" %s\n", outfile);
2031 /* display the usage of NetBSD gzip */
2036 fprintf(stderr, "%s\n", gzip_version);
2039 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
2041 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2042 " -1 --fast fastest (worst) compression\n"
2043 " -2 .. -8 set compression level\n"
2044 " -9 --best best (slowest) compression\n"
2045 " -c --stdout write to stdout, keep original files\n"
2047 " -d --decompress uncompress files\n"
2049 " -f --force force overwriting & compress links\n"
2050 " -h --help display this help\n"
2051 " -k --keep don't delete input files during operation\n"
2052 " -l --list list compressed file contents\n"
2053 " -N --name save or restore original file name and time stamp\n"
2054 " -n --no-name don't save original file name or time stamp\n"
2055 " -q --quiet output no warnings\n"
2056 " -r --recursive recursively compress files in directories\n"
2057 " -S .suf use suffix .suf instead of .gz\n"
2059 " -t --test test compressed file\n"
2060 " -V --version display program version\n"
2061 " -v --verbose print extra statistics\n",
2068 /* display the license information of FreeBSD gzip */
2070 display_license(void)
2073 fprintf(stderr, "%s (based on NetBSD gzip 20091011)\n", gzip_version);
2074 fprintf(stderr, "%s\n", gzip_copyright);
2079 /* display the version of NetBSD gzip */
2081 display_version(void)
2084 fprintf(stderr, "%s\n", gzip_version);
2088 #ifndef NO_BZIP2_SUPPORT
2089 #include "unbzip2.c"
2091 #ifndef NO_COMPRESS_SUPPORT
2092 #include "zuncompress.c"
2094 #ifndef NO_PACK_SUPPORT
2099 read_retry(int fd, void *buf, size_t sz)
2102 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2107 ret = read(fd, cp, left);
2110 } else if (ret == 0) {