1 /* $NetBSD: gzip.c,v 1.116 2018/10/27 11:39:12 skrll 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
94 #ifndef NO_BZIP2_SUPPORT
97 #define BZ2_SUFFIX ".bz2"
98 #define BZIP2_MAGIC "BZh"
101 #ifndef NO_COMPRESS_SUPPORT
102 #define Z_SUFFIX ".Z"
103 #define Z_MAGIC "\037\235"
106 #ifndef NO_PACK_SUPPORT
107 #define PACK_MAGIC "\037\036"
110 #ifndef NO_XZ_SUPPORT
112 #define XZ_SUFFIX ".xz"
113 #define XZ_MAGIC "\3757zXZ"
116 #ifndef NO_LZ_SUPPORT
117 #define LZ_SUFFIX ".lz"
118 #define LZ_MAGIC "LZIP"
121 #define GZ_SUFFIX ".gz"
123 #define BUFLEN (64 * 1024)
125 #define GZIP_MAGIC0 0x1F
126 #define GZIP_MAGIC1 0x8B
127 #define GZIP_OMAGIC1 0x9E
129 #define GZIP_TIMESTAMP (off_t)4
130 #define GZIP_ORIGNAME (off_t)10
132 #define HEAD_CRC 0x02
133 #define EXTRA_FIELD 0x04
134 #define ORIG_NAME 0x08
137 #define OS_CODE 3 /* Unix */
142 const char *normal; /* for unzip - must not be longer than zipped */
144 static suffixes_t suffixes[] = {
145 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
146 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
147 SUFFIX(GZ_SUFFIX, ""),
152 SUFFIX(".taz", ".tar"),
153 SUFFIX(".tgz", ".tar"),
154 #ifndef NO_BZIP2_SUPPORT
155 SUFFIX(BZ2_SUFFIX, ""),
156 SUFFIX(".tbz", ".tar"),
157 SUFFIX(".tbz2", ".tar"),
159 #ifndef NO_COMPRESS_SUPPORT
160 SUFFIX(Z_SUFFIX, ""),
162 #ifndef NO_XZ_SUPPORT
163 SUFFIX(XZ_SUFFIX, ""),
165 #ifndef NO_LZ_SUPPORT
166 SUFFIX(LZ_SUFFIX, ""),
168 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
171 #define NUM_SUFFIXES (nitems(suffixes))
172 #define SUFFIX_MAXLEN 30
174 static const char gzip_version[] = "FreeBSD gzip 20190107";
176 static const char gzip_copyright[] = \
177 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
178 " All rights reserved.\n"
180 " Redistribution and use in source and binary forms, with or without\n"
181 " modification, are permitted provided that the following conditions\n"
183 " 1. Redistributions of source code must retain the above copyright\n"
184 " notice, this list of conditions and the following disclaimer.\n"
185 " 2. Redistributions in binary form must reproduce the above copyright\n"
186 " notice, this list of conditions and the following disclaimer in the\n"
187 " documentation and/or other materials provided with the distribution.\n"
189 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
190 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
191 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
192 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
193 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
194 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
195 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
196 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
197 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
198 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
201 static int cflag; /* stdout mode */
202 static int dflag; /* decompress mode */
203 static int lflag; /* list mode */
204 static int numflag = 6; /* gzip -1..-9 value */
206 static const char *remove_file = NULL; /* file to be removed upon SIGINT */
208 static int fflag; /* force mode */
209 static int kflag; /* don't delete input files */
210 static int nflag; /* don't save name/timestamp */
211 static int Nflag; /* don't restore name/timestamp */
212 static int qflag; /* quiet mode */
213 static int rflag; /* recursive mode */
214 static int tflag; /* test */
215 static int vflag; /* verbose mode */
216 static sig_atomic_t print_info = 0;
218 static int exit_value = 0; /* exit value */
220 static const char *infile; /* name of file coming in */
222 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead2;
223 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
224 !defined(NO_XZ_SUPPORT)
225 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead2;
227 static void maybe_warn(const char *fmt, ...) __printflike(1, 2);
228 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2);
229 static enum filetype file_gettype(u_char *);
230 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
231 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
232 static off_t file_compress(char *, char *, size_t);
233 static off_t file_uncompress(char *, char *, size_t);
234 static void handle_pathname(char *);
235 static void handle_file(char *, struct stat *);
236 static void handle_stdin(void);
237 static void handle_stdout(void);
238 static void print_ratio(off_t, off_t, FILE *);
239 static void print_list(int fd, off_t, const char *, time_t);
240 static void usage(void) __dead2;
241 static void display_version(void) __dead2;
242 static void display_license(void);
243 static const suffixes_t *check_suffix(char *, int);
244 static ssize_t read_retry(int, void *, size_t);
245 static ssize_t write_retry(int, const void *, size_t);
246 static void print_list_out(off_t, off_t, const char*);
248 static void infile_set(const char *newinfile, off_t total);
250 static off_t infile_total; /* total expected to read/write */
251 static off_t infile_current; /* current read/write */
253 static void check_siginfo(void);
254 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
255 static void prepend_gzip(char *, int *, char ***);
256 static void handle_dir(char *);
257 static void print_verbage(const char *, const char *, off_t, off_t);
258 static void print_test(const char *, int);
259 static void copymodes(int fd, const struct stat *, const char *file);
260 static int check_outfile(const char *outfile);
261 static void setup_signals(void);
262 static void infile_newdata(size_t newdata);
263 static void infile_clear(void);
265 #ifndef NO_BZIP2_SUPPORT
266 static off_t unbzip2(int, int, char *, size_t, off_t *);
269 #ifndef NO_COMPRESS_SUPPORT
270 static FILE *zdopen(int);
271 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
274 #ifndef NO_PACK_SUPPORT
275 static off_t unpack(int, int, char *, size_t, off_t *);
278 #ifndef NO_XZ_SUPPORT
279 static off_t unxz(int, int, char *, size_t, off_t *);
280 static off_t unxz_len(int);
283 #ifndef NO_LZ_SUPPORT
284 static off_t unlz(int, int, char *, size_t, off_t *);
287 static const struct option longopts[] = {
288 { "stdout", no_argument, 0, 'c' },
289 { "to-stdout", no_argument, 0, 'c' },
290 { "decompress", no_argument, 0, 'd' },
291 { "uncompress", no_argument, 0, 'd' },
292 { "force", no_argument, 0, 'f' },
293 { "help", no_argument, 0, 'h' },
294 { "keep", no_argument, 0, 'k' },
295 { "list", no_argument, 0, 'l' },
296 { "no-name", no_argument, 0, 'n' },
297 { "name", no_argument, 0, 'N' },
298 { "quiet", no_argument, 0, 'q' },
299 { "recursive", no_argument, 0, 'r' },
300 { "suffix", required_argument, 0, 'S' },
301 { "test", no_argument, 0, 't' },
302 { "verbose", no_argument, 0, 'v' },
303 { "version", no_argument, 0, 'V' },
304 { "fast", no_argument, 0, '1' },
305 { "best", no_argument, 0, '9' },
306 { "ascii", no_argument, 0, 'a' },
307 { "license", no_argument, 0, 'L' },
308 { NULL, no_argument, 0, 0 },
312 main(int argc, char **argv)
314 const char *progname = getprogname();
321 if ((gzip = getenv("GZIP")) != NULL)
322 prepend_gzip(gzip, &argc, &argv);
326 * handle being called `gunzip', `zcat' and `gzcat'
328 if (strcmp(progname, "gunzip") == 0)
330 else if (strcmp(progname, "zcat") == 0 ||
331 strcmp(progname, "gzcat") == 0)
334 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
336 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
338 case '1': case '2': case '3':
339 case '4': case '5': case '6':
340 case '7': case '8': case '9':
357 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
383 len = strlen(optarg);
385 if (len > SUFFIX_MAXLEN)
386 errx(1, "incorrect suffix: '%s': too long", optarg);
387 suffixes[0].zipped = optarg;
388 suffixes[0].ziplen = len;
390 suffixes[NUM_SUFFIXES - 1].zipped = "";
391 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
411 if (dflag) /* stdin mode */
413 else /* stdout mode */
417 handle_pathname(argv[0]);
420 if (qflag == 0 && lflag && argc > 1)
421 print_list(-1, 0, "(totals)", 0);
425 /* maybe print a warning */
427 maybe_warn(const char *fmt, ...)
440 /* ... without an errno. */
442 maybe_warnx(const char *fmt, ...)
455 /* maybe print an error */
457 maybe_err(const char *fmt, ...)
469 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
470 !defined(NO_XZ_SUPPORT)
471 /* ... without an errno. */
473 maybe_errx(const char *fmt, ...)
486 /* split up $GZIP and prepend it to the argument list */
488 prepend_gzip(char *gzip, int *argc, char ***argv)
490 char *s, **nargv, **ac;
493 /* scan how many arguments there are */
495 while (*s == ' ' || *s == '\t')
500 while (*s != ' ' && *s != '\t')
512 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
516 /* stash this away */
519 /* copy the program name first */
521 nargv[i++] = *(ac++);
523 /* take a copy of $GZIP and add it to the array */
528 /* Skip whitespaces. */
529 while (*s == ' ' || *s == '\t')
534 /* Find the end of this argument. */
535 while (*s != ' ' && *s != '\t')
537 /* Argument followed by NUL. */
539 /* Terminate by overwriting ' ' or '\t' with NUL. */
544 /* copy the original arguments and a NULL */
546 nargv[i++] = *(ac++);
550 /* compress input to output. Return bytes read, -1 on error */
552 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
555 char *outbufp, *inbufp;
556 off_t in_tot = 0, out_tot = 0;
561 outbufp = malloc(BUFLEN);
562 inbufp = malloc(BUFLEN);
563 if (outbufp == NULL || inbufp == NULL) {
564 maybe_err("malloc failed");
568 memset(&z, 0, sizeof z);
578 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
579 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
580 *origname ? ORIG_NAME : 0,
583 (mtime >> 16) & 0xff,
584 (mtime >> 24) & 0xff,
585 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
588 /* this need PATH_MAX > BUFLEN ... */
589 maybe_err("snprintf");
593 z.next_out = (unsigned char *)outbufp + i;
594 z.avail_out = BUFLEN - i;
596 error = deflateInit2(&z, numflag, Z_DEFLATED,
597 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
599 maybe_warnx("deflateInit2 failed");
604 crc = crc32(0L, Z_NULL, 0);
606 if (z.avail_out == 0) {
607 if (write_retry(out, outbufp, BUFLEN) != BUFLEN) {
614 z.next_out = (unsigned char *)outbufp;
615 z.avail_out = BUFLEN;
618 if (z.avail_in == 0) {
619 in_size = read(in, inbufp, BUFLEN);
627 infile_newdata(in_size);
629 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
631 z.next_in = (unsigned char *)inbufp;
632 z.avail_in = in_size;
635 error = deflate(&z, Z_NO_FLUSH);
636 if (error != Z_OK && error != Z_STREAM_END) {
637 maybe_warnx("deflate failed");
648 error = deflate(&z, Z_FINISH);
649 if (error != Z_OK && error != Z_STREAM_END) {
650 maybe_warnx("deflate failed");
655 len = (char *)z.next_out - outbufp;
657 w = write_retry(out, outbufp, len);
658 if (w == -1 || (size_t)w != len) {
664 z.next_out = (unsigned char *)outbufp;
665 z.avail_out = BUFLEN;
667 if (error == Z_STREAM_END)
671 if (deflateEnd(&z) != Z_OK) {
672 maybe_warnx("deflateEnd failed");
677 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
679 (int)(crc >> 8) & 0xff,
680 (int)(crc >> 16) & 0xff,
681 (int)(crc >> 24) & 0xff,
683 (int)(in_tot >> 8) & 0xff,
684 (int)(in_tot >> 16) & 0xff,
685 (int)(in_tot >> 24) & 0xff);
687 maybe_err("snprintf");
688 if (write_retry(out, outbufp, i) != i) {
705 * uncompress input to output then close the input. return the
706 * uncompressed size written, and put the compressed sized read
710 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
711 const char *filename)
714 char *outbufp, *inbufp;
715 off_t out_tot = -1, in_tot = 0;
716 uint32_t out_sub_tot = 0;
734 } state = GZSTATE_MAGIC0;
735 int flags = 0, skip_count = 0;
736 int error = Z_STREAM_ERROR, done_reading = 0;
741 #define ADVANCE() { z.next_in++; z.avail_in--; }
743 if ((outbufp = malloc(BUFLEN)) == NULL) {
744 maybe_err("malloc failed");
747 if ((inbufp = malloc(BUFLEN)) == NULL) {
748 maybe_err("malloc failed");
752 memset(&z, 0, sizeof z);
754 z.next_in = (unsigned char *)pre;
755 z.avail_out = BUFLEN;
756 z.next_out = (unsigned char *)outbufp;
766 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
769 if (z.avail_in > 0) {
770 memmove(inbufp, z.next_in, z.avail_in);
772 z.next_in = (unsigned char *)inbufp;
773 in_size = read(in, z.next_in + z.avail_in,
774 BUFLEN - z.avail_in);
777 maybe_warn("failed to read stdin");
779 } else if (in_size == 0) {
782 infile_newdata(in_size);
784 z.avail_in += in_size;
789 if (z.avail_in == 0) {
790 if (done_reading && state != GZSTATE_MAGIC0) {
791 maybe_warnx("%s: unexpected end of file",
799 if (*z.next_in != GZIP_MAGIC0) {
801 maybe_warnx("%s: trailing garbage "
802 "ignored", filename);
806 maybe_warnx("input not gziped (MAGIC0)");
812 crc = crc32(0L, Z_NULL, 0);
816 if (*z.next_in != GZIP_MAGIC1 &&
817 *z.next_in != GZIP_OMAGIC1) {
818 maybe_warnx("input not gziped (MAGIC1)");
826 if (*z.next_in != Z_DEFLATED) {
827 maybe_warnx("unknown compression method");
841 case GZSTATE_SKIPPING:
842 if (skip_count > 0) {
850 if ((flags & EXTRA_FIELD) == 0) {
851 state = GZSTATE_ORIGNAME;
854 skip_count = *z.next_in;
860 skip_count |= ((*z.next_in) << 8);
866 if (skip_count > 0) {
873 case GZSTATE_ORIGNAME:
874 if ((flags & ORIG_NAME) == 0) {
883 case GZSTATE_COMMENT:
884 if ((flags & COMMENT) == 0) {
893 case GZSTATE_HEAD_CRC1:
894 if (flags & HEAD_CRC)
901 case GZSTATE_HEAD_CRC2:
902 if (skip_count > 0) {
910 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
911 maybe_warnx("failed to inflateInit");
918 error = inflate(&z, Z_FINISH);
920 /* Z_BUF_ERROR goes with Z_FINISH... */
922 if (z.avail_out > 0 && !done_reading)
930 maybe_warnx("Z_NEED_DICT error");
933 maybe_warnx("data stream error");
936 maybe_warnx("internal stream error");
939 maybe_warnx("memory allocation error");
943 maybe_warn("unknown error from inflate(): %d",
946 wr = BUFLEN - z.avail_out;
949 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
951 /* don't write anything with -t */
953 write_retry(out, outbufp, wr) != wr) {
954 maybe_warn("error writing to output");
962 if (error == Z_STREAM_END) {
967 z.next_out = (unsigned char *)outbufp;
968 z.avail_out = BUFLEN;
975 if (z.avail_in < 4) {
980 maybe_warnx("truncated input");
983 origcrc = le32dec(&z.next_in[0]);
984 if (origcrc != crc) {
985 maybe_warnx("invalid compressed"
994 if (!z.avail_in && done_reading) {
1003 if (z.avail_in < 4) {
1004 if (!done_reading) {
1008 maybe_warnx("truncated input");
1011 origlen = le32dec(&z.next_in[0]);
1013 if (origlen != out_sub_tot) {
1014 maybe_warnx("invalid compressed"
1015 " data--length error");
1024 maybe_warnx("decompression error");
1027 state = GZSTATE_MAGIC0;
1036 if (state > GZSTATE_INIT)
1049 * set the owner, mode, flags & utimes using the given file descriptor.
1050 * file is only used in possible warning messages.
1053 copymodes(int fd, const struct stat *sbp, const char *file)
1055 struct timespec times[2];
1059 * If we have no info on the input, give this file some
1060 * default values and return..
1063 mode_t mask = umask(022);
1065 (void)fchmod(fd, DEFFILEMODE & ~mask);
1071 /* if the chown fails, remove set-id bits as-per compress(1) */
1072 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1074 maybe_warn("couldn't fchown: %s", file);
1075 sb.st_mode &= ~(S_ISUID|S_ISGID);
1078 /* we only allow set-id and the 9 normal permission bits */
1079 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1080 if (fchmod(fd, sb.st_mode) < 0)
1081 maybe_warn("couldn't fchmod: %s", file);
1083 times[0] = sb.st_atim;
1084 times[1] = sb.st_mtim;
1085 if (futimens(fd, times) < 0)
1086 maybe_warn("couldn't futimens: %s", file);
1088 /* only try flags if they exist already */
1089 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1090 maybe_warn("couldn't fchflags: %s", file);
1093 /* what sort of file is this? */
1094 static enum filetype
1095 file_gettype(u_char *buf)
1098 if (buf[0] == GZIP_MAGIC0 &&
1099 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1102 #ifndef NO_BZIP2_SUPPORT
1103 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1104 buf[3] >= '0' && buf[3] <= '9')
1108 #ifndef NO_COMPRESS_SUPPORT
1109 if (memcmp(buf, Z_MAGIC, 2) == 0)
1113 #ifndef NO_PACK_SUPPORT
1114 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1118 #ifndef NO_XZ_SUPPORT
1119 if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */
1123 #ifndef NO_LZ_SUPPORT
1124 if (memcmp(buf, LZ_MAGIC, 4) == 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 already */
1170 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1171 /* Definitely a different file */
1177 got_sigint(int signo __unused)
1180 if (remove_file != NULL)
1181 unlink(remove_file);
1186 got_siginfo(int signo __unused)
1196 signal(SIGINFO, got_siginfo);
1197 signal(SIGINT, got_sigint);
1201 infile_newdata(size_t newdata)
1204 infile_current += newdata;
1208 infile_set(const char *newinfile, off_t total)
1213 infile_total = total;
1221 infile_total = infile_current = 0;
1224 static const suffixes_t *
1225 check_suffix(char *file, int xlate)
1227 const suffixes_t *s;
1228 int len = strlen(file);
1231 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1232 /* if it doesn't fit in "a.suf", don't bother */
1233 if (s->ziplen >= len)
1235 sp = file + len - s->ziplen;
1236 if (strcmp(s->zipped, sp) != 0)
1239 strcpy(sp, s->normal);
1246 * compress the given file: create a corresponding .gz file and remove the
1250 file_compress(char *file, char *outfile, size_t outsize)
1254 off_t size, in_size;
1255 struct stat isb, osb;
1256 const suffixes_t *suff;
1258 in = open(file, O_RDONLY);
1260 maybe_warn("can't open %s", file);
1264 if (fstat(in, &isb) != 0) {
1265 maybe_warn("couldn't stat: %s", file);
1270 if (fstat(in, &isb) != 0) {
1272 maybe_warn("can't stat %s", file);
1275 infile_set(file, isb.st_size);
1278 if (isb.st_nlink > 1 && fflag == 0) {
1279 maybe_warnx("%s has %ju other link%s -- "
1281 (uintmax_t)isb.st_nlink - 1,
1282 isb.st_nlink == 1 ? "" : "s");
1287 if (fflag == 0 && (suff = check_suffix(file, 0)) &&
1288 suff->zipped[0] != 0) {
1289 maybe_warnx("%s already has %s suffix -- unchanged",
1290 file, suff->zipped);
1295 /* Add (usually) .gz to filename */
1296 if ((size_t)snprintf(outfile, outsize, "%s%s",
1297 file, suffixes[0].zipped) >= outsize)
1298 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1299 suffixes[0].zipped, suffixes[0].ziplen + 1);
1301 if (check_outfile(outfile) == 0) {
1308 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1310 maybe_warn("could not create output: %s", outfile);
1314 remove_file = outfile;
1316 out = STDOUT_FILENO;
1318 in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1323 * If there was an error, in_size will be -1.
1324 * If we compressed to stdout, just return the size.
1325 * Otherwise stat the file and check it is the correct size.
1326 * We only blow away the file if we can stat the output and it
1327 * has the expected size.
1330 return in_size == -1 ? -1 : size;
1332 if (fstat(out, &osb) != 0) {
1333 maybe_warn("couldn't stat: %s", outfile);
1337 if (osb.st_size != size) {
1338 maybe_warnx("output file: %s wrong size (%ju != %ju), deleting",
1339 outfile, (uintmax_t)osb.st_size, (uintmax_t)size);
1343 copymodes(out, &isb, outfile);
1345 if (close(out) == -1)
1346 maybe_warn("couldn't close output");
1348 /* output is good, ok to delete input */
1349 unlink_input(file, &isb);
1353 if (close(out) == -1)
1354 maybe_warn("couldn't close output");
1356 maybe_warnx("leaving original %s", file);
1361 /* uncompress the given file and remove the original */
1363 file_uncompress(char *file, char *outfile, size_t outsize)
1365 struct stat isb, osb;
1368 unsigned char fourbytes[4];
1369 enum filetype method;
1370 int fd, ofd, zfd = -1;
1374 time_t timestamp = 0;
1375 char name[PATH_MAX + 1];
1377 /* gather the old name info */
1379 fd = open(file, O_RDONLY);
1381 maybe_warn("can't open %s", file);
1384 if (fstat(fd, &isb) != 0) {
1385 maybe_warn("can't stat %s", file);
1388 if (S_ISREG(isb.st_mode))
1389 in_size = isb.st_size;
1392 infile_set(file, in_size);
1394 strlcpy(outfile, file, outsize);
1395 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1396 maybe_warnx("%s: unknown suffix -- ignored", file);
1400 rbytes = read(fd, fourbytes, sizeof fourbytes);
1401 if (rbytes != sizeof fourbytes) {
1402 /* we don't want to fail here. */
1406 maybe_warn("can't read %s", file);
1408 goto unexpected_EOF;
1411 infile_newdata(rbytes);
1413 method = file_gettype(fourbytes);
1414 if (fflag == 0 && method == FT_UNKNOWN) {
1415 maybe_warnx("%s: not in gzip format", file);
1420 if (method == FT_GZIP && Nflag) {
1421 unsigned char ts[4]; /* timestamp */
1423 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1424 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1425 goto unexpected_EOF;
1428 maybe_warn("can't read %s", file);
1432 timestamp = le32dec(&ts[0]);
1434 if (fourbytes[3] & ORIG_NAME) {
1435 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1437 maybe_warn("can't read %s", file);
1440 if (name[0] != '\0') {
1443 /* Make sure that name is NUL-terminated */
1444 name[rbytes] = '\0';
1446 /* strip saved directory name */
1447 nf = strrchr(name, '/');
1453 /* preserve original directory name */
1454 dp = strrchr(file, '/');
1459 snprintf(outfile, outsize, "%.*s%.*s",
1461 file, (int) rbytes, nf);
1465 lseek(fd, 0, SEEK_SET);
1467 if (cflag == 0 || lflag) {
1468 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1469 maybe_warnx("%s has %ju other links -- skipping",
1470 file, (uintmax_t)isb.st_nlink - 1);
1473 if (nflag == 0 && timestamp)
1474 isb.st_mtime = timestamp;
1475 if (check_outfile(outfile) == 0)
1480 zfd = STDOUT_FILENO;
1484 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1485 if (zfd == STDOUT_FILENO) {
1486 /* We won't close STDOUT_FILENO later... */
1488 close(STDOUT_FILENO);
1491 maybe_warn("can't open %s", outfile);
1494 remove_file = outfile;
1498 #ifndef NO_BZIP2_SUPPORT
1502 maybe_warnx("no -l with bzip2 files");
1506 size = unbzip2(fd, zfd, NULL, 0, NULL);
1510 #ifndef NO_COMPRESS_SUPPORT
1516 maybe_warnx("no -l with Lempel-Ziv files");
1520 if ((in = zdopen(fd)) == NULL) {
1521 maybe_warn("zdopen for read: %s", file);
1525 out = fdopen(dup(zfd), "w");
1527 maybe_warn("fdopen for write: %s", outfile);
1532 size = zuncompress(in, out, NULL, 0, NULL);
1533 /* need to fclose() if ferror() is true... */
1535 if (error | fclose(in)) {
1537 maybe_warn("failed infile");
1539 maybe_warn("failed infile fclose");
1545 if (fclose(out) != 0) {
1546 maybe_warn("failed outfile fclose");
1555 #ifndef NO_PACK_SUPPORT
1558 maybe_warnx("no -l with packed files");
1562 size = unpack(fd, zfd, NULL, 0, NULL);
1566 #ifndef NO_XZ_SUPPORT
1569 size = unxz_len(fd);
1571 print_list_out(in_size, size, file);
1576 size = unxz(fd, zfd, NULL, 0, NULL);
1580 #ifndef NO_LZ_SUPPORT
1583 maybe_warnx("no -l with lzip files");
1586 size = unlz(fd, zfd, NULL, 0, NULL);
1591 maybe_warnx("no -l for unknown filetypes");
1594 size = cat_fd(NULL, 0, NULL, fd);
1598 print_list(fd, in_size, outfile, isb.st_mtime);
1601 return -1; /* XXX */
1605 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1610 maybe_warn("couldn't close input");
1611 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1612 maybe_warn("couldn't close output");
1617 maybe_warnx("%s: uncompress failed", file);
1621 /* if testing, or we uncompressed to stdout, this is all we need */
1624 /* if we are uncompressing to stdin, don't remove the file. */
1629 * if we create a file...
1632 * if we can't stat the file don't remove the file.
1635 ofd = open(outfile, O_RDWR, 0);
1637 maybe_warn("couldn't open (leaving original): %s",
1641 if (fstat(ofd, &osb) != 0) {
1642 maybe_warn("couldn't stat (leaving original): %s",
1647 if (osb.st_size != size) {
1648 maybe_warnx("stat gave different size: %ju != %ju (leaving original)",
1649 (uintmax_t)size, (uintmax_t)osb.st_size);
1654 copymodes(ofd, &isb, outfile);
1657 unlink_input(file, &isb);
1661 maybe_warnx("%s: unexpected end of file", file);
1665 if (zfd != -1 && zfd != STDOUT_FILENO)
1673 if (print_info == 0)
1677 int pcent = (int)((100.0 * infile_current) / infile_total);
1679 fprintf(stderr, "%s: done %llu/%llu bytes %d%%\n",
1680 infile, (unsigned long long)infile_current,
1681 (unsigned long long)infile_total, pcent);
1683 fprintf(stderr, "%s: done %llu bytes\n",
1684 infile, (unsigned long long)infile_current);
1690 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1697 w = write_retry(STDOUT_FILENO, prepend, count);
1698 if (w == -1 || (size_t)w != count) {
1699 maybe_warn("write to stdout");
1705 rv = read(fd, buf, sizeof buf);
1709 maybe_warn("read from fd %d", fd);
1714 if (write_retry(STDOUT_FILENO, buf, rv) != rv) {
1715 maybe_warn("write to stdout");
1730 unsigned char fourbytes[4];
1733 enum filetype method;
1735 #ifndef NO_COMPRESS_SUPPORT
1739 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1740 maybe_warnx("standard input is a terminal -- ignoring");
1744 if (fstat(STDIN_FILENO, &isb) < 0) {
1745 maybe_warn("fstat");
1748 if (S_ISREG(isb.st_mode))
1749 in_size = isb.st_size;
1752 infile_set("(stdin)", in_size);
1755 print_list(STDIN_FILENO, in_size, infile, isb.st_mtime);
1759 bytes_read = read_retry(STDIN_FILENO, fourbytes, sizeof fourbytes);
1760 if (bytes_read == -1) {
1761 maybe_warn("can't read stdin");
1763 } else if (bytes_read != sizeof(fourbytes)) {
1764 maybe_warnx("(stdin): unexpected end of file");
1768 method = file_gettype(fourbytes);
1772 maybe_warnx("unknown compression format");
1775 usize = cat_fd(fourbytes, sizeof fourbytes, &gsize, STDIN_FILENO);
1778 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1779 (char *)fourbytes, sizeof fourbytes, &gsize, "(stdin)");
1781 #ifndef NO_BZIP2_SUPPORT
1783 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1784 (char *)fourbytes, sizeof fourbytes, &gsize);
1787 #ifndef NO_COMPRESS_SUPPORT
1789 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1790 maybe_warnx("zopen of stdin");
1794 usize = zuncompress(in, stdout, (char *)fourbytes,
1795 sizeof fourbytes, &gsize);
1799 #ifndef NO_PACK_SUPPORT
1801 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1802 (char *)fourbytes, sizeof fourbytes, &gsize);
1805 #ifndef NO_XZ_SUPPORT
1807 usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1808 (char *)fourbytes, sizeof fourbytes, &gsize);
1811 #ifndef NO_LZ_SUPPORT
1813 usize = unlz(STDIN_FILENO, STDOUT_FILENO,
1814 (char *)fourbytes, sizeof fourbytes, &gsize);
1819 if (vflag && !tflag && usize != -1 && gsize != -1)
1820 print_verbage(NULL, NULL, usize, gsize);
1822 print_test("(stdin)", usize != -1);
1838 infile_set("(stdout)", 0);
1840 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1841 maybe_warnx("standard output is a terminal -- ignoring");
1845 /* If stdin is a file use its mtime, otherwise use current time */
1846 ret = fstat(STDIN_FILENO, &sb);
1848 maybe_warn("Can't stat stdin");
1852 if (S_ISREG(sb.st_mode)) {
1853 infile_set("(stdout)", sb.st_size);
1854 mtime = (uint32_t)sb.st_mtime;
1856 systime = time(NULL);
1857 if (systime == -1) {
1861 mtime = (uint32_t)systime;
1865 gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1866 if (vflag && !tflag && usize != -1 && gsize != -1)
1867 print_verbage(NULL, NULL, usize, gsize);
1870 /* do what is asked for, for the path name */
1872 handle_pathname(char *path)
1874 char *opath = path, *s = NULL;
1879 /* check for stdout/stdin */
1880 if (path[0] == '-' && path[1] == '\0') {
1889 if (stat(path, &sb) != 0 || (fflag == 0 && cflag == 0 &&
1890 lstat(path, &sb) != 0)) {
1891 /* lets try <path>.gz if we're decompressing */
1892 if (dflag && s == NULL && errno == ENOENT) {
1894 slen = suffixes[0].ziplen;
1895 s = malloc(len + slen + 1);
1897 maybe_err("malloc");
1898 memcpy(s, path, len);
1899 memcpy(s + len, suffixes[0].zipped, slen + 1);
1903 maybe_warn("can't stat: %s", opath);
1907 if (S_ISDIR(sb.st_mode)) {
1911 maybe_warnx("%s is a directory", path);
1915 if (S_ISREG(sb.st_mode))
1916 handle_file(path, &sb);
1918 maybe_warnx("%s is not a regular file", path);
1925 /* compress/decompress a file */
1927 handle_file(char *file, struct stat *sbp)
1930 char outfile[PATH_MAX];
1932 infile_set(file, sbp->st_size);
1934 usize = file_uncompress(file, outfile, sizeof(outfile));
1936 print_test(file, usize != -1);
1939 gsize = sbp->st_size;
1941 gsize = file_compress(file, outfile, sizeof(outfile));
1944 usize = sbp->st_size;
1948 if (vflag && !tflag)
1949 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1952 /* this is used with -r to recursively descend directories */
1954 handle_dir(char *dir)
1962 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1964 warn("couldn't fts_open %s", dir);
1968 while (errno = 0, (entry = fts_read(fts))) {
1969 switch(entry->fts_info) {
1977 maybe_warn("%s", entry->fts_path);
1980 handle_file(entry->fts_path, entry->fts_statp);
1984 warn("error with fts_read %s", dir);
1985 (void)fts_close(fts);
1988 /* print a ratio - size reduction as a fraction of uncompressed size */
1990 print_ratio(off_t in, off_t out, FILE *where)
1992 int percent10; /* 10 * percent */
1998 if (in == 0 && out == 0)
2002 * Output is more than double size of input! print -99.9%
2003 * Quite possibly we've failed to get the original size.
2008 * We only need 12 bits of result from the final division,
2009 * so reduce the values until a 32bit division will suffice.
2011 while (in > 0x100000) {
2016 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
2021 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
2022 /* Move the '.' to before the last digit */
2023 buff[len - 1] = buff[len - 2];
2024 buff[len - 2] = '.';
2025 fprintf(where, "%5s%%", buff);
2028 /* print compression statistics, and the new name (if there is one!) */
2030 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
2033 fprintf(stderr, "%s:%s ", file,
2034 strlen(file) < 7 ? "\t\t" : "\t");
2035 print_ratio(usize, gsize, stderr);
2037 fprintf(stderr, " -- replaced with %s", nfile);
2038 fprintf(stderr, "\n");
2042 /* print test results */
2044 print_test(const char *file, int ok)
2047 if (exit_value == 0 && ok == 0)
2049 fprintf(stderr, "%s:%s %s\n", file,
2050 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2054 /* print a file's info ala --list */
2056 compressed uncompressed ratio uncompressed_name
2057 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2060 print_list(int fd, off_t out, const char *outfile, time_t ts)
2062 static int first = 1;
2063 static off_t in_tot, out_tot;
2069 printf("method crc date time ");
2071 printf(" compressed uncompressed "
2072 "ratio uncompressed_name\n");
2082 /* read the last 4 bytes - this is the uncompressed size */
2083 rv = lseek(fd, (off_t)(-8), SEEK_END);
2085 unsigned char buf[8];
2088 rv = read(fd, (char *)buf, sizeof(buf));
2090 maybe_warn("read of uncompressed size");
2091 else if (rv != sizeof(buf))
2092 maybe_warnx("read of uncompressed size");
2095 usize = le32dec(&buf[4]);
2097 crc = le32dec(&buf[0]);
2102 if (vflag && fd == -1)
2105 char *date = ctime(&ts);
2107 /* skip the day, 1/100th second, and year */
2110 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2114 print_list_out(out, in, outfile);
2118 print_list_out(off_t out, off_t in, const char *outfile)
2120 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2121 print_ratio(in, out, stdout);
2122 printf(" %s\n", outfile);
2125 /* display the usage of NetBSD gzip */
2130 fprintf(stderr, "%s\n", gzip_version);
2132 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2133 " -1 --fast fastest (worst) compression\n"
2134 " -2 .. -8 set compression level\n"
2135 " -9 --best best (slowest) compression\n"
2136 " -c --stdout write to stdout, keep original files\n"
2138 " -d --decompress uncompress files\n"
2140 " -f --force force overwriting & compress links\n"
2141 " -h --help display this help\n"
2142 " -k --keep don't delete input files during operation\n"
2143 " -l --list list compressed file contents\n"
2144 " -N --name save or restore original file name and time stamp\n"
2145 " -n --no-name don't save original file name or time stamp\n"
2146 " -q --quiet output no warnings\n"
2147 " -r --recursive recursively compress files in directories\n"
2148 " -S .suf use suffix .suf instead of .gz\n"
2150 " -t --test test compressed file\n"
2151 " -V --version display program version\n"
2152 " -v --verbose print extra statistics\n",
2157 /* display the license information of FreeBSD gzip */
2159 display_license(void)
2162 fprintf(stderr, "%s (based on NetBSD gzip 20150113)\n", gzip_version);
2163 fprintf(stderr, "%s\n", gzip_copyright);
2167 /* display the version of NetBSD gzip */
2169 display_version(void)
2172 fprintf(stderr, "%s\n", gzip_version);
2176 #ifndef NO_BZIP2_SUPPORT
2177 #include "unbzip2.c"
2179 #ifndef NO_COMPRESS_SUPPORT
2180 #include "zuncompress.c"
2182 #ifndef NO_PACK_SUPPORT
2185 #ifndef NO_XZ_SUPPORT
2188 #ifndef NO_LZ_SUPPORT
2193 read_retry(int fd, void *buf, size_t sz)
2196 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2201 ret = read(fd, cp, left);
2204 } else if (ret == 0) {
2215 write_retry(int fd, const void *buf, size_t sz)
2217 const char *cp = buf;
2218 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2223 ret = write(fd, cp, left);
2226 } else if (ret == 0) {
2227 abort(); /* Can't happen */