1 /* $NetBSD: gzip.c,v 1.67 2004/09/11 11:07:44 dsl Exp $ */
2 /* $DragonFly: src/usr.bin/gzip/gzip.c,v 1.1 2004/10/26 11:19:31 joerg Exp $ */
5 * Copyright (c) 1997, 1998, 2003, 2004 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.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
25 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * gzip.c -- GPL free gzip using zlib.
35 * RFC 1950 covers the zlib format
36 * RFC 1951 covers the deflate format
37 * RFC 1952 covers the gzip format
40 * - use mmap where possible
41 * - handle some signals better (remove outfile?)
42 * - make bzip2/compress -v/-t/-l support work as well as possible
45 #include <sys/param.h>
64 #define PRIdOFF PRId64
67 /* what type of file are we dealing with */
70 #ifndef NO_BZIP2_SUPPORT
73 #ifndef NO_COMPRESS_SUPPORT
80 #ifndef NO_BZIP2_SUPPORT
83 #define BZ2_SUFFIX ".bz2"
84 #define BZIP2_MAGIC "\102\132\150"
87 #ifndef NO_COMPRESS_SUPPORT
89 #define Z_MAGIC "\037\235"
92 #define GZ_SUFFIX ".gz"
94 #define BUFLEN (64 * 1024)
96 #define GZIP_MAGIC0 0x1F
97 #define GZIP_MAGIC1 0x8B
98 #define GZIP_OMAGIC1 0x9E
100 #define GZIP_TIMESTAMP (off_t)4
101 #define GZIP_ORIGNAME (off_t)10
103 #define HEAD_CRC 0x02
104 #define EXTRA_FIELD 0x04
105 #define ORIG_NAME 0x08
108 #define OS_CODE 3 /* Unix */
113 const char *normal; /* for unzip - must not be longer than zipped */
115 static suffixes_t suffixes[] = {
116 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
117 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
119 SUFFIX(GZ_SUFFIX, ""),
124 SUFFIX(".taz", ".tar"),
125 SUFFIX(".tgz", ".tar"),
126 #ifndef NO_BZIP2_SUPPORT
127 SUFFIX(BZ2_SUFFIX, ""),
129 #ifndef NO_COMPRESS_SUPPORT
130 SUFFIX(Z_SUFFIX, ""),
132 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
136 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
138 static const char gzip_version[] = "NetBSD gzip 20040830";
140 static int cflag; /* stdout mode */
141 static int dflag; /* decompress mode */
142 static int lflag; /* list mode */
143 static int numflag = 6; /* gzip -1..-9 value */
146 static int fflag; /* force mode */
147 static int nflag; /* don't save name/timestamp */
148 static int Nflag; /* don't restore name/timestamp */
149 static int qflag; /* quiet mode */
150 static int rflag; /* recursive mode */
151 static int tflag; /* test */
152 static int vflag; /* verbose mode */
158 static int exit_value = 0; /* exit value */
160 static char *infile; /* name of file coming in */
162 static void maybe_err(const char *fmt, ...)
163 __attribute__((__format__(__printf__, 1, 2)));
164 #ifndef NO_BZIP2_SUPPORT
165 static void maybe_errx(const char *fmt, ...)
166 __attribute__((__format__(__printf__, 1, 2)));
168 static void maybe_warn(const char *fmt, ...)
169 __attribute__((__format__(__printf__, 1, 2)));
170 static void maybe_warnx(const char *fmt, ...)
171 __attribute__((__format__(__printf__, 1, 2)));
172 static enum filetype file_gettype(u_char *);
174 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
176 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
177 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
178 static off_t file_compress(char *, char *, size_t);
179 static off_t file_uncompress(char *, char *, size_t);
180 static void handle_pathname(char *);
181 static void handle_file(char *, struct stat *);
182 static void handle_stdin(void);
183 static void handle_stdout(void);
184 static void print_ratio(off_t, off_t, FILE *);
185 static void print_list(int fd, off_t, const char *, time_t);
186 static void usage(void);
187 static void display_version(void);
188 static const suffixes_t *check_suffix(char *, int);
191 #define unlink_input(f, sb) unlink(f)
193 static off_t cat_fd(unsigned char *, ssize_t, off_t *, int fd);
194 static void prepend_gzip(char *, int *, char ***);
195 static void handle_dir(char *);
196 static void print_verbage(const char *, const char *, off_t, off_t);
197 static void print_test(const char *, int);
198 static void copymodes(const char *, struct stat *);
199 static int check_outfile(const char *outfile, struct stat *sb);
202 #ifndef NO_BZIP2_SUPPORT
203 static off_t unbzip2(int, int, char *, size_t, off_t *);
206 #ifndef NO_COMPRESS_SUPPORT
207 static FILE *zdopen(int);
208 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
211 int main(int, char *p[]);
214 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
216 static const struct option longopts[] = {
217 { "stdout", no_argument, 0, 'c' },
218 { "to-stdout", no_argument, 0, 'c' },
219 { "decompress", no_argument, 0, 'd' },
220 { "uncompress", no_argument, 0, 'd' },
221 { "force", no_argument, 0, 'f' },
222 { "help", no_argument, 0, 'h' },
223 { "list", no_argument, 0, 'l' },
224 { "no-name", no_argument, 0, 'n' },
225 { "name", no_argument, 0, 'N' },
226 { "quiet", no_argument, 0, 'q' },
227 { "recursive", no_argument, 0, 'r' },
228 { "suffix", required_argument, 0, 'S' },
229 { "test", no_argument, 0, 't' },
230 { "verbose", no_argument, 0, 'v' },
231 { "version", no_argument, 0, 'V' },
232 { "fast", no_argument, 0, '1' },
233 { "best", no_argument, 0, '9' },
236 * This is what else GNU gzip implements. --ascii isn't useful
237 * on NetBSD, and I don't care to have a --license.
239 { "ascii", no_argument, 0, 'a' },
240 { "license", no_argument, 0, 'L' },
242 { NULL, no_argument, 0, 0 },
247 main(int argc, char **argv)
249 const char *progname = getprogname();
256 /* XXX set up signals */
259 if ((gzip = getenv("GZIP")) != NULL)
260 prepend_gzip(gzip, &argc, &argv);
265 * handle being called `gunzip', `zcat' and `gzcat'
267 if (strcmp(progname, "gunzip") == 0)
269 else if (strcmp(progname, "zcat") == 0 ||
270 strcmp(progname, "gzcat") == 0)
274 #define OPT_LIST "cdhHltV123456789"
276 #define OPT_LIST "cdfhHlnNqrS:tvV123456789"
279 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
294 case '1': case '2': case '3':
295 case '4': case '5': case '6':
296 case '7': case '8': case '9':
318 len = strlen(optarg);
320 suffixes[0].zipped = optarg;
321 suffixes[0].ziplen = len;
323 suffixes[NUM_SUFFIXES - 1].zipped = "";
324 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
345 if (dflag) /* stdin mode */
347 else /* stdout mode */
351 handle_pathname(argv[0]);
355 if (qflag == 0 && lflag && argc > 1)
356 print_list(-1, 0, "(totals)", 0);
361 /* maybe print a warning */
363 maybe_warn(const char *fmt, ...)
376 /* ... without an errno. */
378 maybe_warnx(const char *fmt, ...)
391 /* maybe print an error */
393 maybe_err(const char *fmt, ...)
405 #ifndef NO_BZIP2_SUPPORT
406 /* ... without an errno. */
408 maybe_errx(const char *fmt, ...)
422 /* split up $GZIP and prepend it to the argument list */
424 prepend_gzip(char *gzip, int *argc, char ***argv)
426 char *s, **nargv, **ac;
429 /* scan how many arguments there are */
430 for (s = gzip; *s; s++) {
431 if (*s == ' ' || *s == '\t')
435 if (*s == ' ' || *s == '\t')
447 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
451 /* stash this away */
454 /* copy the program name first */
456 nargv[i++] = *(ac++);
458 /* take a copy of $GZIP and add it to the array */
463 if (*s == ' ' || *s == '\t')
467 if (*s == ' ' || *s == '\t') {
473 /* copy the original arguments and a NULL */
475 nargv[i++] = *(ac++);
480 /* compress input to output. Return bytes read, -1 on error */
482 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
485 char *outbufp, *inbufp;
486 off_t in_tot = 0, out_tot = 0;
491 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
496 outbufp = malloc(BUFLEN);
497 inbufp = malloc(BUFLEN);
498 if (outbufp == NULL || inbufp == NULL) {
499 maybe_err("malloc failed");
503 memset(&z, 0, sizeof z);
509 memcpy(outbufp, header, sizeof header);
517 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
518 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
519 *origname ? ORIG_NAME : 0,
522 (mtime >> 16) & 0xff,
523 (mtime >> 24) & 0xff,
524 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
527 /* this need PATH_MAX > BUFLEN ... */
528 maybe_err("snprintf");
533 z.next_out = outbufp + i;
534 z.avail_out = BUFLEN - i;
536 error = deflateInit2(&z, numflag, Z_DEFLATED,
537 -MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
539 maybe_warnx("deflateInit2 failed");
544 crc = crc32(0L, Z_NULL, 0);
546 if (z.avail_out == 0) {
547 if (write(out, outbufp, BUFLEN) != BUFLEN) {
554 z.next_out = outbufp;
555 z.avail_out = BUFLEN;
558 if (z.avail_in == 0) {
559 in_size = read(in, inbufp, BUFLEN);
568 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
571 z.avail_in = in_size;
574 error = deflate(&z, Z_NO_FLUSH);
575 if (error != Z_OK && error != Z_STREAM_END) {
576 maybe_warnx("deflate failed");
586 error = deflate(&z, Z_FINISH);
587 if (error != Z_OK && error != Z_STREAM_END) {
588 maybe_warnx("deflate failed");
593 len = (char *)z.next_out - outbufp;
595 if (write(out, outbufp, len) != len) {
601 z.next_out = outbufp;
602 z.avail_out = BUFLEN;
604 if (error == Z_STREAM_END)
608 if (deflateEnd(&z) != Z_OK) {
609 maybe_warnx("deflateEnd failed");
614 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
616 (int)(crc >> 8) & 0xff,
617 (int)(crc >> 16) & 0xff,
618 (int)(crc >> 24) & 0xff,
620 (int)(in_tot >> 8) & 0xff,
621 (int)(in_tot >> 16) & 0xff,
622 (int)(in_tot >> 24) & 0xff);
624 maybe_err("snprintf");
625 if (write(out, outbufp, i) != i) {
642 * uncompress input to output then close the input. return the
643 * uncompressed size written, and put the compressed sized read
647 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
648 const char *filename)
651 char *outbufp, *inbufp;
652 off_t out_tot = prelen, in_tot = 0;
653 uint32_t out_sub_tot = 0;
671 } state = GZSTATE_MAGIC0;
672 int flags = 0, skip_count = 0;
673 int error = 0, done_reading = 0;
677 #define ADVANCE() { z.next_in++; z.avail_in--; }
679 if ((outbufp = malloc(BUFLEN)) == NULL) {
680 maybe_err("malloc failed");
683 if ((inbufp = malloc(BUFLEN)) == NULL) {
684 maybe_err("malloc failed");
688 memset(&z, 0, sizeof z);
691 z.avail_out = BUFLEN;
692 z.next_out = outbufp;
699 if (z.avail_in == 0 && done_reading == 0) {
700 ssize_t in_size = read(in, inbufp, BUFLEN);
705 print_test(filename, 0);
707 maybe_warn("failed to read stdin");
710 } else if (in_size == 0)
713 z.avail_in = in_size;
718 if (z.avail_in == 0) {
719 if (done_reading && state != GZSTATE_MAGIC0)
720 maybe_warnx("%s: unexpected end of file",
726 if (*z.next_in != GZIP_MAGIC0) {
727 maybe_warnx("input not gziped (MAGIC0)");
734 crc = crc32(0L, Z_NULL, 0);
738 if (*z.next_in != GZIP_MAGIC1 &&
739 *z.next_in != GZIP_OMAGIC1) {
740 maybe_warnx("input not gziped (MAGIC1)");
749 if (*z.next_in != Z_DEFLATED) {
750 maybe_warnx("unknown compression method");
765 case GZSTATE_SKIPPING:
766 if (skip_count > 0) {
774 if ((flags & EXTRA_FIELD) == 0) {
775 state = GZSTATE_ORIGNAME;
778 skip_count = *z.next_in;
784 skip_count |= ((*z.next_in) << 8);
790 if (skip_count > 0) {
797 case GZSTATE_ORIGNAME:
798 if ((flags & ORIG_NAME) == 0) {
807 case GZSTATE_COMMENT:
808 if ((flags & COMMENT) == 0) {
817 case GZSTATE_HEAD_CRC1:
818 if (flags & HEAD_CRC)
825 case GZSTATE_HEAD_CRC2:
826 if (skip_count > 0) {
834 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
835 maybe_warnx("failed to inflateInit");
843 error = inflate(&z, Z_FINISH);
844 /* Z_BUF_ERROR goes with Z_FINISH... */
845 if (error != Z_STREAM_END && error != Z_BUF_ERROR)
846 /* Just need more input */
848 wr = BUFLEN - z.avail_out;
851 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
854 /* don't write anything with -t */
857 write(out, outbufp, wr) != wr) {
858 maybe_warn("error writing to output");
867 if (error == Z_STREAM_END) {
872 z.next_out = outbufp;
873 z.avail_out = BUFLEN;
878 static int empty_buffer = 0;
881 if (z.avail_in < 4) {
882 if (!done_reading && empty_buffer++ < 4)
884 maybe_warnx("truncated input");
889 origcrc = ((unsigned)z.next_in[0] & 0xff) |
890 ((unsigned)z.next_in[1] & 0xff) << 8 |
891 ((unsigned)z.next_in[2] & 0xff) << 16 |
892 ((unsigned)z.next_in[3] & 0xff) << 24;
893 if (origcrc != crc) {
894 maybe_warnx("invalid compressed"
910 static int empty_buffer = 0;
913 if (z.avail_in < 4) {
914 if (!done_reading && empty_buffer++ < 4)
916 maybe_warnx("truncated input");
921 origlen = ((unsigned)z.next_in[0] & 0xff) |
922 ((unsigned)z.next_in[1] & 0xff) << 8 |
923 ((unsigned)z.next_in[2] & 0xff) << 16 |
924 ((unsigned)z.next_in[3] & 0xff) << 24;
926 if (origlen != out_sub_tot) {
927 maybe_warnx("invalid compressed"
928 " data--length error");
938 maybe_warnx("decompression error");
942 state = GZSTATE_MAGIC0;
949 if (state > GZSTATE_INIT)
954 print_test(filename, out_tot != -1);
968 * set the owner, mode, flags & utimes for a file
971 copymodes(const char *file, struct stat *sbp)
973 struct timeval times[2];
976 * If we have no info on the input, give this file some
977 * default values and return..
980 mode_t mask = umask(022);
982 (void)chmod(file, DEFFILEMODE & ~mask);
987 /* if the chown fails, remove set-id bits as-per compress(1) */
988 if (chown(file, sbp->st_uid, sbp->st_gid) < 0) {
990 maybe_warn("couldn't chown: %s", file);
991 sbp->st_mode &= ~(S_ISUID|S_ISGID);
994 /* we only allow set-id and the 9 normal permission bits */
995 sbp->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
996 if (chmod(file, sbp->st_mode) < 0)
997 maybe_warn("couldn't chmod: %s", file);
999 /* only try flags if they exist already */
1000 if (sbp->st_flags != 0 && chflags(file, sbp->st_flags) < 0)
1001 maybe_warn("couldn't chflags: %s", file);
1003 TIMESPEC_TO_TIMEVAL(×[0], &sbp->st_atimespec);
1004 TIMESPEC_TO_TIMEVAL(×[1], &sbp->st_mtimespec);
1005 if (utimes(file, times) < 0)
1006 maybe_warn("couldn't utimes: %s", file);
1010 /* what sort of file is this? */
1011 static enum filetype
1012 file_gettype(u_char *buf)
1015 if (buf[0] == GZIP_MAGIC0 &&
1016 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1019 #ifndef NO_BZIP2_SUPPORT
1020 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1021 buf[3] >= '0' && buf[3] <= '9')
1025 #ifndef NO_COMPRESS_SUPPORT
1026 if (memcmp(buf, Z_MAGIC, 2) == 0)
1034 /* check the outfile is OK. */
1036 check_outfile(const char *outfile, struct stat *sb)
1040 if (lflag == 0 && stat(outfile, sb) == 0) {
1043 else if (isatty(STDIN_FILENO)) {
1044 char ans[10] = { 'n', '\0' }; /* default */
1046 fprintf(stderr, "%s already exists -- do you wish to "
1047 "overwrite (y or n)? " , outfile);
1048 (void)fgets(ans, sizeof(ans) - 1, stdin);
1049 if (ans[0] != 'y' && ans[0] != 'Y') {
1050 fprintf(stderr, "\tnot overwritting\n");
1055 maybe_warnx("%s already exists -- skipping", outfile);
1063 unlink_input(const char *file, struct stat *sb)
1067 if (stat(file, &nsb) != 0)
1068 /* Must be gone alrady */
1070 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1071 /* Definitely a different file */
1077 static const suffixes_t *
1078 check_suffix(char *file, int xlate)
1080 const suffixes_t *s;
1081 int len = strlen(file);
1084 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1085 /* if it doesn't fit in "a.suf", don't bother */
1086 if (s->ziplen >= len)
1088 sp = file + len - s->ziplen;
1089 if (strcmp(s->zipped, sp) != 0)
1092 strcpy(sp, s->normal);
1099 * compress the given file: create a corresponding .gz file and remove the
1103 file_compress(char *file, char *outfile, size_t outsize)
1109 struct stat isb, osb;
1110 const suffixes_t *suff;
1113 in = open(file, O_RDONLY);
1115 maybe_warn("can't open %s", file);
1121 if (stat(file, &isb) == 0) {
1122 if (isb.st_nlink > 1 && fflag == 0) {
1123 maybe_warnx("%s has %d other link%s -- "
1124 "skipping", file, isb.st_nlink - 1,
1125 isb.st_nlink == 1 ? "" : "s");
1131 if (fflag == 0 && (suff = check_suffix(file, 0))
1132 && suff->zipped[0] != 0) {
1133 maybe_warnx("%s already has %s suffix -- unchanged",
1134 file, suff->zipped);
1140 /* Add (usually) .gz to filename */
1141 if ((size_t)snprintf(outfile, outsize, "%s%s",
1142 file, suffixes[0].zipped) >= outsize)
1143 memcpy(outfile - suffixes[0].ziplen - 1,
1144 suffixes[0].zipped, suffixes[0].ziplen + 1);
1147 if (check_outfile(outfile, &osb) == 0) {
1155 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1157 maybe_warn("could not create output: %s", outfile);
1162 out = STDOUT_FILENO;
1164 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1169 * If there was an error, insize will be -1.
1170 * If we compressed to stdout, just return the size.
1171 * Otherwise stat the file and check it is the correct size.
1172 * We only blow away the file if we can stat the output and it
1173 * has the expected size.
1176 return insize == -1 ? -1 : size;
1178 if (close(out) == -1)
1179 maybe_warn("couldn't close ouput");
1182 if (stat(outfile, &osb) < 0) {
1183 maybe_warn("couldn't stat: %s", outfile);
1187 if (osb.st_size != size) {
1188 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1189 " != %" PRIdOFF "), deleting",
1190 outfile, osb.st_size, size);
1194 copymodes(outfile, &isb);
1197 /* output is good, ok to delete input */
1198 unlink_input(file, &isb);
1203 maybe_warnx("leaving original %s", file);
1209 /* uncompress the given file and remove the original */
1211 file_uncompress(char *file, char *outfile, size_t outsize)
1213 struct stat isb, osb;
1216 unsigned char header1[4];
1217 enum filetype method;
1220 time_t timestamp = 0;
1221 unsigned char name[PATH_MAX + 1];
1224 /* gather the old name info */
1226 fd = open(file, O_RDONLY);
1228 maybe_warn("can't open %s", file);
1232 strlcpy(outfile, file, outsize);
1233 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1234 maybe_warnx("%s: unknown suffix -- ignored", file);
1238 rbytes = read(fd, header1, sizeof header1);
1239 if (rbytes != sizeof header1) {
1240 /* we don't want to fail here. */
1246 maybe_warn("can't read %s", file);
1248 maybe_warnx("%s: unexpected end of file", file);
1252 method = file_gettype(header1);
1255 if (fflag == 0 && method == FT_UNKNOWN) {
1256 maybe_warnx("%s: not in gzip format", file);
1263 if (method == FT_GZIP && Nflag) {
1264 unsigned char ts[4]; /* timestamp */
1266 if (pread(fd, ts, sizeof ts, GZIP_TIMESTAMP) != sizeof ts) {
1268 maybe_warn("can't read %s", file);
1271 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1273 if (header1[3] & ORIG_NAME) {
1274 rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1276 maybe_warn("can't read %s", file);
1280 /* preserve original directory name */
1281 char *dp = strrchr(file, '/');
1286 snprintf(outfile, outsize, "%.*s%.*s",
1288 file, (int) rbytes, name);
1293 lseek(fd, 0, SEEK_SET);
1295 if (cflag == 0 || lflag) {
1296 if (fstat(fd, &isb) != 0)
1299 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1300 maybe_warnx("%s has %d other links -- skipping",
1301 file, isb.st_nlink - 1);
1304 if (nflag == 0 && timestamp)
1305 isb.st_mtime = timestamp;
1306 if (check_outfile(outfile, &osb) == 0)
1311 if (cflag == 0 && lflag == 0) {
1312 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1313 if (zfd == STDOUT_FILENO) {
1314 /* We won't close STDOUT_FILENO later... */
1316 close(STDOUT_FILENO);
1319 maybe_warn("can't open %s", outfile);
1323 zfd = STDOUT_FILENO;
1325 #ifndef NO_BZIP2_SUPPORT
1326 if (method == FT_BZIP2) {
1330 maybe_warnx("no -l with bzip2 files");
1334 size = unbzip2(fd, zfd, NULL, 0, NULL);
1338 #ifndef NO_COMPRESS_SUPPORT
1339 if (method == FT_Z) {
1344 maybe_warnx("no -l with Lempel-Ziv files");
1348 if ((in = zdopen(fd)) == NULL) {
1349 maybe_warn("zdopen for read: %s", file);
1353 out = fdopen(dup(zfd), "w");
1355 maybe_warn("fdopen for write: %s", outfile);
1360 size = zuncompress(in, out, NULL, 0, NULL);
1361 /* need to fclose() if ferror() is true... */
1362 if (ferror(in) | fclose(in)) {
1363 maybe_warn("failed infile fclose");
1367 if (fclose(out) != 0) {
1368 maybe_warn("failed outfile fclose");
1376 if (method == FT_UNKNOWN) {
1378 maybe_warnx("no -l for unknown filetypes");
1381 size = cat_fd(NULL, 0, NULL, fd);
1386 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1388 return -1; /* XXX */
1391 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1395 maybe_warn("couldn't close input");
1396 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1397 maybe_warn("couldn't close output");
1402 maybe_warnx("%s: uncompress failed", file);
1406 /* if testing, or we uncompressed to stdout, this is all we need */
1411 /* if we are uncompressing to stdin, don't remove the file. */
1416 * if we create a file...
1419 * if we can't stat the file don't remove the file.
1421 if (stat(outfile, &osb) < 0) {
1422 maybe_warn("couldn't stat (leaving original): %s",
1426 if (osb.st_size != size) {
1427 maybe_warn("stat gave different size: %" PRIdOFF
1428 " != %" PRIdOFF " (leaving original)",
1433 unlink_input(file, &isb);
1435 copymodes(outfile, &isb);
1442 if (zfd != -1 && zfd != STDOUT_FILENO)
1449 cat_fd(unsigned char * prepend, ssize_t count, off_t *gsizep, int fd)
1456 if (write(STDOUT_FILENO, prepend, count) != count) {
1457 maybe_warn("write to stdout");
1461 rv = read(fd, buf, sizeof buf);
1465 maybe_warn("read from fd %d", fd);
1469 if (write(STDOUT_FILENO, buf, rv) != rv) {
1470 maybe_warn("write to stdout");
1485 unsigned char header1[4];
1487 enum filetype method;
1488 #ifndef NO_COMPRESS_SUPPORT
1493 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1494 maybe_warnx("standard input is a terminal -- ignoring");
1502 /* XXX could read the whole file, etc. */
1503 if (fstat(STDIN_FILENO, &isb) < 0) {
1504 maybe_warn("fstat");
1507 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1511 if (read(STDIN_FILENO, header1, sizeof header1) != sizeof header1) {
1512 maybe_warn("can't read stdin");
1516 method = file_gettype(header1);
1521 maybe_warnx("unknown compression format");
1524 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1528 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1529 header1, sizeof header1, &gsize, "(stdin)");
1531 #ifndef NO_BZIP2_SUPPORT
1533 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1534 header1, sizeof header1, &gsize);
1537 #ifndef NO_COMPRESS_SUPPORT
1539 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1540 maybe_warnx("zopen of stdin");
1544 usize = zuncompress(in, stdout, header1, sizeof header1, &gsize);
1551 if (vflag && !tflag && usize != -1 && gsize != -1)
1552 print_verbage(NULL, NULL, usize, gsize);
1563 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1564 maybe_warnx("standard output is a terminal -- ignoring");
1568 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", 0);
1571 if (vflag && !tflag && usize != -1 && gsize != -1)
1572 print_verbage(NULL, NULL, usize, gsize);
1576 /* do what is asked for, for the path name */
1578 handle_pathname(char *path)
1580 char *opath = path, *s = NULL;
1585 /* check for stdout/stdin */
1586 if (path[0] == '-' && path[1] == '\0') {
1595 if (stat(path, &sb) < 0) {
1596 /* lets try <path>.gz if we're decompressing */
1597 if (dflag && s == NULL && errno == ENOENT) {
1599 slen = suffixes[0].ziplen;
1600 s = malloc(len + slen + 1);
1602 maybe_err("malloc");
1603 memcpy(s, path, len);
1604 memcpy(s + len, suffixes[0].zipped, slen + 1);
1608 maybe_warn("can't stat: %s", opath);
1612 if (S_ISDIR(sb.st_mode)) {
1618 maybe_warnx("%s is a directory", path);
1622 if (S_ISREG(sb.st_mode))
1623 handle_file(path, &sb);
1625 maybe_warnx("%s is not a regular file", path);
1632 /* compress/decompress a file */
1634 handle_file(char *file, struct stat *sbp)
1637 char outfile[PATH_MAX];
1641 usize = file_uncompress(file, outfile, sizeof(outfile));
1644 gsize = sbp->st_size;
1646 gsize = file_compress(file, outfile, sizeof(outfile));
1649 usize = sbp->st_size;
1654 if (vflag && !tflag)
1655 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1660 /* this is used with -r to recursively descend directories */
1662 handle_dir(char *dir)
1670 fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
1672 warn("couldn't fts_open %s", dir);
1676 while ((entry = fts_read(fts))) {
1677 switch(entry->fts_info) {
1685 maybe_warn("%s", entry->fts_path);
1688 handle_file(entry->fts_name, entry->fts_statp);
1691 (void)fts_close(fts);
1695 /* print a ratio - size reduction as a fraction of uncompressed size */
1697 print_ratio(off_t in, off_t out, FILE *where)
1699 int percent10; /* 10 * percent */
1707 * Output is more than double size of input! print -99.9%
1708 * Quite possibly we've failed to get the original size.
1713 * We only need 12 bits of result from the final division,
1714 * so reduce the values until a 32bit division will suffice.
1716 while (in > 0x100000) {
1721 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1726 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1727 /* Move the '.' to before the last digit */
1728 buff[len - 1] = buff[len - 2];
1729 buff[len - 2] = '.';
1730 fprintf(where, "%5s%%", buff);
1734 /* print compression statistics, and the new name (if there is one!) */
1736 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1739 fprintf(stderr, "%s:%s ", file,
1740 strlen(file) < 7 ? "\t\t" : "\t");
1741 print_ratio(usize, gsize, stderr);
1743 fprintf(stderr, " -- replaced with %s", nfile);
1744 fprintf(stderr, "\n");
1748 /* print test results */
1750 print_test(const char *file, int ok)
1753 if (exit_value == 0 && ok == 0)
1755 fprintf(stderr, "%s:%s %s\n", file,
1756 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1761 /* print a file's info ala --list */
1763 compressed uncompressed ratio uncompressed_name
1764 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1767 print_list(int fd, off_t out, const char *outfile, time_t ts)
1769 static int first = 1;
1771 static off_t in_tot, out_tot;
1780 printf("method crc date time ");
1783 printf(" compressed uncompressed "
1784 "ratio uncompressed_name\n");
1796 /* read the last 4 bytes - this is the uncompressed size */
1797 rv = lseek(fd, (off_t)(-8), SEEK_END);
1799 unsigned char buf[8];
1802 if (read(fd, (char *)buf, sizeof(buf)) != sizeof(buf))
1803 maybe_warn("read of uncompressed size");
1804 usize = buf[4] | buf[5] << 8 | buf[6] << 16 | buf[7] << 24;
1807 crc = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;
1813 if (vflag && fd == -1)
1816 char *date = ctime(&ts);
1818 /* skip the day, 1/100th second, and year */
1821 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
1826 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
1827 print_ratio(in, out, stdout);
1828 printf(" %s\n", outfile);
1831 /* display the usage of NetBSD gzip */
1836 fprintf(stderr, "%s\n", gzip_version);
1838 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n"
1840 " -c --stdout write to stdout, keep original files\n"
1842 " -d --decompress uncompress files\n"
1844 " -f --force force overwriting & compress links\n"
1845 " -h --help display this help\n"
1846 " -n --no-name don't save original file name or time stamp\n"
1847 " -N --name save or restore original file name and time stamp\n"
1848 " -q --quiet output no warnings\n"
1849 " -r --recursive recursively compress files in directories\n"
1850 " -S .suf use suffix .suf instead of .gz\n"
1852 " -t --test test compressed file\n"
1853 " -v --verbose print extra statistics\n"
1854 " -V --version display program version\n"
1855 " -1 --fast fastest (worst) compression\n"
1856 " -2 .. -8 set compression level\n"
1857 " -9 --best best (slowest) compression\n",
1865 /* display the version of NetBSD gzip */
1867 display_version(void)
1870 fprintf(stderr, "%s\n", gzip_version);
1874 #ifndef NO_BZIP2_SUPPORT
1875 #include "unbzip2.c"
1877 #ifndef NO_COMPRESS_SUPPORT
1878 #include "zuncompress.c"