1 /* $NetBSD: gzip.c,v 1.108 2015/04/15 02:29:12 christos 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.");
34 __FBSDID("$FreeBSD$");
38 * gzip.c -- GPL free gzip using zlib.
40 * RFC 1950 covers the zlib format
41 * RFC 1951 covers the deflate format
42 * RFC 1952 covers the gzip format
45 * - use mmap where possible
46 * - make bzip2/compress -v/-t/-l support work as well as possible
49 #include <sys/param.h>
68 /* what type of file are we dealing with */
71 #ifndef NO_BZIP2_SUPPORT
74 #ifndef NO_COMPRESS_SUPPORT
77 #ifndef NO_PACK_SUPPORT
87 #ifndef NO_BZIP2_SUPPORT
90 #define BZ2_SUFFIX ".bz2"
91 #define BZIP2_MAGIC "\102\132\150"
94 #ifndef NO_COMPRESS_SUPPORT
96 #define Z_MAGIC "\037\235"
99 #ifndef NO_PACK_SUPPORT
100 #define PACK_MAGIC "\037\036"
103 #ifndef NO_XZ_SUPPORT
105 #define XZ_SUFFIX ".xz"
106 #define XZ_MAGIC "\3757zXZ"
109 #define GZ_SUFFIX ".gz"
111 #define BUFLEN (64 * 1024)
113 #define GZIP_MAGIC0 0x1F
114 #define GZIP_MAGIC1 0x8B
115 #define GZIP_OMAGIC1 0x9E
117 #define GZIP_TIMESTAMP (off_t)4
118 #define GZIP_ORIGNAME (off_t)10
120 #define HEAD_CRC 0x02
121 #define EXTRA_FIELD 0x04
122 #define ORIG_NAME 0x08
125 #define OS_CODE 3 /* Unix */
130 const char *normal; /* for unzip - must not be longer than zipped */
132 static suffixes_t suffixes[] = {
133 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
134 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
136 SUFFIX(GZ_SUFFIX, ""),
141 SUFFIX(".taz", ".tar"),
142 SUFFIX(".tgz", ".tar"),
143 #ifndef NO_BZIP2_SUPPORT
144 SUFFIX(BZ2_SUFFIX, ""),
145 SUFFIX(".tbz", ".tar"),
146 SUFFIX(".tbz2", ".tar"),
148 #ifndef NO_COMPRESS_SUPPORT
149 SUFFIX(Z_SUFFIX, ""),
151 #ifndef NO_XZ_SUPPORT
152 SUFFIX(XZ_SUFFIX, ""),
154 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
158 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
159 #define SUFFIX_MAXLEN 30
161 static const char gzip_version[] = "FreeBSD gzip 20150413";
164 static const char gzip_copyright[] = \
165 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
166 " All rights reserved.\n"
168 " Redistribution and use in source and binary forms, with or without\n"
169 " modification, are permitted provided that the following conditions\n"
171 " 1. Redistributions of source code must retain the above copyright\n"
172 " notice, this list of conditions and the following disclaimer.\n"
173 " 2. Redistributions in binary form must reproduce the above copyright\n"
174 " notice, this list of conditions and the following disclaimer in the\n"
175 " documentation and/or other materials provided with the distribution.\n"
177 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
178 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
179 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
180 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
181 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
182 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
183 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
184 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
185 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
186 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
190 static int cflag; /* stdout mode */
191 static int dflag; /* decompress mode */
192 static int lflag; /* list mode */
193 static int numflag = 6; /* gzip -1..-9 value */
196 static int fflag; /* force mode */
197 static int kflag; /* don't delete input files */
198 static int nflag; /* don't save name/timestamp */
199 static int Nflag; /* don't restore name/timestamp */
200 static int qflag; /* quiet mode */
201 static int rflag; /* recursive mode */
202 static int tflag; /* test */
203 static int vflag; /* verbose mode */
204 static const char *remove_file = NULL; /* file to be removed upon SIGINT */
210 static int exit_value = 0; /* exit value */
212 static char *infile; /* name of file coming in */
214 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead2;
215 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
216 !defined(NO_XZ_SUPPORT)
217 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead2;
219 static void maybe_warn(const char *fmt, ...) __printflike(1, 2);
220 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2);
221 static enum filetype file_gettype(u_char *);
223 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
225 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
226 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
227 static off_t file_compress(char *, char *, size_t);
228 static off_t file_uncompress(char *, char *, size_t);
229 static void handle_pathname(char *);
230 static void handle_file(char *, struct stat *);
231 static void handle_stdin(void);
232 static void handle_stdout(void);
233 static void print_ratio(off_t, off_t, FILE *);
234 static void print_list(int fd, off_t, const char *, time_t);
235 static void usage(void) __dead2;
236 static void display_version(void) __dead2;
238 static void display_license(void);
239 static void sigint_handler(int);
241 static const suffixes_t *check_suffix(char *, int);
242 static ssize_t read_retry(int, void *, size_t);
245 #define unlink_input(f, sb) unlink(f)
247 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
248 static void prepend_gzip(char *, int *, char ***);
249 static void handle_dir(char *);
250 static void print_verbage(const char *, const char *, off_t, off_t);
251 static void print_test(const char *, int);
252 static void copymodes(int fd, const struct stat *, const char *file);
253 static int check_outfile(const char *outfile);
256 #ifndef NO_BZIP2_SUPPORT
257 static off_t unbzip2(int, int, char *, size_t, off_t *);
260 #ifndef NO_COMPRESS_SUPPORT
261 static FILE *zdopen(int);
262 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
265 #ifndef NO_PACK_SUPPORT
266 static off_t unpack(int, int, char *, size_t, off_t *);
269 #ifndef NO_XZ_SUPPORT
270 static off_t unxz(int, int, char *, size_t, off_t *);
274 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
276 static const struct option longopts[] = {
277 { "stdout", no_argument, 0, 'c' },
278 { "to-stdout", no_argument, 0, 'c' },
279 { "decompress", no_argument, 0, 'd' },
280 { "uncompress", no_argument, 0, 'd' },
281 { "force", no_argument, 0, 'f' },
282 { "help", no_argument, 0, 'h' },
283 { "keep", no_argument, 0, 'k' },
284 { "list", no_argument, 0, 'l' },
285 { "no-name", no_argument, 0, 'n' },
286 { "name", no_argument, 0, 'N' },
287 { "quiet", no_argument, 0, 'q' },
288 { "recursive", no_argument, 0, 'r' },
289 { "suffix", required_argument, 0, 'S' },
290 { "test", no_argument, 0, 't' },
291 { "verbose", no_argument, 0, 'v' },
292 { "version", no_argument, 0, 'V' },
293 { "fast", no_argument, 0, '1' },
294 { "best", no_argument, 0, '9' },
295 { "ascii", no_argument, 0, 'a' },
296 { "license", no_argument, 0, 'L' },
297 { NULL, no_argument, 0, 0 },
302 main(int argc, char **argv)
304 const char *progname = getprogname();
312 if ((gzip = getenv("GZIP")) != NULL)
313 prepend_gzip(gzip, &argc, &argv);
314 signal(SIGINT, sigint_handler);
319 * handle being called `gunzip', `zcat' and `gzcat'
321 if (strcmp(progname, "gunzip") == 0)
323 else if (strcmp(progname, "zcat") == 0 ||
324 strcmp(progname, "gzcat") == 0)
328 #define OPT_LIST "123456789cdhlV"
330 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
333 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
335 case '1': case '2': case '3':
336 case '4': case '5': case '6':
337 case '7': case '8': case '9':
355 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
381 len = strlen(optarg);
383 if (len > SUFFIX_MAXLEN)
384 errx(1, "incorrect suffix: '%s': too long", optarg);
385 suffixes[0].zipped = optarg;
386 suffixes[0].ziplen = len;
388 suffixes[NUM_SUFFIXES - 1].zipped = "";
389 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
410 if (dflag) /* stdin mode */
412 else /* stdout mode */
416 handle_pathname(argv[0]);
420 if (qflag == 0 && lflag && argc > 1)
421 print_list(-1, 0, "(totals)", 0);
426 /* maybe print a warning */
428 maybe_warn(const char *fmt, ...)
441 /* ... without an errno. */
443 maybe_warnx(const char *fmt, ...)
456 /* maybe print an error */
458 maybe_err(const char *fmt, ...)
470 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
471 !defined(NO_XZ_SUPPORT)
472 /* ... without an errno. */
474 maybe_errx(const char *fmt, ...)
488 /* split up $GZIP and prepend it to the argument list */
490 prepend_gzip(char *gzip, int *argc, char ***argv)
492 char *s, **nargv, **ac;
495 /* scan how many arguments there are */
497 while (*s == ' ' || *s == '\t')
502 while (*s != ' ' && *s != '\t')
514 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
518 /* stash this away */
521 /* copy the program name first */
523 nargv[i++] = *(ac++);
525 /* take a copy of $GZIP and add it to the array */
530 /* Skip whitespaces. */
531 while (*s == ' ' || *s == '\t')
536 /* Find the end of this argument. */
537 while (*s != ' ' && *s != '\t')
539 /* Argument followed by NUL. */
541 /* Terminate by overwriting ' ' or '\t' with NUL. */
546 /* copy the original arguments and a NULL */
548 nargv[i++] = *(ac++);
553 /* compress input to output. Return bytes read, -1 on error */
555 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
558 char *outbufp, *inbufp;
559 off_t in_tot = 0, out_tot = 0;
564 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
569 outbufp = malloc(BUFLEN);
570 inbufp = malloc(BUFLEN);
571 if (outbufp == NULL || inbufp == NULL) {
572 maybe_err("malloc failed");
576 memset(&z, 0, sizeof z);
582 memcpy(outbufp, header, sizeof header);
590 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
591 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
592 *origname ? ORIG_NAME : 0,
595 (mtime >> 16) & 0xff,
596 (mtime >> 24) & 0xff,
597 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
600 /* this need PATH_MAX > BUFLEN ... */
601 maybe_err("snprintf");
606 z.next_out = (unsigned char *)outbufp + i;
607 z.avail_out = BUFLEN - i;
609 error = deflateInit2(&z, numflag, Z_DEFLATED,
610 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
612 maybe_warnx("deflateInit2 failed");
617 crc = crc32(0L, Z_NULL, 0);
619 if (z.avail_out == 0) {
620 if (write(out, outbufp, BUFLEN) != BUFLEN) {
627 z.next_out = (unsigned char *)outbufp;
628 z.avail_out = BUFLEN;
631 if (z.avail_in == 0) {
632 in_size = read(in, inbufp, BUFLEN);
641 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
643 z.next_in = (unsigned char *)inbufp;
644 z.avail_in = in_size;
647 error = deflate(&z, Z_NO_FLUSH);
648 if (error != Z_OK && error != Z_STREAM_END) {
649 maybe_warnx("deflate failed");
660 error = deflate(&z, Z_FINISH);
661 if (error != Z_OK && error != Z_STREAM_END) {
662 maybe_warnx("deflate failed");
667 len = (char *)z.next_out - outbufp;
669 w = write(out, outbufp, len);
670 if (w == -1 || (size_t)w != len) {
676 z.next_out = (unsigned char *)outbufp;
677 z.avail_out = BUFLEN;
679 if (error == Z_STREAM_END)
683 if (deflateEnd(&z) != Z_OK) {
684 maybe_warnx("deflateEnd failed");
689 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
691 (int)(crc >> 8) & 0xff,
692 (int)(crc >> 16) & 0xff,
693 (int)(crc >> 24) & 0xff,
695 (int)(in_tot >> 8) & 0xff,
696 (int)(in_tot >> 16) & 0xff,
697 (int)(in_tot >> 24) & 0xff);
699 maybe_err("snprintf");
700 if (write(out, outbufp, i) != i) {
717 * uncompress input to output then close the input. return the
718 * uncompressed size written, and put the compressed sized read
722 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
723 const char *filename)
726 char *outbufp, *inbufp;
727 off_t out_tot = -1, in_tot = 0;
728 uint32_t out_sub_tot = 0;
746 } state = GZSTATE_MAGIC0;
747 int flags = 0, skip_count = 0;
748 int error = Z_STREAM_ERROR, done_reading = 0;
753 #define ADVANCE() { z.next_in++; z.avail_in--; }
755 if ((outbufp = malloc(BUFLEN)) == NULL) {
756 maybe_err("malloc failed");
759 if ((inbufp = malloc(BUFLEN)) == NULL) {
760 maybe_err("malloc failed");
764 memset(&z, 0, sizeof z);
766 z.next_in = (unsigned char *)pre;
767 z.avail_out = BUFLEN;
768 z.next_out = (unsigned char *)outbufp;
777 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
780 if (z.avail_in > 0) {
781 memmove(inbufp, z.next_in, z.avail_in);
783 z.next_in = (unsigned char *)inbufp;
784 in_size = read(in, z.next_in + z.avail_in,
785 BUFLEN - z.avail_in);
788 maybe_warn("failed to read stdin");
790 } else if (in_size == 0) {
794 z.avail_in += in_size;
799 if (z.avail_in == 0) {
800 if (done_reading && state != GZSTATE_MAGIC0) {
801 maybe_warnx("%s: unexpected end of file",
809 if (*z.next_in != GZIP_MAGIC0) {
811 maybe_warnx("%s: trailing garbage "
812 "ignored", filename);
815 maybe_warnx("input not gziped (MAGIC0)");
821 crc = crc32(0L, Z_NULL, 0);
825 if (*z.next_in != GZIP_MAGIC1 &&
826 *z.next_in != GZIP_OMAGIC1) {
827 maybe_warnx("input not gziped (MAGIC1)");
835 if (*z.next_in != Z_DEFLATED) {
836 maybe_warnx("unknown compression method");
850 case GZSTATE_SKIPPING:
851 if (skip_count > 0) {
859 if ((flags & EXTRA_FIELD) == 0) {
860 state = GZSTATE_ORIGNAME;
863 skip_count = *z.next_in;
869 skip_count |= ((*z.next_in) << 8);
875 if (skip_count > 0) {
882 case GZSTATE_ORIGNAME:
883 if ((flags & ORIG_NAME) == 0) {
892 case GZSTATE_COMMENT:
893 if ((flags & COMMENT) == 0) {
902 case GZSTATE_HEAD_CRC1:
903 if (flags & HEAD_CRC)
910 case GZSTATE_HEAD_CRC2:
911 if (skip_count > 0) {
919 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
920 maybe_warnx("failed to inflateInit");
927 error = inflate(&z, Z_FINISH);
929 /* Z_BUF_ERROR goes with Z_FINISH... */
931 if (z.avail_out > 0 && !done_reading)
939 maybe_warnx("Z_NEED_DICT error");
942 maybe_warnx("data stream error");
945 maybe_warnx("internal stream error");
948 maybe_warnx("memory allocation error");
952 maybe_warn("unknown error from inflate(): %d",
955 wr = BUFLEN - z.avail_out;
958 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
961 /* don't write anything with -t */
964 write(out, outbufp, wr) != wr) {
965 maybe_warn("error writing to output");
973 if (error == Z_STREAM_END) {
978 z.next_out = (unsigned char *)outbufp;
979 z.avail_out = BUFLEN;
986 if (z.avail_in < 4) {
991 maybe_warnx("truncated input");
994 origcrc = ((unsigned)z.next_in[0] & 0xff) |
995 ((unsigned)z.next_in[1] & 0xff) << 8 |
996 ((unsigned)z.next_in[2] & 0xff) << 16 |
997 ((unsigned)z.next_in[3] & 0xff) << 24;
998 if (origcrc != crc) {
999 maybe_warnx("invalid compressed"
1000 " data--crc error");
1008 if (!z.avail_in && done_reading) {
1017 if (z.avail_in < 4) {
1018 if (!done_reading) {
1022 maybe_warnx("truncated input");
1025 origlen = ((unsigned)z.next_in[0] & 0xff) |
1026 ((unsigned)z.next_in[1] & 0xff) << 8 |
1027 ((unsigned)z.next_in[2] & 0xff) << 16 |
1028 ((unsigned)z.next_in[3] & 0xff) << 24;
1030 if (origlen != out_sub_tot) {
1031 maybe_warnx("invalid compressed"
1032 " data--length error");
1041 maybe_warnx("decompression error");
1044 state = GZSTATE_MAGIC0;
1053 if (state > GZSTATE_INIT)
1067 * set the owner, mode, flags & utimes using the given file descriptor.
1068 * file is only used in possible warning messages.
1071 copymodes(int fd, const struct stat *sbp, const char *file)
1073 struct timeval times[2];
1077 * If we have no info on the input, give this file some
1078 * default values and return..
1081 mode_t mask = umask(022);
1083 (void)fchmod(fd, DEFFILEMODE & ~mask);
1089 /* if the chown fails, remove set-id bits as-per compress(1) */
1090 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1092 maybe_warn("couldn't fchown: %s", file);
1093 sb.st_mode &= ~(S_ISUID|S_ISGID);
1096 /* we only allow set-id and the 9 normal permission bits */
1097 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1098 if (fchmod(fd, sb.st_mode) < 0)
1099 maybe_warn("couldn't fchmod: %s", file);
1101 TIMESPEC_TO_TIMEVAL(×[0], &sb.st_atim);
1102 TIMESPEC_TO_TIMEVAL(×[1], &sb.st_mtim);
1103 if (futimes(fd, times) < 0)
1104 maybe_warn("couldn't utimes: %s", file);
1106 /* only try flags if they exist already */
1107 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1108 maybe_warn("couldn't fchflags: %s", file);
1112 /* what sort of file is this? */
1113 static enum filetype
1114 file_gettype(u_char *buf)
1117 if (buf[0] == GZIP_MAGIC0 &&
1118 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1121 #ifndef NO_BZIP2_SUPPORT
1122 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1123 buf[3] >= '0' && buf[3] <= '9')
1127 #ifndef NO_COMPRESS_SUPPORT
1128 if (memcmp(buf, Z_MAGIC, 2) == 0)
1132 #ifndef NO_PACK_SUPPORT
1133 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1137 #ifndef NO_XZ_SUPPORT
1138 if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */
1146 /* check the outfile is OK. */
1148 check_outfile(const char *outfile)
1153 if (lflag == 0 && stat(outfile, &sb) == 0) {
1156 else if (isatty(STDIN_FILENO)) {
1157 char ans[10] = { 'n', '\0' }; /* default */
1159 fprintf(stderr, "%s already exists -- do you wish to "
1160 "overwrite (y or n)? " , outfile);
1161 (void)fgets(ans, sizeof(ans) - 1, stdin);
1162 if (ans[0] != 'y' && ans[0] != 'Y') {
1163 fprintf(stderr, "\tnot overwriting\n");
1168 maybe_warnx("%s already exists -- skipping", outfile);
1176 unlink_input(const char *file, const struct stat *sb)
1182 if (stat(file, &nsb) != 0)
1183 /* Must be gone already */
1185 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1186 /* Definitely a different file */
1192 sigint_handler(int signo __unused)
1195 if (remove_file != NULL)
1196 unlink(remove_file);
1201 static const suffixes_t *
1202 check_suffix(char *file, int xlate)
1204 const suffixes_t *s;
1205 int len = strlen(file);
1208 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1209 /* if it doesn't fit in "a.suf", don't bother */
1210 if (s->ziplen >= len)
1212 sp = file + len - s->ziplen;
1213 if (strcmp(s->zipped, sp) != 0)
1216 strcpy(sp, s->normal);
1223 * compress the given file: create a corresponding .gz file and remove the
1227 file_compress(char *file, char *outfile, size_t outsize)
1233 struct stat isb, osb;
1234 const suffixes_t *suff;
1237 in = open(file, O_RDONLY);
1239 maybe_warn("can't open %s", file);
1244 if (fstat(in, &isb) != 0) {
1245 maybe_warn("couldn't stat: %s", file);
1253 if (isb.st_nlink > 1 && fflag == 0) {
1254 maybe_warnx("%s has %d other link%s -- skipping",
1255 file, isb.st_nlink - 1,
1256 (isb.st_nlink - 1) == 1 ? "" : "s");
1261 if (fflag == 0 && (suff = check_suffix(file, 0)) &&
1262 suff->zipped[0] != 0) {
1263 maybe_warnx("%s already has %s suffix -- unchanged",
1264 file, suff->zipped);
1270 /* Add (usually) .gz to filename */
1271 if ((size_t)snprintf(outfile, outsize, "%s%s",
1272 file, suffixes[0].zipped) >= outsize)
1273 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1274 suffixes[0].zipped, suffixes[0].ziplen + 1);
1277 if (check_outfile(outfile) == 0) {
1285 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1287 maybe_warn("could not create output: %s", outfile);
1292 remove_file = outfile;
1295 out = STDOUT_FILENO;
1297 insize = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1302 * If there was an error, insize will be -1.
1303 * If we compressed to stdout, just return the size.
1304 * Otherwise stat the file and check it is the correct size.
1305 * We only blow away the file if we can stat the output and it
1306 * has the expected size.
1309 return (insize == -1 ? -1 : size);
1312 if (fstat(out, &osb) != 0) {
1313 maybe_warn("couldn't stat: %s", outfile);
1317 if (osb.st_size != size) {
1318 maybe_warnx("output file: %s wrong size (%ju != %ju), deleting",
1319 outfile, (uintmax_t)osb.st_size, (uintmax_t)size);
1323 copymodes(out, &isb, outfile);
1326 if (close(out) == -1)
1327 maybe_warn("couldn't close output");
1329 /* output is good, ok to delete input */
1330 unlink_input(file, &isb);
1335 if (close(out) == -1)
1336 maybe_warn("couldn't close output");
1338 maybe_warnx("leaving original %s", file);
1344 /* uncompress the given file and remove the original */
1346 file_uncompress(char *file, char *outfile, size_t outsize)
1348 struct stat isb, osb;
1351 unsigned char header1[4];
1352 enum filetype method;
1353 int fd, ofd, zfd = -1;
1356 time_t timestamp = 0;
1357 char name[PATH_MAX + 1];
1360 /* gather the old name info */
1362 fd = open(file, O_RDONLY);
1364 maybe_warn("can't open %s", file);
1368 strlcpy(outfile, file, outsize);
1369 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1370 maybe_warnx("%s: unknown suffix -- ignored", file);
1374 rbytes = read(fd, header1, sizeof header1);
1375 if (rbytes != sizeof header1) {
1376 /* we don't want to fail here. */
1382 maybe_warn("can't read %s", file);
1384 goto unexpected_EOF;
1388 method = file_gettype(header1);
1390 if (fflag == 0 && method == FT_UNKNOWN) {
1391 maybe_warnx("%s: not in gzip format", file);
1398 if (method == FT_GZIP && Nflag) {
1399 unsigned char ts[4]; /* timestamp */
1401 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1402 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1403 goto unexpected_EOF;
1406 maybe_warn("can't read %s", file);
1409 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1411 if (header1[3] & ORIG_NAME) {
1412 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1414 maybe_warn("can't read %s", file);
1417 if (name[0] != '\0') {
1420 /* Make sure that name is NUL-terminated */
1421 name[rbytes] = '\0';
1423 /* strip saved directory name */
1424 nf = strrchr(name, '/');
1430 /* preserve original directory name */
1431 dp = strrchr(file, '/');
1436 snprintf(outfile, outsize, "%.*s%.*s",
1438 file, (int) rbytes, nf);
1443 lseek(fd, 0, SEEK_SET);
1445 if (cflag == 0 || lflag) {
1446 if (fstat(fd, &isb) != 0)
1449 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1450 maybe_warnx("%s has %d other links -- skipping",
1451 file, isb.st_nlink - 1);
1454 if (nflag == 0 && timestamp)
1455 isb.st_mtime = timestamp;
1456 if (check_outfile(outfile) == 0)
1461 if (cflag == 0 && lflag == 0) {
1462 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1463 if (zfd == STDOUT_FILENO) {
1464 /* We won't close STDOUT_FILENO later... */
1466 close(STDOUT_FILENO);
1469 maybe_warn("can't open %s", outfile);
1473 remove_file = outfile;
1476 zfd = STDOUT_FILENO;
1479 #ifndef NO_BZIP2_SUPPORT
1483 maybe_warnx("no -l with bzip2 files");
1487 size = unbzip2(fd, zfd, NULL, 0, NULL);
1491 #ifndef NO_COMPRESS_SUPPORT
1497 maybe_warnx("no -l with Lempel-Ziv files");
1501 if ((in = zdopen(fd)) == NULL) {
1502 maybe_warn("zdopen for read: %s", file);
1506 out = fdopen(dup(zfd), "w");
1508 maybe_warn("fdopen for write: %s", outfile);
1513 size = zuncompress(in, out, NULL, 0, NULL);
1514 /* need to fclose() if ferror() is true... */
1515 if (ferror(in) | fclose(in)) {
1516 maybe_warn("failed infile fclose");
1520 if (fclose(out) != 0) {
1521 maybe_warn("failed outfile fclose");
1529 #ifndef NO_PACK_SUPPORT
1532 maybe_warnx("no -l with packed files");
1536 size = unpack(fd, zfd, NULL, 0, NULL);
1540 #ifndef NO_XZ_SUPPORT
1543 maybe_warnx("no -l with xz files");
1547 size = unxz(fd, zfd, NULL, 0, NULL);
1554 maybe_warnx("no -l for unknown filetypes");
1557 size = cat_fd(NULL, 0, NULL, fd);
1562 print_list(fd, isb.st_size, outfile, isb.st_mtime);
1564 return -1; /* XXX */
1567 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1572 maybe_warn("couldn't close input");
1573 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1574 maybe_warn("couldn't close output");
1579 maybe_warnx("%s: uncompress failed", file);
1583 /* if testing, or we uncompressed to stdout, this is all we need */
1588 /* if we are uncompressing to stdin, don't remove the file. */
1593 * if we create a file...
1596 * if we can't stat the file don't remove the file.
1599 ofd = open(outfile, O_RDWR, 0);
1601 maybe_warn("couldn't open (leaving original): %s",
1605 if (fstat(ofd, &osb) != 0) {
1606 maybe_warn("couldn't stat (leaving original): %s",
1611 if (osb.st_size != size) {
1612 maybe_warnx("stat gave different size: %ju != %ju (leaving original)",
1613 (uintmax_t)size, (uintmax_t)osb.st_size);
1619 copymodes(ofd, &isb, outfile);
1623 unlink_input(file, &isb);
1627 maybe_warnx("%s: unexpected end of file", file);
1631 if (zfd != -1 && zfd != STDOUT_FILENO)
1638 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1645 w = write(STDOUT_FILENO, prepend, count);
1646 if (w == -1 || (size_t)w != count) {
1647 maybe_warn("write to stdout");
1653 rv = read(fd, buf, sizeof buf);
1657 maybe_warn("read from fd %d", fd);
1661 if (write(STDOUT_FILENO, buf, rv) != rv) {
1662 maybe_warn("write to stdout");
1677 unsigned char header1[4];
1679 enum filetype method;
1681 #ifndef NO_COMPRESS_SUPPORT
1686 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1687 maybe_warnx("standard input is a terminal -- ignoring");
1695 /* XXX could read the whole file, etc. */
1696 if (fstat(STDIN_FILENO, &isb) < 0) {
1697 maybe_warn("fstat");
1700 print_list(STDIN_FILENO, isb.st_size, "stdout", isb.st_mtime);
1704 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1705 if (bytes_read == -1) {
1706 maybe_warn("can't read stdin");
1708 } else if (bytes_read != sizeof(header1)) {
1709 maybe_warnx("(stdin): unexpected end of file");
1713 method = file_gettype(header1);
1718 maybe_warnx("unknown compression format");
1721 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1725 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1726 (char *)header1, sizeof header1, &gsize, "(stdin)");
1728 #ifndef NO_BZIP2_SUPPORT
1730 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1731 (char *)header1, sizeof header1, &gsize);
1734 #ifndef NO_COMPRESS_SUPPORT
1736 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1737 maybe_warnx("zopen of stdin");
1741 usize = zuncompress(in, stdout, (char *)header1,
1742 sizeof header1, &gsize);
1746 #ifndef NO_PACK_SUPPORT
1748 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1749 (char *)header1, sizeof header1, &gsize);
1752 #ifndef NO_XZ_SUPPORT
1754 usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1755 (char *)header1, sizeof header1, &gsize);
1761 if (vflag && !tflag && usize != -1 && gsize != -1)
1762 print_verbage(NULL, NULL, usize, gsize);
1764 print_test("(stdin)", usize != -1);
1779 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1780 maybe_warnx("standard output is a terminal -- ignoring");
1784 /* If stdin is a file use its mtime, otherwise use current time */
1785 ret = fstat(STDIN_FILENO, &sb);
1789 maybe_warn("Can't stat stdin");
1794 if (S_ISREG(sb.st_mode))
1795 mtime = (uint32_t)sb.st_mtime;
1797 systime = time(NULL);
1799 if (systime == -1) {
1804 mtime = (uint32_t)systime;
1807 usize = gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1809 if (vflag && !tflag && usize != -1 && gsize != -1)
1810 print_verbage(NULL, NULL, usize, gsize);
1814 /* do what is asked for, for the path name */
1816 handle_pathname(char *path)
1818 char *opath = path, *s = NULL;
1823 /* check for stdout/stdin */
1824 if (path[0] == '-' && path[1] == '\0') {
1833 if (stat(path, &sb) != 0 || (fflag == 0 && cflag == 0 &&
1834 lstat(path, &sb) != 0)) {
1835 /* lets try <path>.gz if we're decompressing */
1836 if (dflag && s == NULL && errno == ENOENT) {
1838 slen = suffixes[0].ziplen;
1839 s = malloc(len + slen + 1);
1841 maybe_err("malloc");
1842 memcpy(s, path, len);
1843 memcpy(s + len, suffixes[0].zipped, slen + 1);
1847 maybe_warn("can't stat: %s", opath);
1851 if (S_ISDIR(sb.st_mode)) {
1857 maybe_warnx("%s is a directory", path);
1861 if (S_ISREG(sb.st_mode))
1862 handle_file(path, &sb);
1864 maybe_warnx("%s is not a regular file", path);
1871 /* compress/decompress a file */
1873 handle_file(char *file, struct stat *sbp)
1876 char outfile[PATH_MAX];
1880 usize = file_uncompress(file, outfile, sizeof(outfile));
1883 print_test(file, usize != -1);
1887 gsize = sbp->st_size;
1889 gsize = file_compress(file, outfile, sizeof(outfile));
1892 usize = sbp->st_size;
1897 if (vflag && !tflag)
1898 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1903 /* this is used with -r to recursively descend directories */
1905 handle_dir(char *dir)
1913 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1915 warn("couldn't fts_open %s", dir);
1919 while ((entry = fts_read(fts))) {
1920 switch(entry->fts_info) {
1928 maybe_warn("%s", entry->fts_path);
1931 handle_file(entry->fts_path, entry->fts_statp);
1934 (void)fts_close(fts);
1938 /* print a ratio - size reduction as a fraction of uncompressed size */
1940 print_ratio(off_t in, off_t out, FILE *where)
1942 int percent10; /* 10 * percent */
1950 * Output is more than double size of input! print -99.9%
1951 * Quite possibly we've failed to get the original size.
1956 * We only need 12 bits of result from the final division,
1957 * so reduce the values until a 32bit division will suffice.
1959 while (in > 0x100000) {
1964 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
1969 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
1970 /* Move the '.' to before the last digit */
1971 buff[len - 1] = buff[len - 2];
1972 buff[len - 2] = '.';
1973 fprintf(where, "%5s%%", buff);
1977 /* print compression statistics, and the new name (if there is one!) */
1979 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
1982 fprintf(stderr, "%s:%s ", file,
1983 strlen(file) < 7 ? "\t\t" : "\t");
1984 print_ratio(usize, gsize, stderr);
1986 fprintf(stderr, " -- replaced with %s", nfile);
1987 fprintf(stderr, "\n");
1991 /* print test results */
1993 print_test(const char *file, int ok)
1996 if (exit_value == 0 && ok == 0)
1998 fprintf(stderr, "%s:%s %s\n", file,
1999 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2004 /* print a file's info ala --list */
2006 compressed uncompressed ratio uncompressed_name
2007 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2010 print_list(int fd, off_t out, const char *outfile, time_t ts)
2012 static int first = 1;
2014 static off_t in_tot, out_tot;
2022 printf("method crc date time ");
2025 printf(" compressed uncompressed "
2026 "ratio uncompressed_name\n");
2038 /* read the last 4 bytes - this is the uncompressed size */
2039 rv = lseek(fd, (off_t)(-8), SEEK_END);
2041 unsigned char buf[8];
2044 rv = read(fd, (char *)buf, sizeof(buf));
2046 maybe_warn("read of uncompressed size");
2047 else if (rv != sizeof(buf))
2048 maybe_warnx("read of uncompressed size");
2051 usize = buf[4] | buf[5] << 8 |
2052 buf[6] << 16 | buf[7] << 24;
2055 crc = buf[0] | buf[1] << 8 |
2056 buf[2] << 16 | buf[3] << 24;
2063 if (vflag && fd == -1)
2066 char *date = ctime(&ts);
2068 /* skip the day, 1/100th second, and year */
2071 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2076 (void)&ts; /* XXX */
2078 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2079 print_ratio(in, out, stdout);
2080 printf(" %s\n", outfile);
2083 /* display the usage of NetBSD gzip */
2088 fprintf(stderr, "%s\n", gzip_version);
2091 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
2093 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2094 " -1 --fast fastest (worst) compression\n"
2095 " -2 .. -8 set compression level\n"
2096 " -9 --best best (slowest) compression\n"
2097 " -c --stdout write to stdout, keep original files\n"
2099 " -d --decompress uncompress files\n"
2101 " -f --force force overwriting & compress links\n"
2102 " -h --help display this help\n"
2103 " -k --keep don't delete input files during operation\n"
2104 " -l --list list compressed file contents\n"
2105 " -N --name save or restore original file name and time stamp\n"
2106 " -n --no-name don't save original file name or time stamp\n"
2107 " -q --quiet output no warnings\n"
2108 " -r --recursive recursively compress files in directories\n"
2109 " -S .suf use suffix .suf instead of .gz\n"
2111 " -t --test test compressed file\n"
2112 " -V --version display program version\n"
2113 " -v --verbose print extra statistics\n",
2120 /* display the license information of FreeBSD gzip */
2122 display_license(void)
2125 fprintf(stderr, "%s (based on NetBSD gzip 20150113)\n", gzip_version);
2126 fprintf(stderr, "%s\n", gzip_copyright);
2131 /* display the version of NetBSD gzip */
2133 display_version(void)
2136 fprintf(stderr, "%s\n", gzip_version);
2140 #ifndef NO_BZIP2_SUPPORT
2141 #include "unbzip2.c"
2143 #ifndef NO_COMPRESS_SUPPORT
2144 #include "zuncompress.c"
2146 #ifndef NO_PACK_SUPPORT
2149 #ifndef NO_XZ_SUPPORT
2154 read_retry(int fd, void *buf, size_t sz)
2157 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2162 ret = read(fd, cp, left);
2165 } else if (ret == 0) {