1 /* $NetBSD: gzip.c,v 1.116 2018/10/27 11:39:12 skrll Exp $ */
4 * SPDX-License-Identifier: BSD-2-Clause
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
90 #ifndef NO_ZSTD_SUPPORT
97 #ifndef NO_BZIP2_SUPPORT
100 #define BZ2_SUFFIX ".bz2"
101 #define BZIP2_MAGIC "BZh"
104 #ifndef NO_COMPRESS_SUPPORT
105 #define Z_SUFFIX ".Z"
106 #define Z_MAGIC "\037\235"
109 #ifndef NO_PACK_SUPPORT
110 #define PACK_MAGIC "\037\036"
113 #ifndef NO_XZ_SUPPORT
115 #define XZ_SUFFIX ".xz"
116 #define XZ_MAGIC "\3757zXZ"
119 #ifndef NO_LZ_SUPPORT
120 #define LZ_SUFFIX ".lz"
121 #define LZ_MAGIC "LZIP"
124 #ifndef NO_ZSTD_SUPPORT
126 #define ZSTD_SUFFIX ".zst"
127 #define ZSTD_MAGIC "\050\265\057\375"
130 #define GZ_SUFFIX ".gz"
132 #define BUFLEN (64 * 1024)
134 #define GZIP_MAGIC0 0x1F
135 #define GZIP_MAGIC1 0x8B
136 #define GZIP_OMAGIC1 0x9E
138 #define GZIP_TIMESTAMP (off_t)4
139 #define GZIP_ORIGNAME (off_t)10
141 #define HEAD_CRC 0x02
142 #define EXTRA_FIELD 0x04
143 #define ORIG_NAME 0x08
146 #define OS_CODE 3 /* Unix */
151 const char *normal; /* for unzip - must not be longer than zipped */
153 static suffixes_t suffixes[] = {
154 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
155 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
156 SUFFIX(GZ_SUFFIX, ""),
161 SUFFIX(".taz", ".tar"),
162 SUFFIX(".tgz", ".tar"),
163 #ifndef NO_BZIP2_SUPPORT
164 SUFFIX(BZ2_SUFFIX, ""),
165 SUFFIX(".tbz", ".tar"),
166 SUFFIX(".tbz2", ".tar"),
168 #ifndef NO_COMPRESS_SUPPORT
169 SUFFIX(Z_SUFFIX, ""),
171 #ifndef NO_XZ_SUPPORT
172 SUFFIX(XZ_SUFFIX, ""),
174 #ifndef NO_LZ_SUPPORT
175 SUFFIX(LZ_SUFFIX, ""),
177 #ifndef NO_ZSTD_SUPPORT
178 SUFFIX(ZSTD_SUFFIX, ""),
180 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
183 #define NUM_SUFFIXES (nitems(suffixes))
184 #define SUFFIX_MAXLEN 30
186 static const char gzip_version[] = "FreeBSD gzip 20190107";
188 static const char gzip_copyright[] = \
189 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
190 " All rights reserved.\n"
192 " Redistribution and use in source and binary forms, with or without\n"
193 " modification, are permitted provided that the following conditions\n"
195 " 1. Redistributions of source code must retain the above copyright\n"
196 " notice, this list of conditions and the following disclaimer.\n"
197 " 2. Redistributions in binary form must reproduce the above copyright\n"
198 " notice, this list of conditions and the following disclaimer in the\n"
199 " documentation and/or other materials provided with the distribution.\n"
201 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
202 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
203 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
204 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
205 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
206 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
207 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
208 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
209 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
210 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
213 static int cflag; /* stdout mode */
214 static int dflag; /* decompress mode */
215 static int lflag; /* list mode */
216 static int numflag = 6; /* gzip -1..-9 value */
218 static const char *remove_file = NULL; /* file to be removed upon SIGINT */
220 static int fflag; /* force mode */
221 static int kflag; /* don't delete input files */
222 static int nflag; /* don't save name/timestamp */
223 static int Nflag; /* don't restore name/timestamp */
224 static int qflag; /* quiet mode */
225 static int rflag; /* recursive mode */
226 static int tflag; /* test */
227 static int vflag; /* verbose mode */
228 static sig_atomic_t print_info = 0;
230 static int exit_value = 0; /* exit value */
232 static const char *infile; /* name of file coming in */
234 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead2;
235 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
236 !defined(NO_XZ_SUPPORT) || !defined(NO_ZSTD_SUPPORT)
237 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead2;
239 static void maybe_warn(const char *fmt, ...) __printflike(1, 2);
240 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2);
241 static enum filetype file_gettype(u_char *);
242 static off_t gz_compress(int, int, off_t *, const char *, uint32_t);
243 static off_t gz_uncompress(int, int, char *, size_t, off_t *, const char *);
244 static off_t file_compress(char *, char *, size_t);
245 static off_t file_uncompress(char *, char *, size_t);
246 static void handle_pathname(char *);
247 static void handle_file(char *, struct stat *);
248 static void handle_stdin(void);
249 static void handle_stdout(void);
250 static void print_ratio(off_t, off_t, FILE *);
251 static void print_list(int fd, off_t, const char *, time_t);
252 static void usage(void) __dead2;
253 static void display_version(void) __dead2;
254 static void display_license(void);
255 static const suffixes_t *check_suffix(char *, int);
256 static ssize_t read_retry(int, void *, size_t);
257 static ssize_t write_retry(int, const void *, size_t);
258 static void print_list_out(off_t, off_t, const char*);
260 static void infile_set(const char *newinfile, off_t total);
262 static off_t infile_total; /* total expected to read/write */
263 static off_t infile_current; /* current read/write */
265 static void check_siginfo(void);
266 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
267 static void prepend_gzip(char *, int *, char ***);
268 static void handle_dir(char *);
269 static void print_verbage(const char *, const char *, off_t, off_t);
270 static void print_test(const char *, int);
271 static void copymodes(int fd, const struct stat *, const char *file);
272 static int check_outfile(const char *outfile);
273 static void setup_signals(void);
274 static void infile_newdata(size_t newdata);
275 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 *);
292 static off_t unxz_len(int);
295 #ifndef NO_LZ_SUPPORT
296 static off_t unlz(int, int, char *, size_t, off_t *);
299 #ifndef NO_ZSTD_SUPPORT
300 static off_t unzstd(int, int, char *, size_t, off_t *);
303 static const struct option longopts[] = {
304 { "stdout", no_argument, 0, 'c' },
305 { "to-stdout", no_argument, 0, 'c' },
306 { "decompress", no_argument, 0, 'd' },
307 { "uncompress", no_argument, 0, 'd' },
308 { "force", no_argument, 0, 'f' },
309 { "help", no_argument, 0, 'h' },
310 { "keep", no_argument, 0, 'k' },
311 { "list", no_argument, 0, 'l' },
312 { "no-name", no_argument, 0, 'n' },
313 { "name", no_argument, 0, 'N' },
314 { "quiet", no_argument, 0, 'q' },
315 { "recursive", no_argument, 0, 'r' },
316 { "suffix", required_argument, 0, 'S' },
317 { "test", no_argument, 0, 't' },
318 { "verbose", no_argument, 0, 'v' },
319 { "version", no_argument, 0, 'V' },
320 { "fast", no_argument, 0, '1' },
321 { "best", no_argument, 0, '9' },
322 { "ascii", no_argument, 0, 'a' },
323 { "license", no_argument, 0, 'L' },
324 { NULL, no_argument, 0, 0 },
328 main(int argc, char **argv)
330 const char *progname = getprogname();
337 if ((gzip = getenv("GZIP")) != NULL)
338 prepend_gzip(gzip, &argc, &argv);
342 * handle being called `gunzip', `zcat' and `gzcat'
344 if (strcmp(progname, "gunzip") == 0)
346 else if (strcmp(progname, "zcat") == 0 ||
347 strcmp(progname, "gzcat") == 0)
350 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
352 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
354 case '1': case '2': case '3':
355 case '4': case '5': case '6':
356 case '7': case '8': case '9':
373 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
399 len = strlen(optarg);
401 if (len > SUFFIX_MAXLEN)
402 errx(1, "incorrect suffix: '%s': too long", optarg);
403 suffixes[0].zipped = optarg;
404 suffixes[0].ziplen = len;
406 suffixes[NUM_SUFFIXES - 1].zipped = "";
407 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
427 if (dflag) /* stdin mode */
429 else /* stdout mode */
433 handle_pathname(argv[0]);
436 if (qflag == 0 && lflag && argc > 1)
437 print_list(-1, 0, "(totals)", 0);
441 /* maybe print a warning */
443 maybe_warn(const char *fmt, ...)
456 /* ... without an errno. */
458 maybe_warnx(const char *fmt, ...)
471 /* maybe print an error */
473 maybe_err(const char *fmt, ...)
485 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
486 !defined(NO_XZ_SUPPORT) || !defined(NO_ZSTD_SUPPORT)
487 /* ... without an errno. */
489 maybe_errx(const char *fmt, ...)
502 /* split up $GZIP and prepend it to the argument list */
504 prepend_gzip(char *gzip, int *argc, char ***argv)
506 char *s, **nargv, **ac;
509 /* scan how many arguments there are */
511 while (*s == ' ' || *s == '\t')
516 while (*s != ' ' && *s != '\t')
528 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
532 /* stash this away */
535 /* copy the program name first */
537 nargv[i++] = *(ac++);
539 /* take a copy of $GZIP and add it to the array */
544 /* Skip whitespaces. */
545 while (*s == ' ' || *s == '\t')
550 /* Find the end of this argument. */
551 while (*s != ' ' && *s != '\t')
553 /* Argument followed by NUL. */
555 /* Terminate by overwriting ' ' or '\t' with NUL. */
560 /* copy the original arguments and a NULL */
562 nargv[i++] = *(ac++);
566 /* compress input to output. Return bytes read, -1 on error */
568 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
571 char *outbufp, *inbufp;
572 off_t in_tot = 0, out_tot = 0;
577 outbufp = malloc(BUFLEN);
578 inbufp = malloc(BUFLEN);
579 if (outbufp == NULL || inbufp == NULL) {
580 maybe_err("malloc failed");
584 memset(&z, 0, sizeof z);
594 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
595 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
596 *origname ? ORIG_NAME : 0,
599 (mtime >> 16) & 0xff,
600 (mtime >> 24) & 0xff,
601 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
604 /* this need PATH_MAX > BUFLEN ... */
605 maybe_err("snprintf");
609 z.next_out = (unsigned char *)outbufp + i;
610 z.avail_out = BUFLEN - i;
612 error = deflateInit2(&z, numflag, Z_DEFLATED,
613 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
615 maybe_warnx("deflateInit2 failed");
620 crc = crc32(0L, Z_NULL, 0);
622 if (z.avail_out == 0) {
623 if (write_retry(out, outbufp, BUFLEN) != BUFLEN) {
630 z.next_out = (unsigned char *)outbufp;
631 z.avail_out = BUFLEN;
634 if (z.avail_in == 0) {
635 in_size = read(in, inbufp, BUFLEN);
643 infile_newdata(in_size);
645 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
647 z.next_in = (unsigned char *)inbufp;
648 z.avail_in = in_size;
651 error = deflate(&z, Z_NO_FLUSH);
652 if (error != Z_OK && error != Z_STREAM_END) {
653 maybe_warnx("deflate failed");
664 error = deflate(&z, Z_FINISH);
665 if (error != Z_OK && error != Z_STREAM_END) {
666 maybe_warnx("deflate failed");
671 len = (char *)z.next_out - outbufp;
673 w = write_retry(out, outbufp, len);
674 if (w == -1 || (size_t)w != len) {
680 z.next_out = (unsigned char *)outbufp;
681 z.avail_out = BUFLEN;
683 if (error == Z_STREAM_END)
687 if (deflateEnd(&z) != Z_OK) {
688 maybe_warnx("deflateEnd failed");
693 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
695 (int)(crc >> 8) & 0xff,
696 (int)(crc >> 16) & 0xff,
697 (int)(crc >> 24) & 0xff,
699 (int)(in_tot >> 8) & 0xff,
700 (int)(in_tot >> 16) & 0xff,
701 (int)(in_tot >> 24) & 0xff);
703 maybe_err("snprintf");
704 if (write_retry(out, outbufp, i) != i) {
721 * uncompress input to output then close the input. return the
722 * uncompressed size written, and put the compressed sized read
726 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
727 const char *filename)
730 char *outbufp, *inbufp;
731 off_t out_tot = -1, in_tot = 0;
732 uint32_t out_sub_tot = 0;
750 } state = GZSTATE_MAGIC0;
751 int flags = 0, skip_count = 0;
752 int error = Z_STREAM_ERROR, done_reading = 0;
757 #define ADVANCE() { z.next_in++; z.avail_in--; }
759 if ((outbufp = malloc(BUFLEN)) == NULL) {
760 maybe_err("malloc failed");
763 if ((inbufp = malloc(BUFLEN)) == NULL) {
764 maybe_err("malloc failed");
768 memset(&z, 0, sizeof z);
770 z.next_in = (unsigned char *)pre;
771 z.avail_out = BUFLEN;
772 z.next_out = (unsigned char *)outbufp;
782 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
785 if (z.avail_in > 0) {
786 memmove(inbufp, z.next_in, z.avail_in);
788 z.next_in = (unsigned char *)inbufp;
789 in_size = read(in, z.next_in + z.avail_in,
790 BUFLEN - z.avail_in);
793 maybe_warn("failed to read stdin");
795 } else if (in_size == 0) {
798 infile_newdata(in_size);
800 z.avail_in += in_size;
805 if (z.avail_in == 0) {
806 if (done_reading && state != GZSTATE_MAGIC0) {
807 maybe_warnx("%s: unexpected end of file",
815 if (*z.next_in != GZIP_MAGIC0) {
817 maybe_warnx("%s: trailing garbage "
818 "ignored", filename);
822 maybe_warnx("input not gziped (MAGIC0)");
828 crc = crc32(0L, Z_NULL, 0);
832 if (*z.next_in != GZIP_MAGIC1 &&
833 *z.next_in != GZIP_OMAGIC1) {
834 maybe_warnx("input not gziped (MAGIC1)");
842 if (*z.next_in != Z_DEFLATED) {
843 maybe_warnx("unknown compression method");
857 case GZSTATE_SKIPPING:
858 if (skip_count > 0) {
866 if ((flags & EXTRA_FIELD) == 0) {
867 state = GZSTATE_ORIGNAME;
870 skip_count = *z.next_in;
876 skip_count |= ((*z.next_in) << 8);
882 if (skip_count > 0) {
889 case GZSTATE_ORIGNAME:
890 if ((flags & ORIG_NAME) == 0) {
899 case GZSTATE_COMMENT:
900 if ((flags & COMMENT) == 0) {
909 case GZSTATE_HEAD_CRC1:
910 if (flags & HEAD_CRC)
917 case GZSTATE_HEAD_CRC2:
918 if (skip_count > 0) {
926 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
927 maybe_warnx("failed to inflateInit");
934 error = inflate(&z, Z_FINISH);
936 /* Z_BUF_ERROR goes with Z_FINISH... */
938 if (z.avail_out > 0 && !done_reading)
946 maybe_warnx("Z_NEED_DICT error");
949 maybe_warnx("data stream error");
952 maybe_warnx("internal stream error");
955 maybe_warnx("memory allocation error");
959 maybe_warn("unknown error from inflate(): %d",
962 wr = BUFLEN - z.avail_out;
965 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
967 /* don't write anything with -t */
969 write_retry(out, outbufp, wr) != wr) {
970 maybe_warn("error writing to output");
978 if (error == Z_STREAM_END) {
983 z.next_out = (unsigned char *)outbufp;
984 z.avail_out = BUFLEN;
991 if (z.avail_in < 4) {
996 maybe_warnx("truncated input");
999 origcrc = le32dec(&z.next_in[0]);
1000 if (origcrc != crc) {
1001 maybe_warnx("invalid compressed"
1002 " data--crc error");
1010 if (!z.avail_in && done_reading) {
1019 if (z.avail_in < 4) {
1020 if (!done_reading) {
1024 maybe_warnx("truncated input");
1027 origlen = le32dec(&z.next_in[0]);
1029 if (origlen != out_sub_tot) {
1030 maybe_warnx("invalid compressed"
1031 " data--length error");
1040 maybe_warnx("decompression error");
1043 state = GZSTATE_MAGIC0;
1052 if (state > GZSTATE_INIT)
1065 * set the owner, mode, flags & utimes using the given file descriptor.
1066 * file is only used in possible warning messages.
1069 copymodes(int fd, const struct stat *sbp, const char *file)
1071 struct timespec times[2];
1075 * If we have no info on the input, give this file some
1076 * default values and return..
1079 mode_t mask = umask(022);
1081 (void)fchmod(fd, DEFFILEMODE & ~mask);
1087 /* if the chown fails, remove set-id bits as-per compress(1) */
1088 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1090 maybe_warn("couldn't fchown: %s", file);
1091 sb.st_mode &= ~(S_ISUID|S_ISGID);
1094 /* we only allow set-id and the 9 normal permission bits */
1095 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1096 if (fchmod(fd, sb.st_mode) < 0)
1097 maybe_warn("couldn't fchmod: %s", file);
1099 times[0] = sb.st_atim;
1100 times[1] = sb.st_mtim;
1101 if (futimens(fd, times) < 0)
1102 maybe_warn("couldn't futimens: %s", file);
1104 /* only try flags if they exist already */
1105 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1106 maybe_warn("couldn't fchflags: %s", file);
1109 /* what sort of file is this? */
1110 static enum filetype
1111 file_gettype(u_char *buf)
1114 if (buf[0] == GZIP_MAGIC0 &&
1115 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1117 #ifndef NO_BZIP2_SUPPORT
1118 else if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1119 buf[3] >= '0' && buf[3] <= '9')
1122 #ifndef NO_COMPRESS_SUPPORT
1123 else if (memcmp(buf, Z_MAGIC, 2) == 0)
1126 #ifndef NO_PACK_SUPPORT
1127 else if (memcmp(buf, PACK_MAGIC, 2) == 0)
1130 #ifndef NO_XZ_SUPPORT
1131 else if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */
1134 #ifndef NO_LZ_SUPPORT
1135 else if (memcmp(buf, LZ_MAGIC, 4) == 0)
1138 #ifndef NO_ZSTD_SUPPORT
1139 else if (memcmp(buf, ZSTD_MAGIC, 4) == 0)
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 got_sigint(int signo __unused)
1195 if (remove_file != NULL)
1196 unlink(remove_file);
1201 got_siginfo(int signo __unused)
1211 signal(SIGINFO, got_siginfo);
1212 signal(SIGINT, got_sigint);
1216 infile_newdata(size_t newdata)
1219 infile_current += newdata;
1223 infile_set(const char *newinfile, off_t total)
1228 infile_total = total;
1236 infile_total = infile_current = 0;
1239 static const suffixes_t *
1240 check_suffix(char *file, int xlate)
1242 const suffixes_t *s;
1243 int len = strlen(file);
1246 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1247 /* if it doesn't fit in "a.suf", don't bother */
1248 if (s->ziplen >= len)
1250 sp = file + len - s->ziplen;
1251 if (strcmp(s->zipped, sp) != 0)
1254 strcpy(sp, s->normal);
1261 * compress the given file: create a corresponding .gz file and remove the
1265 file_compress(char *file, char *outfile, size_t outsize)
1269 off_t size, in_size;
1270 struct stat isb, osb;
1271 const suffixes_t *suff;
1273 in = open(file, O_RDONLY);
1275 maybe_warn("can't open %s", file);
1279 if (fstat(in, &isb) != 0) {
1280 maybe_warn("couldn't stat: %s", file);
1285 if (fstat(in, &isb) != 0) {
1287 maybe_warn("can't stat %s", file);
1290 infile_set(file, isb.st_size);
1293 if (isb.st_nlink > 1 && fflag == 0) {
1294 maybe_warnx("%s has %ju other link%s -- "
1296 (uintmax_t)isb.st_nlink - 1,
1297 isb.st_nlink == 1 ? "" : "s");
1302 if (fflag == 0 && (suff = check_suffix(file, 0)) &&
1303 suff->zipped[0] != 0) {
1304 maybe_warnx("%s already has %s suffix -- unchanged",
1305 file, suff->zipped);
1310 /* Add (usually) .gz to filename */
1311 if ((size_t)snprintf(outfile, outsize, "%s%s",
1312 file, suffixes[0].zipped) >= outsize)
1313 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1314 suffixes[0].zipped, suffixes[0].ziplen + 1);
1316 if (check_outfile(outfile) == 0) {
1323 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1325 maybe_warn("could not create output: %s", outfile);
1329 remove_file = outfile;
1331 out = STDOUT_FILENO;
1333 in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1338 * If there was an error, in_size will be -1.
1339 * If we compressed to stdout, just return the size.
1340 * Otherwise stat the file and check it is the correct size.
1341 * We only blow away the file if we can stat the output and it
1342 * has the expected size.
1345 return in_size == -1 ? -1 : size;
1347 if (fstat(out, &osb) != 0) {
1348 maybe_warn("couldn't stat: %s", outfile);
1352 if (osb.st_size != size) {
1353 maybe_warnx("output file: %s wrong size (%ju != %ju), deleting",
1354 outfile, (uintmax_t)osb.st_size, (uintmax_t)size);
1358 copymodes(out, &isb, outfile);
1360 if (close(out) == -1)
1361 maybe_warn("couldn't close output");
1363 /* output is good, ok to delete input */
1364 unlink_input(file, &isb);
1368 if (close(out) == -1)
1369 maybe_warn("couldn't close output");
1371 maybe_warnx("leaving original %s", file);
1376 /* uncompress the given file and remove the original */
1378 file_uncompress(char *file, char *outfile, size_t outsize)
1380 struct stat isb, osb;
1383 unsigned char fourbytes[4];
1384 enum filetype method;
1385 int fd, ofd, zfd = -1;
1389 time_t timestamp = 0;
1390 char name[PATH_MAX + 1];
1392 /* gather the old name info */
1394 fd = open(file, O_RDONLY);
1396 maybe_warn("can't open %s", file);
1399 if (fstat(fd, &isb) != 0) {
1400 maybe_warn("can't stat %s", file);
1403 if (S_ISREG(isb.st_mode))
1404 in_size = isb.st_size;
1407 infile_set(file, in_size);
1409 strlcpy(outfile, file, outsize);
1410 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1411 maybe_warnx("%s: unknown suffix -- ignored", file);
1415 rbytes = read(fd, fourbytes, sizeof fourbytes);
1416 if (rbytes != sizeof fourbytes) {
1417 /* we don't want to fail here. */
1421 maybe_warn("can't read %s", file);
1423 goto unexpected_EOF;
1426 infile_newdata(rbytes);
1428 method = file_gettype(fourbytes);
1429 if (fflag == 0 && method == FT_UNKNOWN) {
1430 maybe_warnx("%s: not in gzip format", file);
1435 if (method == FT_GZIP && Nflag) {
1436 unsigned char ts[4]; /* timestamp */
1438 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1439 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1440 goto unexpected_EOF;
1443 maybe_warn("can't read %s", file);
1447 timestamp = le32dec(&ts[0]);
1449 if (fourbytes[3] & ORIG_NAME) {
1450 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1452 maybe_warn("can't read %s", file);
1455 if (name[0] != '\0') {
1458 /* Make sure that name is NUL-terminated */
1459 name[rbytes] = '\0';
1461 /* strip saved directory name */
1462 nf = strrchr(name, '/');
1468 /* preserve original directory name */
1469 dp = strrchr(file, '/');
1474 snprintf(outfile, outsize, "%.*s%.*s",
1476 file, (int) rbytes, nf);
1480 lseek(fd, 0, SEEK_SET);
1482 if (cflag == 0 || lflag) {
1483 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1484 maybe_warnx("%s has %ju other links -- skipping",
1485 file, (uintmax_t)isb.st_nlink - 1);
1488 if (nflag == 0 && timestamp)
1489 isb.st_mtime = timestamp;
1490 if (check_outfile(outfile) == 0)
1495 zfd = STDOUT_FILENO;
1499 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1500 if (zfd == STDOUT_FILENO) {
1501 /* We won't close STDOUT_FILENO later... */
1503 close(STDOUT_FILENO);
1506 maybe_warn("can't open %s", outfile);
1509 remove_file = outfile;
1513 #ifndef NO_BZIP2_SUPPORT
1517 maybe_warnx("no -l with bzip2 files");
1521 size = unbzip2(fd, zfd, NULL, 0, NULL);
1525 #ifndef NO_COMPRESS_SUPPORT
1531 maybe_warnx("no -l with Lempel-Ziv files");
1535 if ((in = zdopen(fd)) == NULL) {
1536 maybe_warn("zdopen for read: %s", file);
1540 out = fdopen(dup(zfd), "w");
1542 maybe_warn("fdopen for write: %s", outfile);
1547 size = zuncompress(in, out, NULL, 0, NULL);
1548 /* need to fclose() if ferror() is true... */
1550 if (error | fclose(in)) {
1552 maybe_warn("failed infile");
1554 maybe_warn("failed infile fclose");
1560 if (fclose(out) != 0) {
1561 maybe_warn("failed outfile fclose");
1570 #ifndef NO_PACK_SUPPORT
1573 maybe_warnx("no -l with packed files");
1577 size = unpack(fd, zfd, NULL, 0, NULL);
1581 #ifndef NO_XZ_SUPPORT
1584 size = unxz_len(fd);
1586 print_list_out(in_size, size, file);
1591 size = unxz(fd, zfd, NULL, 0, NULL);
1595 #ifndef NO_LZ_SUPPORT
1598 maybe_warnx("no -l with lzip files");
1601 size = unlz(fd, zfd, NULL, 0, NULL);
1605 #ifndef NO_ZSTD_SUPPORT
1608 maybe_warnx("no -l with zstd files");
1611 size = unzstd(fd, zfd, NULL, 0, NULL);
1616 maybe_warnx("no -l for unknown filetypes");
1619 size = cat_fd(NULL, 0, NULL, fd);
1623 print_list(fd, in_size, outfile, isb.st_mtime);
1626 return -1; /* XXX */
1630 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1635 maybe_warn("couldn't close input");
1636 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1637 maybe_warn("couldn't close output");
1642 maybe_warnx("%s: uncompress failed", file);
1646 /* if testing, or we uncompressed to stdout, this is all we need */
1649 /* if we are uncompressing to stdin, don't remove the file. */
1654 * if we create a file...
1657 * if we can't stat the file don't remove the file.
1660 ofd = open(outfile, O_RDWR, 0);
1662 maybe_warn("couldn't open (leaving original): %s",
1666 if (fstat(ofd, &osb) != 0) {
1667 maybe_warn("couldn't stat (leaving original): %s",
1672 if (osb.st_size != size) {
1673 maybe_warnx("stat gave different size: %ju != %ju (leaving original)",
1674 (uintmax_t)size, (uintmax_t)osb.st_size);
1679 copymodes(ofd, &isb, outfile);
1682 unlink_input(file, &isb);
1686 maybe_warnx("%s: unexpected end of file", file);
1690 if (zfd != -1 && zfd != STDOUT_FILENO)
1698 if (print_info == 0)
1702 int pcent = (int)((100.0 * infile_current) / infile_total);
1704 fprintf(stderr, "%s: done %llu/%llu bytes %d%%\n",
1705 infile, (unsigned long long)infile_current,
1706 (unsigned long long)infile_total, pcent);
1708 fprintf(stderr, "%s: done %llu bytes\n",
1709 infile, (unsigned long long)infile_current);
1715 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1722 w = write_retry(STDOUT_FILENO, prepend, count);
1723 if (w == -1 || (size_t)w != count) {
1724 maybe_warn("write to stdout");
1730 rv = read(fd, buf, sizeof buf);
1734 maybe_warn("read from fd %d", fd);
1739 if (write_retry(STDOUT_FILENO, buf, rv) != rv) {
1740 maybe_warn("write to stdout");
1755 unsigned char fourbytes[4];
1758 enum filetype method;
1760 #ifndef NO_COMPRESS_SUPPORT
1764 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1765 maybe_warnx("standard input is a terminal -- ignoring");
1769 if (fstat(STDIN_FILENO, &isb) < 0) {
1770 maybe_warn("fstat");
1773 if (S_ISREG(isb.st_mode))
1774 in_size = isb.st_size;
1777 infile_set("(stdin)", in_size);
1780 print_list(STDIN_FILENO, in_size, infile, isb.st_mtime);
1784 bytes_read = read_retry(STDIN_FILENO, fourbytes, sizeof fourbytes);
1785 if (bytes_read == -1) {
1786 maybe_warn("can't read stdin");
1788 } else if (bytes_read != sizeof(fourbytes)) {
1789 maybe_warnx("(stdin): unexpected end of file");
1793 method = file_gettype(fourbytes);
1797 maybe_warnx("unknown compression format");
1800 usize = cat_fd(fourbytes, sizeof fourbytes, &gsize, STDIN_FILENO);
1803 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1804 (char *)fourbytes, sizeof fourbytes, &gsize, "(stdin)");
1806 #ifndef NO_BZIP2_SUPPORT
1808 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1809 (char *)fourbytes, sizeof fourbytes, &gsize);
1812 #ifndef NO_COMPRESS_SUPPORT
1814 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1815 maybe_warnx("zopen of stdin");
1819 usize = zuncompress(in, stdout, (char *)fourbytes,
1820 sizeof fourbytes, &gsize);
1824 #ifndef NO_PACK_SUPPORT
1826 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1827 (char *)fourbytes, sizeof fourbytes, &gsize);
1830 #ifndef NO_XZ_SUPPORT
1832 usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1833 (char *)fourbytes, sizeof fourbytes, &gsize);
1836 #ifndef NO_LZ_SUPPORT
1838 usize = unlz(STDIN_FILENO, STDOUT_FILENO,
1839 (char *)fourbytes, sizeof fourbytes, &gsize);
1842 #ifndef NO_ZSTD_SUPPORT
1844 usize = unzstd(STDIN_FILENO, STDOUT_FILENO,
1845 (char *)fourbytes, sizeof fourbytes, &gsize);
1850 if (vflag && !tflag && usize != -1 && gsize != -1)
1851 print_verbage(NULL, NULL, usize, gsize);
1853 print_test("(stdin)", usize != -1);
1869 infile_set("(stdout)", 0);
1871 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1872 maybe_warnx("standard output is a terminal -- ignoring");
1876 /* If stdin is a file use its mtime, otherwise use current time */
1877 ret = fstat(STDIN_FILENO, &sb);
1879 maybe_warn("Can't stat stdin");
1883 if (S_ISREG(sb.st_mode)) {
1884 infile_set("(stdout)", sb.st_size);
1885 mtime = (uint32_t)sb.st_mtime;
1887 systime = time(NULL);
1888 if (systime == -1) {
1892 mtime = (uint32_t)systime;
1896 gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1897 if (vflag && !tflag && usize != -1 && gsize != -1)
1898 print_verbage(NULL, NULL, usize, gsize);
1901 /* do what is asked for, for the path name */
1903 handle_pathname(char *path)
1905 char *opath = path, *s = NULL;
1910 /* check for stdout/stdin */
1911 if (path[0] == '-' && path[1] == '\0') {
1920 if (stat(path, &sb) != 0 || (fflag == 0 && cflag == 0 &&
1921 lstat(path, &sb) != 0)) {
1922 /* lets try <path>.gz if we're decompressing */
1923 if (dflag && s == NULL && errno == ENOENT) {
1925 slen = suffixes[0].ziplen;
1926 s = malloc(len + slen + 1);
1928 maybe_err("malloc");
1929 memcpy(s, path, len);
1930 memcpy(s + len, suffixes[0].zipped, slen + 1);
1934 maybe_warn("can't stat: %s", opath);
1938 if (S_ISDIR(sb.st_mode)) {
1942 maybe_warnx("%s is a directory", path);
1946 if (S_ISREG(sb.st_mode))
1947 handle_file(path, &sb);
1949 maybe_warnx("%s is not a regular file", path);
1956 /* compress/decompress a file */
1958 handle_file(char *file, struct stat *sbp)
1961 char outfile[PATH_MAX];
1963 infile_set(file, sbp->st_size);
1965 usize = file_uncompress(file, outfile, sizeof(outfile));
1967 print_test(file, usize != -1);
1970 gsize = sbp->st_size;
1972 gsize = file_compress(file, outfile, sizeof(outfile));
1975 usize = sbp->st_size;
1979 if (vflag && !tflag)
1980 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
1983 /* this is used with -r to recursively descend directories */
1985 handle_dir(char *dir)
1993 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
1995 warn("couldn't fts_open %s", dir);
1999 while (errno = 0, (entry = fts_read(fts))) {
2000 switch(entry->fts_info) {
2008 maybe_warn("%s", entry->fts_path);
2011 handle_file(entry->fts_path, entry->fts_statp);
2015 warn("error with fts_read %s", dir);
2016 (void)fts_close(fts);
2019 /* print a ratio - size reduction as a fraction of uncompressed size */
2021 print_ratio(off_t in, off_t out, FILE *where)
2023 int percent10; /* 10 * percent */
2029 if (in == 0 && out == 0)
2033 * Output is more than double size of input! print -99.9%
2034 * Quite possibly we've failed to get the original size.
2039 * We only need 12 bits of result from the final division,
2040 * so reduce the values until a 32bit division will suffice.
2042 while (in > 0x100000) {
2047 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
2052 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
2053 /* Move the '.' to before the last digit */
2054 buff[len - 1] = buff[len - 2];
2055 buff[len - 2] = '.';
2056 fprintf(where, "%5s%%", buff);
2059 /* print compression statistics, and the new name (if there is one!) */
2061 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
2064 fprintf(stderr, "%s:%s ", file,
2065 strlen(file) < 7 ? "\t\t" : "\t");
2066 print_ratio(usize, gsize, stderr);
2068 fprintf(stderr, " -- replaced with %s", nfile);
2069 fprintf(stderr, "\n");
2073 /* print test results */
2075 print_test(const char *file, int ok)
2078 if (exit_value == 0 && ok == 0)
2080 fprintf(stderr, "%s:%s %s\n", file,
2081 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2085 /* print a file's info ala --list */
2087 compressed uncompressed ratio uncompressed_name
2088 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2091 print_list(int fd, off_t out, const char *outfile, time_t ts)
2093 static int first = 1;
2094 static off_t in_tot, out_tot;
2100 printf("method crc date time ");
2102 printf(" compressed uncompressed "
2103 "ratio uncompressed_name\n");
2113 /* read the last 4 bytes - this is the uncompressed size */
2114 rv = lseek(fd, (off_t)(-8), SEEK_END);
2116 unsigned char buf[8];
2119 rv = read(fd, (char *)buf, sizeof(buf));
2121 maybe_warn("read of uncompressed size");
2122 else if (rv != sizeof(buf))
2123 maybe_warnx("read of uncompressed size");
2126 usize = le32dec(&buf[4]);
2128 crc = le32dec(&buf[0]);
2133 if (vflag && fd == -1)
2136 char *date = ctime(&ts);
2138 /* skip the day, 1/100th second, and year */
2141 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2145 print_list_out(out, in, outfile);
2149 print_list_out(off_t out, off_t in, const char *outfile)
2151 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2152 print_ratio(in, out, stdout);
2153 printf(" %s\n", outfile);
2156 /* display the usage of NetBSD gzip */
2161 fprintf(stderr, "%s\n", gzip_version);
2163 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2164 " -1 --fast fastest (worst) compression\n"
2165 " -2 .. -8 set compression level\n"
2166 " -9 --best best (slowest) compression\n"
2167 " -c --stdout write to stdout, keep original files\n"
2169 " -d --decompress uncompress files\n"
2171 " -f --force force overwriting & compress links\n"
2172 " -h --help display this help\n"
2173 " -k --keep don't delete input files during operation\n"
2174 " -l --list list compressed file contents\n"
2175 " -N --name save or restore original file name and time stamp\n"
2176 " -n --no-name don't save original file name or time stamp\n"
2177 " -q --quiet output no warnings\n"
2178 " -r --recursive recursively compress files in directories\n"
2179 " -S .suf use suffix .suf instead of .gz\n"
2181 " -t --test test compressed file\n"
2182 " -V --version display program version\n"
2183 " -v --verbose print extra statistics\n",
2188 /* display the license information of FreeBSD gzip */
2190 display_license(void)
2193 fprintf(stderr, "%s (based on NetBSD gzip 20150113)\n", gzip_version);
2194 fprintf(stderr, "%s\n", gzip_copyright);
2198 /* display the version of NetBSD gzip */
2200 display_version(void)
2203 fprintf(stderr, "%s\n", gzip_version);
2207 #ifndef NO_BZIP2_SUPPORT
2208 #include "unbzip2.c"
2210 #ifndef NO_COMPRESS_SUPPORT
2211 #include "zuncompress.c"
2213 #ifndef NO_PACK_SUPPORT
2216 #ifndef NO_XZ_SUPPORT
2219 #ifndef NO_LZ_SUPPORT
2222 #ifndef NO_ZSTD_SUPPORT
2227 read_retry(int fd, void *buf, size_t sz)
2230 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2235 ret = read(fd, cp, left);
2238 } else if (ret == 0) {
2249 write_retry(int fd, const void *buf, size_t sz)
2251 const char *cp = buf;
2252 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2257 ret = write(fd, cp, left);
2260 } else if (ret == 0) {
2261 abort(); /* Can't happen */