1 /* $NetBSD: gzip.c,v 1.113 2018/06/12 00:42:17 kamil Exp $ */
4 * SPDX-License-Identifier: BSD-2-Clause-NetBSD
6 * Copyright (c) 1997, 1998, 2003, 2004, 2006, 2008, 2009, 2010, 2011, 2015, 2017
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
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 #include <sys/cdefs.h>
35 __COPYRIGHT("@(#) Copyright (c) 1997, 1998, 2003, 2004, 2006, 2008,\
36 2009, 2010, 2011, 2015, 2017 Matthew R. Green. All rights reserved.");
37 __FBSDID("$FreeBSD$");
41 * gzip.c -- GPL free gzip using zlib.
43 * RFC 1950 covers the zlib format
44 * RFC 1951 covers the deflate format
45 * RFC 1952 covers the gzip format
48 * - use mmap where possible
49 * - make bzip2/compress -v/-t/-l support work as well as possible
52 #include <sys/endian.h>
53 #include <sys/param.h>
72 /* what type of file are we dealing with */
75 #ifndef NO_BZIP2_SUPPORT
78 #ifndef NO_COMPRESS_SUPPORT
81 #ifndef NO_PACK_SUPPORT
91 #ifndef NO_BZIP2_SUPPORT
94 #define BZ2_SUFFIX ".bz2"
95 #define BZIP2_MAGIC "BZh"
98 #ifndef NO_COMPRESS_SUPPORT
100 #define Z_MAGIC "\037\235"
103 #ifndef NO_PACK_SUPPORT
104 #define PACK_MAGIC "\037\036"
107 #ifndef NO_XZ_SUPPORT
109 #define XZ_SUFFIX ".xz"
110 #define XZ_MAGIC "\3757zXZ"
113 #define GZ_SUFFIX ".gz"
115 #define BUFLEN (64 * 1024)
117 #define GZIP_MAGIC0 0x1F
118 #define GZIP_MAGIC1 0x8B
119 #define GZIP_OMAGIC1 0x9E
121 #define GZIP_TIMESTAMP (off_t)4
122 #define GZIP_ORIGNAME (off_t)10
124 #define HEAD_CRC 0x02
125 #define EXTRA_FIELD 0x04
126 #define ORIG_NAME 0x08
129 #define OS_CODE 3 /* Unix */
134 const char *normal; /* for unzip - must not be longer than zipped */
136 static suffixes_t suffixes[] = {
137 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
138 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
140 SUFFIX(GZ_SUFFIX, ""),
145 SUFFIX(".taz", ".tar"),
146 SUFFIX(".tgz", ".tar"),
147 #ifndef NO_BZIP2_SUPPORT
148 SUFFIX(BZ2_SUFFIX, ""),
149 SUFFIX(".tbz", ".tar"),
150 SUFFIX(".tbz2", ".tar"),
152 #ifndef NO_COMPRESS_SUPPORT
153 SUFFIX(Z_SUFFIX, ""),
155 #ifndef NO_XZ_SUPPORT
156 SUFFIX(XZ_SUFFIX, ""),
158 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
162 #define NUM_SUFFIXES (nitems(suffixes))
163 #define SUFFIX_MAXLEN 30
165 static const char gzip_version[] = "FreeBSD gzip 20171121";
168 static const char gzip_copyright[] = \
169 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
170 " All rights reserved.\n"
172 " Redistribution and use in source and binary forms, with or without\n"
173 " modification, are permitted provided that the following conditions\n"
175 " 1. Redistributions of source code must retain the above copyright\n"
176 " notice, this list of conditions and the following disclaimer.\n"
177 " 2. Redistributions in binary form must reproduce the above copyright\n"
178 " notice, this list of conditions and the following disclaimer in the\n"
179 " documentation and/or other materials provided with the distribution.\n"
181 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
182 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
183 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
184 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
185 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
186 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
187 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
188 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
189 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
190 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
194 static int cflag; /* stdout mode */
195 static int dflag; /* decompress mode */
196 static int lflag; /* list mode */
197 static int numflag = 6; /* gzip -1..-9 value */
199 static const char *remove_file = NULL; /* file to be removed upon SIGINT */
201 static int fflag; /* force mode */
203 static int kflag; /* don't delete input files */
204 static int nflag; /* don't save name/timestamp */
205 static int Nflag; /* don't restore name/timestamp */
206 static int qflag; /* quiet mode */
207 static int rflag; /* recursive mode */
208 static int tflag; /* test */
209 static int vflag; /* verbose mode */
210 static sig_atomic_t print_info = 0;
216 static int exit_value = 0; /* exit value */
218 static const char *infile; /* name of file coming in */
220 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead2;
221 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
222 !defined(NO_XZ_SUPPORT)
223 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead2;
225 static void maybe_warn(const char *fmt, ...) __printflike(1, 2);
226 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2);
227 static enum filetype file_gettype(u_char *);
229 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
231 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
232 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
233 static off_t file_compress(char *, char *, size_t);
234 static off_t file_uncompress(char *, char *, size_t);
235 static void handle_pathname(char *);
236 static void handle_file(char *, struct stat *);
237 static void handle_stdin(void);
238 static void handle_stdout(void);
239 static void print_ratio(off_t, off_t, FILE *);
240 static void print_list(int fd, off_t, const char *, time_t);
241 static void usage(void) __dead2;
242 static void display_version(void) __dead2;
244 static void display_license(void);
246 static const suffixes_t *check_suffix(char *, int);
247 static ssize_t read_retry(int, void *, size_t);
248 static ssize_t write_retry(int, const void *, size_t);
251 #define infile_set(f,t) infile_set(f)
253 static void infile_set(const char *newinfile, off_t total);
256 #define unlink_input(f, sb) unlink(f)
257 #define check_siginfo() /* nothing */
258 #define setup_signals() /* nothing */
259 #define infile_newdata(t) /* nothing */
261 static off_t infile_total; /* total expected to read/write */
262 static off_t infile_current; /* current read/write */
264 static void check_siginfo(void);
265 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
266 static void prepend_gzip(char *, int *, char ***);
267 static void handle_dir(char *);
268 static void print_verbage(const char *, const char *, off_t, off_t);
269 static void print_test(const char *, int);
270 static void copymodes(int fd, const struct stat *, const char *file);
271 static int check_outfile(const char *outfile);
272 static void setup_signals(void);
273 static void infile_newdata(size_t newdata);
274 static void infile_clear(void);
277 #ifndef NO_BZIP2_SUPPORT
278 static off_t unbzip2(int, int, char *, size_t, off_t *);
281 #ifndef NO_COMPRESS_SUPPORT
282 static FILE *zdopen(int);
283 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
286 #ifndef NO_PACK_SUPPORT
287 static off_t unpack(int, int, char *, size_t, off_t *);
290 #ifndef NO_XZ_SUPPORT
291 static off_t unxz(int, int, char *, size_t, off_t *);
295 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
297 static const struct option longopts[] = {
298 { "stdout", no_argument, 0, 'c' },
299 { "to-stdout", no_argument, 0, 'c' },
300 { "decompress", no_argument, 0, 'd' },
301 { "uncompress", no_argument, 0, 'd' },
302 { "force", no_argument, 0, 'f' },
303 { "help", no_argument, 0, 'h' },
304 { "keep", no_argument, 0, 'k' },
305 { "list", no_argument, 0, 'l' },
306 { "no-name", no_argument, 0, 'n' },
307 { "name", no_argument, 0, 'N' },
308 { "quiet", no_argument, 0, 'q' },
309 { "recursive", no_argument, 0, 'r' },
310 { "suffix", required_argument, 0, 'S' },
311 { "test", no_argument, 0, 't' },
312 { "verbose", no_argument, 0, 'v' },
313 { "version", no_argument, 0, 'V' },
314 { "fast", no_argument, 0, '1' },
315 { "best", no_argument, 0, '9' },
316 { "ascii", no_argument, 0, 'a' },
317 { "license", no_argument, 0, 'L' },
318 { NULL, no_argument, 0, 0 },
323 main(int argc, char **argv)
325 const char *progname = getprogname();
335 if ((gzip = getenv("GZIP")) != NULL)
336 prepend_gzip(gzip, &argc, &argv);
341 * handle being called `gunzip', `zcat' and `gzcat'
343 if (strcmp(progname, "gunzip") == 0)
345 else if (strcmp(progname, "zcat") == 0 ||
346 strcmp(progname, "gzcat") == 0)
350 #define OPT_LIST "123456789cdhlV"
352 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
355 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
357 case '1': case '2': case '3':
358 case '4': case '5': case '6':
359 case '7': case '8': case '9':
377 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
403 len = strlen(optarg);
405 if (len > SUFFIX_MAXLEN)
406 errx(1, "incorrect suffix: '%s': too long", optarg);
407 suffixes[0].zipped = optarg;
408 suffixes[0].ziplen = len;
410 suffixes[NUM_SUFFIXES - 1].zipped = "";
411 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
432 if (dflag) /* stdin mode */
434 else /* stdout mode */
438 handle_pathname(argv[0]);
442 if (qflag == 0 && lflag && argc > 1)
443 print_list(-1, 0, "(totals)", 0);
448 /* maybe print a warning */
450 maybe_warn(const char *fmt, ...)
463 /* ... without an errno. */
465 maybe_warnx(const char *fmt, ...)
478 /* maybe print an error */
480 maybe_err(const char *fmt, ...)
492 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
493 !defined(NO_XZ_SUPPORT)
494 /* ... without an errno. */
496 maybe_errx(const char *fmt, ...)
510 /* split up $GZIP and prepend it to the argument list */
512 prepend_gzip(char *gzip, int *argc, char ***argv)
514 char *s, **nargv, **ac;
517 /* scan how many arguments there are */
519 while (*s == ' ' || *s == '\t')
524 while (*s != ' ' && *s != '\t')
536 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
540 /* stash this away */
543 /* copy the program name first */
545 nargv[i++] = *(ac++);
547 /* take a copy of $GZIP and add it to the array */
552 /* Skip whitespaces. */
553 while (*s == ' ' || *s == '\t')
558 /* Find the end of this argument. */
559 while (*s != ' ' && *s != '\t')
561 /* Argument followed by NUL. */
563 /* Terminate by overwriting ' ' or '\t' with NUL. */
568 /* copy the original arguments and a NULL */
570 nargv[i++] = *(ac++);
575 /* compress input to output. Return bytes read, -1 on error */
577 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
580 char *outbufp, *inbufp;
581 off_t in_tot = 0, out_tot = 0;
586 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
591 outbufp = malloc(BUFLEN);
592 inbufp = malloc(BUFLEN);
593 if (outbufp == NULL || inbufp == NULL) {
594 maybe_err("malloc failed");
598 memset(&z, 0, sizeof z);
604 memcpy(outbufp, header, sizeof header);
612 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
613 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
614 *origname ? ORIG_NAME : 0,
617 (mtime >> 16) & 0xff,
618 (mtime >> 24) & 0xff,
619 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
622 /* this need PATH_MAX > BUFLEN ... */
623 maybe_err("snprintf");
628 z.next_out = (unsigned char *)outbufp + i;
629 z.avail_out = BUFLEN - i;
631 error = deflateInit2(&z, numflag, Z_DEFLATED,
632 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
634 maybe_warnx("deflateInit2 failed");
639 crc = crc32(0L, Z_NULL, 0);
641 if (z.avail_out == 0) {
642 if (write_retry(out, outbufp, BUFLEN) != BUFLEN) {
649 z.next_out = (unsigned char *)outbufp;
650 z.avail_out = BUFLEN;
653 if (z.avail_in == 0) {
654 in_size = read(in, inbufp, BUFLEN);
662 infile_newdata(in_size);
664 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
666 z.next_in = (unsigned char *)inbufp;
667 z.avail_in = in_size;
670 error = deflate(&z, Z_NO_FLUSH);
671 if (error != Z_OK && error != Z_STREAM_END) {
672 maybe_warnx("deflate failed");
683 error = deflate(&z, Z_FINISH);
684 if (error != Z_OK && error != Z_STREAM_END) {
685 maybe_warnx("deflate failed");
690 len = (char *)z.next_out - outbufp;
692 w = write_retry(out, outbufp, len);
693 if (w == -1 || (size_t)w != len) {
699 z.next_out = (unsigned char *)outbufp;
700 z.avail_out = BUFLEN;
702 if (error == Z_STREAM_END)
706 if (deflateEnd(&z) != Z_OK) {
707 maybe_warnx("deflateEnd failed");
712 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
714 (int)(crc >> 8) & 0xff,
715 (int)(crc >> 16) & 0xff,
716 (int)(crc >> 24) & 0xff,
718 (int)(in_tot >> 8) & 0xff,
719 (int)(in_tot >> 16) & 0xff,
720 (int)(in_tot >> 24) & 0xff);
722 maybe_err("snprintf");
723 if (write_retry(out, outbufp, i) != i) {
740 * uncompress input to output then close the input. return the
741 * uncompressed size written, and put the compressed sized read
745 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
746 const char *filename)
749 char *outbufp, *inbufp;
750 off_t out_tot = -1, in_tot = 0;
751 uint32_t out_sub_tot = 0;
769 } state = GZSTATE_MAGIC0;
770 int flags = 0, skip_count = 0;
771 int error = Z_STREAM_ERROR, done_reading = 0;
776 #define ADVANCE() { z.next_in++; z.avail_in--; }
778 if ((outbufp = malloc(BUFLEN)) == NULL) {
779 maybe_err("malloc failed");
782 if ((inbufp = malloc(BUFLEN)) == NULL) {
783 maybe_err("malloc failed");
787 memset(&z, 0, sizeof z);
789 z.next_in = (unsigned char *)pre;
790 z.avail_out = BUFLEN;
791 z.next_out = (unsigned char *)outbufp;
801 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
804 if (z.avail_in > 0) {
805 memmove(inbufp, z.next_in, z.avail_in);
807 z.next_in = (unsigned char *)inbufp;
808 in_size = read(in, z.next_in + z.avail_in,
809 BUFLEN - z.avail_in);
812 maybe_warn("failed to read stdin");
814 } else if (in_size == 0) {
817 infile_newdata(in_size);
819 z.avail_in += in_size;
824 if (z.avail_in == 0) {
825 if (done_reading && state != GZSTATE_MAGIC0) {
826 maybe_warnx("%s: unexpected end of file",
834 if (*z.next_in != GZIP_MAGIC0) {
836 maybe_warnx("%s: trailing garbage "
837 "ignored", filename);
841 maybe_warnx("input not gziped (MAGIC0)");
847 crc = crc32(0L, Z_NULL, 0);
851 if (*z.next_in != GZIP_MAGIC1 &&
852 *z.next_in != GZIP_OMAGIC1) {
853 maybe_warnx("input not gziped (MAGIC1)");
861 if (*z.next_in != Z_DEFLATED) {
862 maybe_warnx("unknown compression method");
876 case GZSTATE_SKIPPING:
877 if (skip_count > 0) {
885 if ((flags & EXTRA_FIELD) == 0) {
886 state = GZSTATE_ORIGNAME;
889 skip_count = *z.next_in;
895 skip_count |= ((*z.next_in) << 8);
901 if (skip_count > 0) {
908 case GZSTATE_ORIGNAME:
909 if ((flags & ORIG_NAME) == 0) {
918 case GZSTATE_COMMENT:
919 if ((flags & COMMENT) == 0) {
928 case GZSTATE_HEAD_CRC1:
929 if (flags & HEAD_CRC)
936 case GZSTATE_HEAD_CRC2:
937 if (skip_count > 0) {
945 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
946 maybe_warnx("failed to inflateInit");
953 error = inflate(&z, Z_FINISH);
955 /* Z_BUF_ERROR goes with Z_FINISH... */
957 if (z.avail_out > 0 && !done_reading)
965 maybe_warnx("Z_NEED_DICT error");
968 maybe_warnx("data stream error");
971 maybe_warnx("internal stream error");
974 maybe_warnx("memory allocation error");
978 maybe_warn("unknown error from inflate(): %d",
981 wr = BUFLEN - z.avail_out;
984 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
987 /* don't write anything with -t */
990 write_retry(out, outbufp, wr) != wr) {
991 maybe_warn("error writing to output");
999 if (error == Z_STREAM_END) {
1004 z.next_out = (unsigned char *)outbufp;
1005 z.avail_out = BUFLEN;
1012 if (z.avail_in < 4) {
1013 if (!done_reading) {
1017 maybe_warnx("truncated input");
1020 origcrc = le32dec(&z.next_in[0]);
1021 if (origcrc != crc) {
1022 maybe_warnx("invalid compressed"
1023 " data--crc error");
1031 if (!z.avail_in && done_reading) {
1040 if (z.avail_in < 4) {
1041 if (!done_reading) {
1045 maybe_warnx("truncated input");
1048 origlen = le32dec(&z.next_in[0]);
1050 if (origlen != out_sub_tot) {
1051 maybe_warnx("invalid compressed"
1052 " data--length error");
1061 maybe_warnx("decompression error");
1064 state = GZSTATE_MAGIC0;
1073 if (state > GZSTATE_INIT)
1087 * set the owner, mode, flags & utimes using the given file descriptor.
1088 * file is only used in possible warning messages.
1091 copymodes(int fd, const struct stat *sbp, const char *file)
1093 struct timespec times[2];
1097 * If we have no info on the input, give this file some
1098 * default values and return..
1101 mode_t mask = umask(022);
1103 (void)fchmod(fd, DEFFILEMODE & ~mask);
1109 /* if the chown fails, remove set-id bits as-per compress(1) */
1110 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1112 maybe_warn("couldn't fchown: %s", file);
1113 sb.st_mode &= ~(S_ISUID|S_ISGID);
1116 /* we only allow set-id and the 9 normal permission bits */
1117 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1118 if (fchmod(fd, sb.st_mode) < 0)
1119 maybe_warn("couldn't fchmod: %s", file);
1121 times[0] = sb.st_atim;
1122 times[1] = sb.st_mtim;
1123 if (futimens(fd, times) < 0)
1124 maybe_warn("couldn't futimens: %s", file);
1126 /* only try flags if they exist already */
1127 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1128 maybe_warn("couldn't fchflags: %s", file);
1132 /* what sort of file is this? */
1133 static enum filetype
1134 file_gettype(u_char *buf)
1137 if (buf[0] == GZIP_MAGIC0 &&
1138 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1141 #ifndef NO_BZIP2_SUPPORT
1142 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1143 buf[3] >= '0' && buf[3] <= '9')
1147 #ifndef NO_COMPRESS_SUPPORT
1148 if (memcmp(buf, Z_MAGIC, 2) == 0)
1152 #ifndef NO_PACK_SUPPORT
1153 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1157 #ifndef NO_XZ_SUPPORT
1158 if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */
1166 /* check the outfile is OK. */
1168 check_outfile(const char *outfile)
1173 if (lflag == 0 && stat(outfile, &sb) == 0) {
1176 else if (isatty(STDIN_FILENO)) {
1177 char ans[10] = { 'n', '\0' }; /* default */
1179 fprintf(stderr, "%s already exists -- do you wish to "
1180 "overwrite (y or n)? " , outfile);
1181 (void)fgets(ans, sizeof(ans) - 1, stdin);
1182 if (ans[0] != 'y' && ans[0] != 'Y') {
1183 fprintf(stderr, "\tnot overwriting\n");
1188 maybe_warnx("%s already exists -- skipping", outfile);
1196 unlink_input(const char *file, const struct stat *sb)
1202 if (stat(file, &nsb) != 0)
1203 /* Must be gone already */
1205 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1206 /* Definitely a different file */
1212 got_sigint(int signo __unused)
1215 if (remove_file != NULL)
1216 unlink(remove_file);
1221 got_siginfo(int signo __unused)
1231 signal(SIGINFO, got_siginfo);
1232 signal(SIGINT, got_sigint);
1236 infile_newdata(size_t newdata)
1239 infile_current += newdata;
1244 infile_set(const char *newinfile, off_t total)
1250 infile_total = total;
1260 infile_total = infile_current = 0;
1264 static const suffixes_t *
1265 check_suffix(char *file, int xlate)
1267 const suffixes_t *s;
1268 int len = strlen(file);
1271 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1272 /* if it doesn't fit in "a.suf", don't bother */
1273 if (s->ziplen >= len)
1275 sp = file + len - s->ziplen;
1276 if (strcmp(s->zipped, sp) != 0)
1279 strcpy(sp, s->normal);
1286 * compress the given file: create a corresponding .gz file and remove the
1290 file_compress(char *file, char *outfile, size_t outsize)
1294 off_t size, in_size;
1296 struct stat isb, osb;
1297 const suffixes_t *suff;
1300 in = open(file, O_RDONLY);
1302 maybe_warn("can't open %s", file);
1307 if (fstat(in, &isb) != 0) {
1308 maybe_warn("couldn't stat: %s", file);
1315 if (fstat(in, &isb) != 0) {
1317 maybe_warn("can't stat %s", file);
1320 infile_set(file, isb.st_size);
1325 if (isb.st_nlink > 1 && fflag == 0) {
1326 maybe_warnx("%s has %ju other link%s -- "
1328 (uintmax_t)isb.st_nlink - 1,
1329 isb.st_nlink == 1 ? "" : "s");
1334 if (fflag == 0 && (suff = check_suffix(file, 0)) &&
1335 suff->zipped[0] != 0) {
1336 maybe_warnx("%s already has %s suffix -- unchanged",
1337 file, suff->zipped);
1343 /* Add (usually) .gz to filename */
1344 if ((size_t)snprintf(outfile, outsize, "%s%s",
1345 file, suffixes[0].zipped) >= outsize)
1346 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1347 suffixes[0].zipped, suffixes[0].ziplen + 1);
1350 if (check_outfile(outfile) == 0) {
1358 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1360 maybe_warn("could not create output: %s", outfile);
1365 remove_file = outfile;
1368 out = STDOUT_FILENO;
1370 in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1375 * If there was an error, in_size will be -1.
1376 * If we compressed to stdout, just return the size.
1377 * Otherwise stat the file and check it is the correct size.
1378 * We only blow away the file if we can stat the output and it
1379 * has the expected size.
1382 return in_size == -1 ? -1 : size;
1385 if (fstat(out, &osb) != 0) {
1386 maybe_warn("couldn't stat: %s", outfile);
1390 if (osb.st_size != size) {
1391 maybe_warnx("output file: %s wrong size (%ju != %ju), deleting",
1392 outfile, (uintmax_t)osb.st_size, (uintmax_t)size);
1396 copymodes(out, &isb, outfile);
1399 if (close(out) == -1)
1400 maybe_warn("couldn't close output");
1402 /* output is good, ok to delete input */
1403 unlink_input(file, &isb);
1408 if (close(out) == -1)
1409 maybe_warn("couldn't close output");
1411 maybe_warnx("leaving original %s", file);
1417 /* uncompress the given file and remove the original */
1419 file_uncompress(char *file, char *outfile, size_t outsize)
1421 struct stat isb, osb;
1424 unsigned char header1[4];
1425 enum filetype method;
1426 int fd, ofd, zfd = -1;
1431 time_t timestamp = 0;
1432 char name[PATH_MAX + 1];
1435 /* gather the old name info */
1437 fd = open(file, O_RDONLY);
1439 maybe_warn("can't open %s", file);
1442 if (fstat(fd, &isb) != 0) {
1443 maybe_warn("can't stat %s", file);
1446 if (S_ISREG(isb.st_mode))
1447 in_size = isb.st_size;
1450 infile_set(file, in_size);
1452 strlcpy(outfile, file, outsize);
1453 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1454 maybe_warnx("%s: unknown suffix -- ignored", file);
1458 rbytes = read(fd, header1, sizeof header1);
1459 if (rbytes != sizeof header1) {
1460 /* we don't want to fail here. */
1466 maybe_warn("can't read %s", file);
1468 goto unexpected_EOF;
1471 infile_newdata(rbytes);
1473 method = file_gettype(header1);
1475 if (fflag == 0 && method == FT_UNKNOWN) {
1476 maybe_warnx("%s: not in gzip format", file);
1483 if (method == FT_GZIP && Nflag) {
1484 unsigned char ts[4]; /* timestamp */
1486 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1487 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1488 goto unexpected_EOF;
1491 maybe_warn("can't read %s", file);
1495 timestamp = le32dec(&ts[0]);
1497 if (header1[3] & ORIG_NAME) {
1498 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1500 maybe_warn("can't read %s", file);
1503 if (name[0] != '\0') {
1506 /* Make sure that name is NUL-terminated */
1507 name[rbytes] = '\0';
1509 /* strip saved directory name */
1510 nf = strrchr(name, '/');
1516 /* preserve original directory name */
1517 dp = strrchr(file, '/');
1522 snprintf(outfile, outsize, "%.*s%.*s",
1524 file, (int) rbytes, nf);
1529 lseek(fd, 0, SEEK_SET);
1531 if (cflag == 0 || lflag) {
1533 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1534 maybe_warnx("%s has %ju other links -- skipping",
1535 file, (uintmax_t)isb.st_nlink - 1);
1538 if (nflag == 0 && timestamp)
1539 isb.st_mtime = timestamp;
1540 if (check_outfile(outfile) == 0)
1546 zfd = STDOUT_FILENO;
1550 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1551 if (zfd == STDOUT_FILENO) {
1552 /* We won't close STDOUT_FILENO later... */
1554 close(STDOUT_FILENO);
1557 maybe_warn("can't open %s", outfile);
1560 remove_file = outfile;
1564 #ifndef NO_BZIP2_SUPPORT
1568 maybe_warnx("no -l with bzip2 files");
1572 size = unbzip2(fd, zfd, NULL, 0, NULL);
1576 #ifndef NO_COMPRESS_SUPPORT
1582 maybe_warnx("no -l with Lempel-Ziv files");
1586 if ((in = zdopen(fd)) == NULL) {
1587 maybe_warn("zdopen for read: %s", file);
1591 out = fdopen(dup(zfd), "w");
1593 maybe_warn("fdopen for write: %s", outfile);
1598 size = zuncompress(in, out, NULL, 0, NULL);
1599 /* need to fclose() if ferror() is true... */
1601 if (error | fclose(in)) {
1603 maybe_warn("failed infile");
1605 maybe_warn("failed infile fclose");
1611 if (fclose(out) != 0) {
1612 maybe_warn("failed outfile fclose");
1621 #ifndef NO_PACK_SUPPORT
1624 maybe_warnx("no -l with packed files");
1628 size = unpack(fd, zfd, NULL, 0, NULL);
1632 #ifndef NO_XZ_SUPPORT
1635 maybe_warnx("no -l with xz files");
1639 size = unxz(fd, zfd, NULL, 0, NULL);
1646 maybe_warnx("no -l for unknown filetypes");
1649 size = cat_fd(NULL, 0, NULL, fd);
1654 print_list(fd, in_size, outfile, isb.st_mtime);
1656 return -1; /* XXX */
1659 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1664 maybe_warn("couldn't close input");
1665 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1666 maybe_warn("couldn't close output");
1671 maybe_warnx("%s: uncompress failed", file);
1675 /* if testing, or we uncompressed to stdout, this is all we need */
1680 /* if we are uncompressing to stdin, don't remove the file. */
1685 * if we create a file...
1688 * if we can't stat the file don't remove the file.
1691 ofd = open(outfile, O_RDWR, 0);
1693 maybe_warn("couldn't open (leaving original): %s",
1697 if (fstat(ofd, &osb) != 0) {
1698 maybe_warn("couldn't stat (leaving original): %s",
1703 if (osb.st_size != size) {
1704 maybe_warnx("stat gave different size: %ju != %ju (leaving original)",
1705 (uintmax_t)size, (uintmax_t)osb.st_size);
1711 copymodes(ofd, &isb, outfile);
1715 unlink_input(file, &isb);
1719 maybe_warnx("%s: unexpected end of file", file);
1723 if (zfd != -1 && zfd != STDOUT_FILENO)
1732 if (print_info == 0)
1736 int pcent = (int)((100.0 * infile_current) / infile_total);
1738 fprintf(stderr, "%s: done %llu/%llu bytes %d%%\n",
1739 infile, (unsigned long long)infile_current,
1740 (unsigned long long)infile_total, pcent);
1742 fprintf(stderr, "%s: done %llu bytes\n",
1743 infile, (unsigned long long)infile_current);
1749 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1756 w = write_retry(STDOUT_FILENO, prepend, count);
1757 if (w == -1 || (size_t)w != count) {
1758 maybe_warn("write to stdout");
1764 rv = read(fd, buf, sizeof buf);
1768 maybe_warn("read from fd %d", fd);
1773 if (write_retry(STDOUT_FILENO, buf, rv) != rv) {
1774 maybe_warn("write to stdout");
1790 unsigned char header1[4];
1793 enum filetype method;
1795 #ifndef NO_COMPRESS_SUPPORT
1800 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1801 maybe_warnx("standard input is a terminal -- ignoring");
1806 if (fstat(STDIN_FILENO, &isb) < 0) {
1807 maybe_warn("fstat");
1810 if (S_ISREG(isb.st_mode))
1811 in_size = isb.st_size;
1814 infile_set("(stdin)", in_size);
1817 print_list(STDIN_FILENO, in_size, infile, isb.st_mtime);
1821 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1822 if (bytes_read == -1) {
1823 maybe_warn("can't read stdin");
1825 } else if (bytes_read != sizeof(header1)) {
1826 maybe_warnx("(stdin): unexpected end of file");
1830 method = file_gettype(header1);
1835 maybe_warnx("unknown compression format");
1838 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1842 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1843 (char *)header1, sizeof header1, &gsize, "(stdin)");
1845 #ifndef NO_BZIP2_SUPPORT
1847 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1848 (char *)header1, sizeof header1, &gsize);
1851 #ifndef NO_COMPRESS_SUPPORT
1853 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1854 maybe_warnx("zopen of stdin");
1858 usize = zuncompress(in, stdout, (char *)header1,
1859 sizeof header1, &gsize);
1863 #ifndef NO_PACK_SUPPORT
1865 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1866 (char *)header1, sizeof header1, &gsize);
1869 #ifndef NO_XZ_SUPPORT
1871 usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1872 (char *)header1, sizeof header1, &gsize);
1878 if (vflag && !tflag && usize != -1 && gsize != -1)
1879 print_verbage(NULL, NULL, usize, gsize);
1881 print_test("(stdin)", usize != -1);
1901 infile_set("(stdout)", 0);
1903 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1904 maybe_warnx("standard output is a terminal -- ignoring");
1908 /* If stdin is a file use its mtime, otherwise use current time */
1909 ret = fstat(STDIN_FILENO, &sb);
1911 maybe_warn("Can't stat stdin");
1915 if (S_ISREG(sb.st_mode)) {
1916 infile_set("(stdout)", sb.st_size);
1917 mtime = (uint32_t)sb.st_mtime;
1919 systime = time(NULL);
1920 if (systime == -1) {
1924 mtime = (uint32_t)systime;
1929 gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1931 if (vflag && !tflag && usize != -1 && gsize != -1)
1932 print_verbage(NULL, NULL, usize, gsize);
1936 /* do what is asked for, for the path name */
1938 handle_pathname(char *path)
1940 char *opath = path, *s = NULL;
1945 /* check for stdout/stdin */
1946 if (path[0] == '-' && path[1] == '\0') {
1955 if (stat(path, &sb) != 0 || (fflag == 0 && cflag == 0 &&
1956 lstat(path, &sb) != 0)) {
1957 /* lets try <path>.gz if we're decompressing */
1958 if (dflag && s == NULL && errno == ENOENT) {
1960 slen = suffixes[0].ziplen;
1961 s = malloc(len + slen + 1);
1963 maybe_err("malloc");
1964 memcpy(s, path, len);
1965 memcpy(s + len, suffixes[0].zipped, slen + 1);
1969 maybe_warn("can't stat: %s", opath);
1973 if (S_ISDIR(sb.st_mode)) {
1979 maybe_warnx("%s is a directory", path);
1983 if (S_ISREG(sb.st_mode))
1984 handle_file(path, &sb);
1986 maybe_warnx("%s is not a regular file", path);
1993 /* compress/decompress a file */
1995 handle_file(char *file, struct stat *sbp)
1998 char outfile[PATH_MAX];
2000 infile_set(file, sbp->st_size);
2002 usize = file_uncompress(file, outfile, sizeof(outfile));
2005 print_test(file, usize != -1);
2009 gsize = sbp->st_size;
2011 gsize = file_compress(file, outfile, sizeof(outfile));
2014 usize = sbp->st_size;
2019 if (vflag && !tflag)
2020 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
2025 /* this is used with -r to recursively descend directories */
2027 handle_dir(char *dir)
2035 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
2037 warn("couldn't fts_open %s", dir);
2041 while ((entry = fts_read(fts))) {
2042 switch(entry->fts_info) {
2050 maybe_warn("%s", entry->fts_path);
2053 handle_file(entry->fts_path, entry->fts_statp);
2056 (void)fts_close(fts);
2060 /* print a ratio - size reduction as a fraction of uncompressed size */
2062 print_ratio(off_t in, off_t out, FILE *where)
2064 int percent10; /* 10 * percent */
2070 if (in == 0 && out == 0)
2074 * Output is more than double size of input! print -99.9%
2075 * Quite possibly we've failed to get the original size.
2080 * We only need 12 bits of result from the final division,
2081 * so reduce the values until a 32bit division will suffice.
2083 while (in > 0x100000) {
2088 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
2093 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
2094 /* Move the '.' to before the last digit */
2095 buff[len - 1] = buff[len - 2];
2096 buff[len - 2] = '.';
2097 fprintf(where, "%5s%%", buff);
2101 /* print compression statistics, and the new name (if there is one!) */
2103 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
2106 fprintf(stderr, "%s:%s ", file,
2107 strlen(file) < 7 ? "\t\t" : "\t");
2108 print_ratio(usize, gsize, stderr);
2110 fprintf(stderr, " -- replaced with %s", nfile);
2111 fprintf(stderr, "\n");
2115 /* print test results */
2117 print_test(const char *file, int ok)
2120 if (exit_value == 0 && ok == 0)
2122 fprintf(stderr, "%s:%s %s\n", file,
2123 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2128 /* print a file's info ala --list */
2130 compressed uncompressed ratio uncompressed_name
2131 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2134 print_list(int fd, off_t out, const char *outfile, time_t ts)
2136 static int first = 1;
2138 static off_t in_tot, out_tot;
2146 printf("method crc date time ");
2149 printf(" compressed uncompressed "
2150 "ratio uncompressed_name\n");
2162 /* read the last 4 bytes - this is the uncompressed size */
2163 rv = lseek(fd, (off_t)(-8), SEEK_END);
2165 unsigned char buf[8];
2168 rv = read(fd, (char *)buf, sizeof(buf));
2170 maybe_warn("read of uncompressed size");
2171 else if (rv != sizeof(buf))
2172 maybe_warnx("read of uncompressed size");
2175 usize = le32dec(&buf[4]);
2178 crc = le32dec(&buf[0]);
2185 if (vflag && fd == -1)
2188 char *date = ctime(&ts);
2190 /* skip the day, 1/100th second, and year */
2193 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2198 (void)&ts; /* XXX */
2200 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2201 print_ratio(in, out, stdout);
2202 printf(" %s\n", outfile);
2205 /* display the usage of NetBSD gzip */
2210 fprintf(stderr, "%s\n", gzip_version);
2213 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
2215 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2216 " -1 --fast fastest (worst) compression\n"
2217 " -2 .. -8 set compression level\n"
2218 " -9 --best best (slowest) compression\n"
2219 " -c --stdout write to stdout, keep original files\n"
2221 " -d --decompress uncompress files\n"
2223 " -f --force force overwriting & compress links\n"
2224 " -h --help display this help\n"
2225 " -k --keep don't delete input files during operation\n"
2226 " -l --list list compressed file contents\n"
2227 " -N --name save or restore original file name and time stamp\n"
2228 " -n --no-name don't save original file name or time stamp\n"
2229 " -q --quiet output no warnings\n"
2230 " -r --recursive recursively compress files in directories\n"
2231 " -S .suf use suffix .suf instead of .gz\n"
2233 " -t --test test compressed file\n"
2234 " -V --version display program version\n"
2235 " -v --verbose print extra statistics\n",
2242 /* display the license information of FreeBSD gzip */
2244 display_license(void)
2247 fprintf(stderr, "%s (based on NetBSD gzip 20150113)\n", gzip_version);
2248 fprintf(stderr, "%s\n", gzip_copyright);
2253 /* display the version of NetBSD gzip */
2255 display_version(void)
2258 fprintf(stderr, "%s\n", gzip_version);
2262 #ifndef NO_BZIP2_SUPPORT
2263 #include "unbzip2.c"
2265 #ifndef NO_COMPRESS_SUPPORT
2266 #include "zuncompress.c"
2268 #ifndef NO_PACK_SUPPORT
2271 #ifndef NO_XZ_SUPPORT
2276 read_retry(int fd, void *buf, size_t sz)
2279 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2284 ret = read(fd, cp, left);
2287 } else if (ret == 0) {
2298 write_retry(int fd, const void *buf, size_t sz)
2300 const char *cp = buf;
2301 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2306 ret = write(fd, cp, left);
2309 } else if (ret == 0) {
2310 abort(); /* Can't happen */