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.6 2006/10/25 08:27:27 swildner 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 nflag
; /* don't save name/timestamp */
152 static int Nflag
; /* don't restore name/timestamp */
153 static int qflag
; /* quiet mode */
154 static int rflag
; /* recursive mode */
155 static int tflag
; /* test */
156 static int vflag
; /* verbose mode */
162 static int exit_value
= 0; /* exit value */
164 static char *infile
; /* name of file coming in */
166 static void maybe_err(const char *fmt
, ...)
167 __attribute__((__format__(__printf__
, 1, 2)));
168 #ifndef NO_BZIP2_SUPPORT
169 static void maybe_errx(const char *fmt
, ...)
170 __attribute__((__format__(__printf__
, 1, 2)));
172 static void maybe_warn(const char *fmt
, ...)
173 __attribute__((__format__(__printf__
, 1, 2)));
174 static void maybe_warnx(const char *fmt
, ...)
175 __attribute__((__format__(__printf__
, 1, 2)));
176 static enum filetype
file_gettype(u_char
*);
178 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
180 static off_t
gz_compress(int, int, off_t
*, const char *, uint32_t);
181 static off_t
gz_uncompress(int, int, char *, size_t, off_t
*, const char *);
182 static off_t
file_compress(char *, char *, size_t);
183 static off_t
file_uncompress(char *, char *, size_t);
184 static void handle_pathname(char *);
185 static void handle_file(char *, struct stat
*);
186 static void handle_stdin(void);
187 static void handle_stdout(void);
188 static void print_ratio(off_t
, off_t
, FILE *);
189 static void print_list(int fd
, off_t
, const char *, time_t);
190 static void usage(void);
191 static void display_version(void);
192 static const suffixes_t
*check_suffix(char *, int);
195 #define unlink_input(f, sb) unlink(f)
197 static off_t
cat_fd(unsigned char *, ssize_t
, off_t
*, int fd
);
198 static void prepend_gzip(char *, int *, char ***);
199 static void handle_dir(char *);
200 static void print_verbage(const char *, const char *, off_t
, off_t
);
201 static void print_test(const char *, int);
202 static void copymodes(const char *, struct stat
*);
203 static int check_outfile(const char *outfile
, struct stat
*sb
);
206 #ifndef NO_BZIP2_SUPPORT
207 static off_t
unbzip2(int, int, char *, size_t, off_t
*);
210 #ifndef NO_COMPRESS_SUPPORT
211 static FILE *zdopen(int);
212 static off_t
zuncompress(FILE *, FILE *, char *, size_t, off_t
*);
215 int main(int, char *p
[]);
218 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
220 static const struct option longopts
[] = {
221 { "stdout", no_argument
, 0, 'c' },
222 { "to-stdout", no_argument
, 0, 'c' },
223 { "decompress", no_argument
, 0, 'd' },
224 { "uncompress", no_argument
, 0, 'd' },
225 { "force", no_argument
, 0, 'f' },
226 { "help", no_argument
, 0, 'h' },
227 { "list", no_argument
, 0, 'l' },
228 { "no-name", no_argument
, 0, 'n' },
229 { "name", no_argument
, 0, 'N' },
230 { "quiet", no_argument
, 0, 'q' },
231 { "recursive", no_argument
, 0, 'r' },
232 { "suffix", required_argument
, 0, 'S' },
233 { "test", no_argument
, 0, 't' },
234 { "verbose", no_argument
, 0, 'v' },
235 { "version", no_argument
, 0, 'V' },
236 { "fast", no_argument
, 0, '1' },
237 { "best", no_argument
, 0, '9' },
240 * This is what else GNU gzip implements. --ascii isn't useful
241 * on NetBSD, and I don't care to have a --license.
243 { "ascii", no_argument
, 0, 'a' },
244 { "license", no_argument
, 0, 'L' },
246 { NULL
, no_argument
, 0, 0 },
251 main(int argc
, char **argv
)
253 const char *progname
= getprogname();
260 /* XXX set up signals */
263 if ((gzip
= getenv("GZIP")) != NULL
)
264 prepend_gzip(gzip
, &argc
, &argv
);
269 * handle being called `gunzip', `zcat' and `gzcat'
271 if (strcmp(progname
, "gunzip") == 0)
273 else if (strcmp(progname
, "zcat") == 0 ||
274 strcmp(progname
, "gzcat") == 0)
278 #define OPT_LIST "cdhHltV123456789"
280 #define OPT_LIST "cdfhHlnNqrS:tvV123456789"
283 while ((ch
= getopt_long(argc
, argv
, OPT_LIST
, longopts
, NULL
)) != -1) {
298 case '1': case '2': case '3':
299 case '4': case '5': case '6':
300 case '7': case '8': case '9':
322 len
= strlen(optarg
);
324 suffixes
[0].zipped
= optarg
;
325 suffixes
[0].ziplen
= len
;
327 suffixes
[NUM_SUFFIXES
- 1].zipped
= "";
328 suffixes
[NUM_SUFFIXES
- 1].ziplen
= 0;
349 if (dflag
) /* stdin mode */
351 else /* stdout mode */
355 handle_pathname(argv
[0]);
359 if (qflag
== 0 && lflag
&& argc
> 1)
360 print_list(-1, 0, "(totals)", 0);
365 /* maybe print a warning */
367 maybe_warn(const char *fmt
, ...)
380 /* ... without an errno. */
382 maybe_warnx(const char *fmt
, ...)
395 /* maybe print an error */
397 maybe_err(const char *fmt
, ...)
409 #ifndef NO_BZIP2_SUPPORT
410 /* ... without an errno. */
412 maybe_errx(const char *fmt
, ...)
426 /* split up $GZIP and prepend it to the argument list */
428 prepend_gzip(char *gzip
, int *argc
, char ***argv
)
430 char *s
, **nargv
, **ac
;
433 /* scan how many arguments there are */
435 while (*s
== ' ' || *s
== '\t')
440 while (*s
!= ' ' && *s
!= '\t')
452 nargv
= (char **)malloc((*argc
+ 1) * sizeof(char *));
456 /* stash this away */
459 /* copy the program name first */
461 nargv
[i
++] = *(ac
++);
463 /* take a copy of $GZIP and add it to the array */
468 /* Skip whitespaces. */
469 while (*s
== ' ' || *s
== '\t')
474 /* Find the end of this argument. */
475 while (*s
!= ' ' && *s
!= '\t')
477 /* Argument followed by NUL. */
479 /* Terminate by overwriting ' ' or '\t' with NUL. */
484 /* copy the original arguments and a NULL */
486 nargv
[i
++] = *(ac
++);
491 /* compress input to output. Return bytes read, -1 on error */
493 gz_compress(int in
, int out
, off_t
*gsizep
, const char *origname
, uint32_t mtime
)
496 char *outbufp
, *inbufp
;
497 off_t in_tot
= 0, out_tot
= 0;
502 static char header
[] = { GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
, 0,
507 outbufp
= malloc(BUFLEN
);
508 inbufp
= malloc(BUFLEN
);
509 if (outbufp
== NULL
|| inbufp
== NULL
) {
510 maybe_err("malloc failed");
514 memset(&z
, 0, sizeof z
);
520 memcpy(outbufp
, header
, sizeof header
);
528 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c%c%c%s",
529 GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
,
530 *origname
? ORIG_NAME
: 0,
533 (mtime
>> 16) & 0xff,
534 (mtime
>> 24) & 0xff,
535 numflag
== 1 ? 4 : numflag
== 9 ? 2 : 0,
538 /* this need PATH_MAX > BUFLEN ... */
539 maybe_err("snprintf");
544 z
.next_out
= outbufp
+ i
;
545 z
.avail_out
= BUFLEN
- i
;
547 error
= deflateInit2(&z
, numflag
, Z_DEFLATED
,
548 -MAX_WBITS
, 8, Z_DEFAULT_STRATEGY
);
550 maybe_warnx("deflateInit2 failed");
555 crc
= crc32(0L, Z_NULL
, 0);
557 if (z
.avail_out
== 0) {
558 if (write(out
, outbufp
, BUFLEN
) != BUFLEN
) {
565 z
.next_out
= outbufp
;
566 z
.avail_out
= BUFLEN
;
569 if (z
.avail_in
== 0) {
570 in_size
= read(in
, inbufp
, BUFLEN
);
579 crc
= crc32(crc
, (const Bytef
*)inbufp
, (unsigned)in_size
);
582 z
.avail_in
= in_size
;
585 error
= deflate(&z
, Z_NO_FLUSH
);
586 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
587 maybe_warnx("deflate failed");
597 error
= deflate(&z
, Z_FINISH
);
598 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
599 maybe_warnx("deflate failed");
604 len
= (char *)z
.next_out
- outbufp
;
606 if (write(out
, outbufp
, len
) != len
) {
612 z
.next_out
= outbufp
;
613 z
.avail_out
= BUFLEN
;
615 if (error
== Z_STREAM_END
)
619 if (deflateEnd(&z
) != Z_OK
) {
620 maybe_warnx("deflateEnd failed");
625 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c",
627 (int)(crc
>> 8) & 0xff,
628 (int)(crc
>> 16) & 0xff,
629 (int)(crc
>> 24) & 0xff,
631 (int)(in_tot
>> 8) & 0xff,
632 (int)(in_tot
>> 16) & 0xff,
633 (int)(in_tot
>> 24) & 0xff);
635 maybe_err("snprintf");
636 if (write(out
, outbufp
, i
) != i
) {
653 * uncompress input to output then close the input. return the
654 * uncompressed size written, and put the compressed sized read
658 gz_uncompress(int in
, int out
, char *pre
, size_t prelen
, off_t
*gsizep
,
659 const char *filename
)
662 char *outbufp
, *inbufp
;
663 off_t out_tot
= prelen
, in_tot
= 0;
664 uint32_t out_sub_tot
= 0;
682 } state
= GZSTATE_MAGIC0
;
683 int flags
= 0, skip_count
= 0;
684 int error
= 0, done_reading
= 0;
688 #define ADVANCE() { z.next_in++; z.avail_in--; }
690 if ((outbufp
= malloc(BUFLEN
)) == NULL
) {
691 maybe_err("malloc failed");
694 if ((inbufp
= malloc(BUFLEN
)) == NULL
) {
695 maybe_err("malloc failed");
699 memset(&z
, 0, sizeof z
);
702 z
.avail_out
= BUFLEN
;
703 z
.next_out
= outbufp
;
710 if (z
.avail_in
== 0 && done_reading
== 0) {
711 ssize_t in_size
= read(in
, inbufp
, BUFLEN
);
716 print_test(filename
, 0);
718 maybe_warn("failed to read stdin");
721 } else if (in_size
== 0)
724 z
.avail_in
= in_size
;
729 if (z
.avail_in
== 0) {
730 if (done_reading
&& state
!= GZSTATE_MAGIC0
)
731 maybe_warnx("%s: unexpected end of file",
737 if (*z
.next_in
!= GZIP_MAGIC0
) {
738 maybe_warnx("input not gziped (MAGIC0)");
745 crc
= crc32(0L, Z_NULL
, 0);
749 if (*z
.next_in
!= GZIP_MAGIC1
&&
750 *z
.next_in
!= GZIP_OMAGIC1
) {
751 maybe_warnx("input not gziped (MAGIC1)");
760 if (*z
.next_in
!= Z_DEFLATED
) {
761 maybe_warnx("unknown compression method");
776 case GZSTATE_SKIPPING
:
777 if (skip_count
> 0) {
785 if ((flags
& EXTRA_FIELD
) == 0) {
786 state
= GZSTATE_ORIGNAME
;
789 skip_count
= *z
.next_in
;
795 skip_count
|= ((*z
.next_in
) << 8);
801 if (skip_count
> 0) {
808 case GZSTATE_ORIGNAME
:
809 if ((flags
& ORIG_NAME
) == 0) {
818 case GZSTATE_COMMENT
:
819 if ((flags
& COMMENT
) == 0) {
828 case GZSTATE_HEAD_CRC1
:
829 if (flags
& HEAD_CRC
)
836 case GZSTATE_HEAD_CRC2
:
837 if (skip_count
> 0) {
845 if (inflateInit2(&z
, -MAX_WBITS
) != Z_OK
) {
846 maybe_warnx("failed to inflateInit");
854 error
= inflate(&z
, Z_FINISH
);
855 /* Z_BUF_ERROR goes with Z_FINISH... */
856 if (error
!= Z_STREAM_END
&& error
!= Z_BUF_ERROR
)
857 /* Just need more input */
859 wr
= BUFLEN
- z
.avail_out
;
862 crc
= crc32(crc
, (const Bytef
*)outbufp
, (unsigned)wr
);
865 /* don't write anything with -t */
868 write(out
, outbufp
, wr
) != wr
) {
869 maybe_warn("error writing to output");
878 if (error
== Z_STREAM_END
) {
883 z
.next_out
= outbufp
;
884 z
.avail_out
= BUFLEN
;
889 static int empty_buffer
= 0;
892 if (z
.avail_in
< 4) {
893 if (!done_reading
&& empty_buffer
++ < 4)
895 maybe_warnx("truncated input");
900 origcrc
= ((unsigned)z
.next_in
[0] & 0xff) |
901 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
902 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
903 ((unsigned)z
.next_in
[3] & 0xff) << 24;
904 if (origcrc
!= crc
) {
905 maybe_warnx("invalid compressed"
921 static int empty_buffer
= 0;
924 if (z
.avail_in
< 4) {
925 if (!done_reading
&& empty_buffer
++ < 4)
927 maybe_warnx("truncated input");
932 origlen
= ((unsigned)z
.next_in
[0] & 0xff) |
933 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
934 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
935 ((unsigned)z
.next_in
[3] & 0xff) << 24;
937 if (origlen
!= out_sub_tot
) {
938 maybe_warnx("invalid compressed"
939 " data--length error");
949 maybe_warnx("decompression error");
953 state
= GZSTATE_MAGIC0
;
960 if (state
> GZSTATE_INIT
)
965 print_test(filename
, out_tot
!= -1);
979 * set the owner, mode, flags & utimes for a file
982 copymodes(const char *file
, struct stat
*sbp
)
984 struct timeval times
[2];
987 * If we have no info on the input, give this file some
988 * default values and return..
991 mode_t mask
= umask(022);
993 (void)chmod(file
, DEFFILEMODE
& ~mask
);
998 /* if the chown fails, remove set-id bits as-per compress(1) */
999 if (chown(file
, sbp
->st_uid
, sbp
->st_gid
) < 0) {
1001 maybe_warn("couldn't chown: %s", file
);
1002 sbp
->st_mode
&= ~(S_ISUID
|S_ISGID
);
1005 /* we only allow set-id and the 9 normal permission bits */
1006 sbp
->st_mode
&= S_ISUID
| S_ISGID
| S_IRWXU
| S_IRWXG
| S_IRWXO
;
1007 if (chmod(file
, sbp
->st_mode
) < 0)
1008 maybe_warn("couldn't chmod: %s", file
);
1010 /* only try flags if they exist already */
1011 if (sbp
->st_flags
!= 0 && chflags(file
, sbp
->st_flags
) < 0)
1012 maybe_warn("couldn't chflags: %s", file
);
1014 TIMESPEC_TO_TIMEVAL(×
[0], &sbp
->st_atimespec
);
1015 TIMESPEC_TO_TIMEVAL(×
[1], &sbp
->st_mtimespec
);
1016 if (utimes(file
, times
) < 0)
1017 maybe_warn("couldn't utimes: %s", file
);
1021 /* what sort of file is this? */
1022 static enum filetype
1023 file_gettype(u_char
*buf
)
1026 if (buf
[0] == GZIP_MAGIC0
&&
1027 (buf
[1] == GZIP_MAGIC1
|| buf
[1] == GZIP_OMAGIC1
))
1030 #ifndef NO_BZIP2_SUPPORT
1031 if (memcmp(buf
, BZIP2_MAGIC
, 3) == 0 &&
1032 buf
[3] >= '0' && buf
[3] <= '9')
1036 #ifndef NO_COMPRESS_SUPPORT
1037 if (memcmp(buf
, Z_MAGIC
, 2) == 0)
1045 /* check the outfile is OK. */
1047 check_outfile(const char *outfile
, struct stat
*sb
)
1051 if (lflag
== 0 && stat(outfile
, sb
) == 0) {
1054 else if (isatty(STDIN_FILENO
)) {
1055 char ans
[10] = { 'n', '\0' }; /* default */
1057 fprintf(stderr
, "%s already exists -- do you wish to "
1058 "overwrite (y or n)? " , outfile
);
1059 (void)fgets(ans
, sizeof(ans
) - 1, stdin
);
1060 if (ans
[0] != 'y' && ans
[0] != 'Y') {
1061 fprintf(stderr
, "\tnot overwriting\n");
1066 maybe_warnx("%s already exists -- skipping", outfile
);
1074 unlink_input(const char *file
, struct stat
*sb
)
1078 if (stat(file
, &nsb
) != 0)
1079 /* Must be gone alrady */
1081 if (nsb
.st_dev
!= sb
->st_dev
|| nsb
.st_ino
!= sb
->st_ino
)
1082 /* Definitely a different file */
1088 static const suffixes_t
*
1089 check_suffix(char *file
, int xlate
)
1091 const suffixes_t
*s
;
1092 int len
= strlen(file
);
1095 for (s
= suffixes
; s
!= suffixes
+ NUM_SUFFIXES
; s
++) {
1096 /* if it doesn't fit in "a.suf", don't bother */
1097 if (s
->ziplen
>= len
)
1099 sp
= file
+ len
- s
->ziplen
;
1100 if (strcmp(s
->zipped
, sp
) != 0)
1103 strcpy(sp
, s
->normal
);
1110 * compress the given file: create a corresponding .gz file and remove the
1114 file_compress(char *file
, char *outfile
, size_t outsize
)
1120 struct stat isb
, osb
;
1121 const suffixes_t
*suff
;
1124 in
= open(file
, O_RDONLY
);
1126 maybe_warn("can't open %s", file
);
1132 if (stat(file
, &isb
) == 0) {
1133 if (isb
.st_nlink
> 1 && fflag
== 0) {
1134 maybe_warnx("%s has %d other link%s -- "
1135 "skipping", file
, isb
.st_nlink
- 1,
1136 isb
.st_nlink
== 1 ? "" : "s");
1142 if (fflag
== 0 && (suff
= check_suffix(file
, 0))
1143 && suff
->zipped
[0] != 0) {
1144 maybe_warnx("%s already has %s suffix -- unchanged",
1145 file
, suff
->zipped
);
1151 /* Add (usually) .gz to filename */
1152 if ((size_t)snprintf(outfile
, outsize
, "%s%s",
1153 file
, suffixes
[0].zipped
) >= outsize
)
1154 memcpy(outfile
- suffixes
[0].ziplen
- 1,
1155 suffixes
[0].zipped
, suffixes
[0].ziplen
+ 1);
1158 if (check_outfile(outfile
, &osb
) == 0) {
1166 out
= open(outfile
, O_WRONLY
| O_CREAT
| O_EXCL
, 0600);
1168 maybe_warn("could not create output: %s", outfile
);
1173 out
= STDOUT_FILENO
;
1175 insize
= gz_compress(in
, out
, &size
, basename(file
), (uint32_t)isb
.st_mtime
);
1180 * If there was an error, insize will be -1.
1181 * If we compressed to stdout, just return the size.
1182 * Otherwise stat the file and check it is the correct size.
1183 * We only blow away the file if we can stat the output and it
1184 * has the expected size.
1187 return insize
== -1 ? -1 : size
;
1189 if (close(out
) == -1)
1190 maybe_warn("couldn't close ouput");
1193 if (stat(outfile
, &osb
) < 0) {
1194 maybe_warn("couldn't stat: %s", outfile
);
1198 if (osb
.st_size
!= size
) {
1199 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1200 " != %" PRIdOFF
"), deleting",
1201 outfile
, osb
.st_size
, size
);
1205 copymodes(outfile
, &isb
);
1208 /* output is good, ok to delete input */
1209 unlink_input(file
, &isb
);
1214 maybe_warnx("leaving original %s", file
);
1220 /* uncompress the given file and remove the original */
1222 file_uncompress(char *file
, char *outfile
, size_t outsize
)
1224 struct stat isb
, osb
;
1227 unsigned char header1
[4];
1228 enum filetype method
;
1231 time_t timestamp
= 0;
1232 unsigned char name
[PATH_MAX
+ 1];
1235 /* gather the old name info */
1237 fd
= open(file
, O_RDONLY
);
1239 maybe_warn("can't open %s", file
);
1243 strlcpy(outfile
, file
, outsize
);
1244 if (check_suffix(outfile
, 1) == NULL
&& !(cflag
|| lflag
)) {
1245 maybe_warnx("%s: unknown suffix -- ignored", file
);
1249 rbytes
= read(fd
, header1
, sizeof header1
);
1250 if (rbytes
!= sizeof header1
) {
1251 /* we don't want to fail here. */
1257 maybe_warn("can't read %s", file
);
1259 maybe_warnx("%s: unexpected end of file", file
);
1263 method
= file_gettype(header1
);
1266 if (fflag
== 0 && method
== FT_UNKNOWN
) {
1267 maybe_warnx("%s: not in gzip format", file
);
1274 if (method
== FT_GZIP
&& Nflag
) {
1275 unsigned char ts
[4]; /* timestamp */
1277 if (pread(fd
, ts
, sizeof ts
, GZIP_TIMESTAMP
) != sizeof ts
) {
1279 maybe_warn("can't read %s", file
);
1282 timestamp
= ts
[3] << 24 | ts
[2] << 16 | ts
[1] << 8 | ts
[0];
1284 if (header1
[3] & ORIG_NAME
) {
1285 rbytes
= pread(fd
, name
, sizeof name
, GZIP_ORIGNAME
);
1287 maybe_warn("can't read %s", file
);
1291 /* preserve original directory name */
1292 char *dp
= strrchr(file
, '/');
1297 snprintf(outfile
, outsize
, "%.*s%.*s",
1299 file
, (int) rbytes
, name
);
1304 lseek(fd
, 0, SEEK_SET
);
1306 if (cflag
== 0 || lflag
) {
1307 if (fstat(fd
, &isb
) != 0)
1310 if (isb
.st_nlink
> 1 && lflag
== 0 && fflag
== 0) {
1311 maybe_warnx("%s has %d other links -- skipping",
1312 file
, isb
.st_nlink
- 1);
1315 if (nflag
== 0 && timestamp
)
1316 isb
.st_mtime
= timestamp
;
1317 if (check_outfile(outfile
, &osb
) == 0)
1322 if (cflag
== 0 && lflag
== 0) {
1323 zfd
= open(outfile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0600);
1324 if (zfd
== STDOUT_FILENO
) {
1325 /* We won't close STDOUT_FILENO later... */
1327 close(STDOUT_FILENO
);
1330 maybe_warn("can't open %s", outfile
);
1334 zfd
= STDOUT_FILENO
;
1336 #ifndef NO_BZIP2_SUPPORT
1337 if (method
== FT_BZIP2
) {
1341 maybe_warnx("no -l with bzip2 files");
1345 size
= unbzip2(fd
, zfd
, NULL
, 0, NULL
);
1349 #ifndef NO_COMPRESS_SUPPORT
1350 if (method
== FT_Z
) {
1355 maybe_warnx("no -l with Lempel-Ziv files");
1359 if ((in
= zdopen(fd
)) == NULL
) {
1360 maybe_warn("zdopen for read: %s", file
);
1364 out
= fdopen(dup(zfd
), "w");
1366 maybe_warn("fdopen for write: %s", outfile
);
1371 size
= zuncompress(in
, out
, NULL
, 0, NULL
);
1372 /* need to fclose() if ferror() is true... */
1373 if (ferror(in
) | fclose(in
)) {
1374 maybe_warn("failed infile fclose");
1378 if (fclose(out
) != 0) {
1379 maybe_warn("failed outfile fclose");
1387 if (method
== FT_UNKNOWN
) {
1389 maybe_warnx("no -l for unknown filetypes");
1392 size
= cat_fd(NULL
, 0, NULL
, fd
);
1397 print_list(fd
, isb
.st_size
, outfile
, isb
.st_mtime
);
1399 return -1; /* XXX */
1402 size
= gz_uncompress(fd
, zfd
, NULL
, 0, NULL
, file
);
1406 maybe_warn("couldn't close input");
1407 if (zfd
!= STDOUT_FILENO
&& close(zfd
) != 0)
1408 maybe_warn("couldn't close output");
1413 maybe_warnx("%s: uncompress failed", file
);
1417 /* if testing, or we uncompressed to stdout, this is all we need */
1422 /* if we are uncompressing to stdin, don't remove the file. */
1427 * if we create a file...
1430 * if we can't stat the file don't remove the file.
1432 if (stat(outfile
, &osb
) < 0) {
1433 maybe_warn("couldn't stat (leaving original): %s",
1437 if (osb
.st_size
!= size
) {
1438 maybe_warn("stat gave different size: %" PRIdOFF
1439 " != %" PRIdOFF
" (leaving original)",
1444 unlink_input(file
, &isb
);
1446 copymodes(outfile
, &isb
);
1453 if (zfd
!= -1 && zfd
!= STDOUT_FILENO
)
1460 cat_fd(unsigned char * prepend
, ssize_t count
, off_t
*gsizep
, int fd
)
1467 if (write(STDOUT_FILENO
, prepend
, count
) != count
) {
1468 maybe_warn("write to stdout");
1472 rv
= read(fd
, buf
, sizeof buf
);
1476 maybe_warn("read from fd %d", fd
);
1480 if (write(STDOUT_FILENO
, buf
, rv
) != rv
) {
1481 maybe_warn("write to stdout");
1496 unsigned char header1
[4];
1498 enum filetype method
;
1499 #ifndef NO_COMPRESS_SUPPORT
1504 if (fflag
== 0 && lflag
== 0 && isatty(STDIN_FILENO
)) {
1505 maybe_warnx("standard input is a terminal -- ignoring");
1513 /* XXX could read the whole file, etc. */
1514 if (fstat(STDIN_FILENO
, &isb
) < 0) {
1515 maybe_warn("fstat");
1518 print_list(STDIN_FILENO
, isb
.st_size
, "stdout", isb
.st_mtime
);
1522 if (read(STDIN_FILENO
, header1
, sizeof header1
) != sizeof header1
) {
1523 maybe_warn("can't read stdin");
1527 method
= file_gettype(header1
);
1532 maybe_warnx("unknown compression format");
1535 usize
= cat_fd(header1
, sizeof header1
, &gsize
, STDIN_FILENO
);
1539 usize
= gz_uncompress(STDIN_FILENO
, STDOUT_FILENO
,
1540 header1
, sizeof header1
, &gsize
, "(stdin)");
1542 #ifndef NO_BZIP2_SUPPORT
1544 usize
= unbzip2(STDIN_FILENO
, STDOUT_FILENO
,
1545 header1
, sizeof header1
, &gsize
);
1548 #ifndef NO_COMPRESS_SUPPORT
1550 if ((in
= zdopen(STDIN_FILENO
)) == NULL
) {
1551 maybe_warnx("zopen of stdin");
1555 usize
= zuncompress(in
, stdout
, header1
, sizeof header1
, &gsize
);
1562 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1563 print_verbage(NULL
, NULL
, usize
, gsize
);
1574 if (fflag
== 0 && isatty(STDOUT_FILENO
)) {
1575 maybe_warnx("standard output is a terminal -- ignoring");
1579 usize
= gz_compress(STDIN_FILENO
, STDOUT_FILENO
, &gsize
, "", 0);
1582 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1583 print_verbage(NULL
, NULL
, usize
, gsize
);
1587 /* do what is asked for, for the path name */
1589 handle_pathname(char *path
)
1591 char *opath
= path
, *s
= NULL
;
1596 /* check for stdout/stdin */
1597 if (path
[0] == '-' && path
[1] == '\0') {
1606 if (stat(path
, &sb
) < 0) {
1607 /* lets try <path>.gz if we're decompressing */
1608 if (dflag
&& s
== NULL
&& errno
== ENOENT
) {
1610 slen
= suffixes
[0].ziplen
;
1611 s
= malloc(len
+ slen
+ 1);
1613 maybe_err("malloc");
1614 memcpy(s
, path
, len
);
1615 memcpy(s
+ len
, suffixes
[0].zipped
, slen
+ 1);
1619 maybe_warn("can't stat: %s", opath
);
1623 if (S_ISDIR(sb
.st_mode
)) {
1629 maybe_warnx("%s is a directory", path
);
1633 if (S_ISREG(sb
.st_mode
))
1634 handle_file(path
, &sb
);
1636 maybe_warnx("%s is not a regular file", path
);
1643 /* compress/decompress a file */
1645 handle_file(char *file
, struct stat
*sbp
)
1648 char outfile
[PATH_MAX
];
1652 usize
= file_uncompress(file
, outfile
, sizeof(outfile
));
1655 gsize
= sbp
->st_size
;
1657 gsize
= file_compress(file
, outfile
, sizeof(outfile
));
1660 usize
= sbp
->st_size
;
1665 if (vflag
&& !tflag
)
1666 print_verbage(file
, (cflag
) ? NULL
: outfile
, usize
, gsize
);
1671 /* this is used with -r to recursively descend directories */
1673 handle_dir(char *dir
)
1681 fts
= fts_open(path_argv
, FTS_PHYSICAL
, NULL
);
1683 warn("couldn't fts_open %s", dir
);
1687 while ((entry
= fts_read(fts
))) {
1688 switch(entry
->fts_info
) {
1696 maybe_warn("%s", entry
->fts_path
);
1699 handle_file(entry
->fts_name
, entry
->fts_statp
);
1702 (void)fts_close(fts
);
1706 /* print a ratio - size reduction as a fraction of uncompressed size */
1708 print_ratio(off_t in
, off_t out
, FILE *where
)
1710 int percent10
; /* 10 * percent */
1718 * Output is more than double size of input! print -99.9%
1719 * Quite possibly we've failed to get the original size.
1724 * We only need 12 bits of result from the final division,
1725 * so reduce the values until a 32bit division will suffice.
1727 while (in
> 0x100000) {
1732 percent10
= ((u_int
)diff
* 2000) / (u_int
)in
- 1000;
1737 len
= snprintf(buff
, sizeof buff
, "%2.2d.", percent10
);
1738 /* Move the '.' to before the last digit */
1739 buff
[len
- 1] = buff
[len
- 2];
1740 buff
[len
- 2] = '.';
1741 fprintf(where
, "%5s%%", buff
);
1745 /* print compression statistics, and the new name (if there is one!) */
1747 print_verbage(const char *file
, const char *nfile
, off_t usize
, off_t gsize
)
1750 fprintf(stderr
, "%s:%s ", file
,
1751 strlen(file
) < 7 ? "\t\t" : "\t");
1752 print_ratio(usize
, gsize
, stderr
);
1754 fprintf(stderr
, " -- replaced with %s", nfile
);
1755 fprintf(stderr
, "\n");
1759 /* print test results */
1761 print_test(const char *file
, int ok
)
1764 if (exit_value
== 0 && ok
== 0)
1766 fprintf(stderr
, "%s:%s %s\n", file
,
1767 strlen(file
) < 7 ? "\t\t" : "\t", ok
? "OK" : "NOT OK");
1772 /* print a file's info ala --list */
1774 compressed uncompressed ratio uncompressed_name
1775 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1778 print_list(int fd
, off_t out
, const char *outfile
, time_t ts
)
1780 static int first
= 1;
1782 static off_t in_tot
, out_tot
;
1791 printf("method crc date time ");
1794 printf(" compressed uncompressed "
1795 "ratio uncompressed_name\n");
1807 /* read the last 4 bytes - this is the uncompressed size */
1808 rv
= lseek(fd
, (off_t
)(-8), SEEK_END
);
1810 unsigned char buf
[8];
1813 if (read(fd
, (char *)buf
, sizeof(buf
)) != sizeof(buf
))
1814 maybe_warn("read of uncompressed size");
1815 usize
= buf
[4] | buf
[5] << 8 | buf
[6] << 16 | buf
[7] << 24;
1818 crc
= buf
[0] | buf
[1] << 8 | buf
[2] << 16 | buf
[3] << 24;
1824 if (vflag
&& fd
== -1)
1827 char *date
= ctime(&ts
);
1829 /* skip the day, 1/100th second, and year */
1832 printf("%5s %08x %11s ", "defla"/*XXX*/, crc
, date
);
1837 printf("%12llu %12llu ", (unsigned long long)out
, (unsigned long long)in
);
1838 print_ratio(in
, out
, stdout
);
1839 printf(" %s\n", outfile
);
1842 /* display the usage of NetBSD gzip */
1847 fprintf(stderr
, "%s\n", gzip_version
);
1849 "usage: %s [-" OPT_LIST
"] [<file> [<file> ...]]\n"
1851 " -c --stdout write to stdout, keep original files\n"
1853 " -d --decompress uncompress files\n"
1855 " -f --force force overwriting & compress links\n"
1856 " -h --help display this help\n"
1857 " -n --no-name don't save original file name or time stamp\n"
1858 " -N --name save or restore original file name and time stamp\n"
1859 " -q --quiet output no warnings\n"
1860 " -r --recursive recursively compress files in directories\n"
1861 " -S .suf use suffix .suf instead of .gz\n"
1863 " -t --test test compressed file\n"
1864 " -v --verbose print extra statistics\n"
1865 " -V --version display program version\n"
1866 " -1 --fast fastest (worst) compression\n"
1867 " -2 .. -8 set compression level\n"
1868 " -9 --best best (slowest) compression\n",
1876 /* display the version of NetBSD gzip */
1878 display_version(void)
1881 fprintf(stderr
, "%s\n", gzip_version
);
1885 #ifndef NO_BZIP2_SUPPORT
1886 #include "unbzip2.c"
1888 #ifndef NO_COMPRESS_SUPPORT
1889 #include "zuncompress.c"