1 /* $NetBSD: gzip.c,v 1.94 2009/04/12 10:31:14 lukem 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 * - handle some signals better (remove outfile?)
47 * - make bzip2/compress -v/-t/-l support work as well as possible
50 #include <sys/param.h>
70 #define PRIdOFF PRId64
73 /* what type of file are we dealing with */
76 #ifndef NO_BZIP2_SUPPORT
79 #ifndef NO_COMPRESS_SUPPORT
82 #ifndef NO_PACK_SUPPORT
89 #ifndef NO_BZIP2_SUPPORT
92 #define BZ2_SUFFIX ".bz2"
93 #define BZIP2_MAGIC "\102\132\150"
96 #ifndef NO_COMPRESS_SUPPORT
98 #define Z_MAGIC "\037\235"
101 #ifndef NO_PACK_SUPPORT
102 #define PACK_MAGIC "\037\036"
105 #define GZ_SUFFIX ".gz"
107 #define BUFLEN (64 * 1024)
109 #define GZIP_MAGIC0 0x1F
110 #define GZIP_MAGIC1 0x8B
111 #define GZIP_OMAGIC1 0x9E
113 #define GZIP_TIMESTAMP (off_t)4
114 #define GZIP_ORIGNAME (off_t)10
116 #define HEAD_CRC 0x02
117 #define EXTRA_FIELD 0x04
118 #define ORIG_NAME 0x08
121 #define OS_CODE 3 /* Unix */
126 const char *normal; /* for unzip - must not be longer than zipped */
128 static suffixes_t suffixes[] = {
129 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
130 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
132 SUFFIX(GZ_SUFFIX, ""),
137 SUFFIX(".taz", ".tar"),
138 SUFFIX(".tgz", ".tar"),
139 #ifndef NO_BZIP2_SUPPORT
140 SUFFIX(BZ2_SUFFIX, ""),
141 SUFFIX(".tbz", ".tar"),
142 SUFFIX(".tbz2", ".tar"),
144 #ifndef NO_COMPRESS_SUPPORT
145 SUFFIX(Z_SUFFIX, ""),
147 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
151 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
153 #define SUFFIX_MAXLEN 30
155 static const char gzip_version[] = "FreeBSD gzip 20090621";
158 static const char gzip_copyright[] = \
159 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
160 " All rights reserved.\n"
162 " Redistribution and use in source and binary forms, with or without\n"
163 " modification, are permitted provided that the following conditions\n"
165 " 1. Redistributions of source code must retain the above copyright\n"
166 " notice, this list of conditions and the following disclaimer.\n"
167 " 2. Redistributions in binary form must reproduce the above copyright\n"
168 " notice, this list of conditions and the following disclaimer in the\n"
169 " documentation and/or other materials provided with the distribution.\n"
171 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
172 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
173 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
174 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
175 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
176 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
177 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
178 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
179 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
180 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
184 static int cflag; /* stdout mode */
185 static int dflag; /* decompress mode */
186 static int lflag; /* list mode */
187 static int numflag = 6; /* gzip -1..-9 value */
190 static int fflag; /* force mode */
191 static int kflag; /* don't delete input files */
192 static int nflag; /* don't save name/timestamp */
193 static int Nflag; /* don't restore name/timestamp */
194 static int qflag; /* quiet mode */
195 static int rflag; /* recursive mode */
196 static int tflag; /* test */
197 static int vflag; /* verbose mode */
203 static int exit_value = 0; /* exit value */
205 static char *infile; /* name of file coming in */
207 static void maybe_err(const char *fmt, ...) __dead2
208 __attribute__((__format__(__printf__, 1, 2)));
209 #ifndef NO_BZIP2_SUPPORT
210 static void maybe_errx(const char *fmt, ...) __dead2
211 __attribute__((__format__(__printf__, 1, 2)));
213 static void maybe_warn(const char *fmt, ...)
214 __attribute__((__format__(__printf__, 1, 2)));
215 static void maybe_warnx(const char *fmt, ...)
216 __attribute__((__format__(__printf__, 1, 2)));
217 static enum filetype file_gettype(u_char *);
219 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
221 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
222 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
223 static off_t file_compress(char *, char *, size_t);
224 static off_t file_uncompress(char *, char *, size_t);
225 static void handle_pathname(char *);
226 static void handle_file(char *, struct stat *);
227 static void handle_stdin(void);
228 static void handle_stdout(void);
229 static void print_ratio(off_t, off_t, FILE *);
230 static void print_list(int fd, off_t, const char *, time_t);
231 static void usage(void);
232 static void display_version(void);
234 static void display_license(void);
236 static const suffixes_t *check_suffix(char *, int);
237 static ssize_t read_retry(int, void *, size_t);
240 #define unlink_input(f, sb) unlink(f)
242 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
243 static void prepend_gzip(char *, int *, char ***);
244 static void handle_dir(char *);
245 static void print_verbage(const char *, const char *, off_t, off_t);
246 static void print_test(const char *, int);
247 static void copymodes(int fd, const struct stat *, const char *file);
248 static int check_outfile(const char *outfile);
251 #ifndef NO_BZIP2_SUPPORT
252 static off_t unbzip2(int, int, char *, size_t, off_t *);
255 #ifndef NO_COMPRESS_SUPPORT
256 static FILE *zdopen(int);
257 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
260 #ifndef NO_PACK_SUPPORT
261 static off_t unpack(int, int, char *, size_t, off_t *);
264 int main(int, char **p);
267 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
269 static const struct option longopts[] = {
270 { "stdout", no_argument, 0, 'c' },
271 { "to-stdout", no_argument, 0, 'c' },
272 { "decompress", no_argument, 0, 'd' },
273 { "uncompress", no_argument, 0, 'd' },
274 { "force", no_argument, 0, 'f' },
275 { "help", no_argument, 0, 'h' },
276 { "keep", no_argument, 0, 'k' },
277 { "list", no_argument, 0, 'l' },
278 { "no-name", no_argument, 0, 'n' },
279 { "name", no_argument, 0, 'N' },
280 { "quiet", no_argument, 0, 'q' },
281 { "recursive", no_argument, 0, 'r' },
282 { "suffix", required_argument, 0, 'S' },
283 { "test", no_argument, 0, 't' },
284 { "verbose", no_argument, 0, 'v' },
285 { "version", no_argument, 0, 'V' },
286 { "fast", no_argument, 0, '1' },
287 { "best", no_argument, 0, '9' },
288 { "ascii", no_argument, 0, 'a' },
289 { "license", no_argument, 0, 'L' },
290 { NULL, no_argument, 0, 0 },
295 main(int argc, char **argv)
297 const char *progname = getprogname();
304 /* XXX set up signals */
307 if ((gzip = getenv("GZIP")) != NULL)
308 prepend_gzip(gzip, &argc, &argv);
313 * handle being called `gunzip', `zcat' and `gzcat'
315 if (strcmp(progname, "gunzip") == 0)
317 else if (strcmp(progname, "zcat") == 0 ||
318 strcmp(progname, "gzcat") == 0)
322 #define OPT_LIST "123456789cdhltV"
324 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
327 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
329 case '1': case '2': case '3':
330 case '4': case '5': case '6':
331 case '7': case '8': case '9':
349 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
375 len = strlen(optarg);
377 if (len > SUFFIX_MAXLEN)
378 errx(1, "incorrect suffix: '%s': too long", optarg);
379 suffixes[0].zipped = optarg;
380 suffixes[0].ziplen = len;
382 suffixes[NUM_SUFFIXES - 1].zipped = "";
383 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
404 if (dflag) /* stdin mode */
406 else /* stdout mode */
410 handle_pathname(argv[0]);
414 if (qflag == 0 && lflag && argc > 1)
415 print_list(-1, 0, "(totals)", 0);
420 /* maybe print a warning */
422 maybe_warn(const char *fmt, ...)
435 /* ... without an errno. */
437 maybe_warnx(const char *fmt, ...)
450 /* maybe print an error */
452 maybe_err(const char *fmt, ...)
464 #ifndef NO_BZIP2_SUPPORT
465 /* ... without an errno. */
467 maybe_errx(const char *fmt, ...)
481 /* split up $GZIP and prepend it to the argument list */
483 prepend_gzip(char *gzip, int *argc, char ***argv)
485 char *s, **nargv, **ac;
488 /* scan how many arguments there are */
490 while (*s == ' ' || *s == '\t')
495 while (*s != ' ' && *s != '\t')
507 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
511 /* stash this away */
514 /* copy the program name first */
516 nargv[i++] = *(ac++);
518 /* take a copy of $GZIP and add it to the array */
523 /* Skip whitespaces. */
524 while (*s == ' ' || *s == '\t')
529 /* Find the end of this argument. */
530 while (*s != ' ' && *s != '\t')
532 /* Argument followed by NUL. */
534 /* Terminate by overwriting ' ' or '\t' with NUL. */
539 /* copy the original arguments and a NULL */
541 nargv[i++] = *(ac++);
546 /* compress input to output. Return bytes read, -1 on error */
548 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
551 char *outbufp, *inbufp;
552 off_t in_tot = 0, out_tot = 0;
557 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
562 outbufp = malloc(BUFLEN);
563 inbufp = malloc(BUFLEN);
564 if (outbufp == NULL || inbufp == NULL) {
565 maybe_err("malloc failed");
569 memset(&z, 0, sizeof z);
575 memcpy(outbufp, header, sizeof header);
583 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
584 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
585 *origname ? ORIG_NAME : 0,
588 (mtime >> 16) & 0xff,
589 (mtime >> 24) & 0xff,
590 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
593 /* this need PATH_MAX > BUFLEN ... */
594 maybe_err("snprintf");
599 z.next_out = (unsigned char *)outbufp + i;
600 z.avail_out = BUFLEN - i;
602 error = deflateInit2(&z, numflag, Z_DEFLATED,
603 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
605 maybe_warnx("deflateInit2 failed");
610 crc = crc32(0L, Z_NULL, 0);
612 if (z.avail_out == 0) {
613 if (write(out, outbufp, BUFLEN) != BUFLEN) {
620 z.next_out = (unsigned char *)outbufp;
621 z.avail_out = BUFLEN;
624 if (z.avail_in == 0) {
625 in_size = read(in, inbufp, BUFLEN);
634 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
636 z.next_in = (unsigned char *)inbufp;
637 z.avail_in = in_size;
640 error = deflate(&z, Z_NO_FLUSH);
641 if (error != Z_OK && error != Z_STREAM_END) {
642 maybe_warnx("deflate failed");
653 error = deflate(&z, Z_FINISH);
654 if (error != Z_OK && error != Z_STREAM_END) {
655 maybe_warnx("deflate failed");
660 len = (char *)z.next_out - outbufp;
662 w = write(out, outbufp, len);
663 if (w == -1 || (size_t)w != len) {
669 z.next_out = (unsigned char *)outbufp;
670 z.avail_out = BUFLEN;
672 if (error == Z_STREAM_END)
676 if (deflateEnd(&z) != Z_OK) {
677 maybe_warnx("deflateEnd failed");
682 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
684 (int)(crc >> 8) & 0xff,
685 (int)(crc >> 16) & 0xff,
686 (int)(crc >> 24) & 0xff,
688 (int)(in_tot >> 8) & 0xff,
689 (int)(in_tot >> 16) & 0xff,
690 (int)(in_tot >> 24) & 0xff);
692 maybe_err("snprintf");
693 if (write(out, outbufp, i) != i) {
710 * uncompress input to output then close the input. return the
711 * uncompressed size written, and put the compressed sized read
715 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
716 const char *filename)
719 char *outbufp, *inbufp;
720 off_t out_tot = -1, in_tot = 0;
721 uint32_t out_sub_tot = 0;
739 } state = GZSTATE_MAGIC0;
740 int flags = 0, skip_count = 0;
741 int error = Z_STREAM_ERROR, done_reading = 0;
746 #define ADVANCE() { z.next_in++; z.avail_in--; }
748 if ((outbufp = malloc(BUFLEN)) == NULL) {
749 maybe_err("malloc failed");
752 if ((inbufp = malloc(BUFLEN)) == NULL) {
753 maybe_err("malloc failed");
757 memset(&z, 0, sizeof z);
759 z.next_in = (unsigned char *)pre;
760 z.avail_out = BUFLEN;
761 z.next_out = (unsigned char *)outbufp;
770 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
773 if (z.avail_in > 0) {
774 memmove(inbufp, z.next_in, z.avail_in);
776 z.next_in = (unsigned char *)inbufp;
777 in_size = read(in, z.next_in + z.avail_in,
778 BUFLEN - z.avail_in);
781 maybe_warn("failed to read stdin");
783 } else if (in_size == 0) {
787 z.avail_in += in_size;
792 if (z.avail_in == 0) {
793 if (done_reading && state != GZSTATE_MAGIC0) {
794 maybe_warnx("%s: unexpected end of file",
802 if (*z.next_in != GZIP_MAGIC0) {
804 maybe_warnx("%s: trailing garbage "
805 "ignored", filename);
808 maybe_warnx("input not gziped (MAGIC0)");
814 crc = crc32(0L, Z_NULL, 0);
818 if (*z.next_in != GZIP_MAGIC1 &&
819 *z.next_in != GZIP_OMAGIC1) {
820 maybe_warnx("input not gziped (MAGIC1)");
828 if (*z.next_in != Z_DEFLATED) {
829 maybe_warnx("unknown compression method");
843 case GZSTATE_SKIPPING:
844 if (skip_count > 0) {
852 if ((flags & EXTRA_FIELD) == 0) {
853 state = GZSTATE_ORIGNAME;
856 skip_count = *z.next_in;
862 skip_count |= ((*z.next_in) << 8);
868 if (skip_count > 0) {
875 case GZSTATE_ORIGNAME:
876 if ((flags & ORIG_NAME) == 0) {
885 case GZSTATE_COMMENT:
886 if ((flags & COMMENT) == 0) {
895 case GZSTATE_HEAD_CRC1:
896 if (flags & HEAD_CRC)
903 case GZSTATE_HEAD_CRC2:
904 if (skip_count > 0) {
912 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
913 maybe_warnx("failed to inflateInit");
920 error = inflate(&z, Z_FINISH);
922 /* Z_BUF_ERROR goes with Z_FINISH... */
929 maybe_warnx("Z_NEED_DICT error");
932 maybe_warnx("data stream error");
935 maybe_warnx("internal stream error");
938 maybe_warnx("memory allocation error");
942 maybe_warn("unknown error from inflate(): %d",
945 wr = BUFLEN - z.avail_out;
948 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
951 /* don't write anything with -t */
954 write(out, outbufp, wr) != wr) {
955 maybe_warn("error writing to output");
963 if (error == Z_STREAM_END) {
968 z.next_out = (unsigned char *)outbufp;
969 z.avail_out = BUFLEN;
976 if (z.avail_in < 4) {
981 maybe_warnx("truncated input");
984 origcrc = ((unsigned)z.next_in[0] & 0xff) |
985 ((unsigned)z.next_in[1] & 0xff) << 8 |
986 ((unsigned)z.next_in[2] & 0xff) << 16 |
987 ((unsigned)z.next_in[3] & 0xff) << 24;
988 if (origcrc != crc) {
989 maybe_warnx("invalid compressed"
998 if (!z.avail_in && done_reading) {
1007 if (z.avail_in < 4) {
1008 if (!done_reading) {
1012 maybe_warnx("truncated input");
1015 origlen = ((unsigned)z.next_in[0] & 0xff) |
1016 ((unsigned)z.next_in[1] & 0xff) << 8 |
1017 ((unsigned)z.next_in[2] & 0xff) << 16 |
1018 ((unsigned)z.next_in[3] & 0xff) << 24;
1020 if (origlen != out_sub_tot) {
1021 maybe_warnx("invalid compressed"
1022 " data--length error");
1031 maybe_warnx("decompression error");
1034 state = GZSTATE_MAGIC0;
1043 if (state > GZSTATE_INIT)
1057 * set the owner, mode, flags & utimes using the given file descriptor.
1058 * file is only used in possible warning messages.
1061 copymodes(int fd, const struct stat *sbp, const char *file)
1063 struct timeval times[2];
1067 * If we have no info on the input, give this file some
1068 * default values and return..
1071 mode_t mask = umask(022);
1073 (void)fchmod(fd, DEFFILEMODE & ~mask);
1079 /* if the chown fails, remove set-id bits as-per compress(1) */
1080 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1082 maybe_warn("couldn't fchown: %s", file);
1083 sb.st_mode &= ~(S_ISUID|S_ISGID);
1086 /* we only allow set-id and the 9 normal permission bits */
1087 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1088 if (fchmod(fd, sb.st_mode) < 0)
1089 maybe_warn("couldn't fchmod: %s", file);
1091 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atimespec);
1092 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtimespec);
1093 if (futimes(fd, times) < 0)
1094 maybe_warn("couldn't utimes: %s", file);
1096 /* only try flags if they exist already */
1097 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1098 maybe_warn("couldn't fchflags: %s", file);
1102 /* what sort of file is this? */
1103 static enum filetype
1104 file_gettype(u_char *buf)
1107 if (buf[0] == GZIP_MAGIC0 &&
1108 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1111 #ifndef NO_BZIP2_SUPPORT
1112 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1113 buf[3] >= '0' && buf[3] <= '9')
1117 #ifndef NO_COMPRESS_SUPPORT
1118 if (memcmp(buf, Z_MAGIC, 2) == 0)
1122 #ifndef NO_PACK_SUPPORT
1123 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1131 /* check the outfile is OK. */
1133 check_outfile(const char *outfile)
1138 if (lflag == 0 && stat(outfile, &sb) == 0) {
1141 else if (isatty(STDIN_FILENO)) {
1142 char ans[10] = { 'n', '\0' }; /* default */
1144 fprintf(stderr, "%s already exists -- do you wish to "
1145 "overwrite (y or n)? " , outfile);
1146 (void)fgets(ans, sizeof(ans) - 1, stdin);
1147 if (ans[0] != 'y' && ans[0] != 'Y') {
1148 fprintf(stderr, "\tnot overwriting\n");
1153 maybe_warnx("%s already exists -- skipping", outfile);
1161 unlink_input(const char *file, const struct stat *sb)
1167 if (stat(file, &nsb) != 0)
1168 /* Must be gone alrady */
1170 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1171 /* Definitely a different file */
1177 static const suffixes_t *
1178 check_suffix(char *file, int xlate)
1180 const suffixes_t *s;
1181 int len = strlen(file);
1184 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1185 /* if it doesn't fit in "a.suf", don't bother */
1186 if (s->ziplen >= len)
1188 sp = file + len - s->ziplen;
1189 if (strcmp(s->zipped, sp) != 0)
1192 strcpy(sp, s->normal);
1199 * compress the given file: create a corresponding .gz file and remove the
1203 file_compress(char *file, char *outfile, size_t outsize)
1209 struct stat isb, osb;
1210 const suffixes_t *suff;
1213 in = open(file, O_RDONLY);
1215 maybe_warn("can't open %s", file);
1221 if (fstat(in, &isb) == 0) {
1222 if (isb.st_nlink > 1 && fflag == 0) {
1223 maybe_warnx("%s has %d other link%s -- "
1224 "skipping", file, isb.st_nlink - 1,
1225 isb.st_nlink == 1 ? "" : "s");
1231 if (fflag == 0 && (suff = check_suffix(file, 0))
1232 && suff->zipped[0] != 0) {
1233 maybe_warnx("%s already has %s suffix -- unchanged",
1234 file, suff->zipped);
1240 /* Add (usually) .gz to filename */
1241 if ((size_t)snprintf(outfile, outsize, "%s%s",
1242 file, suffixes[0].zipped) >= outsize)
1243 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1244 suffixes[0].zipped, suffixes[0].ziplen + 1);
1247 if (check_outfile(outfile) == 0) {
1255 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1257 maybe_warn("could not create output: %s", outfile);
1262 out = STDOUT_FILENO;
1264 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1269 * If there was an error, insize will be -1.
1270 * If we compressed to stdout, just return the size.
1271 * Otherwise stat the file and check it is the correct size.
1272 * We only blow away the file if we can stat the output and it
1273 * has the expected size.
1276 return insize == -1 ? -1 : size;
1279 if (fstat(out, &osb) != 0) {
1280 maybe_warn("couldn't stat: %s", outfile);
1284 if (osb.st_size != size) {
1285 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1286 " != %" PRIdOFF "), deleting",
1287 outfile, osb.st_size, size);
1291 copymodes(out, &isb, outfile);
1293 if (close(out) == -1)
1294 maybe_warn("couldn't close output");
1296 /* output is good, ok to delete input */
1297 unlink_input(file, &isb);
1302 if (close(out) == -1)
1303 maybe_warn("couldn't close output");
1305 maybe_warnx("leaving original %s", file);
1311 /* uncompress the given file and remove the original */
1313 file_uncompress(char *file, char *outfile, size_t outsize)
1315 struct stat isb, osb;
1318 unsigned char header1[4];
1319 enum filetype method;
1320 int fd, ofd, zfd = -1;
1322 time_t timestamp = 0;
1323 unsigned char name[PATH_MAX + 1];
1326 /* gather the old name info */
1328 fd = open(file, O_RDONLY);
1330 maybe_warn("can't open %s", file);
1334 strlcpy(outfile, file, outsize);
1335 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1336 maybe_warnx("%s: unknown suffix -- ignored", file);
1340 rbytes = read(fd, header1, sizeof header1);
1341 if (rbytes != sizeof header1) {
1342 /* we don't want to fail here. */
1348 maybe_warn("can't read %s", file);
1350 goto unexpected_EOF;
1354 method = file_gettype(header1);
1357 if (fflag == 0 && method == FT_UNKNOWN) {
1358 maybe_warnx("%s: not in gzip format", file);
1365 if (method == FT_GZIP && Nflag) {
1366 unsigned char ts[4]; /* timestamp */
1369 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1370 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1371 goto unexpected_EOF;
1374 maybe_warn("can't read %s", file);
1377 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1379 if (header1[3] & ORIG_NAME) {
1380 rbytes = pread(fd, name, sizeof name, GZIP_ORIGNAME);
1382 maybe_warn("can't read %s", file);
1386 /* preserve original directory name */
1387 char *dp = strrchr(file, '/');
1392 snprintf(outfile, outsize, "%.*s%.*s",
1394 file, (int) rbytes, name);
1399 lseek(fd, 0, SEEK_SET);
1401 if (cflag == 0 || lflag) {
1402 if (fstat(fd, &isb) != 0)
1405 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1406 maybe_warnx("%s has %d other links -- skipping",
1407 file, isb.st_nlink - 1);
1410 if (nflag == 0 && timestamp)
1411 isb.st_mtime = timestamp;
1412 if (check_outfile(outfile) == 0)
1417 if (cflag == 0 && lflag == 0) {
1418 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1419 if (zfd == STDOUT_FILENO) {
1420 /* We won't close STDOUT_FILENO later... */
1422 close(STDOUT_FILENO);
1425 maybe_warn("can't open %s", outfile);
1429 zfd = STDOUT_FILENO;
1431 #ifndef NO_BZIP2_SUPPORT
1432 if (method == FT_BZIP2) {
1436 maybe_warnx("no -l with bzip2 files");
1440 size = unbzip2(fd, zfd, NULL, 0, NULL);
1444 #ifndef NO_COMPRESS_SUPPORT
1445 if (method == FT_Z) {
1450 maybe_warnx("no -l with Lempel-Ziv files");
1454 if ((in = zdopen(fd)) == NULL) {
1455 maybe_warn("zdopen for read: %s", file);
1459 out = fdopen(dup(zfd), "w");
1461 maybe_warn("fdopen for write: %s", outfile);
1466 size = zuncompress(in, out, NULL, 0, NULL);
1467 /* need to fclose() if ferror() is true... */
1468 if (ferror(in) | fclose(in)) {
1469 maybe_warn("failed infile fclose");
1473 if (fclose(out) != 0) {
1474 maybe_warn("failed outfile fclose");
1481 #ifndef NO_PACK_SUPPORT
1482 if (method == FT_PACK) {
1484 maybe_warnx("no -l with packed files");
1488 size = unpack(fd, zfd, NULL, 0, NULL);
1493 if (method == FT_UNKNOWN) {
1495 maybe_warnx("no -l for unknown filetypes");
1498 size = cat_fd(NULL, 0, NULL, fd);
1503 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1505 return -1; /* XXX */
1508 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1512 maybe_warn("couldn't close input");
1513 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1514 maybe_warn("couldn't close output");
1519 maybe_warnx("%s: uncompress failed", file);
1523 /* if testing, or we uncompressed to stdout, this is all we need */
1528 /* if we are uncompressing to stdin, don't remove the file. */
1533 * if we create a file...
1536 * if we can't stat the file don't remove the file.
1539 ofd = open(outfile, O_RDWR, 0);
1541 maybe_warn("couldn't open (leaving original): %s",
1545 if (fstat(ofd, &osb) != 0) {
1546 maybe_warn("couldn't stat (leaving original): %s",
1551 if (osb.st_size != size) {
1552 maybe_warnx("stat gave different size: %" PRIdOFF
1553 " != %" PRIdOFF " (leaving original)",
1559 unlink_input(file, &isb);
1561 copymodes(ofd, &isb, outfile);
1567 maybe_warnx("%s: unexpected end of file", file);
1571 if (zfd != -1 && zfd != STDOUT_FILENO)
1578 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1585 w = write(STDOUT_FILENO, prepend, count);
1586 if (w == -1 || (size_t)w != count) {
1587 maybe_warn("write to stdout");
1593 rv = read(fd, buf, sizeof buf);
1597 maybe_warn("read from fd %d", fd);
1601 if (write(STDOUT_FILENO, buf, rv) != rv) {
1602 maybe_warn("write to stdout");
1617 unsigned char header1[4];
1619 enum filetype method;
1621 #ifndef NO_COMPRESS_SUPPORT
1626 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1627 maybe_warnx("standard input is a terminal -- ignoring");
1635 /* XXX could read the whole file, etc. */
1636 if (fstat(STDIN_FILENO, &isb) < 0) {
1637 maybe_warn("fstat");
1640 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1644 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1645 if (bytes_read == -1) {
1646 maybe_warn("can't read stdin");
1648 } else if (bytes_read != sizeof(header1)) {
1649 maybe_warnx("(stdin): unexpected end of file");
1653 method = file_gettype(header1);
1658 maybe_warnx("unknown compression format");
1661 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1665 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1666 (char *)header1, sizeof header1, &gsize, "(stdin)");
1668 #ifndef NO_BZIP2_SUPPORT
1670 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1671 (char *)header1, sizeof header1, &gsize);
1674 #ifndef NO_COMPRESS_SUPPORT
1676 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1677 maybe_warnx("zopen of stdin");
1681 usize = zuncompress(in, stdout, (char *)header1, sizeof header1, &gsize);
1685 #ifndef NO_PACK_SUPPORT
1687 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1688 (char *)header1, sizeof header1, &gsize);
1694 if (vflag && !tflag && usize != -1 && gsize != -1)
1695 print_verbage(NULL, NULL, usize, gsize);
1697 print_test("(stdin)", usize != -1);
1712 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1713 maybe_warnx("standard output is a terminal -- ignoring");
1717 /* If stdin is a file use it's mtime, otherwise use current time */
1718 ret = fstat(STDIN_FILENO, &sb);
1722 maybe_warn("Can't stat stdin");
1727 if (S_ISREG(sb.st_mode))
1728 mtime = (uint32_t)sb.st_mtime;
1730 systime = time(NULL);
1732 if (systime == -1) {
1737 mtime = (uint32_t)systime;
1740 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1742 if (vflag && !tflag && usize != -1 && gsize != -1)
1743 print_verbage(NULL, NULL, usize, gsize);
1747 /* do what is asked for, for the path name */
1749 handle_pathname(char *path)
1751 char *opath = path, *s = NULL;
1756 /* check for stdout/stdin */
1757 if (path[0] == '-' && path[1] == '\0') {
1766 if (stat(path, &sb) != 0) {
1767 /* lets try <path>.gz if we're decompressing */
1768 if (dflag && s == NULL && errno == ENOENT) {
1770 slen = suffixes[0].ziplen;
1771 s = malloc(len + slen + 1);
1773 maybe_err("malloc");
1774 memcpy(s, path, len);
1775 memcpy(s + len, suffixes[0].zipped, slen + 1);
1779 maybe_warn("can't stat: %s", opath);
1783 if (S_ISDIR(sb.st_mode)) {
1789 maybe_warnx("%s is a directory", path);
1793 if (S_ISREG(sb.st_mode))
1794 handle_file(path, &sb);
1796 maybe_warnx("%s is not a regular file", path);
1803 /* compress/decompress a file */
1805 handle_file(char *file, struct stat *sbp)
1808 char outfile[PATH_MAX];
1812 usize = file_uncompress(file, outfile, sizeof(outfile));
1815 print_test(file, usize != -1);
1819 gsize = sbp->st_size;
1821 gsize = file_compress(file, outfile, sizeof(outfile));
1824 usize = sbp->st_size;
1829 if (vflag && !tflag)
1830 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1835 /* this is used with -r to recursively descend directories */
1837 handle_dir(char *dir)
1845 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1847 warn("couldn't fts_open %s", dir);
1851 while ((entry = fts_read(fts))) {
1852 switch(entry->fts_info) {
1860 maybe_warn("%s", entry->fts_path);
1863 handle_file(entry->fts_path, entry->fts_statp);
1866 (void)fts_close(fts);
1870 /* print a ratio - size reduction as a fraction of uncompressed size */
1872 print_ratio(off_t in, off_t out, FILE *where)
1874 int percent10; /* 10 * percent */
1882 * Output is more than double size of input! print -99.9%
1883 * Quite possibly we've failed to get the original size.
1888 * We only need 12 bits of result from the final division,
1889 * so reduce the values until a 32bit division will suffice.
1891 while (in > 0x100000) {
1896 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1901 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1902 /* Move the '.' to before the last digit */
1903 buff[len - 1] = buff[len - 2];
1904 buff[len - 2] = '.';
1905 fprintf(where, "%5s%%", buff);
1909 /* print compression statistics, and the new name (if there is one!) */
1911 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1914 fprintf(stderr, "%s:%s ", file,
1915 strlen(file) < 7 ? "\t\t" : "\t");
1916 print_ratio(usize, gsize, stderr);
1918 fprintf(stderr, " -- replaced with %s", nfile);
1919 fprintf(stderr, "\n");
1923 /* print test results */
1925 print_test(const char *file, int ok)
1928 if (exit_value == 0 && ok == 0)
1930 fprintf(stderr, "%s:%s %s\n", file,
1931 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
1936 /* print a file's info ala --list */
1938 compressed uncompressed ratio uncompressed_name
1939 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1942 print_list(int fd, off_t out, const char *outfile, time_t ts)
1944 static int first = 1;
1946 static off_t in_tot, out_tot;
1954 printf("method crc date time ");
1957 printf(" compressed uncompressed "
1958 "ratio uncompressed_name\n");
1970 /* read the last 4 bytes - this is the uncompressed size */
1971 rv = lseek(fd, (off_t)(-8), SEEK_END);
1973 unsigned char buf[8];
1976 rv = read(fd, (char *)buf, sizeof(buf));
1978 maybe_warn("read of uncompressed size");
1979 else if (rv != sizeof(buf))
1980 maybe_warnx("read of uncompressed size");
1983 usize = buf[4] | buf[5] << 8 |
1984 buf[6] << 16 | buf[7] << 24;
1987 crc = buf[0] | buf[1] << 8 |
1988 buf[2] << 16 | buf[3] << 24;
1995 if (vflag && fd == -1)
1998 char *date = ctime(&ts);
2000 /* skip the day, 1/100th second, and year */
2003 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2008 (void)&ts; /* XXX */
2010 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2011 print_ratio(in, out, stdout);
2012 printf(" %s\n", outfile);
2015 /* display the usage of NetBSD gzip */
2020 fprintf(stderr, "%s\n", gzip_version);
2023 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
2025 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2026 " -1 --fast fastest (worst) compression\n"
2027 " -2 .. -8 set compression level\n"
2028 " -9 --best best (slowest) compression\n"
2029 " -c --stdout write to stdout, keep original files\n"
2031 " -d --decompress uncompress files\n"
2033 " -f --force force overwriting & compress links\n"
2034 " -h --help display this help\n"
2035 " -k --keep don't delete input files during operation\n"
2036 " -l --list list compressed file contents\n"
2037 " -N --name save or restore original file name and time stamp\n"
2038 " -n --no-name don't save original file name or time stamp\n"
2039 " -q --quiet output no warnings\n"
2040 " -r --recursive recursively compress files in directories\n"
2041 " -S .suf use suffix .suf instead of .gz\n"
2043 " -t --test test compressed file\n"
2044 " -V --version display program version\n"
2045 " -v --verbose print extra statistics\n",
2052 /* display the license information of FreeBSD gzip */
2054 display_license(void)
2057 fprintf(stderr, "%s (based on NetBSD gzip 20060927)\n", gzip_version);
2058 fprintf(stderr, "%s\n", gzip_copyright);
2063 /* display the version of NetBSD gzip */
2065 display_version(void)
2068 fprintf(stderr, "%s\n", gzip_version);
2072 #ifndef NO_BZIP2_SUPPORT
2073 #include "unbzip2.c"
2075 #ifndef NO_COMPRESS_SUPPORT
2076 #include "zuncompress.c"
2078 #ifndef NO_PACK_SUPPORT
2083 read_retry(int fd, void *buf, size_t sz)
2086 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2091 ret = read(fd, cp, left);
2094 } else if (ret == 0) {