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.3 2004/10/30 18:48:31 dillon 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
71 /* what type of file are we dealing with */
74 #ifndef NO_BZIP2_SUPPORT
77 #ifndef NO_COMPRESS_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 #define GZ_SUFFIX ".gz"
98 #define BUFLEN (64 * 1024)
100 #define GZIP_MAGIC0 0x1F
101 #define GZIP_MAGIC1 0x8B
102 #define GZIP_OMAGIC1 0x9E
104 #define GZIP_TIMESTAMP (off_t)4
105 #define GZIP_ORIGNAME (off_t)10
107 #define HEAD_CRC 0x02
108 #define EXTRA_FIELD 0x04
109 #define ORIG_NAME 0x08
112 #define OS_CODE 3 /* Unix */
117 const char *normal; /* for unzip - must not be longer than zipped */
119 static suffixes_t suffixes[] = {
120 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
121 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
123 SUFFIX(GZ_SUFFIX, ""),
128 SUFFIX(".taz", ".tar"),
129 SUFFIX(".tgz", ".tar"),
130 #ifndef NO_BZIP2_SUPPORT
131 SUFFIX(BZ2_SUFFIX, ""),
133 #ifndef NO_COMPRESS_SUPPORT
134 SUFFIX(Z_SUFFIX, ""),
136 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
140 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
142 static const char gzip_version[] = "NetBSD gzip 20040830";
144 static int cflag; /* stdout mode */
145 static int dflag; /* decompress mode */
146 static int lflag; /* list mode */
147 static int numflag = 6; /* gzip -1..-9 value */
150 static int fflag; /* force mode */
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);
195 #define unlink_input(f, sb) unlink(f)
197 static off_t cat_fd(unsigned char *, ssize_t, off_t *, int fd);
198 static void prepend_gzip(char *, int *, char ***);
199 static void handle_dir(char *);
200 static void print_verbage(const char *, const char *, off_t, off_t);
201 static void print_test(const char *, int);
202 static void copymodes(const char *, struct stat *);
203 static int check_outfile(const char *outfile, struct stat *sb);
206 #ifndef NO_BZIP2_SUPPORT
207 static off_t unbzip2(int, int, char *, size_t, off_t *);
210 #ifndef NO_COMPRESS_SUPPORT
211 static FILE *zdopen(int);
212 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
215 int main(int, char *p[]);
218 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
220 static const struct option longopts[] = {
221 { "stdout", no_argument, 0, 'c' },
222 { "to-stdout", no_argument, 0, 'c' },
223 { "decompress", no_argument, 0, 'd' },
224 { "uncompress", no_argument, 0, 'd' },
225 { "force", no_argument, 0, 'f' },
226 { "help", no_argument, 0, 'h' },
227 { "list", no_argument, 0, 'l' },
228 { "no-name", no_argument, 0, 'n' },
229 { "name", no_argument, 0, 'N' },
230 { "quiet", no_argument, 0, 'q' },
231 { "recursive", no_argument, 0, 'r' },
232 { "suffix", required_argument, 0, 'S' },
233 { "test", no_argument, 0, 't' },
234 { "verbose", no_argument, 0, 'v' },
235 { "version", no_argument, 0, 'V' },
236 { "fast", no_argument, 0, '1' },
237 { "best", no_argument, 0, '9' },
240 * This is what else GNU gzip implements. --ascii isn't useful
241 * on NetBSD, and I don't care to have a --license.
243 { "ascii", no_argument, 0, 'a' },
244 { "license", no_argument, 0, 'L' },
246 { NULL, no_argument, 0, 0 },
251 main(int argc, char **argv)
253 const char *progname = getprogname();
260 /* XXX set up signals */
263 if ((gzip = getenv("GZIP")) != NULL)
264 prepend_gzip(gzip, &argc, &argv);
269 * handle being called `gunzip', `zcat' and `gzcat'
271 if (strcmp(progname, "gunzip") == 0)
273 else if (strcmp(progname, "zcat") == 0 ||
274 strcmp(progname, "gzcat") == 0)
278 #define OPT_LIST "cdhHltV123456789"
280 #define OPT_LIST "cdfhHlnNqrS:tvV123456789"
283 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
298 case '1': case '2': case '3':
299 case '4': case '5': case '6':
300 case '7': case '8': case '9':
322 len = strlen(optarg);
324 suffixes[0].zipped = optarg;
325 suffixes[0].ziplen = len;
327 suffixes[NUM_SUFFIXES - 1].zipped = "";
328 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
349 if (dflag) /* stdin mode */
351 else /* stdout mode */
355 handle_pathname(argv[0]);
359 if (qflag == 0 && lflag && argc > 1)
360 print_list(-1, 0, "(totals)", 0);
365 /* maybe print a warning */
367 maybe_warn(const char *fmt, ...)
380 /* ... without an errno. */
382 maybe_warnx(const char *fmt, ...)
395 /* maybe print an error */
397 maybe_err(const char *fmt, ...)
409 #ifndef NO_BZIP2_SUPPORT
410 /* ... without an errno. */
412 maybe_errx(const char *fmt, ...)
426 /* split up $GZIP and prepend it to the argument list */
428 prepend_gzip(char *gzip, int *argc, char ***argv)
430 char *s, **nargv, **ac;
433 /* scan how many arguments there are */
434 for (s = gzip; *s; s++) {
435 if (*s == ' ' || *s == '\t')
439 if (*s == ' ' || *s == '\t')
451 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
455 /* stash this away */
458 /* copy the program name first */
460 nargv[i++] = *(ac++);
462 /* take a copy of $GZIP and add it to the array */
467 if (*s == ' ' || *s == '\t')
471 if (*s == ' ' || *s == '\t') {
477 /* copy the original arguments and a NULL */
479 nargv[i++] = *(ac++);
484 /* compress input to output. Return bytes read, -1 on error */
486 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
489 char *outbufp, *inbufp;
490 off_t in_tot = 0, out_tot = 0;
495 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
500 outbufp = malloc(BUFLEN);
501 inbufp = malloc(BUFLEN);
502 if (outbufp == NULL || inbufp == NULL) {
503 maybe_err("malloc failed");
507 memset(&z, 0, sizeof z);
513 memcpy(outbufp, header, sizeof header);
521 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
522 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
523 *origname ? ORIG_NAME : 0,
526 (mtime >> 16) & 0xff,
527 (mtime >> 24) & 0xff,
528 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
531 /* this need PATH_MAX > BUFLEN ... */
532 maybe_err("snprintf");
537 z.next_out = outbufp + i;
538 z.avail_out = BUFLEN - i;
540 error = deflateInit2(&z, numflag, Z_DEFLATED,
541 -MAX_WBITS, 8, Z_DEFAULT_STRATEGY);
543 maybe_warnx("deflateInit2 failed");
548 crc = crc32(0L, Z_NULL, 0);
550 if (z.avail_out == 0) {
551 if (write(out, outbufp, BUFLEN) != BUFLEN) {
558 z.next_out = outbufp;
559 z.avail_out = BUFLEN;
562 if (z.avail_in == 0) {
563 in_size = read(in, inbufp, BUFLEN);
572 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
575 z.avail_in = in_size;
578 error = deflate(&z, Z_NO_FLUSH);
579 if (error != Z_OK && error != Z_STREAM_END) {
580 maybe_warnx("deflate failed");
590 error = deflate(&z, Z_FINISH);
591 if (error != Z_OK && error != Z_STREAM_END) {
592 maybe_warnx("deflate failed");
597 len = (char *)z.next_out - outbufp;
599 if (write(out, outbufp, len) != len) {
605 z.next_out = outbufp;
606 z.avail_out = BUFLEN;
608 if (error == Z_STREAM_END)
612 if (deflateEnd(&z) != Z_OK) {
613 maybe_warnx("deflateEnd failed");
618 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
620 (int)(crc >> 8) & 0xff,
621 (int)(crc >> 16) & 0xff,
622 (int)(crc >> 24) & 0xff,
624 (int)(in_tot >> 8) & 0xff,
625 (int)(in_tot >> 16) & 0xff,
626 (int)(in_tot >> 24) & 0xff);
628 maybe_err("snprintf");
629 if (write(out, outbufp, i) != i) {
646 * uncompress input to output then close the input. return the
647 * uncompressed size written, and put the compressed sized read
651 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
652 const char *filename)
655 char *outbufp, *inbufp;
656 off_t out_tot = prelen, in_tot = 0;
657 uint32_t out_sub_tot = 0;
675 } state = GZSTATE_MAGIC0;
676 int flags = 0, skip_count = 0;
677 int error = 0, done_reading = 0;
681 #define ADVANCE() { z.next_in++; z.avail_in--; }
683 if ((outbufp = malloc(BUFLEN)) == NULL) {
684 maybe_err("malloc failed");
687 if ((inbufp = malloc(BUFLEN)) == NULL) {
688 maybe_err("malloc failed");
692 memset(&z, 0, sizeof z);
695 z.avail_out = BUFLEN;
696 z.next_out = outbufp;
703 if (z.avail_in == 0 && done_reading == 0) {
704 ssize_t in_size = read(in, inbufp, BUFLEN);
709 print_test(filename, 0);
711 maybe_warn("failed to read stdin");
714 } else if (in_size == 0)
717 z.avail_in = in_size;
722 if (z.avail_in == 0) {
723 if (done_reading && state != GZSTATE_MAGIC0)
724 maybe_warnx("%s: unexpected end of file",
730 if (*z.next_in != GZIP_MAGIC0) {
731 maybe_warnx("input not gziped (MAGIC0)");
738 crc = crc32(0L, Z_NULL, 0);
742 if (*z.next_in != GZIP_MAGIC1 &&
743 *z.next_in != GZIP_OMAGIC1) {
744 maybe_warnx("input not gziped (MAGIC1)");
753 if (*z.next_in != Z_DEFLATED) {
754 maybe_warnx("unknown compression method");
769 case GZSTATE_SKIPPING:
770 if (skip_count > 0) {
778 if ((flags & EXTRA_FIELD) == 0) {
779 state = GZSTATE_ORIGNAME;
782 skip_count = *z.next_in;
788 skip_count |= ((*z.next_in) << 8);
794 if (skip_count > 0) {
801 case GZSTATE_ORIGNAME:
802 if ((flags & ORIG_NAME) == 0) {
811 case GZSTATE_COMMENT:
812 if ((flags & COMMENT) == 0) {
821 case GZSTATE_HEAD_CRC1:
822 if (flags & HEAD_CRC)
829 case GZSTATE_HEAD_CRC2:
830 if (skip_count > 0) {
838 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
839 maybe_warnx("failed to inflateInit");
847 error = inflate(&z, Z_FINISH);
848 /* Z_BUF_ERROR goes with Z_FINISH... */
849 if (error != Z_STREAM_END && error != Z_BUF_ERROR)
850 /* Just need more input */
852 wr = BUFLEN - z.avail_out;
855 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
858 /* don't write anything with -t */
861 write(out, outbufp, wr) != wr) {
862 maybe_warn("error writing to output");
871 if (error == Z_STREAM_END) {
876 z.next_out = outbufp;
877 z.avail_out = BUFLEN;
882 static int empty_buffer = 0;
885 if (z.avail_in < 4) {
886 if (!done_reading && empty_buffer++ < 4)
888 maybe_warnx("truncated input");
893 origcrc = ((unsigned)z.next_in[0] & 0xff) |
894 ((unsigned)z.next_in[1] & 0xff) << 8 |
895 ((unsigned)z.next_in[2] & 0xff) << 16 |
896 ((unsigned)z.next_in[3] & 0xff) << 24;
897 if (origcrc != crc) {
898 maybe_warnx("invalid compressed"
914 static int empty_buffer = 0;
917 if (z.avail_in < 4) {
918 if (!done_reading && empty_buffer++ < 4)
920 maybe_warnx("truncated input");
925 origlen = ((unsigned)z.next_in[0] & 0xff) |
926 ((unsigned)z.next_in[1] & 0xff) << 8 |
927 ((unsigned)z.next_in[2] & 0xff) << 16 |
928 ((unsigned)z.next_in[3] & 0xff) << 24;
930 if (origlen != out_sub_tot) {
931 maybe_warnx("invalid compressed"
932 " data--length error");
942 maybe_warnx("decompression error");
946 state = GZSTATE_MAGIC0;
953 if (state > GZSTATE_INIT)
958 print_test(filename, out_tot != -1);
972 * set the owner, mode, flags & utimes for a file
975 copymodes(const char *file, struct stat *sbp)
977 struct timeval times[2];
980 * If we have no info on the input, give this file some
981 * default values and return..
984 mode_t mask = umask(022);
986 (void)chmod(file, DEFFILEMODE & ~mask);
991 /* if the chown fails, remove set-id bits as-per compress(1) */
992 if (chown(file, sbp->st_uid, sbp->st_gid) < 0) {
994 maybe_warn("couldn't chown: %s", file);
995 sbp->st_mode &= ~(S_ISUID|S_ISGID);
998 /* we only allow set-id and the 9 normal permission bits */
999 sbp->st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1000 if (chmod(file, sbp->st_mode) < 0)
1001 maybe_warn("couldn't chmod: %s", file);
1003 /* only try flags if they exist already */
1004 if (sbp->st_flags != 0 && chflags(file, sbp->st_flags) < 0)
1005 maybe_warn("couldn't chflags: %s", file);
1007 TIMESPEC_TO_TIMEVAL(×[0], &sbp->st_atimespec);
1008 TIMESPEC_TO_TIMEVAL(×[1], &sbp->st_mtimespec);
1009 if (utimes(file, times) < 0)
1010 maybe_warn("couldn't utimes: %s", file);
1014 /* what sort of file is this? */
1015 static enum filetype
1016 file_gettype(u_char *buf)
1019 if (buf[0] == GZIP_MAGIC0 &&
1020 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1023 #ifndef NO_BZIP2_SUPPORT
1024 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1025 buf[3] >= '0' && buf[3] <= '9')
1029 #ifndef NO_COMPRESS_SUPPORT
1030 if (memcmp(buf, Z_MAGIC, 2) == 0)
1038 /* check the outfile is OK. */
1040 check_outfile(const char *outfile, struct stat *sb)
1044 if (lflag == 0 && stat(outfile, sb) == 0) {
1047 else if (isatty(STDIN_FILENO)) {
1048 char ans[10] = { 'n', '\0' }; /* default */
1050 fprintf(stderr, "%s already exists -- do you wish to "
1051 "overwrite (y or n)? " , outfile);
1052 (void)fgets(ans, sizeof(ans) - 1, stdin);
1053 if (ans[0] != 'y' && ans[0] != 'Y') {
1054 fprintf(stderr, "\tnot overwritting\n");
1059 maybe_warnx("%s already exists -- skipping", outfile);
1067 unlink_input(const char *file, struct stat *sb)
1071 if (stat(file, &nsb) != 0)
1072 /* Must be gone alrady */
1074 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1075 /* Definitely a different file */
1081 static const suffixes_t *
1082 check_suffix(char *file, int xlate)
1084 const suffixes_t *s;
1085 int len = strlen(file);
1088 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1089 /* if it doesn't fit in "a.suf", don't bother */
1090 if (s->ziplen >= len)
1092 sp = file + len - s->ziplen;
1093 if (strcmp(s->zipped, sp) != 0)
1096 strcpy(sp, s->normal);
1103 * compress the given file: create a corresponding .gz file and remove the
1107 file_compress(char *file, char *outfile, size_t outsize)
1113 struct stat isb, osb;
1114 const suffixes_t *suff;
1117 in = open(file, O_RDONLY);
1119 maybe_warn("can't open %s", file);
1125 if (stat(file, &isb) == 0) {
1126 if (isb.st_nlink > 1 && fflag == 0) {
1127 maybe_warnx("%s has %d other link%s -- "
1128 "skipping", file, isb.st_nlink - 1,
1129 isb.st_nlink == 1 ? "" : "s");
1135 if (fflag == 0 && (suff = check_suffix(file, 0))
1136 && suff->zipped[0] != 0) {
1137 maybe_warnx("%s already has %s suffix -- unchanged",
1138 file, suff->zipped);
1144 /* Add (usually) .gz to filename */
1145 if ((size_t)snprintf(outfile, outsize, "%s%s",
1146 file, suffixes[0].zipped) >= outsize)
1147 memcpy(outfile - suffixes[0].ziplen - 1,
1148 suffixes[0].zipped, suffixes[0].ziplen + 1);
1151 if (check_outfile(outfile, &osb) == 0) {
1159 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1161 maybe_warn("could not create output: %s", outfile);
1166 out = STDOUT_FILENO;
1168 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1173 * If there was an error, insize will be -1.
1174 * If we compressed to stdout, just return the size.
1175 * Otherwise stat the file and check it is the correct size.
1176 * We only blow away the file if we can stat the output and it
1177 * has the expected size.
1180 return insize == -1 ? -1 : size;
1182 if (close(out) == -1)
1183 maybe_warn("couldn't close ouput");
1186 if (stat(outfile, &osb) < 0) {
1187 maybe_warn("couldn't stat: %s", outfile);
1191 if (osb.st_size != size) {
1192 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1193 " != %" PRIdOFF "), deleting",
1194 outfile, osb.st_size, size);
1198 copymodes(outfile, &isb);
1201 /* output is good, ok to delete input */
1202 unlink_input(file, &isb);
1207 maybe_warnx("leaving original %s", file);
1213 /* uncompress the given file and remove the original */
1215 file_uncompress(char *file, char *outfile, size_t outsize)
1217 struct stat isb, osb;
1220 unsigned char header1[4];
1221 enum filetype method;
1224 time_t timestamp = 0;
1225 unsigned char name[PATH_MAX + 1];
1228 /* gather the old name info */
1230 fd = open(file, O_RDONLY);
1232 maybe_warn("can't open %s", file);
1236 strlcpy(outfile, file, outsize);
1237 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1238 maybe_warnx("%s: unknown suffix -- ignored", file);
1242 rbytes = read(fd, header1, sizeof header1);
1243 if (rbytes != sizeof header1) {
1244 /* we don't want to fail here. */
1250 maybe_warn("can't read %s", file);
1252 maybe_warnx("%s: unexpected end of file", file);
1256 method = file_gettype(header1);
1259 if (fflag == 0 && method == FT_UNKNOWN) {
1260 maybe_warnx("%s: not in gzip format", file);
1267 if (method == FT_GZIP && Nflag) {
1268 unsigned char ts[4]; /* timestamp */
1270 if (pread(fd, ts, sizeof ts, GZIP_TIMESTAMP) != sizeof ts) {
1272 maybe_warn("can't read %s", file);
1275 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1277 if (header1[3] & ORIG_NAME) {
1278 rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1280 maybe_warn("can't read %s", file);
1284 /* preserve original directory name */
1285 char *dp = strrchr(file, '/');
1290 snprintf(outfile, outsize, "%.*s%.*s",
1292 file, (int) rbytes, name);
1297 lseek(fd, 0, SEEK_SET);
1299 if (cflag == 0 || lflag) {
1300 if (fstat(fd, &isb) != 0)
1303 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1304 maybe_warnx("%s has %d other links -- skipping",
1305 file, isb.st_nlink - 1);
1308 if (nflag == 0 && timestamp)
1309 isb.st_mtime = timestamp;
1310 if (check_outfile(outfile, &osb) == 0)
1315 if (cflag == 0 && lflag == 0) {
1316 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1317 if (zfd == STDOUT_FILENO) {
1318 /* We won't close STDOUT_FILENO later... */
1320 close(STDOUT_FILENO);
1323 maybe_warn("can't open %s", outfile);
1327 zfd = STDOUT_FILENO;
1329 #ifndef NO_BZIP2_SUPPORT
1330 if (method == FT_BZIP2) {
1334 maybe_warnx("no -l with bzip2 files");
1338 size = unbzip2(fd, zfd, NULL, 0, NULL);
1342 #ifndef NO_COMPRESS_SUPPORT
1343 if (method == FT_Z) {
1348 maybe_warnx("no -l with Lempel-Ziv files");
1352 if ((in = zdopen(fd)) == NULL) {
1353 maybe_warn("zdopen for read: %s", file);
1357 out = fdopen(dup(zfd), "w");
1359 maybe_warn("fdopen for write: %s", outfile);
1364 size = zuncompress(in, out, NULL, 0, NULL);
1365 /* need to fclose() if ferror() is true... */
1366 if (ferror(in) | fclose(in)) {
1367 maybe_warn("failed infile fclose");
1371 if (fclose(out) != 0) {
1372 maybe_warn("failed outfile fclose");
1380 if (method == FT_UNKNOWN) {
1382 maybe_warnx("no -l for unknown filetypes");
1385 size = cat_fd(NULL, 0, NULL, fd);
1390 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1392 return -1; /* XXX */
1395 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1399 maybe_warn("couldn't close input");
1400 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1401 maybe_warn("couldn't close output");
1406 maybe_warnx("%s: uncompress failed", file);
1410 /* if testing, or we uncompressed to stdout, this is all we need */
1415 /* if we are uncompressing to stdin, don't remove the file. */
1420 * if we create a file...
1423 * if we can't stat the file don't remove the file.
1425 if (stat(outfile, &osb) < 0) {
1426 maybe_warn("couldn't stat (leaving original): %s",
1430 if (osb.st_size != size) {
1431 maybe_warn("stat gave different size: %" PRIdOFF
1432 " != %" PRIdOFF " (leaving original)",
1437 unlink_input(file, &isb);
1439 copymodes(outfile, &isb);
1446 if (zfd != -1 && zfd != STDOUT_FILENO)
1453 cat_fd(unsigned char * prepend, ssize_t count, off_t *gsizep, int fd)
1460 if (write(STDOUT_FILENO, prepend, count) != count) {
1461 maybe_warn("write to stdout");
1465 rv = read(fd, buf, sizeof buf);
1469 maybe_warn("read from fd %d", fd);
1473 if (write(STDOUT_FILENO, buf, rv) != rv) {
1474 maybe_warn("write to stdout");
1489 unsigned char header1[4];
1491 enum filetype method;
1492 #ifndef NO_COMPRESS_SUPPORT
1497 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1498 maybe_warnx("standard input is a terminal -- ignoring");
1506 /* XXX could read the whole file, etc. */
1507 if (fstat(STDIN_FILENO, &isb) < 0) {
1508 maybe_warn("fstat");
1511 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1515 if (read(STDIN_FILENO, header1, sizeof header1) != sizeof header1) {
1516 maybe_warn("can't read stdin");
1520 method = file_gettype(header1);
1525 maybe_warnx("unknown compression format");
1528 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1532 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1533 header1, sizeof header1, &gsize, "(stdin)");
1535 #ifndef NO_BZIP2_SUPPORT
1537 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1538 header1, sizeof header1, &gsize);
1541 #ifndef NO_COMPRESS_SUPPORT
1543 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1544 maybe_warnx("zopen of stdin");
1548 usize = zuncompress(in, stdout, header1, sizeof header1, &gsize);
1555 if (vflag && !tflag && usize != -1 && gsize != -1)
1556 print_verbage(NULL, NULL, usize, gsize);
1567 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1568 maybe_warnx("standard output is a terminal -- ignoring");
1572 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", 0);
1575 if (vflag && !tflag && usize != -1 && gsize != -1)
1576 print_verbage(NULL, NULL, usize, gsize);
1580 /* do what is asked for, for the path name */
1582 handle_pathname(char *path)
1584 char *opath = path, *s = NULL;
1589 /* check for stdout/stdin */
1590 if (path[0] == '-' && path[1] == '\0') {
1599 if (stat(path, &sb) < 0) {
1600 /* lets try <path>.gz if we're decompressing */
1601 if (dflag && s == NULL && errno == ENOENT) {
1603 slen = suffixes[0].ziplen;
1604 s = malloc(len + slen + 1);
1606 maybe_err("malloc");
1607 memcpy(s, path, len);
1608 memcpy(s + len, suffixes[0].zipped, slen + 1);
1612 maybe_warn("can't stat: %s", opath);
1616 if (S_ISDIR(sb.st_mode)) {
1622 maybe_warnx("%s is a directory", path);
1626 if (S_ISREG(sb.st_mode))
1627 handle_file(path, &sb);
1629 maybe_warnx("%s is not a regular file", path);
1636 /* compress/decompress a file */
1638 handle_file(char *file, struct stat *sbp)
1641 char outfile[PATH_MAX];
1645 usize = file_uncompress(file, outfile, sizeof(outfile));
1648 gsize = sbp->st_size;
1650 gsize = file_compress(file, outfile, sizeof(outfile));
1653 usize = sbp->st_size;
1658 if (vflag && !tflag)
1659 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1664 /* this is used with -r to recursively descend directories */
1666 handle_dir(char *dir)
1674 fts = fts_open(path_argv, FTS_PHYSICAL, NULL);
1676 warn("couldn't fts_open %s", dir);
1680 while ((entry = fts_read(fts))) {
1681 switch(entry->fts_info) {
1689 maybe_warn("%s", entry->fts_path);
1692 handle_file(entry->fts_name, entry->fts_statp);
1695 (void)fts_close(fts);
1699 /* print a ratio - size reduction as a fraction of uncompressed size */
1701 print_ratio(off_t in, off_t out, FILE *where)
1703 int percent10; /* 10 * percent */
1711 * Output is more than double size of input! print -99.9%
1712 * Quite possibly we've failed to get the original size.
1717 * We only need 12 bits of result from the final division,
1718 * so reduce the values until a 32bit division will suffice.
1720 while (in > 0x100000) {
1725 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1730 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1731 /* Move the '.' to before the last digit */
1732 buff[len - 1] = buff[len - 2];
1733 buff[len - 2] = '.';
1734 fprintf(where, "%5s%%", buff);
1738 /* print compression statistics, and the new name (if there is one!) */
1740 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1743 fprintf(stderr, "%s:%s ", file,
1744 strlen(file) < 7 ? "\t\t" : "\t");
1745 print_ratio(usize, gsize, stderr);
1747 fprintf(stderr, " -- replaced with %s", nfile);
1748 fprintf(stderr, "\n");
1752 /* print test results */
1754 print_test(const char *file, int ok)
1757 if (exit_value == 0 && ok == 0)
1759 fprintf(stderr, "%s:%s %s\n", file,
1760 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1765 /* print a file's info ala --list */
1767 compressed uncompressed ratio uncompressed_name
1768 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1771 print_list(int fd, off_t out, const char *outfile, time_t ts)
1773 static int first = 1;
1775 static off_t in_tot, out_tot;
1784 printf("method crc date time ");
1787 printf(" compressed uncompressed "
1788 "ratio uncompressed_name\n");
1800 /* read the last 4 bytes - this is the uncompressed size */
1801 rv = lseek(fd, (off_t)(-8), SEEK_END);
1803 unsigned char buf[8];
1806 if (read(fd, (char *)buf, sizeof(buf)) != sizeof(buf))
1807 maybe_warn("read of uncompressed size");
1808 usize = buf[4] | buf[5] << 8 | buf[6] << 16 | buf[7] << 24;
1811 crc = buf[0] | buf[1] << 8 | buf[2] << 16 | buf[3] << 24;
1817 if (vflag && fd == -1)
1820 char *date = ctime(&ts);
1822 /* skip the day, 1/100th second, and year */
1825 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
1830 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
1831 print_ratio(in, out, stdout);
1832 printf(" %s\n", outfile);
1835 /* display the usage of NetBSD gzip */
1840 fprintf(stderr, "%s\n", gzip_version);
1842 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n"
1844 " -c --stdout write to stdout, keep original files\n"
1846 " -d --decompress uncompress files\n"
1848 " -f --force force overwriting & compress links\n"
1849 " -h --help display this help\n"
1850 " -n --no-name don't save original file name or time stamp\n"
1851 " -N --name save or restore original file name and time stamp\n"
1852 " -q --quiet output no warnings\n"
1853 " -r --recursive recursively compress files in directories\n"
1854 " -S .suf use suffix .suf instead of .gz\n"
1856 " -t --test test compressed file\n"
1857 " -v --verbose print extra statistics\n"
1858 " -V --version display program version\n"
1859 " -1 --fast fastest (worst) compression\n"
1860 " -2 .. -8 set compression level\n"
1861 " -9 --best best (slowest) compression\n",
1869 /* display the version of NetBSD gzip */
1871 display_version(void)
1874 fprintf(stderr, "%s\n", gzip_version);
1878 #ifndef NO_BZIP2_SUPPORT
1879 #include "unbzip2.c"
1881 #ifndef NO_COMPRESS_SUPPORT
1882 #include "zuncompress.c"