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 */
148 SUFFIX(GZ_SUFFIX, ""),
153 SUFFIX(".taz", ".tar"),
154 SUFFIX(".tgz", ".tar"),
155 #ifndef NO_BZIP2_SUPPORT
156 SUFFIX(BZ2_SUFFIX, ""),
157 SUFFIX(".tbz", ".tar"),
158 SUFFIX(".tbz2", ".tar"),
160 #ifndef NO_COMPRESS_SUPPORT
161 SUFFIX(Z_SUFFIX, ""),
163 #ifndef NO_XZ_SUPPORT
164 SUFFIX(XZ_SUFFIX, ""),
166 #ifndef NO_LZ_SUPPORT
167 SUFFIX(LZ_SUFFIX, ""),
169 SUFFIX(GZ_SUFFIX, ""), /* Overwritten by -S "" */
173 #define NUM_SUFFIXES (nitems(suffixes))
174 #define SUFFIX_MAXLEN 30
176 static const char gzip_version[] = "FreeBSD gzip 20190107";
179 static const char gzip_copyright[] = \
180 " Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green\n"
181 " All rights reserved.\n"
183 " Redistribution and use in source and binary forms, with or without\n"
184 " modification, are permitted provided that the following conditions\n"
186 " 1. Redistributions of source code must retain the above copyright\n"
187 " notice, this list of conditions and the following disclaimer.\n"
188 " 2. Redistributions in binary form must reproduce the above copyright\n"
189 " notice, this list of conditions and the following disclaimer in the\n"
190 " documentation and/or other materials provided with the distribution.\n"
192 " THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR\n"
193 " IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n"
194 " OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n"
195 " IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,\n"
196 " INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n"
197 " BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n"
198 " LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n"
199 " AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n"
200 " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n"
201 " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n"
205 static int cflag; /* stdout mode */
206 static int dflag; /* decompress mode */
207 static int lflag; /* list mode */
208 static int numflag = 6; /* gzip -1..-9 value */
210 static const char *remove_file = NULL; /* file to be removed upon SIGINT */
212 static int fflag; /* force mode */
214 static int kflag; /* don't delete input files */
215 static int nflag; /* don't save name/timestamp */
216 static int Nflag; /* don't restore name/timestamp */
217 static int qflag; /* quiet mode */
218 static int rflag; /* recursive mode */
219 static int tflag; /* test */
220 static int vflag; /* verbose mode */
221 static sig_atomic_t print_info = 0;
227 static int exit_value = 0; /* exit value */
229 static const char *infile; /* name of file coming in */
231 static void maybe_err(const char *fmt, ...) __printflike(1, 2) __dead2;
232 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
233 !defined(NO_XZ_SUPPORT)
234 static void maybe_errx(const char *fmt, ...) __printflike(1, 2) __dead2;
236 static void maybe_warn(const char *fmt, ...) __printflike(1, 2);
237 static void maybe_warnx(const char *fmt, ...) __printflike(1, 2);
238 static enum filetype file_gettype(u_char *);
240 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
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;
255 static void display_license(void);
257 static const suffixes_t *check_suffix(char *, int);
258 static ssize_t read_retry(int, void *, size_t);
259 static ssize_t write_retry(int, const void *, size_t);
260 static void print_list_out(off_t, off_t, const char*);
263 #define infile_set(f,t) infile_set(f)
265 static void infile_set(const char *newinfile, off_t total);
268 #define unlink_input(f, sb) unlink(f)
269 #define check_siginfo() /* nothing */
270 #define setup_signals() /* nothing */
271 #define infile_newdata(t) /* nothing */
273 static off_t infile_total; /* total expected to read/write */
274 static off_t infile_current; /* current read/write */
276 static void check_siginfo(void);
277 static off_t cat_fd(unsigned char *, size_t, off_t *, int fd);
278 static void prepend_gzip(char *, int *, char ***);
279 static void handle_dir(char *);
280 static void print_verbage(const char *, const char *, off_t, off_t);
281 static void print_test(const char *, int);
282 static void copymodes(int fd, const struct stat *, const char *file);
283 static int check_outfile(const char *outfile);
284 static void setup_signals(void);
285 static void infile_newdata(size_t newdata);
286 static void infile_clear(void);
289 #ifndef NO_BZIP2_SUPPORT
290 static off_t unbzip2(int, int, char *, size_t, off_t *);
293 #ifndef NO_COMPRESS_SUPPORT
294 static FILE *zdopen(int);
295 static off_t zuncompress(FILE *, FILE *, char *, size_t, off_t *);
298 #ifndef NO_PACK_SUPPORT
299 static off_t unpack(int, int, char *, size_t, off_t *);
302 #ifndef NO_XZ_SUPPORT
303 static off_t unxz(int, int, char *, size_t, off_t *);
304 static off_t unxz_len(int);
307 #ifndef NO_LZ_SUPPORT
308 static off_t unlz(int, int, char *, size_t, off_t *);
312 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
314 static const struct option longopts[] = {
315 { "stdout", no_argument, 0, 'c' },
316 { "to-stdout", no_argument, 0, 'c' },
317 { "decompress", no_argument, 0, 'd' },
318 { "uncompress", no_argument, 0, 'd' },
319 { "force", no_argument, 0, 'f' },
320 { "help", no_argument, 0, 'h' },
321 { "keep", no_argument, 0, 'k' },
322 { "list", no_argument, 0, 'l' },
323 { "no-name", no_argument, 0, 'n' },
324 { "name", no_argument, 0, 'N' },
325 { "quiet", no_argument, 0, 'q' },
326 { "recursive", no_argument, 0, 'r' },
327 { "suffix", required_argument, 0, 'S' },
328 { "test", no_argument, 0, 't' },
329 { "verbose", no_argument, 0, 'v' },
330 { "version", no_argument, 0, 'V' },
331 { "fast", no_argument, 0, '1' },
332 { "best", no_argument, 0, '9' },
333 { "ascii", no_argument, 0, 'a' },
334 { "license", no_argument, 0, 'L' },
335 { NULL, no_argument, 0, 0 },
340 main(int argc, char **argv)
342 const char *progname = getprogname();
352 if ((gzip = getenv("GZIP")) != NULL)
353 prepend_gzip(gzip, &argc, &argv);
358 * handle being called `gunzip', `zcat' and `gzcat'
360 if (strcmp(progname, "gunzip") == 0)
362 else if (strcmp(progname, "zcat") == 0 ||
363 strcmp(progname, "gzcat") == 0)
367 #define OPT_LIST "123456789cdhlV"
369 #define OPT_LIST "123456789acdfhklLNnqrS:tVv"
372 while ((ch = getopt_long(argc, argv, OPT_LIST, longopts, NULL)) != -1) {
374 case '1': case '2': case '3':
375 case '4': case '5': case '6':
376 case '7': case '8': case '9':
394 fprintf(stderr, "%s: option --ascii ignored on this system\n", progname);
420 len = strlen(optarg);
422 if (len > SUFFIX_MAXLEN)
423 errx(1, "incorrect suffix: '%s': too long", optarg);
424 suffixes[0].zipped = optarg;
425 suffixes[0].ziplen = len;
427 suffixes[NUM_SUFFIXES - 1].zipped = "";
428 suffixes[NUM_SUFFIXES - 1].ziplen = 0;
449 if (dflag) /* stdin mode */
451 else /* stdout mode */
455 handle_pathname(argv[0]);
459 if (qflag == 0 && lflag && argc > 1)
460 print_list(-1, 0, "(totals)", 0);
465 /* maybe print a warning */
467 maybe_warn(const char *fmt, ...)
480 /* ... without an errno. */
482 maybe_warnx(const char *fmt, ...)
495 /* maybe print an error */
497 maybe_err(const char *fmt, ...)
509 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
510 !defined(NO_XZ_SUPPORT)
511 /* ... without an errno. */
513 maybe_errx(const char *fmt, ...)
527 /* split up $GZIP and prepend it to the argument list */
529 prepend_gzip(char *gzip, int *argc, char ***argv)
531 char *s, **nargv, **ac;
534 /* scan how many arguments there are */
536 while (*s == ' ' || *s == '\t')
541 while (*s != ' ' && *s != '\t')
553 nargv = (char **)malloc((*argc + 1) * sizeof(char *));
557 /* stash this away */
560 /* copy the program name first */
562 nargv[i++] = *(ac++);
564 /* take a copy of $GZIP and add it to the array */
569 /* Skip whitespaces. */
570 while (*s == ' ' || *s == '\t')
575 /* Find the end of this argument. */
576 while (*s != ' ' && *s != '\t')
578 /* Argument followed by NUL. */
580 /* Terminate by overwriting ' ' or '\t' with NUL. */
585 /* copy the original arguments and a NULL */
587 nargv[i++] = *(ac++);
592 /* compress input to output. Return bytes read, -1 on error */
594 gz_compress(int in, int out, off_t *gsizep, const char *origname, uint32_t mtime)
597 char *outbufp, *inbufp;
598 off_t in_tot = 0, out_tot = 0;
603 static char header[] = { GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED, 0,
608 outbufp = malloc(BUFLEN);
609 inbufp = malloc(BUFLEN);
610 if (outbufp == NULL || inbufp == NULL) {
611 maybe_err("malloc failed");
615 memset(&z, 0, sizeof z);
621 memcpy(outbufp, header, sizeof header);
629 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c%c%c%s",
630 GZIP_MAGIC0, GZIP_MAGIC1, Z_DEFLATED,
631 *origname ? ORIG_NAME : 0,
634 (mtime >> 16) & 0xff,
635 (mtime >> 24) & 0xff,
636 numflag == 1 ? 4 : numflag == 9 ? 2 : 0,
639 /* this need PATH_MAX > BUFLEN ... */
640 maybe_err("snprintf");
645 z.next_out = (unsigned char *)outbufp + i;
646 z.avail_out = BUFLEN - i;
648 error = deflateInit2(&z, numflag, Z_DEFLATED,
649 (-MAX_WBITS), 8, Z_DEFAULT_STRATEGY);
651 maybe_warnx("deflateInit2 failed");
656 crc = crc32(0L, Z_NULL, 0);
658 if (z.avail_out == 0) {
659 if (write_retry(out, outbufp, BUFLEN) != BUFLEN) {
666 z.next_out = (unsigned char *)outbufp;
667 z.avail_out = BUFLEN;
670 if (z.avail_in == 0) {
671 in_size = read(in, inbufp, BUFLEN);
679 infile_newdata(in_size);
681 crc = crc32(crc, (const Bytef *)inbufp, (unsigned)in_size);
683 z.next_in = (unsigned char *)inbufp;
684 z.avail_in = in_size;
687 error = deflate(&z, Z_NO_FLUSH);
688 if (error != Z_OK && error != Z_STREAM_END) {
689 maybe_warnx("deflate failed");
700 error = deflate(&z, Z_FINISH);
701 if (error != Z_OK && error != Z_STREAM_END) {
702 maybe_warnx("deflate failed");
707 len = (char *)z.next_out - outbufp;
709 w = write_retry(out, outbufp, len);
710 if (w == -1 || (size_t)w != len) {
716 z.next_out = (unsigned char *)outbufp;
717 z.avail_out = BUFLEN;
719 if (error == Z_STREAM_END)
723 if (deflateEnd(&z) != Z_OK) {
724 maybe_warnx("deflateEnd failed");
729 i = snprintf(outbufp, BUFLEN, "%c%c%c%c%c%c%c%c",
731 (int)(crc >> 8) & 0xff,
732 (int)(crc >> 16) & 0xff,
733 (int)(crc >> 24) & 0xff,
735 (int)(in_tot >> 8) & 0xff,
736 (int)(in_tot >> 16) & 0xff,
737 (int)(in_tot >> 24) & 0xff);
739 maybe_err("snprintf");
740 if (write_retry(out, outbufp, i) != i) {
757 * uncompress input to output then close the input. return the
758 * uncompressed size written, and put the compressed sized read
762 gz_uncompress(int in, int out, char *pre, size_t prelen, off_t *gsizep,
763 const char *filename)
766 char *outbufp, *inbufp;
767 off_t out_tot = -1, in_tot = 0;
768 uint32_t out_sub_tot = 0;
786 } state = GZSTATE_MAGIC0;
787 int flags = 0, skip_count = 0;
788 int error = Z_STREAM_ERROR, done_reading = 0;
793 #define ADVANCE() { z.next_in++; z.avail_in--; }
795 if ((outbufp = malloc(BUFLEN)) == NULL) {
796 maybe_err("malloc failed");
799 if ((inbufp = malloc(BUFLEN)) == NULL) {
800 maybe_err("malloc failed");
804 memset(&z, 0, sizeof z);
806 z.next_in = (unsigned char *)pre;
807 z.avail_out = BUFLEN;
808 z.next_out = (unsigned char *)outbufp;
818 if ((z.avail_in == 0 || needmore) && done_reading == 0) {
821 if (z.avail_in > 0) {
822 memmove(inbufp, z.next_in, z.avail_in);
824 z.next_in = (unsigned char *)inbufp;
825 in_size = read(in, z.next_in + z.avail_in,
826 BUFLEN - z.avail_in);
829 maybe_warn("failed to read stdin");
831 } else if (in_size == 0) {
834 infile_newdata(in_size);
836 z.avail_in += in_size;
841 if (z.avail_in == 0) {
842 if (done_reading && state != GZSTATE_MAGIC0) {
843 maybe_warnx("%s: unexpected end of file",
851 if (*z.next_in != GZIP_MAGIC0) {
853 maybe_warnx("%s: trailing garbage "
854 "ignored", filename);
858 maybe_warnx("input not gziped (MAGIC0)");
864 crc = crc32(0L, Z_NULL, 0);
868 if (*z.next_in != GZIP_MAGIC1 &&
869 *z.next_in != GZIP_OMAGIC1) {
870 maybe_warnx("input not gziped (MAGIC1)");
878 if (*z.next_in != Z_DEFLATED) {
879 maybe_warnx("unknown compression method");
893 case GZSTATE_SKIPPING:
894 if (skip_count > 0) {
902 if ((flags & EXTRA_FIELD) == 0) {
903 state = GZSTATE_ORIGNAME;
906 skip_count = *z.next_in;
912 skip_count |= ((*z.next_in) << 8);
918 if (skip_count > 0) {
925 case GZSTATE_ORIGNAME:
926 if ((flags & ORIG_NAME) == 0) {
935 case GZSTATE_COMMENT:
936 if ((flags & COMMENT) == 0) {
945 case GZSTATE_HEAD_CRC1:
946 if (flags & HEAD_CRC)
953 case GZSTATE_HEAD_CRC2:
954 if (skip_count > 0) {
962 if (inflateInit2(&z, -MAX_WBITS) != Z_OK) {
963 maybe_warnx("failed to inflateInit");
970 error = inflate(&z, Z_FINISH);
972 /* Z_BUF_ERROR goes with Z_FINISH... */
974 if (z.avail_out > 0 && !done_reading)
982 maybe_warnx("Z_NEED_DICT error");
985 maybe_warnx("data stream error");
988 maybe_warnx("internal stream error");
991 maybe_warnx("memory allocation error");
995 maybe_warn("unknown error from inflate(): %d",
998 wr = BUFLEN - z.avail_out;
1001 crc = crc32(crc, (const Bytef *)outbufp, (unsigned)wr);
1004 /* don't write anything with -t */
1007 write_retry(out, outbufp, wr) != wr) {
1008 maybe_warn("error writing to output");
1016 if (error == Z_STREAM_END) {
1021 z.next_out = (unsigned char *)outbufp;
1022 z.avail_out = BUFLEN;
1029 if (z.avail_in < 4) {
1030 if (!done_reading) {
1034 maybe_warnx("truncated input");
1037 origcrc = le32dec(&z.next_in[0]);
1038 if (origcrc != crc) {
1039 maybe_warnx("invalid compressed"
1040 " data--crc error");
1048 if (!z.avail_in && done_reading) {
1057 if (z.avail_in < 4) {
1058 if (!done_reading) {
1062 maybe_warnx("truncated input");
1065 origlen = le32dec(&z.next_in[0]);
1067 if (origlen != out_sub_tot) {
1068 maybe_warnx("invalid compressed"
1069 " data--length error");
1078 maybe_warnx("decompression error");
1081 state = GZSTATE_MAGIC0;
1090 if (state > GZSTATE_INIT)
1104 * set the owner, mode, flags & utimes using the given file descriptor.
1105 * file is only used in possible warning messages.
1108 copymodes(int fd, const struct stat *sbp, const char *file)
1110 struct timespec times[2];
1114 * If we have no info on the input, give this file some
1115 * default values and return..
1118 mode_t mask = umask(022);
1120 (void)fchmod(fd, DEFFILEMODE & ~mask);
1126 /* if the chown fails, remove set-id bits as-per compress(1) */
1127 if (fchown(fd, sb.st_uid, sb.st_gid) < 0) {
1129 maybe_warn("couldn't fchown: %s", file);
1130 sb.st_mode &= ~(S_ISUID|S_ISGID);
1133 /* we only allow set-id and the 9 normal permission bits */
1134 sb.st_mode &= S_ISUID | S_ISGID | S_IRWXU | S_IRWXG | S_IRWXO;
1135 if (fchmod(fd, sb.st_mode) < 0)
1136 maybe_warn("couldn't fchmod: %s", file);
1138 times[0] = sb.st_atim;
1139 times[1] = sb.st_mtim;
1140 if (futimens(fd, times) < 0)
1141 maybe_warn("couldn't futimens: %s", file);
1143 /* only try flags if they exist already */
1144 if (sb.st_flags != 0 && fchflags(fd, sb.st_flags) < 0)
1145 maybe_warn("couldn't fchflags: %s", file);
1149 /* what sort of file is this? */
1150 static enum filetype
1151 file_gettype(u_char *buf)
1154 if (buf[0] == GZIP_MAGIC0 &&
1155 (buf[1] == GZIP_MAGIC1 || buf[1] == GZIP_OMAGIC1))
1158 #ifndef NO_BZIP2_SUPPORT
1159 if (memcmp(buf, BZIP2_MAGIC, 3) == 0 &&
1160 buf[3] >= '0' && buf[3] <= '9')
1164 #ifndef NO_COMPRESS_SUPPORT
1165 if (memcmp(buf, Z_MAGIC, 2) == 0)
1169 #ifndef NO_PACK_SUPPORT
1170 if (memcmp(buf, PACK_MAGIC, 2) == 0)
1174 #ifndef NO_XZ_SUPPORT
1175 if (memcmp(buf, XZ_MAGIC, 4) == 0) /* XXX: We only have 4 bytes */
1179 #ifndef NO_LZ_SUPPORT
1180 if (memcmp(buf, LZ_MAGIC, 4) == 0)
1188 /* check the outfile is OK. */
1190 check_outfile(const char *outfile)
1195 if (lflag == 0 && stat(outfile, &sb) == 0) {
1198 else if (isatty(STDIN_FILENO)) {
1199 char ans[10] = { 'n', '\0' }; /* default */
1201 fprintf(stderr, "%s already exists -- do you wish to "
1202 "overwrite (y or n)? " , outfile);
1203 (void)fgets(ans, sizeof(ans) - 1, stdin);
1204 if (ans[0] != 'y' && ans[0] != 'Y') {
1205 fprintf(stderr, "\tnot overwriting\n");
1210 maybe_warnx("%s already exists -- skipping", outfile);
1218 unlink_input(const char *file, const struct stat *sb)
1224 if (stat(file, &nsb) != 0)
1225 /* Must be gone already */
1227 if (nsb.st_dev != sb->st_dev || nsb.st_ino != sb->st_ino)
1228 /* Definitely a different file */
1234 got_sigint(int signo __unused)
1237 if (remove_file != NULL)
1238 unlink(remove_file);
1243 got_siginfo(int signo __unused)
1253 signal(SIGINFO, got_siginfo);
1254 signal(SIGINT, got_sigint);
1258 infile_newdata(size_t newdata)
1261 infile_current += newdata;
1266 infile_set(const char *newinfile, off_t total)
1272 infile_total = total;
1282 infile_total = infile_current = 0;
1286 static const suffixes_t *
1287 check_suffix(char *file, int xlate)
1289 const suffixes_t *s;
1290 int len = strlen(file);
1293 for (s = suffixes; s != suffixes + NUM_SUFFIXES; s++) {
1294 /* if it doesn't fit in "a.suf", don't bother */
1295 if (s->ziplen >= len)
1297 sp = file + len - s->ziplen;
1298 if (strcmp(s->zipped, sp) != 0)
1301 strcpy(sp, s->normal);
1308 * compress the given file: create a corresponding .gz file and remove the
1312 file_compress(char *file, char *outfile, size_t outsize)
1316 off_t size, in_size;
1318 struct stat isb, osb;
1319 const suffixes_t *suff;
1322 in = open(file, O_RDONLY);
1324 maybe_warn("can't open %s", file);
1329 if (fstat(in, &isb) != 0) {
1330 maybe_warn("couldn't stat: %s", file);
1337 if (fstat(in, &isb) != 0) {
1339 maybe_warn("can't stat %s", file);
1342 infile_set(file, isb.st_size);
1347 if (isb.st_nlink > 1 && fflag == 0) {
1348 maybe_warnx("%s has %ju other link%s -- "
1350 (uintmax_t)isb.st_nlink - 1,
1351 isb.st_nlink == 1 ? "" : "s");
1356 if (fflag == 0 && (suff = check_suffix(file, 0)) &&
1357 suff->zipped[0] != 0) {
1358 maybe_warnx("%s already has %s suffix -- unchanged",
1359 file, suff->zipped);
1365 /* Add (usually) .gz to filename */
1366 if ((size_t)snprintf(outfile, outsize, "%s%s",
1367 file, suffixes[0].zipped) >= outsize)
1368 memcpy(outfile + outsize - suffixes[0].ziplen - 1,
1369 suffixes[0].zipped, suffixes[0].ziplen + 1);
1372 if (check_outfile(outfile) == 0) {
1380 out = open(outfile, O_WRONLY | O_CREAT | O_EXCL, 0600);
1382 maybe_warn("could not create output: %s", outfile);
1387 remove_file = outfile;
1390 out = STDOUT_FILENO;
1392 in_size = gz_compress(in, out, &size, basename(file), (uint32_t)isb.st_mtime);
1397 * If there was an error, in_size will be -1.
1398 * If we compressed to stdout, just return the size.
1399 * Otherwise stat the file and check it is the correct size.
1400 * We only blow away the file if we can stat the output and it
1401 * has the expected size.
1404 return in_size == -1 ? -1 : size;
1407 if (fstat(out, &osb) != 0) {
1408 maybe_warn("couldn't stat: %s", outfile);
1412 if (osb.st_size != size) {
1413 maybe_warnx("output file: %s wrong size (%ju != %ju), deleting",
1414 outfile, (uintmax_t)osb.st_size, (uintmax_t)size);
1418 copymodes(out, &isb, outfile);
1421 if (close(out) == -1)
1422 maybe_warn("couldn't close output");
1424 /* output is good, ok to delete input */
1425 unlink_input(file, &isb);
1430 if (close(out) == -1)
1431 maybe_warn("couldn't close output");
1433 maybe_warnx("leaving original %s", file);
1439 /* uncompress the given file and remove the original */
1441 file_uncompress(char *file, char *outfile, size_t outsize)
1443 struct stat isb, osb;
1446 unsigned char fourbytes[4];
1447 enum filetype method;
1448 int fd, ofd, zfd = -1;
1453 time_t timestamp = 0;
1454 char name[PATH_MAX + 1];
1457 /* gather the old name info */
1459 fd = open(file, O_RDONLY);
1461 maybe_warn("can't open %s", file);
1464 if (fstat(fd, &isb) != 0) {
1465 maybe_warn("can't stat %s", file);
1468 if (S_ISREG(isb.st_mode))
1469 in_size = isb.st_size;
1472 infile_set(file, in_size);
1474 strlcpy(outfile, file, outsize);
1475 if (check_suffix(outfile, 1) == NULL && !(cflag || lflag)) {
1476 maybe_warnx("%s: unknown suffix -- ignored", file);
1480 rbytes = read(fd, fourbytes, sizeof fourbytes);
1481 if (rbytes != sizeof fourbytes) {
1482 /* we don't want to fail here. */
1488 maybe_warn("can't read %s", file);
1490 goto unexpected_EOF;
1493 infile_newdata(rbytes);
1495 method = file_gettype(fourbytes);
1497 if (fflag == 0 && method == FT_UNKNOWN) {
1498 maybe_warnx("%s: not in gzip format", file);
1505 if (method == FT_GZIP && Nflag) {
1506 unsigned char ts[4]; /* timestamp */
1508 rv = pread(fd, ts, sizeof ts, GZIP_TIMESTAMP);
1509 if (rv >= 0 && rv < (ssize_t)(sizeof ts))
1510 goto unexpected_EOF;
1513 maybe_warn("can't read %s", file);
1517 timestamp = le32dec(&ts[0]);
1519 if (fourbytes[3] & ORIG_NAME) {
1520 rbytes = pread(fd, name, sizeof(name) - 1, GZIP_ORIGNAME);
1522 maybe_warn("can't read %s", file);
1525 if (name[0] != '\0') {
1528 /* Make sure that name is NUL-terminated */
1529 name[rbytes] = '\0';
1531 /* strip saved directory name */
1532 nf = strrchr(name, '/');
1538 /* preserve original directory name */
1539 dp = strrchr(file, '/');
1544 snprintf(outfile, outsize, "%.*s%.*s",
1546 file, (int) rbytes, nf);
1551 lseek(fd, 0, SEEK_SET);
1553 if (cflag == 0 || lflag) {
1555 if (isb.st_nlink > 1 && lflag == 0 && fflag == 0) {
1556 maybe_warnx("%s has %ju other links -- skipping",
1557 file, (uintmax_t)isb.st_nlink - 1);
1560 if (nflag == 0 && timestamp)
1561 isb.st_mtime = timestamp;
1562 if (check_outfile(outfile) == 0)
1568 zfd = STDOUT_FILENO;
1572 zfd = open(outfile, O_WRONLY|O_CREAT|O_EXCL, 0600);
1573 if (zfd == STDOUT_FILENO) {
1574 /* We won't close STDOUT_FILENO later... */
1576 close(STDOUT_FILENO);
1579 maybe_warn("can't open %s", outfile);
1582 remove_file = outfile;
1586 #ifndef NO_BZIP2_SUPPORT
1590 maybe_warnx("no -l with bzip2 files");
1594 size = unbzip2(fd, zfd, NULL, 0, NULL);
1598 #ifndef NO_COMPRESS_SUPPORT
1604 maybe_warnx("no -l with Lempel-Ziv files");
1608 if ((in = zdopen(fd)) == NULL) {
1609 maybe_warn("zdopen for read: %s", file);
1613 out = fdopen(dup(zfd), "w");
1615 maybe_warn("fdopen for write: %s", outfile);
1620 size = zuncompress(in, out, NULL, 0, NULL);
1621 /* need to fclose() if ferror() is true... */
1623 if (error | fclose(in)) {
1625 maybe_warn("failed infile");
1627 maybe_warn("failed infile fclose");
1633 if (fclose(out) != 0) {
1634 maybe_warn("failed outfile fclose");
1643 #ifndef NO_PACK_SUPPORT
1646 maybe_warnx("no -l with packed files");
1650 size = unpack(fd, zfd, NULL, 0, NULL);
1654 #ifndef NO_XZ_SUPPORT
1657 size = unxz_len(fd);
1658 print_list_out(in_size, size, file);
1661 size = unxz(fd, zfd, NULL, 0, NULL);
1665 #ifndef NO_LZ_SUPPORT
1668 maybe_warnx("no -l with lzip files");
1671 size = unlz(fd, zfd, NULL, 0, NULL);
1677 maybe_warnx("no -l for unknown filetypes");
1680 size = cat_fd(NULL, 0, NULL, fd);
1685 print_list(fd, in_size, outfile, isb.st_mtime);
1687 return -1; /* XXX */
1690 size = gz_uncompress(fd, zfd, NULL, 0, NULL, file);
1695 maybe_warn("couldn't close input");
1696 if (zfd != STDOUT_FILENO && close(zfd) != 0)
1697 maybe_warn("couldn't close output");
1702 maybe_warnx("%s: uncompress failed", file);
1706 /* if testing, or we uncompressed to stdout, this is all we need */
1711 /* if we are uncompressing to stdin, don't remove the file. */
1716 * if we create a file...
1719 * if we can't stat the file don't remove the file.
1722 ofd = open(outfile, O_RDWR, 0);
1724 maybe_warn("couldn't open (leaving original): %s",
1728 if (fstat(ofd, &osb) != 0) {
1729 maybe_warn("couldn't stat (leaving original): %s",
1734 if (osb.st_size != size) {
1735 maybe_warnx("stat gave different size: %ju != %ju (leaving original)",
1736 (uintmax_t)size, (uintmax_t)osb.st_size);
1742 copymodes(ofd, &isb, outfile);
1746 unlink_input(file, &isb);
1750 maybe_warnx("%s: unexpected end of file", file);
1754 if (zfd != -1 && zfd != STDOUT_FILENO)
1763 if (print_info == 0)
1767 int pcent = (int)((100.0 * infile_current) / infile_total);
1769 fprintf(stderr, "%s: done %llu/%llu bytes %d%%\n",
1770 infile, (unsigned long long)infile_current,
1771 (unsigned long long)infile_total, pcent);
1773 fprintf(stderr, "%s: done %llu bytes\n",
1774 infile, (unsigned long long)infile_current);
1780 cat_fd(unsigned char * prepend, size_t count, off_t *gsizep, int fd)
1787 w = write_retry(STDOUT_FILENO, prepend, count);
1788 if (w == -1 || (size_t)w != count) {
1789 maybe_warn("write to stdout");
1795 rv = read(fd, buf, sizeof buf);
1799 maybe_warn("read from fd %d", fd);
1804 if (write_retry(STDOUT_FILENO, buf, rv) != rv) {
1805 maybe_warn("write to stdout");
1821 unsigned char fourbytes[4];
1824 enum filetype method;
1826 #ifndef NO_COMPRESS_SUPPORT
1831 if (fflag == 0 && lflag == 0 && isatty(STDIN_FILENO)) {
1832 maybe_warnx("standard input is a terminal -- ignoring");
1837 if (fstat(STDIN_FILENO, &isb) < 0) {
1838 maybe_warn("fstat");
1841 if (S_ISREG(isb.st_mode))
1842 in_size = isb.st_size;
1845 infile_set("(stdin)", in_size);
1848 print_list(STDIN_FILENO, in_size, infile, isb.st_mtime);
1852 bytes_read = read_retry(STDIN_FILENO, fourbytes, sizeof fourbytes);
1853 if (bytes_read == -1) {
1854 maybe_warn("can't read stdin");
1856 } else if (bytes_read != sizeof(fourbytes)) {
1857 maybe_warnx("(stdin): unexpected end of file");
1861 method = file_gettype(fourbytes);
1866 maybe_warnx("unknown compression format");
1869 usize = cat_fd(fourbytes, sizeof fourbytes, &gsize, STDIN_FILENO);
1873 usize = gz_uncompress(STDIN_FILENO, STDOUT_FILENO,
1874 (char *)fourbytes, sizeof fourbytes, &gsize, "(stdin)");
1876 #ifndef NO_BZIP2_SUPPORT
1878 usize = unbzip2(STDIN_FILENO, STDOUT_FILENO,
1879 (char *)fourbytes, sizeof fourbytes, &gsize);
1882 #ifndef NO_COMPRESS_SUPPORT
1884 if ((in = zdopen(STDIN_FILENO)) == NULL) {
1885 maybe_warnx("zopen of stdin");
1889 usize = zuncompress(in, stdout, (char *)fourbytes,
1890 sizeof fourbytes, &gsize);
1894 #ifndef NO_PACK_SUPPORT
1896 usize = unpack(STDIN_FILENO, STDOUT_FILENO,
1897 (char *)fourbytes, sizeof fourbytes, &gsize);
1900 #ifndef NO_XZ_SUPPORT
1902 usize = unxz(STDIN_FILENO, STDOUT_FILENO,
1903 (char *)fourbytes, sizeof fourbytes, &gsize);
1906 #ifndef NO_LZ_SUPPORT
1908 usize = unlz(STDIN_FILENO, STDOUT_FILENO,
1909 (char *)fourbytes, sizeof fourbytes, &gsize);
1915 if (vflag && !tflag && usize != -1 && gsize != -1)
1916 print_verbage(NULL, NULL, usize, gsize);
1918 print_test("(stdin)", usize != -1);
1938 infile_set("(stdout)", 0);
1940 if (fflag == 0 && isatty(STDOUT_FILENO)) {
1941 maybe_warnx("standard output is a terminal -- ignoring");
1945 /* If stdin is a file use its mtime, otherwise use current time */
1946 ret = fstat(STDIN_FILENO, &sb);
1948 maybe_warn("Can't stat stdin");
1952 if (S_ISREG(sb.st_mode)) {
1953 infile_set("(stdout)", sb.st_size);
1954 mtime = (uint32_t)sb.st_mtime;
1956 systime = time(NULL);
1957 if (systime == -1) {
1961 mtime = (uint32_t)systime;
1966 gz_compress(STDIN_FILENO, STDOUT_FILENO, &gsize, "", mtime);
1968 if (vflag && !tflag && usize != -1 && gsize != -1)
1969 print_verbage(NULL, NULL, usize, gsize);
1973 /* do what is asked for, for the path name */
1975 handle_pathname(char *path)
1977 char *opath = path, *s = NULL;
1982 /* check for stdout/stdin */
1983 if (path[0] == '-' && path[1] == '\0') {
1992 if (stat(path, &sb) != 0 || (fflag == 0 && cflag == 0 &&
1993 lstat(path, &sb) != 0)) {
1994 /* lets try <path>.gz if we're decompressing */
1995 if (dflag && s == NULL && errno == ENOENT) {
1997 slen = suffixes[0].ziplen;
1998 s = malloc(len + slen + 1);
2000 maybe_err("malloc");
2001 memcpy(s, path, len);
2002 memcpy(s + len, suffixes[0].zipped, slen + 1);
2006 maybe_warn("can't stat: %s", opath);
2010 if (S_ISDIR(sb.st_mode)) {
2016 maybe_warnx("%s is a directory", path);
2020 if (S_ISREG(sb.st_mode))
2021 handle_file(path, &sb);
2023 maybe_warnx("%s is not a regular file", path);
2030 /* compress/decompress a file */
2032 handle_file(char *file, struct stat *sbp)
2035 char outfile[PATH_MAX];
2037 infile_set(file, sbp->st_size);
2039 usize = file_uncompress(file, outfile, sizeof(outfile));
2042 print_test(file, usize != -1);
2046 gsize = sbp->st_size;
2048 gsize = file_compress(file, outfile, sizeof(outfile));
2051 usize = sbp->st_size;
2056 if (vflag && !tflag)
2057 print_verbage(file, (cflag) ? NULL : outfile, usize, gsize);
2062 /* this is used with -r to recursively descend directories */
2064 handle_dir(char *dir)
2072 fts = fts_open(path_argv, FTS_PHYSICAL | FTS_NOCHDIR, NULL);
2074 warn("couldn't fts_open %s", dir);
2078 while ((entry = fts_read(fts))) {
2079 switch(entry->fts_info) {
2087 maybe_warn("%s", entry->fts_path);
2090 handle_file(entry->fts_path, entry->fts_statp);
2093 (void)fts_close(fts);
2097 /* print a ratio - size reduction as a fraction of uncompressed size */
2099 print_ratio(off_t in, off_t out, FILE *where)
2101 int percent10; /* 10 * percent */
2107 if (in == 0 && out == 0)
2111 * Output is more than double size of input! print -99.9%
2112 * Quite possibly we've failed to get the original size.
2117 * We only need 12 bits of result from the final division,
2118 * so reduce the values until a 32bit division will suffice.
2120 while (in > 0x100000) {
2125 percent10 = ((u_int)diff * 2000) / (u_int)in - 1000;
2130 len = snprintf(buff, sizeof buff, "%2.2d.", percent10);
2131 /* Move the '.' to before the last digit */
2132 buff[len - 1] = buff[len - 2];
2133 buff[len - 2] = '.';
2134 fprintf(where, "%5s%%", buff);
2138 /* print compression statistics, and the new name (if there is one!) */
2140 print_verbage(const char *file, const char *nfile, off_t usize, off_t gsize)
2143 fprintf(stderr, "%s:%s ", file,
2144 strlen(file) < 7 ? "\t\t" : "\t");
2145 print_ratio(usize, gsize, stderr);
2147 fprintf(stderr, " -- replaced with %s", nfile);
2148 fprintf(stderr, "\n");
2152 /* print test results */
2154 print_test(const char *file, int ok)
2157 if (exit_value == 0 && ok == 0)
2159 fprintf(stderr, "%s:%s %s\n", file,
2160 strlen(file) < 7 ? "\t\t" : "\t", ok ? "OK" : "NOT OK");
2165 /* print a file's info ala --list */
2167 compressed uncompressed ratio uncompressed_name
2168 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
2171 print_list(int fd, off_t out, const char *outfile, time_t ts)
2173 static int first = 1;
2175 static off_t in_tot, out_tot;
2183 printf("method crc date time ");
2186 printf(" compressed uncompressed "
2187 "ratio uncompressed_name\n");
2199 /* read the last 4 bytes - this is the uncompressed size */
2200 rv = lseek(fd, (off_t)(-8), SEEK_END);
2202 unsigned char buf[8];
2205 rv = read(fd, (char *)buf, sizeof(buf));
2207 maybe_warn("read of uncompressed size");
2208 else if (rv != sizeof(buf))
2209 maybe_warnx("read of uncompressed size");
2212 usize = le32dec(&buf[4]);
2215 crc = le32dec(&buf[0]);
2222 if (vflag && fd == -1)
2225 char *date = ctime(&ts);
2227 /* skip the day, 1/100th second, and year */
2230 printf("%5s %08x %11s ", "defla"/*XXX*/, crc, date);
2235 (void)&ts; /* XXX */
2237 print_list_out(out, in, outfile);
2241 print_list_out(off_t out, off_t in, const char *outfile)
2243 printf("%12llu %12llu ", (unsigned long long)out, (unsigned long long)in);
2244 print_ratio(in, out, stdout);
2245 printf(" %s\n", outfile);
2248 /* display the usage of NetBSD gzip */
2253 fprintf(stderr, "%s\n", gzip_version);
2256 "usage: %s [-" OPT_LIST "] [<file> [<file> ...]]\n",
2258 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
2259 " -1 --fast fastest (worst) compression\n"
2260 " -2 .. -8 set compression level\n"
2261 " -9 --best best (slowest) compression\n"
2262 " -c --stdout write to stdout, keep original files\n"
2264 " -d --decompress uncompress files\n"
2266 " -f --force force overwriting & compress links\n"
2267 " -h --help display this help\n"
2268 " -k --keep don't delete input files during operation\n"
2269 " -l --list list compressed file contents\n"
2270 " -N --name save or restore original file name and time stamp\n"
2271 " -n --no-name don't save original file name or time stamp\n"
2272 " -q --quiet output no warnings\n"
2273 " -r --recursive recursively compress files in directories\n"
2274 " -S .suf use suffix .suf instead of .gz\n"
2276 " -t --test test compressed file\n"
2277 " -V --version display program version\n"
2278 " -v --verbose print extra statistics\n",
2285 /* display the license information of FreeBSD gzip */
2287 display_license(void)
2290 fprintf(stderr, "%s (based on NetBSD gzip 20150113)\n", gzip_version);
2291 fprintf(stderr, "%s\n", gzip_copyright);
2296 /* display the version of NetBSD gzip */
2298 display_version(void)
2301 fprintf(stderr, "%s\n", gzip_version);
2305 #ifndef NO_BZIP2_SUPPORT
2306 #include "unbzip2.c"
2308 #ifndef NO_COMPRESS_SUPPORT
2309 #include "zuncompress.c"
2311 #ifndef NO_PACK_SUPPORT
2314 #ifndef NO_XZ_SUPPORT
2317 #ifndef NO_LZ_SUPPORT
2322 read_retry(int fd, void *buf, size_t sz)
2325 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2330 ret = read(fd, cp, left);
2333 } else if (ret == 0) {
2344 write_retry(int fd, const void *buf, size_t sz)
2346 const char *cp = buf;
2347 size_t left = MIN(sz, (size_t) SSIZE_MAX);
2352 ret = write(fd, cp, left);
2355 } else if (ret == 0) {
2356 abort(); /* Can't happen */