1 /* $NetBSD: gzip.c,v 1.67 2004/09/11 11:07:44 dsl Exp $ */
2 /* $DragonFly: src/usr.bin/gzip/gzip.c,v 1.7 2007/12/06 19:54:52 hasso Exp $ */
5 * Copyright (c) 1997, 1998, 2003, 2004 Matthew R. Green
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
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 * gzip.c -- GPL free gzip using zlib.
35 * RFC 1950 covers the zlib format
36 * RFC 1951 covers the deflate format
37 * RFC 1952 covers the gzip format
40 * - use mmap where possible
41 * - handle some signals better (remove outfile?)
42 * - make bzip2/compress -v/-t/-l support work as well as possible
45 #include <sys/param.h>
64 #define PRIdOFF PRId64
71 /* what type of file are we dealing with */
74 #ifndef NO_BZIP2_SUPPORT
77 #ifndef NO_COMPRESS_SUPPORT
84 #ifndef NO_BZIP2_SUPPORT
87 #define BZ2_SUFFIX ".bz2"
88 #define BZIP2_MAGIC "\102\132\150"
91 #ifndef NO_COMPRESS_SUPPORT
93 #define Z_MAGIC "\037\235"
96 #define GZ_SUFFIX ".gz"
98 #define BUFLEN (64 * 1024)
100 #define GZIP_MAGIC0 0x1F
101 #define GZIP_MAGIC1 0x8B
102 #define GZIP_OMAGIC1 0x9E
104 #define GZIP_TIMESTAMP (off_t)4
105 #define GZIP_ORIGNAME (off_t)10
107 #define HEAD_CRC 0x02
108 #define EXTRA_FIELD 0x04
109 #define ORIG_NAME 0x08
112 #define OS_CODE 3 /* Unix */
117 const char *normal
; /* for unzip - must not be longer than zipped */
119 static suffixes_t suffixes
[] = {
120 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
121 SUFFIX(GZ_SUFFIX
, ""), /* Overwritten by -S .xxx */
123 SUFFIX(GZ_SUFFIX
, ""),
128 SUFFIX(".taz", ".tar"),
129 SUFFIX(".tgz", ".tar"),
130 #ifndef NO_BZIP2_SUPPORT
131 SUFFIX(BZ2_SUFFIX
, ""),
133 #ifndef NO_COMPRESS_SUPPORT
134 SUFFIX(Z_SUFFIX
, ""),
136 SUFFIX(GZ_SUFFIX
, ""), /* Overwritten by -S "" */
140 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
142 static const char gzip_version
[] = "NetBSD gzip 20040830";
144 static int cflag
; /* stdout mode */
145 static int dflag
; /* decompress mode */
146 static int lflag
; /* list mode */
147 static int numflag
= 6; /* gzip -1..-9 value */
150 static int fflag
; /* force mode */
151 static int kflag
; /* don't delete input files */
152 static int nflag
; /* don't save name/timestamp */
153 static int Nflag
; /* don't restore name/timestamp */
154 static int qflag
; /* quiet mode */
155 static int rflag
; /* recursive mode */
156 static int tflag
; /* test */
157 static int vflag
; /* verbose mode */
163 static int exit_value
= 0; /* exit value */
165 static char *infile
; /* name of file coming in */
167 static void maybe_err(const char *fmt
, ...)
168 __attribute__((__format__(__printf__
, 1, 2)));
169 #ifndef NO_BZIP2_SUPPORT
170 static void maybe_errx(const char *fmt
, ...)
171 __attribute__((__format__(__printf__
, 1, 2)));
173 static void maybe_warn(const char *fmt
, ...)
174 __attribute__((__format__(__printf__
, 1, 2)));
175 static void maybe_warnx(const char *fmt
, ...)
176 __attribute__((__format__(__printf__
, 1, 2)));
177 static enum filetype
file_gettype(u_char
*);
179 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
181 static off_t
gz_compress(int, int, off_t
*, const char *, uint32_t);
182 static off_t
gz_uncompress(int, int, char *, size_t, off_t
*, const char *);
183 static off_t
file_compress(char *, char *, size_t);
184 static off_t
file_uncompress(char *, char *, size_t);
185 static void handle_pathname(char *);
186 static void handle_file(char *, struct stat
*);
187 static void handle_stdin(void);
188 static void handle_stdout(void);
189 static void print_ratio(off_t
, off_t
, FILE *);
190 static void print_list(int fd
, off_t
, const char *, time_t);
191 static void usage(void);
192 static void display_version(void);
193 static const suffixes_t
*check_suffix(char *, int);
196 #define unlink_input(f, sb) unlink(f)
198 static off_t
cat_fd(unsigned char *, ssize_t
, off_t
*, int fd
);
199 static void prepend_gzip(char *, int *, char ***);
200 static void handle_dir(char *);
201 static void print_verbage(const char *, const char *, off_t
, off_t
);
202 static void print_test(const char *, int);
203 static void copymodes(const char *, struct stat
*);
204 static int check_outfile(const char *outfile
, struct stat
*sb
);
207 #ifndef NO_BZIP2_SUPPORT
208 static off_t
unbzip2(int, int, char *, size_t, off_t
*);
211 #ifndef NO_COMPRESS_SUPPORT
212 static FILE *zdopen(int);
213 static off_t
zuncompress(FILE *, FILE *, char *, size_t, off_t
*);
216 int main(int, char *p
[]);
219 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
221 static const struct option longopts
[] = {
222 { "stdout", no_argument
, 0, 'c' },
223 { "to-stdout", no_argument
, 0, 'c' },
224 { "decompress", no_argument
, 0, 'd' },
225 { "uncompress", no_argument
, 0, 'd' },
226 { "force", no_argument
, 0, 'f' },
227 { "help", no_argument
, 0, 'h' },
228 { "keep", no_argument
, 0, 'k' },
229 { "list", no_argument
, 0, 'l' },
230 { "no-name", no_argument
, 0, 'n' },
231 { "name", no_argument
, 0, 'N' },
232 { "quiet", no_argument
, 0, 'q' },
233 { "recursive", no_argument
, 0, 'r' },
234 { "suffix", required_argument
, 0, 'S' },
235 { "test", no_argument
, 0, 't' },
236 { "verbose", no_argument
, 0, 'v' },
237 { "version", no_argument
, 0, 'V' },
238 { "fast", no_argument
, 0, '1' },
239 { "best", no_argument
, 0, '9' },
242 * This is what else GNU gzip implements. --ascii isn't useful
243 * on NetBSD, and I don't care to have a --license.
245 { "ascii", no_argument
, 0, 'a' },
246 { "license", no_argument
, 0, 'L' },
248 { NULL
, no_argument
, 0, 0 },
253 main(int argc
, char **argv
)
255 const char *progname
= getprogname();
262 /* XXX set up signals */
265 if ((gzip
= getenv("GZIP")) != NULL
)
266 prepend_gzip(gzip
, &argc
, &argv
);
271 * handle being called `gunzip', `zcat' and `gzcat'
273 if (strcmp(progname
, "gunzip") == 0)
275 else if (strcmp(progname
, "zcat") == 0 ||
276 strcmp(progname
, "gzcat") == 0)
280 #define OPT_LIST "cdhHltV123456789"
282 #define OPT_LIST "cdfhHklnNqrS:tvV123456789"
285 while ((ch
= getopt_long(argc
, argv
, OPT_LIST
, longopts
, NULL
)) != -1) {
300 case '1': case '2': case '3':
301 case '4': case '5': case '6':
302 case '7': case '8': case '9':
327 len
= strlen(optarg
);
329 suffixes
[0].zipped
= optarg
;
330 suffixes
[0].ziplen
= len
;
332 suffixes
[NUM_SUFFIXES
- 1].zipped
= "";
333 suffixes
[NUM_SUFFIXES
- 1].ziplen
= 0;
354 if (dflag
) /* stdin mode */
356 else /* stdout mode */
360 handle_pathname(argv
[0]);
364 if (qflag
== 0 && lflag
&& argc
> 1)
365 print_list(-1, 0, "(totals)", 0);
370 /* maybe print a warning */
372 maybe_warn(const char *fmt
, ...)
385 /* ... without an errno. */
387 maybe_warnx(const char *fmt
, ...)
400 /* maybe print an error */
402 maybe_err(const char *fmt
, ...)
414 #ifndef NO_BZIP2_SUPPORT
415 /* ... without an errno. */
417 maybe_errx(const char *fmt
, ...)
431 /* split up $GZIP and prepend it to the argument list */
433 prepend_gzip(char *gzip
, int *argc
, char ***argv
)
435 char *s
, **nargv
, **ac
;
438 /* scan how many arguments there are */
440 while (*s
== ' ' || *s
== '\t')
445 while (*s
!= ' ' && *s
!= '\t')
457 nargv
= (char **)malloc((*argc
+ 1) * sizeof(char *));
461 /* stash this away */
464 /* copy the program name first */
466 nargv
[i
++] = *(ac
++);
468 /* take a copy of $GZIP and add it to the array */
473 /* Skip whitespaces. */
474 while (*s
== ' ' || *s
== '\t')
479 /* Find the end of this argument. */
480 while (*s
!= ' ' && *s
!= '\t')
482 /* Argument followed by NUL. */
484 /* Terminate by overwriting ' ' or '\t' with NUL. */
489 /* copy the original arguments and a NULL */
491 nargv
[i
++] = *(ac
++);
496 /* compress input to output. Return bytes read, -1 on error */
498 gz_compress(int in
, int out
, off_t
*gsizep
, const char *origname
, uint32_t mtime
)
501 char *outbufp
, *inbufp
;
502 off_t in_tot
= 0, out_tot
= 0;
507 static char header
[] = { GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
, 0,
512 outbufp
= malloc(BUFLEN
);
513 inbufp
= malloc(BUFLEN
);
514 if (outbufp
== NULL
|| inbufp
== NULL
) {
515 maybe_err("malloc failed");
519 memset(&z
, 0, sizeof z
);
525 memcpy(outbufp
, header
, sizeof header
);
533 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c%c%c%s",
534 GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
,
535 *origname
? ORIG_NAME
: 0,
538 (mtime
>> 16) & 0xff,
539 (mtime
>> 24) & 0xff,
540 numflag
== 1 ? 4 : numflag
== 9 ? 2 : 0,
543 /* this need PATH_MAX > BUFLEN ... */
544 maybe_err("snprintf");
549 z
.next_out
= outbufp
+ i
;
550 z
.avail_out
= BUFLEN
- i
;
552 error
= deflateInit2(&z
, numflag
, Z_DEFLATED
,
553 -MAX_WBITS
, 8, Z_DEFAULT_STRATEGY
);
555 maybe_warnx("deflateInit2 failed");
560 crc
= crc32(0L, Z_NULL
, 0);
562 if (z
.avail_out
== 0) {
563 if (write(out
, outbufp
, BUFLEN
) != BUFLEN
) {
570 z
.next_out
= outbufp
;
571 z
.avail_out
= BUFLEN
;
574 if (z
.avail_in
== 0) {
575 in_size
= read(in
, inbufp
, BUFLEN
);
584 crc
= crc32(crc
, (const Bytef
*)inbufp
, (unsigned)in_size
);
587 z
.avail_in
= in_size
;
590 error
= deflate(&z
, Z_NO_FLUSH
);
591 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
592 maybe_warnx("deflate failed");
602 error
= deflate(&z
, Z_FINISH
);
603 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
604 maybe_warnx("deflate failed");
609 len
= (char *)z
.next_out
- outbufp
;
611 if (write(out
, outbufp
, len
) != len
) {
617 z
.next_out
= outbufp
;
618 z
.avail_out
= BUFLEN
;
620 if (error
== Z_STREAM_END
)
624 if (deflateEnd(&z
) != Z_OK
) {
625 maybe_warnx("deflateEnd failed");
630 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c",
632 (int)(crc
>> 8) & 0xff,
633 (int)(crc
>> 16) & 0xff,
634 (int)(crc
>> 24) & 0xff,
636 (int)(in_tot
>> 8) & 0xff,
637 (int)(in_tot
>> 16) & 0xff,
638 (int)(in_tot
>> 24) & 0xff);
640 maybe_err("snprintf");
641 if (write(out
, outbufp
, i
) != i
) {
658 * uncompress input to output then close the input. return the
659 * uncompressed size written, and put the compressed sized read
663 gz_uncompress(int in
, int out
, char *pre
, size_t prelen
, off_t
*gsizep
,
664 const char *filename
)
667 char *outbufp
, *inbufp
;
668 off_t out_tot
= prelen
, in_tot
= 0;
669 uint32_t out_sub_tot
= 0;
687 } state
= GZSTATE_MAGIC0
;
688 int flags
= 0, skip_count
= 0;
689 int error
= 0, done_reading
= 0;
693 #define ADVANCE() { z.next_in++; z.avail_in--; }
695 if ((outbufp
= malloc(BUFLEN
)) == NULL
) {
696 maybe_err("malloc failed");
699 if ((inbufp
= malloc(BUFLEN
)) == NULL
) {
700 maybe_err("malloc failed");
704 memset(&z
, 0, sizeof z
);
707 z
.avail_out
= BUFLEN
;
708 z
.next_out
= outbufp
;
715 if (z
.avail_in
== 0 && done_reading
== 0) {
716 ssize_t in_size
= read(in
, inbufp
, BUFLEN
);
721 print_test(filename
, 0);
723 maybe_warn("failed to read stdin");
726 } else if (in_size
== 0)
729 z
.avail_in
= in_size
;
734 if (z
.avail_in
== 0) {
735 if (done_reading
&& state
!= GZSTATE_MAGIC0
)
736 maybe_warnx("%s: unexpected end of file",
742 if (*z
.next_in
!= GZIP_MAGIC0
) {
743 maybe_warnx("input not gziped (MAGIC0)");
750 crc
= crc32(0L, Z_NULL
, 0);
754 if (*z
.next_in
!= GZIP_MAGIC1
&&
755 *z
.next_in
!= GZIP_OMAGIC1
) {
756 maybe_warnx("input not gziped (MAGIC1)");
765 if (*z
.next_in
!= Z_DEFLATED
) {
766 maybe_warnx("unknown compression method");
781 case GZSTATE_SKIPPING
:
782 if (skip_count
> 0) {
790 if ((flags
& EXTRA_FIELD
) == 0) {
791 state
= GZSTATE_ORIGNAME
;
794 skip_count
= *z
.next_in
;
800 skip_count
|= ((*z
.next_in
) << 8);
806 if (skip_count
> 0) {
813 case GZSTATE_ORIGNAME
:
814 if ((flags
& ORIG_NAME
) == 0) {
823 case GZSTATE_COMMENT
:
824 if ((flags
& COMMENT
) == 0) {
833 case GZSTATE_HEAD_CRC1
:
834 if (flags
& HEAD_CRC
)
841 case GZSTATE_HEAD_CRC2
:
842 if (skip_count
> 0) {
850 if (inflateInit2(&z
, -MAX_WBITS
) != Z_OK
) {
851 maybe_warnx("failed to inflateInit");
859 error
= inflate(&z
, Z_FINISH
);
860 /* Z_BUF_ERROR goes with Z_FINISH... */
861 if (error
!= Z_STREAM_END
&& error
!= Z_BUF_ERROR
)
862 /* Just need more input */
864 wr
= BUFLEN
- z
.avail_out
;
867 crc
= crc32(crc
, (const Bytef
*)outbufp
, (unsigned)wr
);
870 /* don't write anything with -t */
873 write(out
, outbufp
, wr
) != wr
) {
874 maybe_warn("error writing to output");
883 if (error
== Z_STREAM_END
) {
888 z
.next_out
= outbufp
;
889 z
.avail_out
= BUFLEN
;
894 static int empty_buffer
= 0;
897 if (z
.avail_in
< 4) {
898 if (!done_reading
&& empty_buffer
++ < 4)
900 maybe_warnx("truncated input");
905 origcrc
= ((unsigned)z
.next_in
[0] & 0xff) |
906 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
907 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
908 ((unsigned)z
.next_in
[3] & 0xff) << 24;
909 if (origcrc
!= crc
) {
910 maybe_warnx("invalid compressed"
926 static int empty_buffer
= 0;
929 if (z
.avail_in
< 4) {
930 if (!done_reading
&& empty_buffer
++ < 4)
932 maybe_warnx("truncated input");
937 origlen
= ((unsigned)z
.next_in
[0] & 0xff) |
938 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
939 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
940 ((unsigned)z
.next_in
[3] & 0xff) << 24;
942 if (origlen
!= out_sub_tot
) {
943 maybe_warnx("invalid compressed"
944 " data--length error");
954 maybe_warnx("decompression error");
958 state
= GZSTATE_MAGIC0
;
965 if (state
> GZSTATE_INIT
)
970 print_test(filename
, out_tot
!= -1);
984 * set the owner, mode, flags & utimes for a file
987 copymodes(const char *file
, struct stat
*sbp
)
989 struct timeval times
[2];
992 * If we have no info on the input, give this file some
993 * default values and return..
996 mode_t mask
= umask(022);
998 (void)chmod(file
, DEFFILEMODE
& ~mask
);
1003 /* if the chown fails, remove set-id bits as-per compress(1) */
1004 if (chown(file
, sbp
->st_uid
, sbp
->st_gid
) < 0) {
1006 maybe_warn("couldn't chown: %s", file
);
1007 sbp
->st_mode
&= ~(S_ISUID
|S_ISGID
);
1010 /* we only allow set-id and the 9 normal permission bits */
1011 sbp
->st_mode
&= S_ISUID
| S_ISGID
| S_IRWXU
| S_IRWXG
| S_IRWXO
;
1012 if (chmod(file
, sbp
->st_mode
) < 0)
1013 maybe_warn("couldn't chmod: %s", file
);
1015 /* only try flags if they exist already */
1016 if (sbp
->st_flags
!= 0 && chflags(file
, sbp
->st_flags
) < 0)
1017 maybe_warn("couldn't chflags: %s", file
);
1019 TIMESPEC_TO_TIMEVAL(×
[0], &sbp
->st_atimespec
);
1020 TIMESPEC_TO_TIMEVAL(×
[1], &sbp
->st_mtimespec
);
1021 if (utimes(file
, times
) < 0)
1022 maybe_warn("couldn't utimes: %s", file
);
1026 /* what sort of file is this? */
1027 static enum filetype
1028 file_gettype(u_char
*buf
)
1031 if (buf
[0] == GZIP_MAGIC0
&&
1032 (buf
[1] == GZIP_MAGIC1
|| buf
[1] == GZIP_OMAGIC1
))
1035 #ifndef NO_BZIP2_SUPPORT
1036 if (memcmp(buf
, BZIP2_MAGIC
, 3) == 0 &&
1037 buf
[3] >= '0' && buf
[3] <= '9')
1041 #ifndef NO_COMPRESS_SUPPORT
1042 if (memcmp(buf
, Z_MAGIC
, 2) == 0)
1050 /* check the outfile is OK. */
1052 check_outfile(const char *outfile
, struct stat
*sb
)
1056 if (lflag
== 0 && stat(outfile
, sb
) == 0) {
1059 else if (isatty(STDIN_FILENO
)) {
1060 char ans
[10] = { 'n', '\0' }; /* default */
1062 fprintf(stderr
, "%s already exists -- do you wish to "
1063 "overwrite (y or n)? " , outfile
);
1064 (void)fgets(ans
, sizeof(ans
) - 1, stdin
);
1065 if (ans
[0] != 'y' && ans
[0] != 'Y') {
1066 fprintf(stderr
, "\tnot overwriting\n");
1071 maybe_warnx("%s already exists -- skipping", outfile
);
1079 unlink_input(const char *file
, struct stat
*sb
)
1086 if (stat(file
, &nsb
) != 0)
1087 /* Must be gone alrady */
1089 if (nsb
.st_dev
!= sb
->st_dev
|| nsb
.st_ino
!= sb
->st_ino
)
1090 /* Definitely a different file */
1096 static const suffixes_t
*
1097 check_suffix(char *file
, int xlate
)
1099 const suffixes_t
*s
;
1100 int len
= strlen(file
);
1103 for (s
= suffixes
; s
!= suffixes
+ NUM_SUFFIXES
; s
++) {
1104 /* if it doesn't fit in "a.suf", don't bother */
1105 if (s
->ziplen
>= len
)
1107 sp
= file
+ len
- s
->ziplen
;
1108 if (strcmp(s
->zipped
, sp
) != 0)
1111 strcpy(sp
, s
->normal
);
1118 * compress the given file: create a corresponding .gz file and remove the
1122 file_compress(char *file
, char *outfile
, size_t outsize
)
1128 struct stat isb
, osb
;
1129 const suffixes_t
*suff
;
1132 in
= open(file
, O_RDONLY
);
1134 maybe_warn("can't open %s", file
);
1140 if (stat(file
, &isb
) == 0) {
1141 if (isb
.st_nlink
> 1 && fflag
== 0) {
1142 maybe_warnx("%s has %d other link%s -- "
1143 "skipping", file
, isb
.st_nlink
- 1,
1144 isb
.st_nlink
== 1 ? "" : "s");
1150 if (fflag
== 0 && (suff
= check_suffix(file
, 0))
1151 && suff
->zipped
[0] != 0) {
1152 maybe_warnx("%s already has %s suffix -- unchanged",
1153 file
, suff
->zipped
);
1159 /* Add (usually) .gz to filename */
1160 if ((size_t)snprintf(outfile
, outsize
, "%s%s",
1161 file
, suffixes
[0].zipped
) >= outsize
)
1162 memcpy(outfile
- suffixes
[0].ziplen
- 1,
1163 suffixes
[0].zipped
, suffixes
[0].ziplen
+ 1);
1166 if (check_outfile(outfile
, &osb
) == 0) {
1174 out
= open(outfile
, O_WRONLY
| O_CREAT
| O_EXCL
, 0600);
1176 maybe_warn("could not create output: %s", outfile
);
1181 out
= STDOUT_FILENO
;
1183 insize
= gz_compress(in
, out
, &size
, basename(file
), (uint32_t)isb
.st_mtime
);
1188 * If there was an error, insize will be -1.
1189 * If we compressed to stdout, just return the size.
1190 * Otherwise stat the file and check it is the correct size.
1191 * We only blow away the file if we can stat the output and it
1192 * has the expected size.
1195 return insize
== -1 ? -1 : size
;
1197 if (close(out
) == -1)
1198 maybe_warn("couldn't close ouput");
1201 if (stat(outfile
, &osb
) < 0) {
1202 maybe_warn("couldn't stat: %s", outfile
);
1206 if (osb
.st_size
!= size
) {
1207 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1208 " != %" PRIdOFF
"), deleting",
1209 outfile
, osb
.st_size
, size
);
1213 copymodes(outfile
, &isb
);
1216 /* output is good, ok to delete input */
1217 unlink_input(file
, &isb
);
1222 maybe_warnx("leaving original %s", file
);
1228 /* uncompress the given file and remove the original */
1230 file_uncompress(char *file
, char *outfile
, size_t outsize
)
1232 struct stat isb
, osb
;
1235 unsigned char header1
[4];
1236 enum filetype method
;
1239 time_t timestamp
= 0;
1240 unsigned char name
[PATH_MAX
+ 1];
1243 /* gather the old name info */
1245 fd
= open(file
, O_RDONLY
);
1247 maybe_warn("can't open %s", file
);
1251 strlcpy(outfile
, file
, outsize
);
1252 if (check_suffix(outfile
, 1) == NULL
&& !(cflag
|| lflag
)) {
1253 maybe_warnx("%s: unknown suffix -- ignored", file
);
1257 rbytes
= read(fd
, header1
, sizeof header1
);
1258 if (rbytes
!= sizeof header1
) {
1259 /* we don't want to fail here. */
1265 maybe_warn("can't read %s", file
);
1267 maybe_warnx("%s: unexpected end of file", file
);
1271 method
= file_gettype(header1
);
1274 if (fflag
== 0 && method
== FT_UNKNOWN
) {
1275 maybe_warnx("%s: not in gzip format", file
);
1282 if (method
== FT_GZIP
&& Nflag
) {
1283 unsigned char ts
[4]; /* timestamp */
1285 if (pread(fd
, ts
, sizeof ts
, GZIP_TIMESTAMP
) != sizeof ts
) {
1287 maybe_warn("can't read %s", file
);
1290 timestamp
= ts
[3] << 24 | ts
[2] << 16 | ts
[1] << 8 | ts
[0];
1292 if (header1
[3] & ORIG_NAME
) {
1293 rbytes
= pread(fd
, name
, sizeof name
, GZIP_ORIGNAME
);
1295 maybe_warn("can't read %s", file
);
1299 /* preserve original directory name */
1300 char *dp
= strrchr(file
, '/');
1305 snprintf(outfile
, outsize
, "%.*s%.*s",
1307 file
, (int) rbytes
, name
);
1312 lseek(fd
, 0, SEEK_SET
);
1314 if (cflag
== 0 || lflag
) {
1315 if (fstat(fd
, &isb
) != 0)
1318 if (isb
.st_nlink
> 1 && lflag
== 0 && fflag
== 0) {
1319 maybe_warnx("%s has %d other links -- skipping",
1320 file
, isb
.st_nlink
- 1);
1323 if (nflag
== 0 && timestamp
)
1324 isb
.st_mtime
= timestamp
;
1325 if (check_outfile(outfile
, &osb
) == 0)
1330 if (cflag
== 0 && lflag
== 0) {
1331 zfd
= open(outfile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0600);
1332 if (zfd
== STDOUT_FILENO
) {
1333 /* We won't close STDOUT_FILENO later... */
1335 close(STDOUT_FILENO
);
1338 maybe_warn("can't open %s", outfile
);
1342 zfd
= STDOUT_FILENO
;
1344 #ifndef NO_BZIP2_SUPPORT
1345 if (method
== FT_BZIP2
) {
1349 maybe_warnx("no -l with bzip2 files");
1353 size
= unbzip2(fd
, zfd
, NULL
, 0, NULL
);
1357 #ifndef NO_COMPRESS_SUPPORT
1358 if (method
== FT_Z
) {
1363 maybe_warnx("no -l with Lempel-Ziv files");
1367 if ((in
= zdopen(fd
)) == NULL
) {
1368 maybe_warn("zdopen for read: %s", file
);
1372 out
= fdopen(dup(zfd
), "w");
1374 maybe_warn("fdopen for write: %s", outfile
);
1379 size
= zuncompress(in
, out
, NULL
, 0, NULL
);
1380 /* need to fclose() if ferror() is true... */
1381 if (ferror(in
) | fclose(in
)) {
1382 maybe_warn("failed infile fclose");
1386 if (fclose(out
) != 0) {
1387 maybe_warn("failed outfile fclose");
1395 if (method
== FT_UNKNOWN
) {
1397 maybe_warnx("no -l for unknown filetypes");
1400 size
= cat_fd(NULL
, 0, NULL
, fd
);
1405 print_list(fd
, isb
.st_size
, outfile
, isb
.st_mtime
);
1407 return -1; /* XXX */
1410 size
= gz_uncompress(fd
, zfd
, NULL
, 0, NULL
, file
);
1414 maybe_warn("couldn't close input");
1415 if (zfd
!= STDOUT_FILENO
&& close(zfd
) != 0)
1416 maybe_warn("couldn't close output");
1421 maybe_warnx("%s: uncompress failed", file
);
1425 /* if testing, or we uncompressed to stdout, this is all we need */
1430 /* if we are uncompressing to stdin, don't remove the file. */
1435 * if we create a file...
1438 * if we can't stat the file don't remove the file.
1440 if (stat(outfile
, &osb
) < 0) {
1441 maybe_warn("couldn't stat (leaving original): %s",
1445 if (osb
.st_size
!= size
) {
1446 maybe_warn("stat gave different size: %" PRIdOFF
1447 " != %" PRIdOFF
" (leaving original)",
1452 unlink_input(file
, &isb
);
1454 copymodes(outfile
, &isb
);
1461 if (zfd
!= -1 && zfd
!= STDOUT_FILENO
)
1468 cat_fd(unsigned char * prepend
, ssize_t count
, off_t
*gsizep
, int fd
)
1475 if (write(STDOUT_FILENO
, prepend
, count
) != count
) {
1476 maybe_warn("write to stdout");
1480 rv
= read(fd
, buf
, sizeof buf
);
1484 maybe_warn("read from fd %d", fd
);
1488 if (write(STDOUT_FILENO
, buf
, rv
) != rv
) {
1489 maybe_warn("write to stdout");
1504 unsigned char header1
[4];
1506 enum filetype method
;
1507 #ifndef NO_COMPRESS_SUPPORT
1512 if (fflag
== 0 && lflag
== 0 && isatty(STDIN_FILENO
)) {
1513 maybe_warnx("standard input is a terminal -- ignoring");
1521 /* XXX could read the whole file, etc. */
1522 if (fstat(STDIN_FILENO
, &isb
) < 0) {
1523 maybe_warn("fstat");
1526 print_list(STDIN_FILENO
, isb
.st_size
, "stdout", isb
.st_mtime
);
1530 if (read(STDIN_FILENO
, header1
, sizeof header1
) != sizeof header1
) {
1531 maybe_warn("can't read stdin");
1535 method
= file_gettype(header1
);
1540 maybe_warnx("unknown compression format");
1543 usize
= cat_fd(header1
, sizeof header1
, &gsize
, STDIN_FILENO
);
1547 usize
= gz_uncompress(STDIN_FILENO
, STDOUT_FILENO
,
1548 header1
, sizeof header1
, &gsize
, "(stdin)");
1550 #ifndef NO_BZIP2_SUPPORT
1552 usize
= unbzip2(STDIN_FILENO
, STDOUT_FILENO
,
1553 header1
, sizeof header1
, &gsize
);
1556 #ifndef NO_COMPRESS_SUPPORT
1558 if ((in
= zdopen(STDIN_FILENO
)) == NULL
) {
1559 maybe_warnx("zopen of stdin");
1563 usize
= zuncompress(in
, stdout
, header1
, sizeof header1
, &gsize
);
1570 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1571 print_verbage(NULL
, NULL
, usize
, gsize
);
1582 if (fflag
== 0 && isatty(STDOUT_FILENO
)) {
1583 maybe_warnx("standard output is a terminal -- ignoring");
1587 usize
= gz_compress(STDIN_FILENO
, STDOUT_FILENO
, &gsize
, "", 0);
1590 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1591 print_verbage(NULL
, NULL
, usize
, gsize
);
1595 /* do what is asked for, for the path name */
1597 handle_pathname(char *path
)
1599 char *opath
= path
, *s
= NULL
;
1604 /* check for stdout/stdin */
1605 if (path
[0] == '-' && path
[1] == '\0') {
1614 if (stat(path
, &sb
) < 0) {
1615 /* lets try <path>.gz if we're decompressing */
1616 if (dflag
&& s
== NULL
&& errno
== ENOENT
) {
1618 slen
= suffixes
[0].ziplen
;
1619 s
= malloc(len
+ slen
+ 1);
1621 maybe_err("malloc");
1622 memcpy(s
, path
, len
);
1623 memcpy(s
+ len
, suffixes
[0].zipped
, slen
+ 1);
1627 maybe_warn("can't stat: %s", opath
);
1631 if (S_ISDIR(sb
.st_mode
)) {
1637 maybe_warnx("%s is a directory", path
);
1641 if (S_ISREG(sb
.st_mode
))
1642 handle_file(path
, &sb
);
1644 maybe_warnx("%s is not a regular file", path
);
1651 /* compress/decompress a file */
1653 handle_file(char *file
, struct stat
*sbp
)
1656 char outfile
[PATH_MAX
];
1660 usize
= file_uncompress(file
, outfile
, sizeof(outfile
));
1663 gsize
= sbp
->st_size
;
1665 gsize
= file_compress(file
, outfile
, sizeof(outfile
));
1668 usize
= sbp
->st_size
;
1673 if (vflag
&& !tflag
)
1674 print_verbage(file
, (cflag
) ? NULL
: outfile
, usize
, gsize
);
1679 /* this is used with -r to recursively descend directories */
1681 handle_dir(char *dir
)
1689 fts
= fts_open(path_argv
, FTS_PHYSICAL
| FTS_NOCHDIR
, NULL
);
1691 warn("couldn't fts_open %s", dir
);
1695 while ((entry
= fts_read(fts
))) {
1696 switch(entry
->fts_info
) {
1704 maybe_warn("%s", entry
->fts_path
);
1707 handle_file(entry
->fts_path
, entry
->fts_statp
);
1710 (void)fts_close(fts
);
1714 /* print a ratio - size reduction as a fraction of uncompressed size */
1716 print_ratio(off_t in
, off_t out
, FILE *where
)
1718 int percent10
; /* 10 * percent */
1726 * Output is more than double size of input! print -99.9%
1727 * Quite possibly we've failed to get the original size.
1732 * We only need 12 bits of result from the final division,
1733 * so reduce the values until a 32bit division will suffice.
1735 while (in
> 0x100000) {
1740 percent10
= ((u_int
)diff
* 2000) / (u_int
)in
- 1000;
1745 len
= snprintf(buff
, sizeof buff
, "%2.2d.", percent10
);
1746 /* Move the '.' to before the last digit */
1747 buff
[len
- 1] = buff
[len
- 2];
1748 buff
[len
- 2] = '.';
1749 fprintf(where
, "%5s%%", buff
);
1753 /* print compression statistics, and the new name (if there is one!) */
1755 print_verbage(const char *file
, const char *nfile
, off_t usize
, off_t gsize
)
1758 fprintf(stderr
, "%s:%s ", file
,
1759 strlen(file
) < 7 ? "\t\t" : "\t");
1760 print_ratio(usize
, gsize
, stderr
);
1762 fprintf(stderr
, " -- replaced with %s", nfile
);
1763 fprintf(stderr
, "\n");
1767 /* print test results */
1769 print_test(const char *file
, int ok
)
1772 if (exit_value
== 0 && ok
== 0)
1774 fprintf(stderr
, "%s:%s %s\n", file
,
1775 strlen(file
) < 7 ? "\t\t" : "\t", ok
? "OK" : "NOT OK");
1780 /* print a file's info ala --list */
1782 compressed uncompressed ratio uncompressed_name
1783 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1786 print_list(int fd
, off_t out
, const char *outfile
, time_t ts
)
1788 static int first
= 1;
1790 static off_t in_tot
, out_tot
;
1799 printf("method crc date time ");
1802 printf(" compressed uncompressed "
1803 "ratio uncompressed_name\n");
1815 /* read the last 4 bytes - this is the uncompressed size */
1816 rv
= lseek(fd
, (off_t
)(-8), SEEK_END
);
1818 unsigned char buf
[8];
1821 if (read(fd
, (char *)buf
, sizeof(buf
)) != sizeof(buf
))
1822 maybe_warn("read of uncompressed size");
1823 usize
= buf
[4] | buf
[5] << 8 | buf
[6] << 16 | buf
[7] << 24;
1826 crc
= buf
[0] | buf
[1] << 8 | buf
[2] << 16 | buf
[3] << 24;
1832 if (vflag
&& fd
== -1)
1835 char *date
= ctime(&ts
);
1837 /* skip the day, 1/100th second, and year */
1840 printf("%5s %08x %11s ", "defla"/*XXX*/, crc
, date
);
1845 printf("%12llu %12llu ", (unsigned long long)out
, (unsigned long long)in
);
1846 print_ratio(in
, out
, stdout
);
1847 printf(" %s\n", outfile
);
1850 /* display the usage of NetBSD gzip */
1855 fprintf(stderr
, "%s\n", gzip_version
);
1858 "usage: %s [-" OPT_LIST
"] [<file> [<file> ...]]\n",
1860 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
1861 " -c --stdout write to stdout, keep original files\n"
1863 " -d --decompress uncompress files\n"
1865 " -f --force force overwriting & compress links\n"
1866 " -h --help display this help\n"
1867 " -k --keep don't delete input files during operation\n"
1868 " -n --no-name don't save original file name or time stamp\n"
1869 " -N --name save or restore original file name and time stamp\n"
1870 " -q --quiet output no warnings\n"
1871 " -r --recursive recursively compress files in directories\n"
1872 " -S .suf use suffix .suf instead of .gz\n"
1874 " -t --test test compressed file\n"
1875 " -v --verbose print extra statistics\n"
1876 " -V --version display program version\n"
1877 " -1 --fast fastest (worst) compression\n"
1878 " -2 .. -8 set compression level\n"
1879 " -9 --best best (slowest) compression\n",
1885 /* display the version of NetBSD gzip */
1887 display_version(void)
1890 fprintf(stderr
, "%s\n", gzip_version
);
1894 #ifndef NO_BZIP2_SUPPORT
1895 #include "unbzip2.c"
1897 #ifndef NO_COMPRESS_SUPPORT
1898 #include "zuncompress.c"