1 /* $NetBSD: gzip.c,v 1.108 2015/04/15 02:29:12 christos Exp $ */
4 * Copyright (c) 1997, 1998, 2003, 2004, 2006 Matthew R. Green
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/cdefs.h>
31 __COPYRIGHT("@(#) Copyright (c) 1997, 1998, 2003, 2004, 2006\
32 Matthew R. Green. All rights reserved.");
33 __RCSID("$NetBSD: gzip.c,v 1.108 2015/04/15 02:29:12 christos Exp $");
37 * gzip.c -- GPL free gzip using zlib.
39 * RFC 1950 covers the zlib format
40 * RFC 1951 covers the deflate format
41 * RFC 1952 covers the gzip format
44 * - use mmap where possible
45 * - handle some signals better (remove outfile?)
46 * - make bzip2/compress -v/-t/-l support work as well as possible
49 #include <sys/param.h>
69 #define PRIdOFF PRId64
72 /* what type of file are we dealing with */
75 #ifndef NO_BZIP2_SUPPORT
78 #ifndef NO_COMPRESS_SUPPORT
81 #ifndef NO_PACK_SUPPORT
91 #ifndef NO_BZIP2_SUPPORT
94 #define BZ2_SUFFIX ".bz2"
95 #define BZIP2_MAGIC "\102\132\150"
98 #ifndef NO_COMPRESS_SUPPORT
100 #define Z_MAGIC "\037\235"
103 #ifndef NO_PACK_SUPPORT
104 #define PACK_MAGIC "\037\036"
107 #ifndef NO_XZ_SUPPORT
109 #define XZ_SUFFIX ".xz"
110 #define XZ_MAGIC "\3757zXZ"
113 #define GZ_SUFFIX ".gz"
115 #define BUFLEN (64 * 1024)
117 #define GZIP_MAGIC0 0x1F
118 #define GZIP_MAGIC1 0x8B
119 #define GZIP_OMAGIC1 0x9E
121 #define GZIP_TIMESTAMP (off_t)4
122 #define GZIP_ORIGNAME (off_t)10
124 #define HEAD_CRC 0x02
125 #define EXTRA_FIELD 0x04
126 #define ORIG_NAME 0x08
129 #define OS_CODE 3 /* Unix */
134 const char *normal
; /* for unzip - must not be longer than zipped */
136 static suffixes_t suffixes
[] = {
137 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
138 SUFFIX(GZ_SUFFIX
, ""), /* Overwritten by -S .xxx */
140 SUFFIX(GZ_SUFFIX
, ""),
145 SUFFIX(".taz", ".tar"),
146 SUFFIX(".tgz", ".tar"),
147 #ifndef NO_BZIP2_SUPPORT
148 SUFFIX(BZ2_SUFFIX
, ""),
150 #ifndef NO_COMPRESS_SUPPORT
151 SUFFIX(Z_SUFFIX
, ""),
153 #ifndef NO_XZ_SUPPORT
154 SUFFIX(XZ_SUFFIX
, ""),
156 SUFFIX(GZ_SUFFIX
, ""), /* Overwritten by -S "" */
160 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
161 #define SUFFIX_MAXLEN 30
163 static const char gzip_version
[] = "NetBSD gzip 20150113";
165 static int cflag
; /* stdout mode */
166 static int dflag
; /* decompress mode */
167 static int lflag
; /* list mode */
168 static int numflag
= 6; /* gzip -1..-9 value */
171 static int fflag
; /* force mode */
172 static int kflag
; /* don't delete input files */
173 static int nflag
; /* don't save name/timestamp */
174 static int Nflag
; /* don't restore name/timestamp */
175 static int qflag
; /* quiet mode */
176 static int rflag
; /* recursive mode */
177 static int tflag
; /* test */
178 static int vflag
; /* verbose mode */
184 static int exit_value
= 0; /* exit value */
186 static char *infile
; /* name of file coming in */
188 static void maybe_err(const char *fmt
, ...) __printflike(1, 2) __dead
;
189 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
190 !defined(NO_XZ_SUPPORT)
191 static void maybe_errx(const char *fmt
, ...) __printflike(1, 2) __dead
;
193 static void maybe_warn(const char *fmt
, ...) __printflike(1, 2);
194 static void maybe_warnx(const char *fmt
, ...) __printflike(1, 2);
195 static enum filetype
file_gettype(u_char
*);
197 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
199 static off_t
gz_compress(int, int, off_t
*, const char *, uint32_t);
200 static off_t
gz_uncompress(int, int, char *, size_t, off_t
*, const char *);
201 static off_t
file_compress(char *, char *, size_t);
202 static off_t
file_uncompress(char *, char *, size_t);
203 static void handle_pathname(char *);
204 static void handle_file(char *, struct stat
*);
205 static void handle_stdin(void);
206 static void handle_stdout(void);
207 static void print_ratio(off_t
, off_t
, FILE *);
208 static void print_list(int fd
, off_t
, const char *, time_t);
209 __dead
static void usage(void);
210 __dead
static void display_version(void);
211 static const suffixes_t
*check_suffix(char *, int);
212 static ssize_t
read_retry(int, void *, size_t);
215 #define unlink_input(f, sb) unlink(f)
217 static off_t
cat_fd(unsigned char *, size_t, off_t
*, int fd
);
218 static void prepend_gzip(char *, int *, char ***);
219 static void handle_dir(char *);
220 static void print_verbage(const char *, const char *, off_t
, off_t
);
221 static void print_test(const char *, int);
222 static void copymodes(int fd
, const struct stat
*, const char *file
);
223 static int check_outfile(const char *outfile
);
226 #ifndef NO_BZIP2_SUPPORT
227 static off_t
unbzip2(int, int, char *, size_t, off_t
*);
230 #ifndef NO_COMPRESS_SUPPORT
231 static FILE *zdopen(int);
232 static off_t
zuncompress(FILE *, FILE *, char *, size_t, off_t
*);
235 #ifndef NO_PACK_SUPPORT
236 static off_t
unpack(int, int, char *, size_t, off_t
*);
239 #ifndef NO_XZ_SUPPORT
240 static off_t
unxz(int, int, char *, size_t, off_t
*);
244 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
246 static const struct option longopts
[] = {
247 { "stdout", no_argument
, 0, 'c' },
248 { "to-stdout", no_argument
, 0, 'c' },
249 { "decompress", no_argument
, 0, 'd' },
250 { "uncompress", no_argument
, 0, 'd' },
251 { "force", no_argument
, 0, 'f' },
252 { "help", no_argument
, 0, 'h' },
253 { "keep", no_argument
, 0, 'k' },
254 { "list", no_argument
, 0, 'l' },
255 { "no-name", no_argument
, 0, 'n' },
256 { "name", no_argument
, 0, 'N' },
257 { "quiet", no_argument
, 0, 'q' },
258 { "recursive", no_argument
, 0, 'r' },
259 { "suffix", required_argument
, 0, 'S' },
260 { "test", no_argument
, 0, 't' },
261 { "verbose", no_argument
, 0, 'v' },
262 { "version", no_argument
, 0, 'V' },
263 { "fast", no_argument
, 0, '1' },
264 { "best", no_argument
, 0, '9' },
267 * This is what else GNU gzip implements. --ascii isn't useful
268 * on NetBSD, and I don't care to have a --license.
270 { "ascii", no_argument
, 0, 'a' },
271 { "license", no_argument
, 0, 'L' },
273 { NULL
, no_argument
, 0, 0 },
278 main(int argc
, char **argv
)
280 const char *progname
= getprogname();
287 /* XXX set up signals */
290 if ((gzip
= getenv("GZIP")) != NULL
)
291 prepend_gzip(gzip
, &argc
, &argv
);
296 * handle being called `gunzip', `zcat' and `gzcat'
298 if (strcmp(progname
, "gunzip") == 0)
300 else if (strcmp(progname
, "zcat") == 0 ||
301 strcmp(progname
, "gzcat") == 0)
305 #define OPT_LIST "123456789cdhlV"
307 #define OPT_LIST "123456789cdfhklNnqrS:tVv"
310 while ((ch
= getopt_long(argc
, argv
, OPT_LIST
, longopts
, NULL
)) != -1) {
312 case '1': case '2': case '3':
313 case '4': case '5': case '6':
314 case '7': case '8': case '9':
352 len
= strlen(optarg
);
354 if (len
> SUFFIX_MAXLEN
)
355 errx(1, "incorrect suffix: '%s'", optarg
);
356 suffixes
[0].zipped
= optarg
;
357 suffixes
[0].ziplen
= len
;
359 suffixes
[NUM_SUFFIXES
- 1].zipped
= "";
360 suffixes
[NUM_SUFFIXES
- 1].ziplen
= 0;
381 if (dflag
) /* stdin mode */
383 else /* stdout mode */
387 handle_pathname(argv
[0]);
391 if (qflag
== 0 && lflag
&& argc
> 1)
392 print_list(-1, 0, "(totals)", 0);
397 /* maybe print a warning */
399 maybe_warn(const char *fmt
, ...)
412 /* ... without an errno. */
414 maybe_warnx(const char *fmt
, ...)
427 /* maybe print an error */
429 maybe_err(const char *fmt
, ...)
441 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT) || \
442 !defined(NO_XZ_SUPPORT)
443 /* ... without an errno. */
445 maybe_errx(const char *fmt
, ...)
459 /* split up $GZIP and prepend it to the argument list */
461 prepend_gzip(char *gzip
, int *argc
, char ***argv
)
463 char *s
, **nargv
, **ac
;
466 /* scan how many arguments there are */
468 while (*s
== ' ' || *s
== '\t')
473 while (*s
!= ' ' && *s
!= '\t')
485 nargv
= (char **)malloc((*argc
+ 1) * sizeof(char *));
489 /* stash this away */
492 /* copy the program name first */
494 nargv
[i
++] = *(ac
++);
496 /* take a copy of $GZIP and add it to the array */
501 /* Skip whitespaces. */
502 while (*s
== ' ' || *s
== '\t')
507 /* Find the end of this argument. */
508 while (*s
!= ' ' && *s
!= '\t')
510 /* Argument followed by NUL. */
512 /* Terminate by overwriting ' ' or '\t' with NUL. */
517 /* copy the original arguments and a NULL */
519 nargv
[i
++] = *(ac
++);
524 /* compress input to output. Return bytes read, -1 on error */
526 gz_compress(int in
, int out
, off_t
*gsizep
, const char *origname
, uint32_t mtime
)
529 char *outbufp
, *inbufp
;
530 off_t in_tot
= 0, out_tot
= 0;
535 static char header
[] = { GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
, 0,
540 outbufp
= malloc(BUFLEN
);
541 inbufp
= malloc(BUFLEN
);
542 if (outbufp
== NULL
|| inbufp
== NULL
) {
543 maybe_err("malloc failed");
547 memset(&z
, 0, sizeof z
);
553 memcpy(outbufp
, header
, sizeof header
);
561 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c%c%c%s",
562 GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
,
563 *origname
? ORIG_NAME
: 0,
566 (mtime
>> 16) & 0xff,
567 (mtime
>> 24) & 0xff,
568 numflag
== 1 ? 4 : numflag
== 9 ? 2 : 0,
571 /* this need PATH_MAX > BUFLEN ... */
572 maybe_err("snprintf");
577 z
.next_out
= (unsigned char *)outbufp
+ i
;
578 z
.avail_out
= BUFLEN
- i
;
580 error
= deflateInit2(&z
, numflag
, Z_DEFLATED
,
581 (-MAX_WBITS
), 8, Z_DEFAULT_STRATEGY
);
583 maybe_warnx("deflateInit2 failed");
588 crc
= crc32(0L, Z_NULL
, 0);
590 if (z
.avail_out
== 0) {
591 if (write(out
, outbufp
, BUFLEN
) != BUFLEN
) {
598 z
.next_out
= (unsigned char *)outbufp
;
599 z
.avail_out
= BUFLEN
;
602 if (z
.avail_in
== 0) {
603 in_size
= read(in
, inbufp
, BUFLEN
);
612 crc
= crc32(crc
, (const Bytef
*)inbufp
, (unsigned)in_size
);
614 z
.next_in
= (unsigned char *)inbufp
;
615 z
.avail_in
= in_size
;
618 error
= deflate(&z
, Z_NO_FLUSH
);
619 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
620 maybe_warnx("deflate failed");
631 error
= deflate(&z
, Z_FINISH
);
632 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
633 maybe_warnx("deflate failed");
638 len
= (char *)z
.next_out
- outbufp
;
640 w
= write(out
, outbufp
, len
);
641 if (w
== -1 || (size_t)w
!= len
) {
647 z
.next_out
= (unsigned char *)outbufp
;
648 z
.avail_out
= BUFLEN
;
650 if (error
== Z_STREAM_END
)
654 if (deflateEnd(&z
) != Z_OK
) {
655 maybe_warnx("deflateEnd failed");
660 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c",
662 (int)(crc
>> 8) & 0xff,
663 (int)(crc
>> 16) & 0xff,
664 (int)(crc
>> 24) & 0xff,
666 (int)(in_tot
>> 8) & 0xff,
667 (int)(in_tot
>> 16) & 0xff,
668 (int)(in_tot
>> 24) & 0xff);
670 maybe_err("snprintf");
672 if (in_tot
> 0xffffffff)
673 maybe_warn("input file size >= 4GB cannot be saved");
675 if (write(out
, outbufp
, i
) != i
) {
692 * uncompress input to output then close the input. return the
693 * uncompressed size written, and put the compressed sized read
697 gz_uncompress(int in
, int out
, char *pre
, size_t prelen
, off_t
*gsizep
,
698 const char *filename
)
701 char *outbufp
, *inbufp
;
702 off_t out_tot
= -1, in_tot
= 0;
703 uint32_t out_sub_tot
= 0;
721 } state
= GZSTATE_MAGIC0
;
722 int flags
= 0, skip_count
= 0;
723 int error
= Z_STREAM_ERROR
, done_reading
= 0;
728 #define ADVANCE() { z.next_in++; z.avail_in--; }
730 if ((outbufp
= malloc(BUFLEN
)) == NULL
) {
731 maybe_err("malloc failed");
734 if ((inbufp
= malloc(BUFLEN
)) == NULL
) {
735 maybe_err("malloc failed");
739 memset(&z
, 0, sizeof z
);
741 z
.next_in
= (unsigned char *)pre
;
742 z
.avail_out
= BUFLEN
;
743 z
.next_out
= (unsigned char *)outbufp
;
752 if ((z
.avail_in
== 0 || needmore
) && done_reading
== 0) {
755 if (z
.avail_in
> 0) {
756 memmove(inbufp
, z
.next_in
, z
.avail_in
);
758 z
.next_in
= (unsigned char *)inbufp
;
759 in_size
= read(in
, z
.next_in
+ z
.avail_in
,
760 BUFLEN
- z
.avail_in
);
763 maybe_warn("failed to read stdin");
765 } else if (in_size
== 0) {
769 z
.avail_in
+= in_size
;
774 if (z
.avail_in
== 0) {
775 if (done_reading
&& state
!= GZSTATE_MAGIC0
) {
776 maybe_warnx("%s: unexpected end of file",
784 if (*z
.next_in
!= GZIP_MAGIC0
) {
786 maybe_warnx("%s: trailing garbage "
787 "ignored", filename
);
790 maybe_warnx("input not gziped (MAGIC0)");
796 crc
= crc32(0L, Z_NULL
, 0);
800 if (*z
.next_in
!= GZIP_MAGIC1
&&
801 *z
.next_in
!= GZIP_OMAGIC1
) {
802 maybe_warnx("input not gziped (MAGIC1)");
810 if (*z
.next_in
!= Z_DEFLATED
) {
811 maybe_warnx("unknown compression method");
825 case GZSTATE_SKIPPING
:
826 if (skip_count
> 0) {
834 if ((flags
& EXTRA_FIELD
) == 0) {
835 state
= GZSTATE_ORIGNAME
;
838 skip_count
= *z
.next_in
;
844 skip_count
|= ((*z
.next_in
) << 8);
850 if (skip_count
> 0) {
857 case GZSTATE_ORIGNAME
:
858 if ((flags
& ORIG_NAME
) == 0) {
867 case GZSTATE_COMMENT
:
868 if ((flags
& COMMENT
) == 0) {
877 case GZSTATE_HEAD_CRC1
:
878 if (flags
& HEAD_CRC
)
885 case GZSTATE_HEAD_CRC2
:
886 if (skip_count
> 0) {
894 if (inflateInit2(&z
, -MAX_WBITS
) != Z_OK
) {
895 maybe_warnx("failed to inflateInit");
902 error
= inflate(&z
, Z_FINISH
);
904 /* Z_BUF_ERROR goes with Z_FINISH... */
906 if (z
.avail_out
> 0 && !done_reading
)
914 maybe_warnx("Z_NEED_DICT error");
917 maybe_warnx("data stream error");
920 maybe_warnx("internal stream error");
923 maybe_warnx("memory allocation error");
927 maybe_warn("unknown error from inflate(): %d",
930 wr
= BUFLEN
- z
.avail_out
;
933 crc
= crc32(crc
, (const Bytef
*)outbufp
, (unsigned)wr
);
936 /* don't write anything with -t */
939 write(out
, outbufp
, wr
) != wr
) {
940 maybe_warn("error writing to output");
948 if (error
== Z_STREAM_END
) {
953 z
.next_out
= (unsigned char *)outbufp
;
954 z
.avail_out
= BUFLEN
;
961 if (z
.avail_in
< 4) {
966 maybe_warnx("truncated input");
969 origcrc
= ((unsigned)z
.next_in
[0] & 0xff) |
970 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
971 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
972 ((unsigned)z
.next_in
[3] & 0xff) << 24;
973 if (origcrc
!= crc
) {
974 maybe_warnx("invalid compressed"
983 if (!z
.avail_in
&& done_reading
) {
992 if (z
.avail_in
< 4) {
997 maybe_warnx("truncated input");
1000 origlen
= ((unsigned)z
.next_in
[0] & 0xff) |
1001 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
1002 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
1003 ((unsigned)z
.next_in
[3] & 0xff) << 24;
1005 if (origlen
!= out_sub_tot
) {
1006 maybe_warnx("invalid compressed"
1007 " data--length error");
1016 maybe_warnx("decompression error");
1019 state
= GZSTATE_MAGIC0
;
1028 if (state
> GZSTATE_INIT
)
1042 * set the owner, mode, flags & utimes using the given file descriptor.
1043 * file is only used in possible warning messages.
1046 copymodes(int fd
, const struct stat
*sbp
, const char *file
)
1048 struct timeval times
[2];
1052 * If we have no info on the input, give this file some
1053 * default values and return..
1056 mode_t mask
= umask(022);
1058 (void)fchmod(fd
, DEFFILEMODE
& ~mask
);
1064 /* if the chown fails, remove set-id bits as-per compress(1) */
1065 if (fchown(fd
, sb
.st_uid
, sb
.st_gid
) < 0) {
1067 maybe_warn("couldn't fchown: %s", file
);
1068 sb
.st_mode
&= ~(S_ISUID
|S_ISGID
);
1071 /* we only allow set-id and the 9 normal permission bits */
1072 sb
.st_mode
&= S_ISUID
| S_ISGID
| S_IRWXU
| S_IRWXG
| S_IRWXO
;
1073 if (fchmod(fd
, sb
.st_mode
) < 0)
1074 maybe_warn("couldn't fchmod: %s", file
);
1076 /* only try flags if they exist already */
1077 #if !defined(__minix)
1078 if (sb
.st_flags
!= 0 && fchflags(fd
, sb
.st_flags
) < 0)
1079 maybe_warn("couldn't fchflags: %s", file
);
1080 #endif /* !defined(__minix) */
1082 TIMESPEC_TO_TIMEVAL(×
[0], &sb
.st_atimespec
);
1083 TIMESPEC_TO_TIMEVAL(×
[1], &sb
.st_mtimespec
);
1084 if (futimes(fd
, times
) < 0)
1085 maybe_warn("couldn't utimes: %s", file
);
1089 /* what sort of file is this? */
1090 static enum filetype
1091 file_gettype(u_char
*buf
)
1094 if (buf
[0] == GZIP_MAGIC0
&&
1095 (buf
[1] == GZIP_MAGIC1
|| buf
[1] == GZIP_OMAGIC1
))
1098 #ifndef NO_BZIP2_SUPPORT
1099 if (memcmp(buf
, BZIP2_MAGIC
, 3) == 0 &&
1100 buf
[3] >= '0' && buf
[3] <= '9')
1104 #ifndef NO_COMPRESS_SUPPORT
1105 if (memcmp(buf
, Z_MAGIC
, 2) == 0)
1109 #ifndef NO_PACK_SUPPORT
1110 if (memcmp(buf
, PACK_MAGIC
, 2) == 0)
1114 #ifndef NO_XZ_SUPPORT
1115 if (memcmp(buf
, XZ_MAGIC
, 4) == 0) /* XXX: We only have 4 bytes */
1123 /* check the outfile is OK. */
1125 check_outfile(const char *outfile
)
1130 if (lflag
== 0 && stat(outfile
, &sb
) == 0) {
1133 else if (isatty(STDIN_FILENO
)) {
1134 char ans
[10] = { 'n', '\0' }; /* default */
1136 fprintf(stderr
, "%s already exists -- do you wish to "
1137 "overwrite (y or n)? " , outfile
);
1138 (void)fgets(ans
, sizeof(ans
) - 1, stdin
);
1139 if (ans
[0] != 'y' && ans
[0] != 'Y') {
1140 fprintf(stderr
, "\tnot overwriting\n");
1145 maybe_warnx("%s already exists -- skipping", outfile
);
1153 unlink_input(const char *file
, const struct stat
*sb
)
1159 if (stat(file
, &nsb
) != 0)
1160 /* Must be gone already */
1162 if (nsb
.st_dev
!= sb
->st_dev
|| nsb
.st_ino
!= sb
->st_ino
)
1163 /* Definitely a different file */
1169 static const suffixes_t
*
1170 check_suffix(char *file
, int xlate
)
1172 const suffixes_t
*s
;
1173 int len
= strlen(file
);
1176 for (s
= suffixes
; s
!= suffixes
+ NUM_SUFFIXES
; s
++) {
1177 /* if it doesn't fit in "a.suf", don't bother */
1178 if (s
->ziplen
>= len
)
1180 sp
= file
+ len
- s
->ziplen
;
1181 if (strcmp(s
->zipped
, sp
) != 0)
1184 strcpy(sp
, s
->normal
);
1191 * compress the given file: create a corresponding .gz file and remove the
1195 file_compress(char *file
, char *outfile
, size_t outsize
)
1201 struct stat isb
, osb
;
1202 const suffixes_t
*suff
;
1205 in
= open(file
, O_RDONLY
);
1207 maybe_warn("can't open %s", file
);
1213 if (fstat(in
, &isb
) == 0) {
1214 if (isb
.st_nlink
> 1 && fflag
== 0) {
1215 maybe_warnx("%s has %d other link%s -- "
1216 "skipping", file
, isb
.st_nlink
- 1,
1217 isb
.st_nlink
== 1 ? "" : "s");
1223 if (fflag
== 0 && (suff
= check_suffix(file
, 0))
1224 && suff
->zipped
[0] != 0) {
1225 maybe_warnx("%s already has %s suffix -- unchanged",
1226 file
, suff
->zipped
);
1232 /* Add (usually) .gz to filename */
1233 if ((size_t)snprintf(outfile
, outsize
, "%s%s",
1234 file
, suffixes
[0].zipped
) >= outsize
)
1235 memcpy(outfile
+ outsize
- suffixes
[0].ziplen
- 1,
1236 suffixes
[0].zipped
, suffixes
[0].ziplen
+ 1);
1239 if (check_outfile(outfile
) == 0) {
1247 out
= open(outfile
, O_WRONLY
| O_CREAT
| O_EXCL
, 0600);
1249 maybe_warn("could not create output: %s", outfile
);
1254 out
= STDOUT_FILENO
;
1256 insize
= gz_compress(in
, out
, &size
, basename(file
), (uint32_t)isb
.st_mtime
);
1261 * If there was an error, insize will be -1.
1262 * If we compressed to stdout, just return the size.
1263 * Otherwise stat the file and check it is the correct size.
1264 * We only blow away the file if we can stat the output and it
1265 * has the expected size.
1268 return insize
== -1 ? -1 : size
;
1271 if (fstat(out
, &osb
) != 0) {
1272 maybe_warn("couldn't stat: %s", outfile
);
1276 if (osb
.st_size
!= size
) {
1277 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1278 " != %" PRIdOFF
"), deleting",
1279 outfile
, osb
.st_size
, size
);
1283 copymodes(out
, &isb
, outfile
);
1285 if (close(out
) == -1)
1286 maybe_warn("couldn't close output");
1288 /* output is good, ok to delete input */
1289 unlink_input(file
, &isb
);
1294 if (close(out
) == -1)
1295 maybe_warn("couldn't close output");
1297 maybe_warnx("leaving original %s", file
);
1303 /* uncompress the given file and remove the original */
1305 file_uncompress(char *file
, char *outfile
, size_t outsize
)
1307 struct stat isb
, osb
;
1310 unsigned char header1
[4];
1311 enum filetype method
;
1312 int fd
, ofd
, zfd
= -1;
1315 time_t timestamp
= 0;
1316 char name
[PATH_MAX
+ 1];
1319 /* gather the old name info */
1321 fd
= open(file
, O_RDONLY
);
1323 maybe_warn("can't open %s", file
);
1327 strlcpy(outfile
, file
, outsize
);
1328 if (check_suffix(outfile
, 1) == NULL
&& !(cflag
|| lflag
)) {
1329 maybe_warnx("%s: unknown suffix -- ignored", file
);
1333 rbytes
= read(fd
, header1
, sizeof header1
);
1334 if (rbytes
!= sizeof header1
) {
1335 /* we don't want to fail here. */
1341 maybe_warn("can't read %s", file
);
1343 goto unexpected_EOF
;
1347 method
= file_gettype(header1
);
1349 if (fflag
== 0 && method
== FT_UNKNOWN
) {
1350 maybe_warnx("%s: not in gzip format", file
);
1357 if (method
== FT_GZIP
&& Nflag
) {
1358 unsigned char ts
[4]; /* timestamp */
1360 rv
= pread(fd
, ts
, sizeof ts
, GZIP_TIMESTAMP
);
1361 if (rv
>= 0 && rv
< (ssize_t
)(sizeof ts
))
1362 goto unexpected_EOF
;
1365 maybe_warn("can't read %s", file
);
1368 timestamp
= ts
[3] << 24 | ts
[2] << 16 | ts
[1] << 8 | ts
[0];
1370 if (header1
[3] & ORIG_NAME
) {
1371 rbytes
= pread(fd
, name
, sizeof(name
) - 1, GZIP_ORIGNAME
);
1373 maybe_warn("can't read %s", file
);
1376 if (name
[0] != '\0') {
1379 /* Make sure that name is NUL-terminated */
1380 name
[rbytes
] = '\0';
1382 /* strip saved directory name */
1383 nf
= strrchr(name
, '/');
1389 /* preserve original directory name */
1390 dp
= strrchr(file
, '/');
1395 snprintf(outfile
, outsize
, "%.*s%.*s",
1397 file
, (int) rbytes
, nf
);
1402 lseek(fd
, 0, SEEK_SET
);
1404 if (cflag
== 0 || lflag
) {
1405 if (fstat(fd
, &isb
) != 0)
1408 if (isb
.st_nlink
> 1 && lflag
== 0 && fflag
== 0) {
1409 maybe_warnx("%s has %d other links -- skipping",
1410 file
, isb
.st_nlink
- 1);
1413 if (nflag
== 0 && timestamp
)
1414 isb
.st_mtime
= timestamp
;
1415 if (check_outfile(outfile
) == 0)
1420 if (cflag
== 0 && lflag
== 0) {
1421 zfd
= open(outfile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0600);
1422 if (zfd
== STDOUT_FILENO
) {
1423 /* We won't close STDOUT_FILENO later... */
1425 close(STDOUT_FILENO
);
1428 maybe_warn("can't open %s", outfile
);
1432 zfd
= STDOUT_FILENO
;
1435 #ifndef NO_BZIP2_SUPPORT
1439 maybe_warnx("no -l with bzip2 files");
1443 size
= unbzip2(fd
, zfd
, NULL
, 0, NULL
);
1447 #ifndef NO_COMPRESS_SUPPORT
1453 maybe_warnx("no -l with Lempel-Ziv files");
1457 if ((in
= zdopen(fd
)) == NULL
) {
1458 maybe_warn("zdopen for read: %s", file
);
1462 out
= fdopen(dup(zfd
), "w");
1464 maybe_warn("fdopen for write: %s", outfile
);
1469 size
= zuncompress(in
, out
, NULL
, 0, NULL
);
1470 /* need to fclose() if ferror() is true... */
1471 if (ferror(in
) | fclose(in
)) {
1472 maybe_warn("failed infile fclose");
1476 if (fclose(out
) != 0) {
1477 maybe_warn("failed outfile fclose");
1485 #ifndef NO_PACK_SUPPORT
1488 maybe_warnx("no -l with packed files");
1492 size
= unpack(fd
, zfd
, NULL
, 0, NULL
);
1496 #ifndef NO_XZ_SUPPORT
1499 maybe_warnx("no -l with xz files");
1503 size
= unxz(fd
, zfd
, NULL
, 0, NULL
);
1510 maybe_warnx("no -l for unknown filetypes");
1513 size
= cat_fd(NULL
, 0, NULL
, fd
);
1518 print_list(fd
, isb
.st_size
, outfile
, isb
.st_mtime
);
1520 return -1; /* XXX */
1523 size
= gz_uncompress(fd
, zfd
, NULL
, 0, NULL
, file
);
1528 maybe_warn("couldn't close input");
1529 if (zfd
!= STDOUT_FILENO
&& close(zfd
) != 0)
1530 maybe_warn("couldn't close output");
1535 maybe_warnx("%s: uncompress failed", file
);
1539 /* if testing, or we uncompressed to stdout, this is all we need */
1544 /* if we are uncompressing to stdin, don't remove the file. */
1549 * if we create a file...
1552 * if we can't stat the file don't remove the file.
1555 ofd
= open(outfile
, O_RDWR
, 0);
1557 maybe_warn("couldn't open (leaving original): %s",
1561 if (fstat(ofd
, &osb
) != 0) {
1562 maybe_warn("couldn't stat (leaving original): %s",
1567 if (osb
.st_size
!= size
) {
1568 maybe_warnx("stat gave different size: %" PRIdOFF
1569 " != %" PRIdOFF
" (leaving original)",
1575 unlink_input(file
, &isb
);
1577 copymodes(ofd
, &isb
, outfile
);
1583 maybe_warnx("%s: unexpected end of file", file
);
1587 if (zfd
!= -1 && zfd
!= STDOUT_FILENO
)
1594 cat_fd(unsigned char * prepend
, size_t count
, off_t
*gsizep
, int fd
)
1601 w
= write(STDOUT_FILENO
, prepend
, count
);
1602 if (w
== -1 || (size_t)w
!= count
) {
1603 maybe_warn("write to stdout");
1609 rv
= read(fd
, buf
, sizeof buf
);
1613 maybe_warn("read from fd %d", fd
);
1617 if (write(STDOUT_FILENO
, buf
, rv
) != rv
) {
1618 maybe_warn("write to stdout");
1633 unsigned char header1
[4];
1635 enum filetype method
;
1637 #ifndef NO_COMPRESS_SUPPORT
1642 if (fflag
== 0 && lflag
== 0 && isatty(STDIN_FILENO
)) {
1643 maybe_warnx("standard input is a terminal -- ignoring");
1651 /* XXX could read the whole file, etc. */
1652 if (fstat(STDIN_FILENO
, &isb
) < 0) {
1653 maybe_warn("fstat");
1656 print_list(STDIN_FILENO
, isb
.st_size
, "stdout", isb
.st_mtime
);
1660 bytes_read
= read_retry(STDIN_FILENO
, header1
, sizeof header1
);
1661 if (bytes_read
== -1) {
1662 maybe_warn("can't read stdin");
1664 } else if (bytes_read
!= sizeof(header1
)) {
1665 maybe_warnx("(stdin): unexpected end of file");
1669 method
= file_gettype(header1
);
1674 maybe_warnx("unknown compression format");
1677 usize
= cat_fd(header1
, sizeof header1
, &gsize
, STDIN_FILENO
);
1681 usize
= gz_uncompress(STDIN_FILENO
, STDOUT_FILENO
,
1682 (char *)header1
, sizeof header1
, &gsize
, "(stdin)");
1684 #ifndef NO_BZIP2_SUPPORT
1686 usize
= unbzip2(STDIN_FILENO
, STDOUT_FILENO
,
1687 (char *)header1
, sizeof header1
, &gsize
);
1690 #ifndef NO_COMPRESS_SUPPORT
1692 if ((in
= zdopen(STDIN_FILENO
)) == NULL
) {
1693 maybe_warnx("zopen of stdin");
1697 usize
= zuncompress(in
, stdout
, (char *)header1
,
1698 sizeof header1
, &gsize
);
1702 #ifndef NO_PACK_SUPPORT
1704 usize
= unpack(STDIN_FILENO
, STDOUT_FILENO
,
1705 (char *)header1
, sizeof header1
, &gsize
);
1708 #ifndef NO_XZ_SUPPORT
1710 usize
= unxz(STDIN_FILENO
, STDOUT_FILENO
,
1711 (char *)header1
, sizeof header1
, &gsize
);
1717 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1718 print_verbage(NULL
, NULL
, usize
, gsize
);
1720 print_test("(stdin)", usize
!= -1);
1735 if (fflag
== 0 && isatty(STDOUT_FILENO
)) {
1736 maybe_warnx("standard output is a terminal -- ignoring");
1740 /* If stdin is a file use its mtime, otherwise use current time */
1741 ret
= fstat(STDIN_FILENO
, &sb
);
1745 maybe_warn("Can't stat stdin");
1750 if (S_ISREG(sb
.st_mode
))
1751 mtime
= (uint32_t)sb
.st_mtime
;
1753 systime
= time(NULL
);
1755 if (systime
== -1) {
1760 mtime
= (uint32_t)systime
;
1763 usize
= gz_compress(STDIN_FILENO
, STDOUT_FILENO
, &gsize
, "", mtime
);
1765 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1766 print_verbage(NULL
, NULL
, usize
, gsize
);
1770 /* do what is asked for, for the path name */
1772 handle_pathname(char *path
)
1774 char *opath
= path
, *s
= NULL
;
1779 /* check for stdout/stdin */
1780 if (path
[0] == '-' && path
[1] == '\0') {
1789 if (stat(path
, &sb
) != 0) {
1790 /* lets try <path>.gz if we're decompressing */
1791 if (dflag
&& s
== NULL
&& errno
== ENOENT
) {
1793 slen
= suffixes
[0].ziplen
;
1794 s
= malloc(len
+ slen
+ 1);
1796 maybe_err("malloc");
1797 memcpy(s
, path
, len
);
1798 memcpy(s
+ len
, suffixes
[0].zipped
, slen
+ 1);
1802 maybe_warn("can't stat: %s", opath
);
1806 if (S_ISDIR(sb
.st_mode
)) {
1812 maybe_warnx("%s is a directory", path
);
1816 if (S_ISREG(sb
.st_mode
))
1817 handle_file(path
, &sb
);
1819 maybe_warnx("%s is not a regular file", path
);
1826 /* compress/decompress a file */
1828 handle_file(char *file
, struct stat
*sbp
)
1831 char outfile
[PATH_MAX
];
1835 usize
= file_uncompress(file
, outfile
, sizeof(outfile
));
1838 print_test(file
, usize
!= -1);
1842 gsize
= sbp
->st_size
;
1844 gsize
= file_compress(file
, outfile
, sizeof(outfile
));
1847 usize
= sbp
->st_size
;
1852 if (vflag
&& !tflag
)
1853 print_verbage(file
, (cflag
) ? NULL
: outfile
, usize
, gsize
);
1858 /* this is used with -r to recursively descend directories */
1860 handle_dir(char *dir
)
1868 fts
= fts_open(path_argv
, FTS_PHYSICAL
, NULL
);
1870 warn("couldn't fts_open %s", dir
);
1874 while ((entry
= fts_read(fts
))) {
1875 switch(entry
->fts_info
) {
1883 maybe_warn("%s", entry
->fts_path
);
1886 handle_file(entry
->fts_name
, entry
->fts_statp
);
1889 (void)fts_close(fts
);
1893 /* print a ratio - size reduction as a fraction of uncompressed size */
1895 print_ratio(off_t in
, off_t out
, FILE *where
)
1897 int percent10
; /* 10 * percent */
1905 * Output is more than double size of input! print -99.9%
1906 * Quite possibly we've failed to get the original size.
1911 * We only need 12 bits of result from the final division,
1912 * so reduce the values until a 32bit division will suffice.
1914 while (in
> 0x100000) {
1919 percent10
= ((u_int
)diff
* 2000) / (u_int
)in
- 1000;
1924 len
= snprintf(buff
, sizeof buff
, "%2.2d.", percent10
);
1925 /* Move the '.' to before the last digit */
1926 buff
[len
- 1] = buff
[len
- 2];
1927 buff
[len
- 2] = '.';
1928 fprintf(where
, "%5s%%", buff
);
1932 /* print compression statistics, and the new name (if there is one!) */
1934 print_verbage(const char *file
, const char *nfile
, off_t usize
, off_t gsize
)
1937 fprintf(stderr
, "%s:%s ", file
,
1938 strlen(file
) < 7 ? "\t\t" : "\t");
1939 print_ratio(usize
, gsize
, stderr
);
1941 fprintf(stderr
, " -- replaced with %s", nfile
);
1942 fprintf(stderr
, "\n");
1946 /* print test results */
1948 print_test(const char *file
, int ok
)
1951 if (exit_value
== 0 && ok
== 0)
1953 fprintf(stderr
, "%s:%s %s\n", file
,
1954 strlen(file
) < 7 ? "\t\t" : "\t", ok
? "OK" : "NOT OK");
1959 /* print a file's info ala --list */
1961 compressed uncompressed ratio uncompressed_name
1962 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1965 print_list(int fd
, off_t out
, const char *outfile
, time_t ts
)
1967 static int first
= 1;
1969 static off_t in_tot
, out_tot
;
1977 printf("method crc date time ");
1980 printf(" compressed uncompressed "
1981 "ratio uncompressed_name\n");
1993 /* read the last 4 bytes - this is the uncompressed size */
1994 rv
= lseek(fd
, (off_t
)(-8), SEEK_END
);
1996 unsigned char buf
[8];
1999 rv
= read(fd
, (char *)buf
, sizeof(buf
));
2001 maybe_warn("read of uncompressed size");
2002 else if (rv
!= sizeof(buf
))
2003 maybe_warnx("read of uncompressed size");
2006 usize
= buf
[4] | buf
[5] << 8 |
2007 buf
[6] << 16 | buf
[7] << 24;
2010 crc
= buf
[0] | buf
[1] << 8 |
2011 buf
[2] << 16 | buf
[3] << 24;
2018 if (vflag
&& fd
== -1)
2021 char *date
= ctime(&ts
);
2023 /* skip the day, 1/100th second, and year */
2026 printf("%5s %08x %11s ", "defla"/*XXX*/, crc
, date
);
2031 printf("%12llu %12llu ", (unsigned long long)out
, (unsigned long long)in
);
2032 print_ratio(in
, out
, stdout
);
2033 printf(" %s\n", outfile
);
2036 /* display the usage of NetBSD gzip */
2041 fprintf(stderr
, "%s\n", gzip_version
);
2043 "usage: %s [-" OPT_LIST
"] [<file> [<file> ...]]\n"
2045 " -1 --fast fastest (worst) compression\n"
2046 " -2 .. -8 set compression level\n"
2047 " -9 --best best (slowest) compression\n"
2048 " -c --stdout write to stdout, keep original files\n"
2050 " -d --decompress uncompress files\n"
2052 " -f --force force overwriting & compress links\n"
2053 " -h --help display this help\n"
2054 " -k --keep don't delete input files during operation\n"
2055 " -l --list list compressed file contents\n"
2056 " -N --name save or restore original file name and time stamp\n"
2057 " -n --no-name don't save original file name or time stamp\n"
2058 " -q --quiet output no warnings\n"
2059 " -r --recursive recursively compress files in directories\n"
2060 " -S .suf use suffix .suf instead of .gz\n"
2062 " -t --test test compressed file\n"
2063 " -V --version display program version\n"
2064 " -v --verbose print extra statistics\n",
2072 /* display the version of NetBSD gzip */
2074 display_version(void)
2077 fprintf(stderr
, "%s\n", gzip_version
);
2081 #ifndef NO_BZIP2_SUPPORT
2082 #include "unbzip2.c"
2084 #ifndef NO_COMPRESS_SUPPORT
2085 #include "zuncompress.c"
2087 #ifndef NO_PACK_SUPPORT
2090 #ifndef NO_XZ_SUPPORT
2095 read_retry(int fd
, void *buf
, size_t sz
)
2098 size_t left
= MIN(sz
, (size_t) SSIZE_MAX
);
2103 ret
= read(fd
, cp
, left
);
2106 } else if (ret
== 0) {