1 /* $NetBSD: gzip.c,v 1.94 2009/04/12 10:31:14 lukem Exp $ */
2 /* $DragonFly: src/usr.bin/gzip/gzip.c,v 1.7 2007/12/06 19:54:52 hasso Exp $ */
5 * Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * gzip.c -- GPL free gzip using zlib.
33 * RFC 1950 covers the zlib format
34 * RFC 1951 covers the deflate format
35 * RFC 1952 covers the gzip format
38 * - use mmap where possible
39 * - handle some signals better (remove outfile?)
40 * - make bzip2/compress -v/-t/-l support work as well as possible
43 #include <sys/param.h>
63 #define PRIdOFF PRId64
70 /* what type of file are we dealing with */
73 #ifndef NO_BZIP2_SUPPORT
76 #ifndef NO_COMPRESS_SUPPORT
83 #ifndef NO_BZIP2_SUPPORT
86 #define BZ2_SUFFIX ".bz2"
87 #define BZIP2_MAGIC "\102\132\150"
90 #ifndef NO_COMPRESS_SUPPORT
92 #define Z_MAGIC "\037\235"
95 #define GZ_SUFFIX ".gz"
97 #define BUFLEN (64 * 1024)
99 #define GZIP_MAGIC0 0x1F
100 #define GZIP_MAGIC1 0x8B
101 #define GZIP_OMAGIC1 0x9E
103 #define GZIP_TIMESTAMP (off_t)4
104 #define GZIP_ORIGNAME (off_t)10
106 #define HEAD_CRC 0x02
107 #define EXTRA_FIELD 0x04
108 #define ORIG_NAME 0x08
111 #define OS_CODE 3 /* Unix */
116 const char *normal; /* for unzip - must not be longer than zipped */
118 static suffixes_t suffixes[] = {
119 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
120 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
122 SUFFIX(GZ_SUFFIX, ""),
127 SUFFIX(".taz", ".tar"),
128 SUFFIX(".tgz", ".tar"),
129 #ifndef NO_BZIP2_SUPPORT
130 SUFFIX(BZ2_SUFFIX, ""),
132 #ifndef NO_COMPRESS_SUPPORT
133 SUFFIX(Z_SUFFIX, ""),
135 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
139 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
141 static const char gzip_version[] = "NetBSD gzip 20060927";
143 static int cflag; /* stdout mode */
144 static int dflag; /* decompress mode */
145 static int lflag; /* list mode */
146 static int numflag = 6; /* gzip -1..-9 value */
149 static int fflag; /* force mode */
150 static int kflag; /* don't delete input files */
151 static int nflag; /* don't save name/timestamp */
152 static int Nflag; /* don't restore name/timestamp */
153 static int qflag; /* quiet mode */
154 static int rflag; /* recursive mode */
155 static int tflag; /* test */
156 static int vflag; /* verbose mode */
162 static int exit_value = 0; /* exit value */
164 static char *infile; /* name of file coming in */
166 static void maybe_err(const char *fmt, ...)
167 __attribute__((__format__(__printf__, 1, 2)));
168 #ifndef NO_BZIP2_SUPPORT
169 static void maybe_errx(const char *fmt, ...)
170 __attribute__((__format__(__printf__, 1, 2)));
172 static void maybe_warn(const char *fmt, ...)
173 __attribute__((__format__(__printf__, 1, 2)));
174 static void maybe_warnx(const char *fmt, ...)
175 __attribute__((__format__(__printf__, 1, 2)));
176 static enum filetype file_gettype(u_char *);
178 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
180 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
181 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
182 static off_t file_compress(char *, char *, size_t);
183 static off_t file_uncompress(char *, char *, size_t);
184 static void handle_pathname(char *);
185 static void handle_file(char *, struct stat *);
186 static void handle_stdin(void);
187 static void handle_stdout(void);
188 static void print_ratio(off_t, off_t, FILE *);
189 static void print_list(int fd, off_t, const char *, time_t);
190 static void usage(void);
191 static void display_version(void);
192 static const suffixes_t *check_suffix(char *, int);
193 static ssize_t read_retry(int, void *, size_t);
196 #define unlink_input(f, sb) unlink(f)
198 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
199 static void prepend_gzip(char *, int *, char ***);
200 static void handle_dir(char *);
201 static void print_verbage(const char *, const char *, off_t, off_t);
202 static void print_test(const char *, int);
203 static void copymodes(int fd, const struct stat *, const char *file);
204 static int check_outfile(const char *outfile);
207 #ifndef NO_BZIP2_SUPPORT
208 static off_t unbzip2(int, int, char *, size_t, off_t *);
211 #ifndef NO_COMPRESS_SUPPORT
212 static FILE *zdopen(int);
213 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
216 int main(int, char *p[]);
219 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
221 static const struct option longopts[] = {
222 { "stdout", no_argument, 0, 'c' },
223 { "to-stdout", no_argument, 0, 'c' },
224 { "decompress", no_argument, 0, 'd' },
225 { "uncompress", no_argument, 0, 'd' },
226 { "force", no_argument, 0, 'f' },
227 { "help", no_argument, 0, 'h' },
228 { "keep", no_argument, 0, 'k' },
229 { "list", no_argument, 0, 'l' },
230 { "no-name", no_argument, 0, 'n' },
231 { "name", no_argument, 0, 'N' },
232 { "quiet", no_argument, 0, 'q' },
233 { "recursive", no_argument, 0, 'r' },
234 { "suffix", required_argument, 0, 'S' },
235 { "test", no_argument, 0, 't' },
236 { "verbose", no_argument, 0, 'v' },
237 { "version", no_argument, 0, 'V' },
238 { "fast", no_argument, 0, '1' },
239 { "best", no_argument, 0, '9' },
242 * This is what else GNU gzip implements. --ascii isn't useful
243 * on NetBSD, and I don't care to have a --license.
245 { "ascii", no_argument, 0, 'a' },
246 { "license", no_argument, 0, 'L' },
248 { NULL, no_argument, 0, 0 },
253 main(int argc, char **argv)
255 const char *progname = getprogname();
262 /* XXX set up signals */
265 if ((gzip = getenv("GZIP")) != NULL)
266 prepend_gzip(gzip, &argc, &argv);
271 * handle being called `gunzip', `zcat' and `gzcat'
273 if (strcmp(progname, "gunzip") == 0)
275 else if (strcmp(progname, "zcat") == 0 ||
276 strcmp(progname, "gzcat") == 0)
280 #define OPT_LIST "123456789cdhltV"
282 #define OPT_LIST "123456789cdfhklNnqrS:tVv"
285 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
287 case '1': case '2': case '3':
288 case '4': case '5': case '6':
289 case '7': case '8': case '9':
327 len = strlen(optarg);
329 suffixes[0].zipped = optarg;
330 suffixes[0].ziplen = len;
332 suffixes[NUM_SUFFIXES - 1].zipped = "";
333 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
354 if (dflag) /* stdin mode */
356 else /* stdout mode */
360 handle_pathname(argv[0]);
364 if (qflag == 0 && lflag && argc > 1)
365 print_list(-1, 0, "(totals)", 0);
370 /* maybe print a warning */
372 maybe_warn(const char *fmt, ...)
385 /* ... without an errno. */
387 maybe_warnx(const char *fmt, ...)
400 /* maybe print an error */
402 maybe_err(const char *fmt, ...)
414 #ifndef NO_BZIP2_SUPPORT
415 /* ... without an errno. */
417 maybe_errx(const char *fmt, ...)
431 /* split up $GZIP and prepend it to the argument list */
433 prepend_gzip(char *gzip, int *argc, char ***argv)
435 char *s, **nargv, **ac;
438 /* scan how many arguments there are */
440 while (*s == ' ' || *s == '\t')
445 while (*s != ' ' && *s != '\t')
457 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
461 /* stash this away */
464 /* copy the program name first */
466 nargv[i++] = *(ac++);
468 /* take a copy of $GZIP and add it to the array */
473 /* Skip whitespaces. */
474 while (*s == ' ' || *s == '\t')
479 /* Find the end of this argument. */
480 while (*s != ' ' && *s != '\t')
482 /* Argument followed by NUL. */
484 /* Terminate by overwriting ' ' or '\t' with NUL. */
489 /* copy the original arguments and a NULL */
491 nargv[i++] = *(ac++);
496 /* compress input to output. Return bytes read, -1 on error */
498 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
501 char *outbufp, *inbufp;
502 off_t in_tot = 0, out_tot = 0;
507 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
512 outbufp = malloc(BUFLEN);
513 inbufp = malloc(BUFLEN);
514 if (outbufp == NULL || inbufp == NULL) {
515 maybe_err("malloc failed");
519 memset(&z, 0, sizeof z);
525 memcpy(outbufp, header, sizeof header);
533 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
534 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
535 *origname ? ORIG_NAME : 0,
538 (mtime >> 16) & 0xff,
539 (mtime >> 24) & 0xff,
540 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
543 /* this need PATH_MAX > BUFLEN ... */
544 maybe_err("snprintf");
549 z.next_out = outbufp + i;
550 z.avail_out = BUFLEN - i;
552 error = deflateInit2(&z, numflag, Z_DEFLATED,
553 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
555 maybe_warnx("deflateInit2 failed");
560 crc = crc32(0L, Z_NULL, 0);
562 if (z.avail_out == 0) {
563 if (write(out, outbufp, BUFLEN) != BUFLEN) {
570 z.next_out = outbufp;
571 z.avail_out = BUFLEN;
574 if (z.avail_in == 0) {
575 in_size = read(in, inbufp, BUFLEN);
584 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
587 z.avail_in = in_size;
590 error = deflate(&z, Z_NO_FLUSH);
591 if (error != Z_OK && error != Z_STREAM_END) {
592 maybe_warnx("deflate failed");
603 error = deflate(&z, Z_FINISH);
604 if (error != Z_OK && error != Z_STREAM_END) {
605 maybe_warnx("deflate failed");
610 len = (char *)z.next_out - outbufp;
612 w = write(out, outbufp, len);
613 if (w == -1 || (size_t)w != len) {
619 z.next_out = outbufp;
620 z.avail_out = BUFLEN;
622 if (error == Z_STREAM_END)
626 if (deflateEnd(&z) != Z_OK) {
627 maybe_warnx("deflateEnd failed");
632 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
634 (int)(crc >> 8) & 0xff,
635 (int)(crc >> 16) & 0xff,
636 (int)(crc >> 24) & 0xff,
638 (int)(in_tot >> 8) & 0xff,
639 (int)(in_tot >> 16) & 0xff,
640 (int)(in_tot >> 24) & 0xff);
642 maybe_err("snprintf");
644 if (in_tot > 0xffffffff)
645 maybe_warn("input file size >= 4GB cannot be saved");
647 if (write(out, outbufp, i) != i) {
664 * uncompress input to output then close the input. return the
665 * uncompressed size written, and put the compressed sized read
669 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
670 const char *filename)
673 char *outbufp, *inbufp;
674 off_t out_tot = -1, in_tot = 0;
675 uint32_t out_sub_tot = 0;
693 } state = GZSTATE_MAGIC0;
694 int flags = 0, skip_count = 0;
695 int error = Z_STREAM_ERROR, done_reading = 0;
700 #define ADVANCE() { z.next_in++; z.avail_in--; }
702 if ((outbufp = malloc(BUFLEN)) == NULL) {
703 maybe_err("malloc failed");
706 if ((inbufp = malloc(BUFLEN)) == NULL) {
707 maybe_err("malloc failed");
711 memset(&z, 0, sizeof z);
714 z.avail_out = BUFLEN;
715 z.next_out = outbufp;
724 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
727 if (z.avail_in > 0) {
728 memmove(inbufp, z.next_in, z.avail_in);
731 in_size = read(in, z.next_in + z.avail_in,
732 BUFLEN - z.avail_in);
735 maybe_warn("failed to read stdin");
737 } else if (in_size == 0) {
741 z.avail_in += in_size;
746 if (z.avail_in == 0) {
747 if (done_reading && state != GZSTATE_MAGIC0) {
748 maybe_warnx("%s: unexpected end of file",
756 if (*z.next_in != GZIP_MAGIC0) {
758 maybe_warnx("%s: trailing garbage "
759 "ignored", filename);
762 maybe_warnx("input not gziped (MAGIC0)");
768 crc = crc32(0L, Z_NULL, 0);
772 if (*z.next_in != GZIP_MAGIC1 &&
773 *z.next_in != GZIP_OMAGIC1) {
774 maybe_warnx("input not gziped (MAGIC1)");
782 if (*z.next_in != Z_DEFLATED) {
783 maybe_warnx("unknown compression method");
797 case GZSTATE_SKIPPING:
798 if (skip_count > 0) {
806 if ((flags & EXTRA_FIELD) == 0) {
807 state = GZSTATE_ORIGNAME;
810 skip_count = *z.next_in;
816 skip_count |= ((*z.next_in) << 8);
822 if (skip_count > 0) {
829 case GZSTATE_ORIGNAME:
830 if ((flags & ORIG_NAME) == 0) {
839 case GZSTATE_COMMENT:
840 if ((flags & COMMENT) == 0) {
849 case GZSTATE_HEAD_CRC1:
850 if (flags & HEAD_CRC)
857 case GZSTATE_HEAD_CRC2:
858 if (skip_count > 0) {
866 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
867 maybe_warnx("failed to inflateInit");
874 error = inflate(&z, Z_FINISH);
876 /* Z_BUF_ERROR goes with Z_FINISH... */
883 maybe_warnx("Z_NEED_DICT error");
886 maybe_warnx("data stream error");
889 maybe_warnx("internal stream error");
892 maybe_warnx("memory allocation error");
896 maybe_warn("unknown error from inflate(): %d",
899 wr = BUFLEN - z.avail_out;
902 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
905 /* don't write anything with -t */
908 write(out, outbufp, wr) != wr) {
909 maybe_warn("error writing to output");
917 if (error == Z_STREAM_END) {
922 z.next_out = outbufp;
923 z.avail_out = BUFLEN;
930 if (z.avail_in < 4) {
935 maybe_warnx("truncated input");
938 origcrc = ((unsigned)z.next_in[0] & 0xff) |
939 ((unsigned)z.next_in[1] & 0xff) << 8 |
940 ((unsigned)z.next_in[2] & 0xff) << 16 |
941 ((unsigned)z.next_in[3] & 0xff) << 24;
942 if (origcrc != crc) {
943 maybe_warnx("invalid compressed"
952 if (!z.avail_in && done_reading) {
961 if (z.avail_in < 4) {
966 maybe_warnx("truncated input");
969 origlen = ((unsigned)z.next_in[0] & 0xff) |
970 ((unsigned)z.next_in[1] & 0xff) << 8 |
971 ((unsigned)z.next_in[2] & 0xff) << 16 |
972 ((unsigned)z.next_in[3] & 0xff) << 24;
974 if (origlen != out_sub_tot) {
975 maybe_warnx("invalid compressed"
976 " data--length error");
985 maybe_warnx("decompression error");
988 state = GZSTATE_MAGIC0;
997 if (state > GZSTATE_INIT)
1011 * set the owner, mode, flags & utimes using the given file descriptor.
1012 * file is only used in possible warning messages.
1015 copymodes(int fd, const struct stat *sbp, const char *file)
1017 struct timeval times[2];
1021 * If we have no info on the input, give this file some
1022 * default values and return..
1025 mode_t mask = umask(022);
1027 (void)fchmod(fd, DEFFILEMODE & ~mask);
1033 /* if the chown fails, remove set-id bits as-per compress(1) */
1034 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1036 maybe_warn("couldn't fchown: %s", file);
1037 sb.st_mode &= ~(S_ISUID|S_ISGID);
1040 /* we only allow set-id and the 9 normal permission bits */
1041 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1042 if (fchmod(fd, sb.st_mode) < 0)
1043 maybe_warn("couldn't fchmod: %s", file);
1045 /* only try flags if they exist already */
1046 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1047 maybe_warn("couldn't fchflags: %s", file);
1049 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atimespec);
1050 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtimespec);
1051 if (futimes(fd, times) < 0)
1052 maybe_warn("couldn't utimes: %s", file);
1056 /* what sort of file is this? */
1057 static enum filetype
1058 file_gettype(u_char *buf)
1061 if (buf[0] == GZIP_MAGIC0 &&
1062 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1065 #ifndef NO_BZIP2_SUPPORT
1066 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1067 buf[3] >= '0' && buf[3] <= '9')
1071 #ifndef NO_COMPRESS_SUPPORT
1072 if (memcmp(buf, Z_MAGIC, 2) == 0)
1080 /* check the outfile is OK. */
1082 check_outfile(const char *outfile)
1087 if (lflag == 0 && stat(outfile, &sb) == 0) {
1090 else if (isatty(STDIN_FILENO)) {
1091 char ans[10] = { 'n', '\0' }; /* default */
1093 fprintf(stderr, "%s already exists -- do you wish to "
1094 "overwrite (y or n)? " , outfile);
1095 (void)fgets(ans, sizeof(ans) - 1, stdin);
1096 if (ans[0] != 'y' && ans[0] != 'Y') {
1097 fprintf(stderr, "\tnot overwriting\n");
1102 maybe_warnx("%s already exists -- skipping", outfile);
1110 unlink_input(const char *file, const struct stat *sb)
1116 if (stat(file, &nsb) != 0)
1117 /* Must be gone alrady */
1119 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1120 /* Definitely a different file */
1126 static const suffixes_t *
1127 check_suffix(char *file, int xlate)
1129 const suffixes_t *s;
1130 int len = strlen(file);
1133 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1134 /* if it doesn't fit in "a.suf", don't bother */
1135 if (s->ziplen >= len)
1137 sp = file + len - s->ziplen;
1138 if (strcmp(s->zipped, sp) != 0)
1141 strcpy(sp, s->normal);
1148 * compress the given file: create a corresponding .gz file and remove the
1152 file_compress(char *file, char *outfile, size_t outsize)
1158 struct stat isb, osb;
1159 const suffixes_t *suff;
1162 in = open(file, O_RDONLY);
1164 maybe_warn("can't open %s", file);
1170 if (fstat(in, &isb) == 0) {
1171 if (isb.st_nlink > 1 && fflag == 0) {
1172 maybe_warnx("%s has %d other link%s -- "
1173 "skipping", file, isb.st_nlink - 1,
1174 isb.st_nlink == 1 ? "" : "s");
1180 if (fflag == 0 && (suff = check_suffix(file, 0))
1181 && suff->zipped[0] != 0) {
1182 maybe_warnx("%s already has %s suffix -- unchanged",
1183 file, suff->zipped);
1189 /* Add (usually) .gz to filename */
1190 if ((size_t)snprintf(outfile, outsize, "%s%s",
1191 file, suffixes[0].zipped) >= outsize)
1192 memcpy(outfile - suffixes[0].ziplen - 1,
1193 suffixes[0].zipped, suffixes[0].ziplen + 1);
1196 if (check_outfile(outfile) == 0) {
1204 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1206 maybe_warn("could not create output: %s", outfile);
1211 out = STDOUT_FILENO;
1213 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1218 * If there was an error, insize will be -1.
1219 * If we compressed to stdout, just return the size.
1220 * Otherwise stat the file and check it is the correct size.
1221 * We only blow away the file if we can stat the output and it
1222 * has the expected size.
1225 return insize == -1 ? -1 : size;
1228 if (fstat(out, &osb) != 0) {
1229 maybe_warn("couldn't stat: %s", outfile);
1233 if (osb.st_size != size) {
1234 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1235 " != %" PRIdOFF "), deleting",
1236 outfile, osb.st_size, size);
1240 copymodes(out, &isb, outfile);
1242 if (close(out) == -1)
1243 maybe_warn("couldn't close output");
1245 /* output is good, ok to delete input */
1246 unlink_input(file, &isb);
1251 if (close(out) == -1)
1252 maybe_warn("couldn't close output");
1254 maybe_warnx("leaving original %s", file);
1260 /* uncompress the given file and remove the original */
1262 file_uncompress(char *file, char *outfile, size_t outsize)
1264 struct stat isb, osb;
1267 unsigned char header1[4];
1268 enum filetype method;
1269 int fd, ofd, zfd = -1;
1272 time_t timestamp = 0;
1273 unsigned char name[PATH_MAX + 1];
1276 /* gather the old name info */
1278 fd = open(file, O_RDONLY);
1280 maybe_warn("can't open %s", file);
1284 strlcpy(outfile, file, outsize);
1285 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1286 maybe_warnx("%s: unknown suffix -- ignored", file);
1290 rbytes = read(fd, header1, sizeof header1);
1291 if (rbytes != sizeof header1) {
1292 /* we don't want to fail here. */
1298 maybe_warn("can't read %s", file);
1300 goto unexpected_EOF;
1304 method = file_gettype(header1);
1307 if (fflag == 0 && method == FT_UNKNOWN) {
1308 maybe_warnx("%s: not in gzip format", file);
1315 if (method == FT_GZIP && Nflag) {
1316 unsigned char ts[4]; /* timestamp */
1318 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1319 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1320 goto unexpected_EOF;
1323 maybe_warn("can't read %s", file);
1326 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1328 if (header1[3] & ORIG_NAME) {
1329 rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1331 maybe_warn("can't read %s", file);
1335 /* preserve original directory name */
1336 char *dp = strrchr(file, '/');
1341 snprintf(outfile, outsize, "%.*s%.*s",
1343 file, (int) rbytes, name);
1348 lseek(fd, 0, SEEK_SET);
1350 if (cflag == 0 || lflag) {
1351 if (fstat(fd, &isb) != 0)
1354 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1355 maybe_warnx("%s has %d other links -- skipping",
1356 file, isb.st_nlink - 1);
1359 if (nflag == 0 && timestamp)
1360 isb.st_mtime = timestamp;
1361 if (check_outfile(outfile) == 0)
1366 if (cflag == 0 && lflag == 0) {
1367 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1368 if (zfd == STDOUT_FILENO) {
1369 /* We won't close STDOUT_FILENO later... */
1371 close(STDOUT_FILENO);
1374 maybe_warn("can't open %s", outfile);
1378 zfd = STDOUT_FILENO;
1380 #ifndef NO_BZIP2_SUPPORT
1381 if (method == FT_BZIP2) {
1385 maybe_warnx("no -l with bzip2 files");
1389 size = unbzip2(fd, zfd, NULL, 0, NULL);
1393 #ifndef NO_COMPRESS_SUPPORT
1394 if (method == FT_Z) {
1399 maybe_warnx("no -l with Lempel-Ziv files");
1403 if ((in = zdopen(fd)) == NULL) {
1404 maybe_warn("zdopen for read: %s", file);
1408 out = fdopen(dup(zfd), "w");
1410 maybe_warn("fdopen for write: %s", outfile);
1415 size = zuncompress(in, out, NULL, 0, NULL);
1416 /* need to fclose() if ferror() is true... */
1417 if (ferror(in) | fclose(in)) {
1418 maybe_warn("failed infile fclose");
1422 if (fclose(out) != 0) {
1423 maybe_warn("failed outfile fclose");
1431 if (method == FT_UNKNOWN) {
1433 maybe_warnx("no -l for unknown filetypes");
1436 size = cat_fd(NULL, 0, NULL, fd);
1441 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1443 return -1; /* XXX */
1446 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1450 maybe_warn("couldn't close input");
1451 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1452 maybe_warn("couldn't close output");
1457 maybe_warnx("%s: uncompress failed", file);
1461 /* if testing, or we uncompressed to stdout, this is all we need */
1466 /* if we are uncompressing to stdin, don't remove the file. */
1471 * if we create a file...
1474 * if we can't stat the file don't remove the file.
1477 ofd = open(outfile, O_RDWR, 0);
1479 maybe_warn("couldn't open (leaving original): %s",
1483 if (fstat(ofd, &osb) != 0) {
1484 maybe_warn("couldn't stat (leaving original): %s",
1489 if (osb.st_size != size) {
1490 maybe_warnx("stat gave different size: %" PRIdOFF
1491 " != %" PRIdOFF " (leaving original)",
1497 unlink_input(file, &isb);
1499 copymodes(ofd, &isb, outfile);
1505 maybe_warnx("%s: unexpected end of file", file);
1509 if (zfd != -1 && zfd != STDOUT_FILENO)
1516 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1523 w = write(STDOUT_FILENO, prepend, count);
1524 if (w == -1 || (size_t)w != count) {
1525 maybe_warn("write to stdout");
1531 rv = read(fd, buf, sizeof buf);
1535 maybe_warn("read from fd %d", fd);
1539 if (write(STDOUT_FILENO, buf, rv) != rv) {
1540 maybe_warn("write to stdout");
1555 unsigned char header1[4];
1557 enum filetype method;
1559 #ifndef NO_COMPRESS_SUPPORT
1564 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1565 maybe_warnx("standard input is a terminal -- ignoring");
1573 /* XXX could read the whole file, etc. */
1574 if (fstat(STDIN_FILENO, &isb) < 0) {
1575 maybe_warn("fstat");
1578 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1582 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1583 if (bytes_read == -1) {
1584 maybe_warn("can't read stdin");
1586 } else if (bytes_read != sizeof(header1)) {
1587 maybe_warnx("(stdin): unexpected end of file");
1591 method = file_gettype(header1);
1596 maybe_warnx("unknown compression format");
1599 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1603 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1604 header1, sizeof header1, &gsize, "(stdin)");
1606 #ifndef NO_BZIP2_SUPPORT
1608 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1609 header1, sizeof header1, &gsize);
1612 #ifndef NO_COMPRESS_SUPPORT
1614 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1615 maybe_warnx("zopen of stdin");
1619 usize = zuncompress(in, stdout, header1, sizeof header1, &gsize);
1626 if (vflag && !tflag && usize != -1 && gsize != -1)
1627 print_verbage(NULL, NULL, usize, gsize);
1629 print_test("(stdin)", usize != -1);
1644 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1645 maybe_warnx("standard output is a terminal -- ignoring");
1649 /* If stdin is a file use it's mtime, otherwise use current time */
1650 ret = fstat(STDIN_FILENO, &sb);
1654 maybe_warn("Can't stat stdin");
1659 if (S_ISREG(sb.st_mode))
1660 mtime = (uint32_t)sb.st_mtime;
1662 systime = time(NULL);
1664 if (systime == -1) {
1669 mtime = (uint32_t)systime;
1672 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1674 if (vflag && !tflag && usize != -1 && gsize != -1)
1675 print_verbage(NULL, NULL, usize, gsize);
1679 /* do what is asked for, for the path name */
1681 handle_pathname(char *path)
1683 char *opath = path, *s = NULL;
1688 /* check for stdout/stdin */
1689 if (path[0] == '-' && path[1] == '\0') {
1698 if (stat(path, &sb) != 0) {
1699 /* lets try <path>.gz if we're decompressing */
1700 if (dflag && s == NULL && errno == ENOENT) {
1702 slen = suffixes[0].ziplen;
1703 s = malloc(len + slen + 1);
1705 maybe_err("malloc");
1706 memcpy(s, path, len);
1707 memcpy(s + len, suffixes[0].zipped, slen + 1);
1711 maybe_warn("can't stat: %s", opath);
1715 if (S_ISDIR(sb.st_mode)) {
1721 maybe_warnx("%s is a directory", path);
1725 if (S_ISREG(sb.st_mode))
1726 handle_file(path, &sb);
1728 maybe_warnx("%s is not a regular file", path);
1735 /* compress/decompress a file */
1737 handle_file(char *file, struct stat *sbp)
1740 char outfile[PATH_MAX];
1744 usize = file_uncompress(file, outfile, sizeof(outfile));
1747 print_test(file, usize != -1);
1751 gsize = sbp->st_size;
1753 gsize = file_compress(file, outfile, sizeof(outfile));
1756 usize = sbp->st_size;
1761 if (vflag && !tflag)
1762 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1767 /* this is used with -r to recursively descend directories */
1769 handle_dir(char *dir)
1777 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1779 warn("couldn't fts_open %s", dir);
1783 while ((entry = fts_read(fts))) {
1784 switch(entry->fts_info) {
1792 maybe_warn("%s", entry->fts_path);
1795 handle_file(entry->fts_path, entry->fts_statp);
1798 (void)fts_close(fts);
1802 /* print a ratio - size reduction as a fraction of uncompressed size */
1804 print_ratio(off_t in, off_t out, FILE *where)
1806 int percent10; /* 10 * percent */
1814 * Output is more than double size of input! print -99.9%
1815 * Quite possibly we've failed to get the original size.
1820 * We only need 12 bits of result from the final division,
1821 * so reduce the values until a 32bit division will suffice.
1823 while (in > 0x100000) {
1828 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1833 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1834 /* Move the '.' to before the last digit */
1835 buff[len - 1] = buff[len - 2];
1836 buff[len - 2] = '.';
1837 fprintf(where, "%5s%%", buff);
1841 /* print compression statistics, and the new name (if there is one!) */
1843 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1846 fprintf(stderr, "%s:%s ", file,
1847 strlen(file) < 7 ? "\t\t" : "\t");
1848 print_ratio(usize, gsize, stderr);
1850 fprintf(stderr, " -- replaced with %s", nfile);
1851 fprintf(stderr, "\n");
1855 /* print test results */
1857 print_test(const char *file, int ok)
1860 if (exit_value == 0 && ok == 0)
1862 fprintf(stderr, "%s:%s %s\n", file,
1863 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1868 /* print a file's info ala --list */
1870 compressed uncompressed ratio uncompressed_name
1871 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1874 print_list(int fd, off_t out, const char *outfile, time_t ts)
1876 static int first = 1;
1878 static off_t in_tot, out_tot;
1886 printf("method crc date time ");
1889 printf(" compressed uncompressed "
1890 "ratio uncompressed_name\n");
1902 /* read the last 4 bytes - this is the uncompressed size */
1903 rv = lseek(fd, (off_t)(-8), SEEK_END);
1905 unsigned char buf[8];
1908 rv = read(fd, (char *)buf, sizeof(buf));
1910 maybe_warn("read of uncompressed size");
1911 else if (rv != sizeof(buf))
1912 maybe_warnx("read of uncompressed size");
1915 usize = buf[4] | buf[5] << 8 |
1916 buf[6] << 16 | buf[7] << 24;
1919 crc = buf[0] | buf[1] << 8 |
1920 buf[2] << 16 | buf[3] << 24;
1927 if (vflag && fd == -1)
1930 char *date = ctime(&ts);
1932 /* skip the day, 1/100th second, and year */
1935 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
1940 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
1941 print_ratio(in, out, stdout);
1942 printf(" %s\n", outfile);
1945 /* display the usage of NetBSD gzip */
1950 fprintf(stderr, "%s\n", gzip_version);
1953 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
1955 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
1956 " -1 --fast fastest (worst) compression\n"
1957 " -2 .. -8 set compression level\n"
1958 " -9 --best best (slowest) compression\n"
1959 " -c --stdout write to stdout, keep original files\n"
1961 " -d --decompress uncompress files\n"
1963 " -f --force force overwriting & compress links\n"
1964 " -h --help display this help\n"
1965 " -k --keep don't delete input files during operation\n"
1966 " -l --list list compressed file contents\n"
1967 " -N --name save or restore original file name and time stamp\n"
1968 " -n --no-name don't save original file name or time stamp\n"
1969 " -q --quiet output no warnings\n"
1970 " -r --recursive recursively compress files in directories\n"
1971 " -S .suf use suffix .suf instead of .gz\n"
1973 " -t --test test compressed file\n"
1974 " -V --version display program version\n"
1975 " -v --verbose print extra statistics\n",
1981 /* display the version of NetBSD gzip */
1983 display_version(void)
1986 fprintf(stderr, "%s\n", gzip_version);
1990 #ifndef NO_BZIP2_SUPPORT
1991 #include "unbzip2.c"
1993 #ifndef NO_COMPRESS_SUPPORT
1994 #include "zuncompress.c"
1998 read_retry(int fd, void *buf, size_t sz)
2001 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2006 ret = read(fd, cp, left);
2009 } else if (ret == 0) {