1 /* $NetBSD: gzip.c,v 1.112 2017/08/23 13:04:17 christos 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/param.h>
71 /* what type of file are we dealing with */
74 #ifndef NO_BZIP2_SUPPORT
77 #ifndef NO_COMPRESS_SUPPORT
80 #ifndef NO_PACK_SUPPORT
90 #ifndef NO_BZIP2_SUPPORT
93 #define BZ2_SUFFIX ".bz2"
94 #define BZIP2_MAGIC "BZh"
97 #ifndef NO_COMPRESS_SUPPORT
99 #define Z_MAGIC "\037\235"
102 #ifndef NO_PACK_SUPPORT
103 #define PACK_MAGIC "\037\036"
106 #ifndef NO_XZ_SUPPORT
108 #define XZ_SUFFIX ".xz"
109 #define XZ_MAGIC "\3757zXZ"
112 #define GZ_SUFFIX ".gz"
114 #define BUFLEN (64 * 1024)
116 #define GZIP_MAGIC0 0x1F
117 #define GZIP_MAGIC1 0x8B
118 #define GZIP_OMAGIC1 0x9E
120 #define GZIP_TIMESTAMP (off_t)4
121 #define GZIP_ORIGNAME (off_t)10
123 #define HEAD_CRC 0x02
124 #define EXTRA_FIELD 0x04
125 #define ORIG_NAME 0x08
128 #define OS_CODE 3 /* Unix */
133 const char *normal; /* for unzip - must not be longer than zipped */
135 static suffixes_t suffixes[] = {
136 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
137 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S .xxx */
139 SUFFIX(GZ_SUFFIX, ""),
144 SUFFIX(".taz", ".tar"),
145 SUFFIX(".tgz", ".tar"),
146 #ifndef NO_BZIP2_SUPPORT
147 SUFFIX(BZ2_SUFFIX, ""),
148 SUFFIX(".tbz", ".tar"),
149 SUFFIX(".tbz2", ".tar"),
151 #ifndef NO_COMPRESS_SUPPORT
152 SUFFIX(Z_SUFFIX, ""),
154 #ifndef NO_XZ_SUPPORT
155 SUFFIX(XZ_SUFFIX, ""),
157 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
161 #define NUM_SUFFIXES (nitems(suffixes))
162 #define SUFFIX_MAXLEN 30
164 static const char gzip_version[] = "FreeBSD gzip 20171121";
167 static const char gzip_copyright[] = \
168 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
169 " All rights reserved.\n"
171 " Redistribution and use in source and binary forms, with or without\n"
172 " modification, are permitted provided that the following conditions\n"
174 " 1. Redistributions of source code must retain the above copyright\n"
175 " notice, this list of conditions and the following disclaimer.\n"
176 " 2. Redistributions in binary form must reproduce the above copyright\n"
177 " notice, this list of conditions and the following disclaimer in the\n"
178 " documentation and/or other materials provided with the distribution.\n"
180 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
181 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
182 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
183 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
184 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
185 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
186 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
187 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
188 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
189 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
193 static int cflag; /* stdout mode */
194 static int dflag; /* decompress mode */
195 static int lflag; /* list mode */
196 static int numflag = 6; /* gzip -1..-9 value */
198 static const char *remove_file = NULL; /* file to be removed upon SIGINT */
200 static int fflag; /* force mode */
202 static int kflag; /* don't delete input files */
203 static int nflag; /* don't save name/timestamp */
204 static int Nflag; /* don't restore name/timestamp */
205 static int qflag; /* quiet mode */
206 static int rflag; /* recursive mode */
207 static int tflag; /* test */
208 static int vflag; /* verbose mode */
209 static sig_atomic_t print_info = 0;
215 static int exit_value = 0; /* exit value */
217 static const char *infile; /* name of file coming in */
219 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead2;
220 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
221 !defined(NO_XZ_SUPPORT)
222 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead2;
224 static void maybe_warn(const char *fmt, ...) __printflike(1, 2);
225 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2);
226 static enum filetype file_gettype(u_char *);
228 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
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;
243 static void display_license(void);
245 static const suffixes_t *check_suffix(char *, int);
246 static ssize_t read_retry(int, void *, size_t);
247 static ssize_t write_retry(int, const void *, size_t);
250 #define infile_set(f,t) infile_set(f)
252 static void infile_set(const char *newinfile, off_t total);
255 #define unlink_input(f, sb) unlink(f)
256 #define check_siginfo() /* nothing */
257 #define setup_signals() /* nothing */
258 #define infile_newdata(t) /* nothing */
260 static off_t infile_total; /* total expected to read/write */
261 static off_t infile_current; /* current read/write */
263 static void check_siginfo(void);
264 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
265 static void prepend_gzip(char *, int *, char ***);
266 static void handle_dir(char *);
267 static void print_verbage(const char *, const char *, off_t, off_t);
268 static void print_test(const char *, int);
269 static void copymodes(int fd, const struct stat *, const char *file);
270 static int check_outfile(const char *outfile);
271 static void setup_signals(void);
272 static void infile_newdata(size_t newdata);
273 static void infile_clear(void);
276 #ifndef NO_BZIP2_SUPPORT
277 static off_t unbzip2(int, int, char *, size_t, off_t *);
280 #ifndef NO_COMPRESS_SUPPORT
281 static FILE *zdopen(int);
282 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
285 #ifndef NO_PACK_SUPPORT
286 static off_t unpack(int, int, char *, size_t, off_t *);
289 #ifndef NO_XZ_SUPPORT
290 static off_t unxz(int, int, char *, size_t, off_t *);
294 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
296 static const struct option longopts[] = {
297 { "stdout", no_argument, 0, 'c' },
298 { "to-stdout", no_argument, 0, 'c' },
299 { "decompress", no_argument, 0, 'd' },
300 { "uncompress", no_argument, 0, 'd' },
301 { "force", no_argument, 0, 'f' },
302 { "help", no_argument, 0, 'h' },
303 { "keep", no_argument, 0, 'k' },
304 { "list", no_argument, 0, 'l' },
305 { "no-name", no_argument, 0, 'n' },
306 { "name", no_argument, 0, 'N' },
307 { "quiet", no_argument, 0, 'q' },
308 { "recursive", no_argument, 0, 'r' },
309 { "suffix", required_argument, 0, 'S' },
310 { "test", no_argument, 0, 't' },
311 { "verbose", no_argument, 0, 'v' },
312 { "version", no_argument, 0, 'V' },
313 { "fast", no_argument, 0, '1' },
314 { "best", no_argument, 0, '9' },
315 { "ascii", no_argument, 0, 'a' },
316 { "license", no_argument, 0, 'L' },
317 { NULL, no_argument, 0, 0 },
322 main(int argc, char **argv)
324 const char *progname = getprogname();
334 if ((gzip = getenv("GZIP")) != NULL)
335 prepend_gzip(gzip, &argc, &argv);
340 * handle being called `gunzip', `zcat' and `gzcat'
342 if (strcmp(progname, "gunzip") == 0)
344 else if (strcmp(progname, "zcat") == 0 ||
345 strcmp(progname, "gzcat") == 0)
349 #define OPT_LIST "123456789cdhlV"
351 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
354 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
356 case '1': case '2': case '3':
357 case '4': case '5': case '6':
358 case '7': case '8': case '9':
376 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
402 len = strlen(optarg);
404 if (len > SUFFIX_MAXLEN)
405 errx(1, "incorrect suffix: '%s': too long", optarg);
406 suffixes[0].zipped = optarg;
407 suffixes[0].ziplen = len;
409 suffixes[NUM_SUFFIXES - 1].zipped = "";
410 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
431 if (dflag) /* stdin mode */
433 else /* stdout mode */
437 handle_pathname(argv[0]);
441 if (qflag == 0 && lflag && argc > 1)
442 print_list(-1, 0, "(totals)", 0);
447 /* maybe print a warning */
449 maybe_warn(const char *fmt, ...)
462 /* ... without an errno. */
464 maybe_warnx(const char *fmt, ...)
477 /* maybe print an error */
479 maybe_err(const char *fmt, ...)
491 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
492 !defined(NO_XZ_SUPPORT)
493 /* ... without an errno. */
495 maybe_errx(const char *fmt, ...)
509 /* split up $GZIP and prepend it to the argument list */
511 prepend_gzip(char *gzip, int *argc, char ***argv)
513 char *s, **nargv, **ac;
516 /* scan how many arguments there are */
518 while (*s == ' ' || *s == '\t')
523 while (*s != ' ' && *s != '\t')
535 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
539 /* stash this away */
542 /* copy the program name first */
544 nargv[i++] = *(ac++);
546 /* take a copy of $GZIP and add it to the array */
551 /* Skip whitespaces. */
552 while (*s == ' ' || *s == '\t')
557 /* Find the end of this argument. */
558 while (*s != ' ' && *s != '\t')
560 /* Argument followed by NUL. */
562 /* Terminate by overwriting ' ' or '\t' with NUL. */
567 /* copy the original arguments and a NULL */
569 nargv[i++] = *(ac++);
574 /* compress input to output. Return bytes read, -1 on error */
576 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
579 char *outbufp, *inbufp;
580 off_t in_tot = 0, out_tot = 0;
585 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
590 outbufp = malloc(BUFLEN);
591 inbufp = malloc(BUFLEN);
592 if (outbufp == NULL || inbufp == NULL) {
593 maybe_err("malloc failed");
597 memset(&z, 0, sizeof z);
603 memcpy(outbufp, header, sizeof header);
611 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
612 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
613 *origname ? ORIG_NAME : 0,
616 (mtime >> 16) & 0xff,
617 (mtime >> 24) & 0xff,
618 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
621 /* this need PATH_MAX > BUFLEN ... */
622 maybe_err("snprintf");
627 z.next_out = (unsigned char *)outbufp + i;
628 z.avail_out = BUFLEN - i;
630 error = deflateInit2(&z, numflag, Z_DEFLATED,
631 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
633 maybe_warnx("deflateInit2 failed");
638 crc = crc32(0L, Z_NULL, 0);
640 if (z.avail_out == 0) {
641 if (write_retry(out, outbufp, BUFLEN) != BUFLEN) {
648 z.next_out = (unsigned char *)outbufp;
649 z.avail_out = BUFLEN;
652 if (z.avail_in == 0) {
653 in_size = read(in, inbufp, BUFLEN);
661 infile_newdata(in_size);
663 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
665 z.next_in = (unsigned char *)inbufp;
666 z.avail_in = in_size;
669 error = deflate(&z, Z_NO_FLUSH);
670 if (error != Z_OK && error != Z_STREAM_END) {
671 maybe_warnx("deflate failed");
682 error = deflate(&z, Z_FINISH);
683 if (error != Z_OK && error != Z_STREAM_END) {
684 maybe_warnx("deflate failed");
689 len = (char *)z.next_out - outbufp;
691 w = write_retry(out, outbufp, len);
692 if (w == -1 || (size_t)w != len) {
698 z.next_out = (unsigned char *)outbufp;
699 z.avail_out = BUFLEN;
701 if (error == Z_STREAM_END)
705 if (deflateEnd(&z) != Z_OK) {
706 maybe_warnx("deflateEnd failed");
711 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
713 (int)(crc >> 8) & 0xff,
714 (int)(crc >> 16) & 0xff,
715 (int)(crc >> 24) & 0xff,
717 (int)(in_tot >> 8) & 0xff,
718 (int)(in_tot >> 16) & 0xff,
719 (int)(in_tot >> 24) & 0xff);
721 maybe_err("snprintf");
722 if (write_retry(out, outbufp, i) != i) {
739 * uncompress input to output then close the input. return the
740 * uncompressed size written, and put the compressed sized read
744 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
745 const char *filename)
748 char *outbufp, *inbufp;
749 off_t out_tot = -1, in_tot = 0;
750 uint32_t out_sub_tot = 0;
768 } state = GZSTATE_MAGIC0;
769 int flags = 0, skip_count = 0;
770 int error = Z_STREAM_ERROR, done_reading = 0;
775 #define ADVANCE() { z.next_in++; z.avail_in--; }
777 if ((outbufp = malloc(BUFLEN)) == NULL) {
778 maybe_err("malloc failed");
781 if ((inbufp = malloc(BUFLEN)) == NULL) {
782 maybe_err("malloc failed");
786 memset(&z, 0, sizeof z);
788 z.next_in = (unsigned char *)pre;
789 z.avail_out = BUFLEN;
790 z.next_out = (unsigned char *)outbufp;
800 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
803 if (z.avail_in > 0) {
804 memmove(inbufp, z.next_in, z.avail_in);
806 z.next_in = (unsigned char *)inbufp;
807 in_size = read(in, z.next_in + z.avail_in,
808 BUFLEN - z.avail_in);
811 maybe_warn("failed to read stdin");
813 } else if (in_size == 0) {
816 infile_newdata(in_size);
818 z.avail_in += in_size;
823 if (z.avail_in == 0) {
824 if (done_reading && state != GZSTATE_MAGIC0) {
825 maybe_warnx("%s: unexpected end of file",
833 if (*z.next_in != GZIP_MAGIC0) {
835 maybe_warnx("%s: trailing garbage "
836 "ignored", filename);
840 maybe_warnx("input not gziped (MAGIC0)");
846 crc = crc32(0L, Z_NULL, 0);
850 if (*z.next_in != GZIP_MAGIC1 &&
851 *z.next_in != GZIP_OMAGIC1) {
852 maybe_warnx("input not gziped (MAGIC1)");
860 if (*z.next_in != Z_DEFLATED) {
861 maybe_warnx("unknown compression method");
875 case GZSTATE_SKIPPING:
876 if (skip_count > 0) {
884 if ((flags & EXTRA_FIELD) == 0) {
885 state = GZSTATE_ORIGNAME;
888 skip_count = *z.next_in;
894 skip_count |= ((*z.next_in) << 8);
900 if (skip_count > 0) {
907 case GZSTATE_ORIGNAME:
908 if ((flags & ORIG_NAME) == 0) {
917 case GZSTATE_COMMENT:
918 if ((flags & COMMENT) == 0) {
927 case GZSTATE_HEAD_CRC1:
928 if (flags & HEAD_CRC)
935 case GZSTATE_HEAD_CRC2:
936 if (skip_count > 0) {
944 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
945 maybe_warnx("failed to inflateInit");
952 error = inflate(&z, Z_FINISH);
954 /* Z_BUF_ERROR goes with Z_FINISH... */
956 if (z.avail_out > 0 && !done_reading)
964 maybe_warnx("Z_NEED_DICT error");
967 maybe_warnx("data stream error");
970 maybe_warnx("internal stream error");
973 maybe_warnx("memory allocation error");
977 maybe_warn("unknown error from inflate(): %d",
980 wr = BUFLEN - z.avail_out;
983 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
986 /* don't write anything with -t */
989 write_retry(out, outbufp, wr) != wr) {
990 maybe_warn("error writing to output");
998 if (error == Z_STREAM_END) {
1003 z.next_out = (unsigned char *)outbufp;
1004 z.avail_out = BUFLEN;
1011 if (z.avail_in < 4) {
1012 if (!done_reading) {
1016 maybe_warnx("truncated input");
1019 origcrc = ((unsigned)z.next_in[0] & 0xff) |
1020 ((unsigned)z.next_in[1] & 0xff) << 8 |
1021 ((unsigned)z.next_in[2] & 0xff) << 16 |
1022 ((unsigned)z.next_in[3] & 0xff) << 24;
1023 if (origcrc != crc) {
1024 maybe_warnx("invalid compressed"
1025 " data--crc error");
1033 if (!z.avail_in && done_reading) {
1042 if (z.avail_in < 4) {
1043 if (!done_reading) {
1047 maybe_warnx("truncated input");
1050 origlen = ((unsigned)z.next_in[0] & 0xff) |
1051 ((unsigned)z.next_in[1] & 0xff) << 8 |
1052 ((unsigned)z.next_in[2] & 0xff) << 16 |
1053 ((unsigned)z.next_in[3] & 0xff) << 24;
1055 if (origlen != out_sub_tot) {
1056 maybe_warnx("invalid compressed"
1057 " data--length error");
1066 maybe_warnx("decompression error");
1069 state = GZSTATE_MAGIC0;
1078 if (state > GZSTATE_INIT)
1092 * set the owner, mode, flags & utimes using the given file descriptor.
1093 * file is only used in possible warning messages.
1096 copymodes(int fd, const struct stat *sbp, const char *file)
1098 struct timespec times[2];
1102 * If we have no info on the input, give this file some
1103 * default values and return..
1106 mode_t mask = umask(022);
1108 (void)fchmod(fd, DEFFILEMODE & ~mask);
1114 /* if the chown fails, remove set-id bits as-per compress(1) */
1115 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1117 maybe_warn("couldn't fchown: %s", file);
1118 sb.st_mode &= ~(S_ISUID|S_ISGID);
1121 /* we only allow set-id and the 9 normal permission bits */
1122 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1123 if (fchmod(fd, sb.st_mode) < 0)
1124 maybe_warn("couldn't fchmod: %s", file);
1126 times[0] = sb.st_atim;
1127 times[1] = sb.st_mtim;
1128 if (futimens(fd, times) < 0)
1129 maybe_warn("couldn't futimens: %s", file);
1131 /* only try flags if they exist already */
1132 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1133 maybe_warn("couldn't fchflags: %s", file);
1137 /* what sort of file is this? */
1138 static enum filetype
1139 file_gettype(u_char *buf)
1142 if (buf[0] == GZIP_MAGIC0 &&
1143 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1146 #ifndef NO_BZIP2_SUPPORT
1147 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1148 buf[3] >= '0' && buf[3] <= '9')
1152 #ifndef NO_COMPRESS_SUPPORT
1153 if (memcmp(buf, Z_MAGIC, 2) == 0)
1157 #ifndef NO_PACK_SUPPORT
1158 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1162 #ifndef NO_XZ_SUPPORT
1163 if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */
1171 /* check the outfile is OK. */
1173 check_outfile(const char *outfile)
1178 if (lflag == 0 && stat(outfile, &sb) == 0) {
1181 else if (isatty(STDIN_FILENO)) {
1182 char ans[10] = { 'n', '\0' }; /* default */
1184 fprintf(stderr, "%s already exists -- do you wish to "
1185 "overwrite (y or n)? " , outfile);
1186 (void)fgets(ans, sizeof(ans) - 1, stdin);
1187 if (ans[0] != 'y' && ans[0] != 'Y') {
1188 fprintf(stderr, "\tnot overwriting\n");
1193 maybe_warnx("%s already exists -- skipping", outfile);
1201 unlink_input(const char *file, const struct stat *sb)
1207 if (stat(file, &nsb) != 0)
1208 /* Must be gone already */
1210 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1211 /* Definitely a different file */
1217 got_sigint(int signo __unused)
1220 if (remove_file != NULL)
1221 unlink(remove_file);
1226 got_siginfo(int signo __unused)
1236 signal(SIGINFO, got_siginfo);
1237 signal(SIGINT, got_sigint);
1241 infile_newdata(size_t newdata)
1244 infile_current += newdata;
1249 infile_set(const char *newinfile, off_t total)
1255 infile_total = total;
1265 infile_total = infile_current = 0;
1269 static const suffixes_t *
1270 check_suffix(char *file, int xlate)
1272 const suffixes_t *s;
1273 int len = strlen(file);
1276 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1277 /* if it doesn't fit in "a.suf", don't bother */
1278 if (s->ziplen >= len)
1280 sp = file + len - s->ziplen;
1281 if (strcmp(s->zipped, sp) != 0)
1284 strcpy(sp, s->normal);
1291 * compress the given file: create a corresponding .gz file and remove the
1295 file_compress(char *file, char *outfile, size_t outsize)
1299 off_t size, in_size;
1301 struct stat isb, osb;
1302 const suffixes_t *suff;
1305 in = open(file, O_RDONLY);
1307 maybe_warn("can't open %s", file);
1312 if (fstat(in, &isb) != 0) {
1313 maybe_warn("couldn't stat: %s", file);
1320 if (fstat(in, &isb) != 0) {
1322 maybe_warn("can't stat %s", file);
1325 infile_set(file, isb.st_size);
1330 if (isb.st_nlink > 1 && fflag == 0) {
1331 maybe_warnx("%s has %ju other link%s -- "
1333 (uintmax_t)isb.st_nlink - 1,
1334 isb.st_nlink == 1 ? "" : "s");
1339 if (fflag == 0 && (suff = check_suffix(file, 0)) &&
1340 suff->zipped[0] != 0) {
1341 maybe_warnx("%s already has %s suffix -- unchanged",
1342 file, suff->zipped);
1348 /* Add (usually) .gz to filename */
1349 if ((size_t)snprintf(outfile, outsize, "%s%s",
1350 file, suffixes[0].zipped) >= outsize)
1351 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1352 suffixes[0].zipped, suffixes[0].ziplen + 1);
1355 if (check_outfile(outfile) == 0) {
1363 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1365 maybe_warn("could not create output: %s", outfile);
1370 remove_file = outfile;
1373 out = STDOUT_FILENO;
1375 in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1380 * If there was an error, in_size will be -1.
1381 * If we compressed to stdout, just return the size.
1382 * Otherwise stat the file and check it is the correct size.
1383 * We only blow away the file if we can stat the output and it
1384 * has the expected size.
1387 return in_size == -1 ? -1 : size;
1390 if (fstat(out, &osb) != 0) {
1391 maybe_warn("couldn't stat: %s", outfile);
1395 if (osb.st_size != size) {
1396 maybe_warnx("output file: %s wrong size (%ju != %ju), deleting",
1397 outfile, (uintmax_t)osb.st_size, (uintmax_t)size);
1401 copymodes(out, &isb, outfile);
1404 if (close(out) == -1)
1405 maybe_warn("couldn't close output");
1407 /* output is good, ok to delete input */
1408 unlink_input(file, &isb);
1413 if (close(out) == -1)
1414 maybe_warn("couldn't close output");
1416 maybe_warnx("leaving original %s", file);
1422 /* uncompress the given file and remove the original */
1424 file_uncompress(char *file, char *outfile, size_t outsize)
1426 struct stat isb, osb;
1429 unsigned char header1[4];
1430 enum filetype method;
1431 int fd, ofd, zfd = -1;
1435 time_t timestamp = 0;
1436 char name[PATH_MAX + 1];
1439 /* gather the old name info */
1441 fd = open(file, O_RDONLY);
1443 maybe_warn("can't open %s", file);
1446 if (fstat(fd, &isb) != 0) {
1447 maybe_warn("can't stat %s", file);
1450 if (S_ISREG(isb.st_mode))
1451 in_size = isb.st_size;
1454 infile_set(file, in_size);
1456 strlcpy(outfile, file, outsize);
1457 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1458 maybe_warnx("%s: unknown suffix -- ignored", file);
1462 rbytes = read(fd, header1, sizeof header1);
1463 if (rbytes != sizeof header1) {
1464 /* we don't want to fail here. */
1470 maybe_warn("can't read %s", file);
1472 goto unexpected_EOF;
1475 infile_newdata(rbytes);
1477 method = file_gettype(header1);
1479 if (fflag == 0 && method == FT_UNKNOWN) {
1480 maybe_warnx("%s: not in gzip format", file);
1487 if (method == FT_GZIP && Nflag) {
1488 unsigned char ts[4]; /* timestamp */
1490 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1491 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1492 goto unexpected_EOF;
1495 maybe_warn("can't read %s", file);
1499 timestamp = ts[3] << 24 | ts[2] << 16 | ts[1] << 8 | ts[0];
1501 if (header1[3] & ORIG_NAME) {
1502 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1504 maybe_warn("can't read %s", file);
1507 if (name[0] != '\0') {
1510 /* Make sure that name is NUL-terminated */
1511 name[rbytes] = '\0';
1513 /* strip saved directory name */
1514 nf = strrchr(name, '/');
1520 /* preserve original directory name */
1521 dp = strrchr(file, '/');
1526 snprintf(outfile, outsize, "%.*s%.*s",
1528 file, (int) rbytes, nf);
1533 lseek(fd, 0, SEEK_SET);
1535 if (cflag == 0 || lflag) {
1537 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1538 maybe_warnx("%s has %ju other links -- skipping",
1539 file, (uintmax_t)isb.st_nlink - 1);
1542 if (nflag == 0 && timestamp)
1543 isb.st_mtime = timestamp;
1544 if (check_outfile(outfile) == 0)
1550 zfd = STDOUT_FILENO;
1554 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1555 if (zfd == STDOUT_FILENO) {
1556 /* We won't close STDOUT_FILENO later... */
1558 close(STDOUT_FILENO);
1561 maybe_warn("can't open %s", outfile);
1564 remove_file = outfile;
1568 #ifndef NO_BZIP2_SUPPORT
1572 maybe_warnx("no -l with bzip2 files");
1576 size = unbzip2(fd, zfd, NULL, 0, NULL);
1580 #ifndef NO_COMPRESS_SUPPORT
1586 maybe_warnx("no -l with Lempel-Ziv files");
1590 if ((in = zdopen(fd)) == NULL) {
1591 maybe_warn("zdopen for read: %s", file);
1595 out = fdopen(dup(zfd), "w");
1597 maybe_warn("fdopen for write: %s", outfile);
1602 size = zuncompress(in, out, NULL, 0, NULL);
1603 /* need to fclose() if ferror() is true... */
1604 if (ferror(in) | fclose(in)) {
1605 maybe_warn("failed infile fclose");
1609 if (fclose(out) != 0) {
1610 maybe_warn("failed outfile fclose");
1618 #ifndef NO_PACK_SUPPORT
1621 maybe_warnx("no -l with packed files");
1625 size = unpack(fd, zfd, NULL, 0, NULL);
1629 #ifndef NO_XZ_SUPPORT
1632 maybe_warnx("no -l with xz files");
1636 size = unxz(fd, zfd, NULL, 0, NULL);
1643 maybe_warnx("no -l for unknown filetypes");
1646 size = cat_fd(NULL, 0, NULL, fd);
1651 print_list(fd, in_size, outfile, isb.st_mtime);
1653 return -1; /* XXX */
1656 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1661 maybe_warn("couldn't close input");
1662 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1663 maybe_warn("couldn't close output");
1668 maybe_warnx("%s: uncompress failed", file);
1672 /* if testing, or we uncompressed to stdout, this is all we need */
1677 /* if we are uncompressing to stdin, don't remove the file. */
1682 * if we create a file...
1685 * if we can't stat the file don't remove the file.
1688 ofd = open(outfile, O_RDWR, 0);
1690 maybe_warn("couldn't open (leaving original): %s",
1694 if (fstat(ofd, &osb) != 0) {
1695 maybe_warn("couldn't stat (leaving original): %s",
1700 if (osb.st_size != size) {
1701 maybe_warnx("stat gave different size: %ju != %ju (leaving original)",
1702 (uintmax_t)size, (uintmax_t)osb.st_size);
1708 copymodes(ofd, &isb, outfile);
1712 unlink_input(file, &isb);
1716 maybe_warnx("%s: unexpected end of file", file);
1720 if (zfd != -1 && zfd != STDOUT_FILENO)
1729 if (print_info == 0)
1733 int pcent = (int)((100.0 * infile_current) / infile_total);
1735 fprintf(stderr, "%s: done %llu/%llu bytes %d%%\n",
1736 infile, (unsigned long long)infile_current,
1737 (unsigned long long)infile_total, pcent);
1739 fprintf(stderr, "%s: done %llu bytes\n",
1740 infile, (unsigned long long)infile_current);
1746 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1753 w = write_retry(STDOUT_FILENO, prepend, count);
1754 if (w == -1 || (size_t)w != count) {
1755 maybe_warn("write to stdout");
1761 rv = read(fd, buf, sizeof buf);
1765 maybe_warn("read from fd %d", fd);
1770 if (write_retry(STDOUT_FILENO, buf, rv) != rv) {
1771 maybe_warn("write to stdout");
1787 unsigned char header1[4];
1790 enum filetype method;
1792 #ifndef NO_COMPRESS_SUPPORT
1797 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1798 maybe_warnx("standard input is a terminal -- ignoring");
1803 if (fstat(STDIN_FILENO, &isb) < 0) {
1804 maybe_warn("fstat");
1807 if (S_ISREG(isb.st_mode))
1808 in_size = isb.st_size;
1811 infile_set("(stdin)", in_size);
1814 print_list(STDIN_FILENO, in_size, infile, isb.st_mtime);
1818 bytes_read = read_retry(STDIN_FILENO, header1, sizeof header1);
1819 if (bytes_read == -1) {
1820 maybe_warn("can't read stdin");
1822 } else if (bytes_read != sizeof(header1)) {
1823 maybe_warnx("(stdin): unexpected end of file");
1827 method = file_gettype(header1);
1832 maybe_warnx("unknown compression format");
1835 usize = cat_fd(header1, sizeof header1, &gsize, STDIN_FILENO);
1839 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1840 (char *)header1, sizeof header1, &gsize, "(stdin)");
1842 #ifndef NO_BZIP2_SUPPORT
1844 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1845 (char *)header1, sizeof header1, &gsize);
1848 #ifndef NO_COMPRESS_SUPPORT
1850 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1851 maybe_warnx("zopen of stdin");
1855 usize = zuncompress(in, stdout, (char *)header1,
1856 sizeof header1, &gsize);
1860 #ifndef NO_PACK_SUPPORT
1862 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1863 (char *)header1, sizeof header1, &gsize);
1866 #ifndef NO_XZ_SUPPORT
1868 usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1869 (char *)header1, sizeof header1, &gsize);
1875 if (vflag && !tflag && usize != -1 && gsize != -1)
1876 print_verbage(NULL, NULL, usize, gsize);
1878 print_test("(stdin)", usize != -1);
1898 infile_set("(stdout)", 0);
1900 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1901 maybe_warnx("standard output is a terminal -- ignoring");
1905 /* If stdin is a file use its mtime, otherwise use current time */
1906 ret = fstat(STDIN_FILENO, &sb);
1908 maybe_warn("Can't stat stdin");
1912 if (S_ISREG(sb.st_mode)) {
1913 infile_set("(stdout)", sb.st_size);
1914 mtime = (uint32_t)sb.st_mtime;
1916 systime = time(NULL);
1917 if (systime == -1) {
1921 mtime = (uint32_t)systime;
1926 gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1928 if (vflag && !tflag && usize != -1 && gsize != -1)
1929 print_verbage(NULL, NULL, usize, gsize);
1933 /* do what is asked for, for the path name */
1935 handle_pathname(char *path)
1937 char *opath = path, *s = NULL;
1942 /* check for stdout/stdin */
1943 if (path[0] == '-' && path[1] == '\0') {
1952 if (stat(path, &sb) != 0 || (fflag == 0 && cflag == 0 &&
1953 lstat(path, &sb) != 0)) {
1954 /* lets try <path>.gz if we're decompressing */
1955 if (dflag && s == NULL && errno == ENOENT) {
1957 slen = suffixes[0].ziplen;
1958 s = malloc(len + slen + 1);
1960 maybe_err("malloc");
1961 memcpy(s, path, len);
1962 memcpy(s + len, suffixes[0].zipped, slen + 1);
1966 maybe_warn("can't stat: %s", opath);
1970 if (S_ISDIR(sb.st_mode)) {
1976 maybe_warnx("%s is a directory", path);
1980 if (S_ISREG(sb.st_mode))
1981 handle_file(path, &sb);
1983 maybe_warnx("%s is not a regular file", path);
1990 /* compress/decompress a file */
1992 handle_file(char *file, struct stat *sbp)
1995 char outfile[PATH_MAX];
1997 infile_set(file, sbp->st_size);
1999 usize = file_uncompress(file, outfile, sizeof(outfile));
2002 print_test(file, usize != -1);
2006 gsize = sbp->st_size;
2008 gsize = file_compress(file, outfile, sizeof(outfile));
2011 usize = sbp->st_size;
2016 if (vflag && !tflag)
2017 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
2022 /* this is used with -r to recursively descend directories */
2024 handle_dir(char *dir)
2032 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
2034 warn("couldn't fts_open %s", dir);
2038 while ((entry = fts_read(fts))) {
2039 switch(entry->fts_info) {
2047 maybe_warn("%s", entry->fts_path);
2050 handle_file(entry->fts_path, entry->fts_statp);
2053 (void)fts_close(fts);
2057 /* print a ratio - size reduction as a fraction of uncompressed size */
2059 print_ratio(off_t in, off_t out, FILE *where)
2061 int percent10; /* 10 * percent */
2067 if (in == 0 && out == 0)
2071 * Output is more than double size of input! print -99.9%
2072 * Quite possibly we've failed to get the original size.
2077 * We only need 12 bits of result from the final division,
2078 * so reduce the values until a 32bit division will suffice.
2080 while (in > 0x100000) {
2085 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
2090 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
2091 /* Move the '.' to before the last digit */
2092 buff[len - 1] = buff[len - 2];
2093 buff[len - 2] = '.';
2094 fprintf(where, "%5s%%", buff);
2098 /* print compression statistics, and the new name (if there is one!) */
2100 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
2103 fprintf(stderr, "%s:%s ", file,
2104 strlen(file) < 7 ? "\t\t" : "\t");
2105 print_ratio(usize, gsize, stderr);
2107 fprintf(stderr, " -- replaced with %s", nfile);
2108 fprintf(stderr, "\n");
2112 /* print test results */
2114 print_test(const char *file, int ok)
2117 if (exit_value == 0 && ok == 0)
2119 fprintf(stderr, "%s:%s %s\n", file,
2120 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2125 /* print a file's info ala --list */
2127 compressed uncompressed ratio uncompressed_name
2128 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2131 print_list(int fd, off_t out, const char *outfile, time_t ts)
2133 static int first = 1;
2135 static off_t in_tot, out_tot;
2143 printf("method crc date time ");
2146 printf(" compressed uncompressed "
2147 "ratio uncompressed_name\n");
2159 /* read the last 4 bytes - this is the uncompressed size */
2160 rv = lseek(fd, (off_t)(-8), SEEK_END);
2162 unsigned char buf[8];
2165 rv = read(fd, (char *)buf, sizeof(buf));
2167 maybe_warn("read of uncompressed size");
2168 else if (rv != sizeof(buf))
2169 maybe_warnx("read of uncompressed size");
2172 usize = buf[4] | buf[5] << 8 |
2173 buf[6] << 16 | buf[7] << 24;
2176 crc = buf[0] | buf[1] << 8 |
2177 buf[2] << 16 | buf[3] << 24;
2184 if (vflag && fd == -1)
2187 char *date = ctime(&ts);
2189 /* skip the day, 1/100th second, and year */
2192 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2197 (void)&ts; /* XXX */
2199 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2200 print_ratio(in, out, stdout);
2201 printf(" %s\n", outfile);
2204 /* display the usage of NetBSD gzip */
2209 fprintf(stderr, "%s\n", gzip_version);
2212 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
2214 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2215 " -1 --fast fastest (worst) compression\n"
2216 " -2 .. -8 set compression level\n"
2217 " -9 --best best (slowest) compression\n"
2218 " -c --stdout write to stdout, keep original files\n"
2220 " -d --decompress uncompress files\n"
2222 " -f --force force overwriting & compress links\n"
2223 " -h --help display this help\n"
2224 " -k --keep don't delete input files during operation\n"
2225 " -l --list list compressed file contents\n"
2226 " -N --name save or restore original file name and time stamp\n"
2227 " -n --no-name don't save original file name or time stamp\n"
2228 " -q --quiet output no warnings\n"
2229 " -r --recursive recursively compress files in directories\n"
2230 " -S .suf use suffix .suf instead of .gz\n"
2232 " -t --test test compressed file\n"
2233 " -V --version display program version\n"
2234 " -v --verbose print extra statistics\n",
2241 /* display the license information of FreeBSD gzip */
2243 display_license(void)
2246 fprintf(stderr, "%s (based on NetBSD gzip 20150113)\n", gzip_version);
2247 fprintf(stderr, "%s\n", gzip_copyright);
2252 /* display the version of NetBSD gzip */
2254 display_version(void)
2257 fprintf(stderr, "%s\n", gzip_version);
2261 #ifndef NO_BZIP2_SUPPORT
2262 #include "unbzip2.c"
2264 #ifndef NO_COMPRESS_SUPPORT
2265 #include "zuncompress.c"
2267 #ifndef NO_PACK_SUPPORT
2270 #ifndef NO_XZ_SUPPORT
2275 read_retry(int fd, void *buf, size_t sz)
2278 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2283 ret = read(fd, cp, left);
2286 } else if (ret == 0) {
2297 write_retry(int fd, const void *buf, size_t sz)
2299 const char *cp = buf;
2300 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2305 ret = write(fd, cp, left);
2308 } else if (ret == 0) {
2309 abort(); /* Can't happen */