1 /* $NetBSD: gzip.c,v 1.94 2009/04/12 10:31:14 lukem 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, 2006 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.
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
22 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
23 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
25 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * gzip.c -- GPL free gzip using zlib.
33 * RFC 1950 covers the zlib format
34 * RFC 1951 covers the deflate format
35 * RFC 1952 covers the gzip format
38 * - use mmap where possible
39 * - handle some signals better (remove outfile?)
40 * - make bzip2/compress -v/-t/-l support work as well as possible
43 #include <sys/param.h>
63 #define PRIdOFF PRId64
70 /* what type of file are we dealing with */
73 #ifndef NO_BZIP2_SUPPORT
76 #ifndef NO_COMPRESS_SUPPORT
79 #ifndef NO_PACK_SUPPORT
86 #ifndef NO_BZIP2_SUPPORT
89 #define BZ2_SUFFIX ".bz2"
90 #define BZIP2_MAGIC "\102\132\150"
93 #ifndef NO_COMPRESS_SUPPORT
95 #define Z_MAGIC "\037\235"
98 #ifndef NO_PACK_SUPPORT
99 #define PACK_MAGIC "\037\036"
102 #define GZ_SUFFIX ".gz"
104 #define BUFLEN (64 * 1024)
106 #define GZIP_MAGIC0 0x1F
107 #define GZIP_MAGIC1 0x8B
108 #define GZIP_OMAGIC1 0x9E
110 #define GZIP_TIMESTAMP (off_t)4
111 #define GZIP_ORIGNAME (off_t)10
113 #define HEAD_CRC 0x02
114 #define EXTRA_FIELD 0x04
115 #define ORIG_NAME 0x08
118 #define OS_CODE 3 /* Unix */
123 const char *normal
; /* for unzip - must not be longer than zipped */
125 static suffixes_t suffixes
[] = {
126 #define SUFFIX(Z, N) {Z, sizeof Z - 1, N}
127 SUFFIX(GZ_SUFFIX
, ""), /* Overwritten by -S .xxx */
129 SUFFIX(GZ_SUFFIX
, ""),
134 SUFFIX(".taz", ".tar"),
135 SUFFIX(".tgz", ".tar"),
136 #ifndef NO_BZIP2_SUPPORT
137 SUFFIX(BZ2_SUFFIX
, ""),
139 #ifndef NO_COMPRESS_SUPPORT
140 SUFFIX(Z_SUFFIX
, ""),
142 SUFFIX(GZ_SUFFIX
, ""), /* Overwritten by -S "" */
146 #define NUM_SUFFIXES (sizeof suffixes / sizeof suffixes[0])
148 #define SUFFIX_MAXLEN 30
150 static const char gzip_version
[] = "NetBSD gzip 20060927";
152 static int cflag
; /* stdout mode */
153 static int dflag
; /* decompress mode */
154 static int lflag
; /* list mode */
155 static int numflag
= 6; /* gzip -1..-9 value */
158 static int fflag
; /* force mode */
159 static int kflag
; /* don't delete input files */
160 static int nflag
; /* don't save name/timestamp */
161 static int Nflag
; /* don't restore name/timestamp */
162 static int qflag
; /* quiet mode */
163 static int rflag
; /* recursive mode */
164 static int tflag
; /* test */
165 static int vflag
; /* verbose mode */
171 static int exit_value
= 0; /* exit value */
173 static char *infile
; /* name of file coming in */
175 static void maybe_err(const char *fmt
, ...)
176 __attribute__((__format__(__printf__
, 1, 2)));
177 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT)
178 static void maybe_errx(const char *fmt
, ...)
179 __attribute__((__format__(__printf__
, 1, 2)));
181 static void maybe_warn(const char *fmt
, ...)
182 __attribute__((__format__(__printf__
, 1, 2)));
183 static void maybe_warnx(const char *fmt
, ...)
184 __attribute__((__format__(__printf__
, 1, 2)));
185 static enum filetype
file_gettype(u_char
*);
187 #define gz_compress(if, of, sz, fn, tm) gz_compress(if, of, sz)
189 static off_t
gz_compress(int, int, off_t
*, const char *, uint32_t);
190 static off_t
gz_uncompress(int, int, char *, size_t, off_t
*, const char *);
191 static off_t
file_compress(char *, char *, size_t);
192 static off_t
file_uncompress(char *, char *, size_t);
193 static void handle_pathname(char *);
194 static void handle_file(char *, struct stat
*);
195 static void handle_stdin(void);
196 static void handle_stdout(void);
197 static void print_ratio(off_t
, off_t
, FILE *);
198 static void print_list(int fd
, off_t
, const char *, time_t);
199 static void usage(void);
200 static void display_version(void);
201 static const suffixes_t
*check_suffix(char *, int);
202 static ssize_t
read_retry(int, void *, size_t);
205 #define unlink_input(f, sb) unlink(f)
207 static off_t
cat_fd(unsigned char *, size_t, off_t
*, int fd
);
208 static void prepend_gzip(char *, int *, char ***);
209 static void handle_dir(char *);
210 static void print_verbage(const char *, const char *, off_t
, off_t
);
211 static void print_test(const char *, int);
212 static void copymodes(int fd
, const struct stat
*, const char *file
);
213 static int check_outfile(const char *outfile
);
216 #ifndef NO_BZIP2_SUPPORT
217 static off_t
unbzip2(int, int, char *, size_t, off_t
*);
220 #ifndef NO_COMPRESS_SUPPORT
221 static FILE *zdopen(int);
222 static off_t
zuncompress(FILE *, FILE *, char *, size_t, off_t
*);
225 #ifndef NO_PACK_SUPPORT
226 static off_t
unpack(int, int, char *, size_t, off_t
*);
229 int main(int, char *p
[]);
232 #define getopt_long(a,b,c,d,e) getopt(a,b,c)
234 static const struct option longopts
[] = {
235 { "stdout", no_argument
, 0, 'c' },
236 { "to-stdout", no_argument
, 0, 'c' },
237 { "decompress", no_argument
, 0, 'd' },
238 { "uncompress", no_argument
, 0, 'd' },
239 { "force", no_argument
, 0, 'f' },
240 { "help", no_argument
, 0, 'h' },
241 { "keep", no_argument
, 0, 'k' },
242 { "list", no_argument
, 0, 'l' },
243 { "no-name", no_argument
, 0, 'n' },
244 { "name", no_argument
, 0, 'N' },
245 { "quiet", no_argument
, 0, 'q' },
246 { "recursive", no_argument
, 0, 'r' },
247 { "suffix", required_argument
, 0, 'S' },
248 { "test", no_argument
, 0, 't' },
249 { "verbose", no_argument
, 0, 'v' },
250 { "version", no_argument
, 0, 'V' },
251 { "fast", no_argument
, 0, '1' },
252 { "best", no_argument
, 0, '9' },
255 * This is what else GNU gzip implements. --ascii isn't useful
256 * on NetBSD, and I don't care to have a --license.
258 { "ascii", no_argument
, 0, 'a' },
259 { "license", no_argument
, 0, 'L' },
261 { NULL
, no_argument
, 0, 0 },
266 main(int argc
, char **argv
)
268 const char *progname
= getprogname();
275 /* XXX set up signals */
278 if ((gzip
= getenv("GZIP")) != NULL
)
279 prepend_gzip(gzip
, &argc
, &argv
);
284 * handle being called `gunzip', `zcat' and `gzcat'
286 if (strcmp(progname
, "gunzip") == 0)
288 else if (strcmp(progname
, "zcat") == 0 ||
289 strcmp(progname
, "gzcat") == 0)
293 #define OPT_LIST "123456789cdhltV"
295 #define OPT_LIST "123456789cdfhklNnqrS:tVv"
298 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':
340 len
= strlen(optarg
);
342 if (len
>= SUFFIX_MAXLEN
)
343 errx(1, "incorrect suffix: '%s'", optarg
);
344 suffixes
[0].zipped
= optarg
;
345 suffixes
[0].ziplen
= len
;
347 suffixes
[NUM_SUFFIXES
- 1].zipped
= "";
348 suffixes
[NUM_SUFFIXES
- 1].ziplen
= 0;
369 if (dflag
) /* stdin mode */
371 else /* stdout mode */
375 handle_pathname(argv
[0]);
379 if (qflag
== 0 && lflag
&& argc
> 1)
380 print_list(-1, 0, "(totals)", 0);
385 /* maybe print a warning */
387 maybe_warn(const char *fmt
, ...)
400 /* ... without an errno. */
402 maybe_warnx(const char *fmt
, ...)
415 /* maybe print an error */
417 maybe_err(const char *fmt
, ...)
429 #if !defined(NO_BZIP2_SUPPORT) || !defined(NO_PACK_SUPPORT)
430 /* ... without an errno. */
432 maybe_errx(const char *fmt
, ...)
446 /* split up $GZIP and prepend it to the argument list */
448 prepend_gzip(char *gzip
, int *argc
, char ***argv
)
450 char *s
, **nargv
, **ac
;
453 /* scan how many arguments there are */
455 while (*s
== ' ' || *s
== '\t')
460 while (*s
!= ' ' && *s
!= '\t')
472 nargv
= (char **)malloc((*argc
+ 1) * sizeof(char *));
476 /* stash this away */
479 /* copy the program name first */
481 nargv
[i
++] = *(ac
++);
483 /* take a copy of $GZIP and add it to the array */
488 /* Skip whitespaces. */
489 while (*s
== ' ' || *s
== '\t')
494 /* Find the end of this argument. */
495 while (*s
!= ' ' && *s
!= '\t')
497 /* Argument followed by NUL. */
499 /* Terminate by overwriting ' ' or '\t' with NUL. */
504 /* copy the original arguments and a NULL */
506 nargv
[i
++] = *(ac
++);
511 /* compress input to output. Return bytes read, -1 on error */
513 gz_compress(int in
, int out
, off_t
*gsizep
, const char *origname
, uint32_t mtime
)
516 char *outbufp
, *inbufp
;
517 off_t in_tot
= 0, out_tot
= 0;
522 static char header
[] = { GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
, 0,
527 outbufp
= malloc(BUFLEN
);
528 inbufp
= malloc(BUFLEN
);
529 if (outbufp
== NULL
|| inbufp
== NULL
) {
530 maybe_err("malloc failed");
534 memset(&z
, 0, sizeof z
);
540 memcpy(outbufp
, header
, sizeof header
);
548 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c%c%c%s",
549 GZIP_MAGIC0
, GZIP_MAGIC1
, Z_DEFLATED
,
550 *origname
? ORIG_NAME
: 0,
553 (mtime
>> 16) & 0xff,
554 (mtime
>> 24) & 0xff,
555 numflag
== 1 ? 4 : numflag
== 9 ? 2 : 0,
558 /* this need PATH_MAX > BUFLEN ... */
559 maybe_err("snprintf");
564 z
.next_out
= outbufp
+ i
;
565 z
.avail_out
= BUFLEN
- i
;
567 error
= deflateInit2(&z
, numflag
, Z_DEFLATED
,
568 (-MAX_WBITS
), 8, Z_DEFAULT_STRATEGY
);
570 maybe_warnx("deflateInit2 failed");
575 crc
= crc32(0L, Z_NULL
, 0);
577 if (z
.avail_out
== 0) {
578 if (write(out
, outbufp
, BUFLEN
) != BUFLEN
) {
585 z
.next_out
= outbufp
;
586 z
.avail_out
= BUFLEN
;
589 if (z
.avail_in
== 0) {
590 in_size
= read(in
, inbufp
, BUFLEN
);
599 crc
= crc32(crc
, (const Bytef
*)inbufp
, (unsigned)in_size
);
602 z
.avail_in
= in_size
;
605 error
= deflate(&z
, Z_NO_FLUSH
);
606 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
607 maybe_warnx("deflate failed");
618 error
= deflate(&z
, Z_FINISH
);
619 if (error
!= Z_OK
&& error
!= Z_STREAM_END
) {
620 maybe_warnx("deflate failed");
625 len
= (char *)z
.next_out
- outbufp
;
627 w
= write(out
, outbufp
, len
);
628 if (w
== -1 || (size_t)w
!= len
) {
634 z
.next_out
= outbufp
;
635 z
.avail_out
= BUFLEN
;
637 if (error
== Z_STREAM_END
)
641 if (deflateEnd(&z
) != Z_OK
) {
642 maybe_warnx("deflateEnd failed");
647 i
= snprintf(outbufp
, BUFLEN
, "%c%c%c%c%c%c%c%c",
649 (int)(crc
>> 8) & 0xff,
650 (int)(crc
>> 16) & 0xff,
651 (int)(crc
>> 24) & 0xff,
653 (int)(in_tot
>> 8) & 0xff,
654 (int)(in_tot
>> 16) & 0xff,
655 (int)(in_tot
>> 24) & 0xff);
657 maybe_err("snprintf");
659 if (in_tot
> 0xffffffff)
660 maybe_warn("input file size >= 4GB cannot be saved");
662 if (write(out
, outbufp
, i
) != i
) {
679 * uncompress input to output then close the input. return the
680 * uncompressed size written, and put the compressed sized read
684 gz_uncompress(int in
, int out
, char *pre
, size_t prelen
, off_t
*gsizep
,
685 const char *filename
)
688 char *outbufp
, *inbufp
;
689 off_t out_tot
= -1, in_tot
= 0;
690 uint32_t out_sub_tot
= 0;
708 } state
= GZSTATE_MAGIC0
;
709 int flags
= 0, skip_count
= 0;
710 int error
= Z_STREAM_ERROR
, done_reading
= 0;
715 #define ADVANCE() { z.next_in++; z.avail_in--; }
717 if ((outbufp
= malloc(BUFLEN
)) == NULL
) {
718 maybe_err("malloc failed");
721 if ((inbufp
= malloc(BUFLEN
)) == NULL
) {
722 maybe_err("malloc failed");
726 memset(&z
, 0, sizeof z
);
729 z
.avail_out
= BUFLEN
;
730 z
.next_out
= outbufp
;
739 if ((z
.avail_in
== 0 || needmore
) && done_reading
== 0) {
742 if (z
.avail_in
> 0) {
743 memmove(inbufp
, z
.next_in
, z
.avail_in
);
746 in_size
= read(in
, z
.next_in
+ z
.avail_in
,
747 BUFLEN
- z
.avail_in
);
750 maybe_warn("failed to read stdin");
752 } else if (in_size
== 0) {
756 z
.avail_in
+= in_size
;
761 if (z
.avail_in
== 0) {
762 if (done_reading
&& state
!= GZSTATE_MAGIC0
) {
763 maybe_warnx("%s: unexpected end of file",
771 if (*z
.next_in
!= GZIP_MAGIC0
) {
773 maybe_warnx("%s: trailing garbage "
774 "ignored", filename
);
777 maybe_warnx("input not gziped (MAGIC0)");
783 crc
= crc32(0L, Z_NULL
, 0);
787 if (*z
.next_in
!= GZIP_MAGIC1
&&
788 *z
.next_in
!= GZIP_OMAGIC1
) {
789 maybe_warnx("input not gziped (MAGIC1)");
797 if (*z
.next_in
!= Z_DEFLATED
) {
798 maybe_warnx("unknown compression method");
812 case GZSTATE_SKIPPING
:
813 if (skip_count
> 0) {
821 if ((flags
& EXTRA_FIELD
) == 0) {
822 state
= GZSTATE_ORIGNAME
;
825 skip_count
= *z
.next_in
;
831 skip_count
|= ((*z
.next_in
) << 8);
837 if (skip_count
> 0) {
844 case GZSTATE_ORIGNAME
:
845 if ((flags
& ORIG_NAME
) == 0) {
854 case GZSTATE_COMMENT
:
855 if ((flags
& COMMENT
) == 0) {
864 case GZSTATE_HEAD_CRC1
:
865 if (flags
& HEAD_CRC
)
872 case GZSTATE_HEAD_CRC2
:
873 if (skip_count
> 0) {
881 if (inflateInit2(&z
, -MAX_WBITS
) != Z_OK
) {
882 maybe_warnx("failed to inflateInit");
889 error
= inflate(&z
, Z_FINISH
);
891 /* Z_BUF_ERROR goes with Z_FINISH... */
898 maybe_warnx("Z_NEED_DICT error");
901 maybe_warnx("data stream error");
904 maybe_warnx("internal stream error");
907 maybe_warnx("memory allocation error");
911 maybe_warn("unknown error from inflate(): %d",
914 wr
= BUFLEN
- z
.avail_out
;
917 crc
= crc32(crc
, (const Bytef
*)outbufp
, (unsigned)wr
);
920 /* don't write anything with -t */
923 write(out
, outbufp
, wr
) != wr
) {
924 maybe_warn("error writing to output");
932 if (error
== Z_STREAM_END
) {
937 z
.next_out
= outbufp
;
938 z
.avail_out
= BUFLEN
;
945 if (z
.avail_in
< 4) {
950 maybe_warnx("truncated input");
953 origcrc
= ((unsigned)z
.next_in
[0] & 0xff) |
954 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
955 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
956 ((unsigned)z
.next_in
[3] & 0xff) << 24;
957 if (origcrc
!= crc
) {
958 maybe_warnx("invalid compressed"
967 if (!z
.avail_in
&& done_reading
) {
976 if (z
.avail_in
< 4) {
981 maybe_warnx("truncated input");
984 origlen
= ((unsigned)z
.next_in
[0] & 0xff) |
985 ((unsigned)z
.next_in
[1] & 0xff) << 8 |
986 ((unsigned)z
.next_in
[2] & 0xff) << 16 |
987 ((unsigned)z
.next_in
[3] & 0xff) << 24;
989 if (origlen
!= out_sub_tot
) {
990 maybe_warnx("invalid compressed"
991 " data--length error");
1000 maybe_warnx("decompression error");
1003 state
= GZSTATE_MAGIC0
;
1012 if (state
> GZSTATE_INIT
)
1026 * set the owner, mode, flags & utimes using the given file descriptor.
1027 * file is only used in possible warning messages.
1030 copymodes(int fd
, const struct stat
*sbp
, const char *file
)
1032 struct timeval times
[2];
1036 * If we have no info on the input, give this file some
1037 * default values and return..
1040 mode_t mask
= umask(022);
1042 (void)fchmod(fd
, DEFFILEMODE
& ~mask
);
1048 /* if the chown fails, remove set-id bits as-per compress(1) */
1049 if (fchown(fd
, sb
.st_uid
, sb
.st_gid
) < 0) {
1051 maybe_warn("couldn't fchown: %s", file
);
1052 sb
.st_mode
&= ~(S_ISUID
|S_ISGID
);
1055 /* we only allow set-id and the 9 normal permission bits */
1056 sb
.st_mode
&= S_ISUID
| S_ISGID
| S_IRWXU
| S_IRWXG
| S_IRWXO
;
1057 if (fchmod(fd
, sb
.st_mode
) < 0)
1058 maybe_warn("couldn't fchmod: %s", file
);
1060 /* only try flags if they exist already */
1061 if (sb
.st_flags
!= 0 && fchflags(fd
, sb
.st_flags
) < 0)
1062 maybe_warn("couldn't fchflags: %s", file
);
1064 TIMESPEC_TO_TIMEVAL(×
[0], &sb
.st_atimespec
);
1065 TIMESPEC_TO_TIMEVAL(×
[1], &sb
.st_mtimespec
);
1066 if (futimes(fd
, times
) < 0)
1067 maybe_warn("couldn't utimes: %s", file
);
1071 /* what sort of file is this? */
1072 static enum filetype
1073 file_gettype(u_char
*buf
)
1076 if (buf
[0] == GZIP_MAGIC0
&&
1077 (buf
[1] == GZIP_MAGIC1
|| buf
[1] == GZIP_OMAGIC1
))
1080 #ifndef NO_BZIP2_SUPPORT
1081 if (memcmp(buf
, BZIP2_MAGIC
, 3) == 0 &&
1082 buf
[3] >= '0' && buf
[3] <= '9')
1086 #ifndef NO_COMPRESS_SUPPORT
1087 if (memcmp(buf
, Z_MAGIC
, 2) == 0)
1091 #ifndef NO_PACK_SUPPORT
1092 if (memcmp(buf
, PACK_MAGIC
, 2) == 0)
1100 /* check the outfile is OK. */
1102 check_outfile(const char *outfile
)
1107 if (lflag
== 0 && stat(outfile
, &sb
) == 0) {
1110 else if (isatty(STDIN_FILENO
)) {
1111 char ans
[10] = { 'n', '\0' }; /* default */
1113 fprintf(stderr
, "%s already exists -- do you wish to "
1114 "overwrite (y or n)? " , outfile
);
1115 (void)fgets(ans
, sizeof(ans
) - 1, stdin
);
1116 if (ans
[0] != 'y' && ans
[0] != 'Y') {
1117 fprintf(stderr
, "\tnot overwriting\n");
1122 maybe_warnx("%s already exists -- skipping", outfile
);
1130 unlink_input(const char *file
, const struct stat
*sb
)
1136 if (stat(file
, &nsb
) != 0)
1137 /* Must be gone alrady */
1139 if (nsb
.st_dev
!= sb
->st_dev
|| nsb
.st_ino
!= sb
->st_ino
)
1140 /* Definitely a different file */
1146 static const suffixes_t
*
1147 check_suffix(char *file
, int xlate
)
1149 const suffixes_t
*s
;
1150 int len
= strlen(file
);
1153 for (s
= suffixes
; s
!= suffixes
+ NUM_SUFFIXES
; s
++) {
1154 /* if it doesn't fit in "a.suf", don't bother */
1155 if (s
->ziplen
>= len
)
1157 sp
= file
+ len
- s
->ziplen
;
1158 if (strcmp(s
->zipped
, sp
) != 0)
1161 strcpy(sp
, s
->normal
);
1168 * compress the given file: create a corresponding .gz file and remove the
1172 file_compress(char *file
, char *outfile
, size_t outsize
)
1178 struct stat isb
, osb
;
1179 const suffixes_t
*suff
;
1182 in
= open(file
, O_RDONLY
);
1184 maybe_warn("can't open %s", file
);
1190 if (fstat(in
, &isb
) == 0) {
1191 if (isb
.st_nlink
> 1 && fflag
== 0) {
1192 maybe_warnx("%s has %d other link%s -- "
1193 "skipping", file
, isb
.st_nlink
- 1,
1194 isb
.st_nlink
== 1 ? "" : "s");
1200 if (fflag
== 0 && (suff
= check_suffix(file
, 0))
1201 && suff
->zipped
[0] != 0) {
1202 maybe_warnx("%s already has %s suffix -- unchanged",
1203 file
, suff
->zipped
);
1209 /* Add (usually) .gz to filename */
1210 if ((size_t)snprintf(outfile
, outsize
, "%s%s",
1211 file
, suffixes
[0].zipped
) >= outsize
) {
1212 errx(1, "file path too long: %s", file
);
1215 if (check_outfile(outfile
) == 0) {
1223 out
= open(outfile
, O_WRONLY
| O_CREAT
| O_EXCL
, 0600);
1225 maybe_warn("could not create output: %s", outfile
);
1230 out
= STDOUT_FILENO
;
1232 insize
= gz_compress(in
, out
, &size
, basename(file
), (uint32_t)isb
.st_mtime
);
1237 * If there was an error, insize will be -1.
1238 * If we compressed to stdout, just return the size.
1239 * Otherwise stat the file and check it is the correct size.
1240 * We only blow away the file if we can stat the output and it
1241 * has the expected size.
1244 return insize
== -1 ? -1 : size
;
1247 if (fstat(out
, &osb
) != 0) {
1248 maybe_warn("couldn't stat: %s", outfile
);
1252 if (osb
.st_size
!= size
) {
1253 maybe_warnx("output file: %s wrong size (%" PRIdOFF
1254 " != %" PRIdOFF
"), deleting",
1255 outfile
, osb
.st_size
, size
);
1259 copymodes(out
, &isb
, outfile
);
1261 if (close(out
) == -1)
1262 maybe_warn("couldn't close output");
1264 /* output is good, ok to delete input */
1265 unlink_input(file
, &isb
);
1270 if (close(out
) == -1)
1271 maybe_warn("couldn't close output");
1273 maybe_warnx("leaving original %s", file
);
1279 /* uncompress the given file and remove the original */
1281 file_uncompress(char *file
, char *outfile
, size_t outsize
)
1283 struct stat isb
, osb
;
1286 unsigned char header1
[4];
1287 enum filetype method
;
1288 int fd
, ofd
, zfd
= -1;
1291 time_t timestamp
= 0;
1292 unsigned char name
[PATH_MAX
+ 1];
1295 /* gather the old name info */
1297 fd
= open(file
, O_RDONLY
);
1299 maybe_warn("can't open %s", file
);
1303 if ((size_t)snprintf(outfile
, outsize
, "%s", file
) >= outsize
)
1304 errx(1, "file path too long: %s", file
);
1305 if (check_suffix(outfile
, 1) == NULL
&& !(cflag
|| lflag
)) {
1306 maybe_warnx("%s: unknown suffix -- ignored", file
);
1310 rbytes
= read(fd
, header1
, sizeof header1
);
1311 if (rbytes
!= sizeof header1
) {
1312 /* we don't want to fail here. */
1318 maybe_warn("can't read %s", file
);
1320 goto unexpected_EOF
;
1324 method
= file_gettype(header1
);
1327 if (fflag
== 0 && method
== FT_UNKNOWN
) {
1328 maybe_warnx("%s: not in gzip format", file
);
1335 if (method
== FT_GZIP
&& Nflag
) {
1336 unsigned char ts
[4]; /* timestamp */
1338 rv
= pread(fd
, ts
, sizeof ts
, GZIP_TIMESTAMP
);
1339 if (rv
>= 0 && rv
< (ssize_t
)(sizeof ts
))
1340 goto unexpected_EOF
;
1343 maybe_warn("can't read %s", file
);
1346 timestamp
= ts
[3] << 24 | ts
[2] << 16 | ts
[1] << 8 | ts
[0];
1348 if (header1
[3] & ORIG_NAME
) {
1349 rbytes
= pread(fd
, name
, sizeof name
, GZIP_ORIGNAME
);
1351 maybe_warn("can't read %s", file
);
1355 /* preserve original directory name */
1356 char *dp
= strrchr(file
, '/');
1361 snprintf(outfile
, outsize
, "%.*s%.*s",
1363 file
, (int) rbytes
, name
);
1368 lseek(fd
, 0, SEEK_SET
);
1370 if (cflag
== 0 || lflag
) {
1371 if (fstat(fd
, &isb
) != 0)
1374 if (isb
.st_nlink
> 1 && lflag
== 0 && fflag
== 0) {
1375 maybe_warnx("%s has %d other links -- skipping",
1376 file
, isb
.st_nlink
- 1);
1379 if (nflag
== 0 && timestamp
)
1380 isb
.st_mtime
= timestamp
;
1381 if (check_outfile(outfile
) == 0)
1386 if (cflag
== 0 && lflag
== 0) {
1387 zfd
= open(outfile
, O_WRONLY
|O_CREAT
|O_EXCL
, 0600);
1388 if (zfd
== STDOUT_FILENO
) {
1389 /* We won't close STDOUT_FILENO later... */
1391 close(STDOUT_FILENO
);
1394 maybe_warn("can't open %s", outfile
);
1398 zfd
= STDOUT_FILENO
;
1400 #ifndef NO_BZIP2_SUPPORT
1401 if (method
== FT_BZIP2
) {
1405 maybe_warnx("no -l with bzip2 files");
1409 size
= unbzip2(fd
, zfd
, NULL
, 0, NULL
);
1413 #ifndef NO_COMPRESS_SUPPORT
1414 if (method
== FT_Z
) {
1419 maybe_warnx("no -l with Lempel-Ziv files");
1423 if ((in
= zdopen(fd
)) == NULL
) {
1424 maybe_warn("zdopen for read: %s", file
);
1428 out
= fdopen(dup(zfd
), "w");
1430 maybe_warn("fdopen for write: %s", outfile
);
1435 size
= zuncompress(in
, out
, NULL
, 0, NULL
);
1436 /* need to fclose() if ferror() is true... */
1437 if (ferror(in
) | fclose(in
)) {
1438 maybe_warn("failed infile fclose");
1442 if (fclose(out
) != 0) {
1443 maybe_warn("failed outfile fclose");
1450 #ifndef NO_PACK_SUPPORT
1451 if (method
== FT_PACK
) {
1453 maybe_warnx("no -l with packed files");
1457 size
= unpack(fd
, zfd
, NULL
, 0, NULL
);
1462 if (method
== FT_UNKNOWN
) {
1464 maybe_warnx("no -l for unknown filetypes");
1467 size
= cat_fd(NULL
, 0, NULL
, fd
);
1472 print_list(fd
, isb
.st_size
, outfile
, isb
.st_mtime
);
1474 return -1; /* XXX */
1477 size
= gz_uncompress(fd
, zfd
, NULL
, 0, NULL
, file
);
1481 maybe_warn("couldn't close input");
1482 if (zfd
!= STDOUT_FILENO
&& close(zfd
) != 0)
1483 maybe_warn("couldn't close output");
1488 maybe_warnx("%s: uncompress failed", file
);
1492 /* if testing, or we uncompressed to stdout, this is all we need */
1497 /* if we are uncompressing to stdin, don't remove the file. */
1502 * if we create a file...
1505 * if we can't stat the file don't remove the file.
1508 ofd
= open(outfile
, O_RDWR
, 0);
1510 maybe_warn("couldn't open (leaving original): %s",
1514 if (fstat(ofd
, &osb
) != 0) {
1515 maybe_warn("couldn't stat (leaving original): %s",
1520 if (osb
.st_size
!= size
) {
1521 maybe_warnx("stat gave different size: %" PRIdOFF
1522 " != %" PRIdOFF
" (leaving original)",
1528 unlink_input(file
, &isb
);
1530 copymodes(ofd
, &isb
, outfile
);
1536 maybe_warnx("%s: unexpected end of file", file
);
1540 if (zfd
!= -1 && zfd
!= STDOUT_FILENO
)
1547 cat_fd(unsigned char * prepend
, size_t count
, off_t
*gsizep
, int fd
)
1554 w
= write(STDOUT_FILENO
, prepend
, count
);
1555 if (w
== -1 || (size_t)w
!= count
) {
1556 maybe_warn("write to stdout");
1562 rv
= read(fd
, buf
, sizeof buf
);
1566 maybe_warn("read from fd %d", fd
);
1570 if (write(STDOUT_FILENO
, buf
, rv
) != rv
) {
1571 maybe_warn("write to stdout");
1586 unsigned char header1
[4];
1588 enum filetype method
;
1590 #ifndef NO_COMPRESS_SUPPORT
1595 if (fflag
== 0 && lflag
== 0 && isatty(STDIN_FILENO
)) {
1596 maybe_warnx("standard input is a terminal -- ignoring");
1604 /* XXX could read the whole file, etc. */
1605 if (fstat(STDIN_FILENO
, &isb
) < 0) {
1606 maybe_warn("fstat");
1609 print_list(STDIN_FILENO
, isb
.st_size
, "stdout", isb
.st_mtime
);
1613 bytes_read
= read_retry(STDIN_FILENO
, header1
, sizeof header1
);
1614 if (bytes_read
== -1) {
1615 maybe_warn("can't read stdin");
1617 } else if (bytes_read
!= sizeof(header1
)) {
1618 maybe_warnx("(stdin): unexpected end of file");
1622 method
= file_gettype(header1
);
1627 maybe_warnx("unknown compression format");
1630 usize
= cat_fd(header1
, sizeof header1
, &gsize
, STDIN_FILENO
);
1634 usize
= gz_uncompress(STDIN_FILENO
, STDOUT_FILENO
,
1635 header1
, sizeof header1
, &gsize
, "(stdin)");
1637 #ifndef NO_BZIP2_SUPPORT
1639 usize
= unbzip2(STDIN_FILENO
, STDOUT_FILENO
,
1640 header1
, sizeof header1
, &gsize
);
1643 #ifndef NO_COMPRESS_SUPPORT
1645 if ((in
= zdopen(STDIN_FILENO
)) == NULL
) {
1646 maybe_warnx("zopen of stdin");
1650 usize
= zuncompress(in
, stdout
, header1
, sizeof header1
, &gsize
);
1654 #ifndef NO_PACK_SUPPORT
1656 usize
= unpack(STDIN_FILENO
, STDOUT_FILENO
,
1657 (char *)header1
, sizeof header1
, &gsize
);
1663 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1664 print_verbage(NULL
, NULL
, usize
, gsize
);
1666 print_test("(stdin)", usize
!= -1);
1681 if (fflag
== 0 && isatty(STDOUT_FILENO
)) {
1682 maybe_warnx("standard output is a terminal -- ignoring");
1686 /* If stdin is a file use it's mtime, otherwise use current time */
1687 ret
= fstat(STDIN_FILENO
, &sb
);
1691 maybe_warn("Can't stat stdin");
1696 if (S_ISREG(sb
.st_mode
))
1697 mtime
= (uint32_t)sb
.st_mtime
;
1699 systime
= time(NULL
);
1701 if (systime
== -1) {
1706 mtime
= (uint32_t)systime
;
1709 usize
= gz_compress(STDIN_FILENO
, STDOUT_FILENO
, &gsize
, "", mtime
);
1711 if (vflag
&& !tflag
&& usize
!= -1 && gsize
!= -1)
1712 print_verbage(NULL
, NULL
, usize
, gsize
);
1716 /* do what is asked for, for the path name */
1718 handle_pathname(char *path
)
1720 char *opath
= path
, *s
= NULL
;
1725 /* check for stdout/stdin */
1726 if (path
[0] == '-' && path
[1] == '\0') {
1735 if (stat(path
, &sb
) != 0) {
1736 /* lets try <path>.gz if we're decompressing */
1737 if (dflag
&& s
== NULL
&& errno
== ENOENT
) {
1739 slen
= suffixes
[0].ziplen
;
1740 s
= malloc(len
+ slen
+ 1);
1742 maybe_err("malloc");
1743 memcpy(s
, path
, len
);
1744 memcpy(s
+ len
, suffixes
[0].zipped
, slen
+ 1);
1748 maybe_warn("can't stat: %s", opath
);
1752 if (S_ISDIR(sb
.st_mode
)) {
1758 maybe_warnx("%s is a directory", path
);
1762 if (S_ISREG(sb
.st_mode
))
1763 handle_file(path
, &sb
);
1765 maybe_warnx("%s is not a regular file", path
);
1772 /* compress/decompress a file */
1774 handle_file(char *file
, struct stat
*sbp
)
1777 char outfile
[PATH_MAX
];
1781 usize
= file_uncompress(file
, outfile
, sizeof(outfile
));
1784 print_test(file
, usize
!= -1);
1788 gsize
= sbp
->st_size
;
1790 gsize
= file_compress(file
, outfile
, sizeof(outfile
));
1793 usize
= sbp
->st_size
;
1798 if (vflag
&& !tflag
)
1799 print_verbage(file
, (cflag
) ? NULL
: outfile
, usize
, gsize
);
1804 /* this is used with -r to recursively descend directories */
1806 handle_dir(char *dir
)
1814 fts
= fts_open(path_argv
, FTS_PHYSICAL
| FTS_NOCHDIR
, NULL
);
1816 warn("couldn't fts_open %s", dir
);
1820 while ((entry
= fts_read(fts
))) {
1821 switch(entry
->fts_info
) {
1829 maybe_warn("%s", entry
->fts_path
);
1832 handle_file(entry
->fts_path
, entry
->fts_statp
);
1835 (void)fts_close(fts
);
1839 /* print a ratio - size reduction as a fraction of uncompressed size */
1841 print_ratio(off_t in
, off_t out
, FILE *where
)
1843 int percent10
; /* 10 * percent */
1851 * Output is more than double size of input! print -99.9%
1852 * Quite possibly we've failed to get the original size.
1857 * We only need 12 bits of result from the final division,
1858 * so reduce the values until a 32bit division will suffice.
1860 while (in
> 0x100000) {
1865 percent10
= ((u_int
)diff
* 2000) / (u_int
)in
- 1000;
1870 len
= snprintf(buff
, sizeof buff
, "%2.2d.", percent10
);
1871 /* Move the '.' to before the last digit */
1872 buff
[len
- 1] = buff
[len
- 2];
1873 buff
[len
- 2] = '.';
1874 fprintf(where
, "%5s%%", buff
);
1878 /* print compression statistics, and the new name (if there is one!) */
1880 print_verbage(const char *file
, const char *nfile
, off_t usize
, off_t gsize
)
1883 fprintf(stderr
, "%s:%s ", file
,
1884 strlen(file
) < 7 ? "\t\t" : "\t");
1885 print_ratio(usize
, gsize
, stderr
);
1887 fprintf(stderr
, " -- replaced with %s", nfile
);
1888 fprintf(stderr
, "\n");
1892 /* print test results */
1894 print_test(const char *file
, int ok
)
1897 if (exit_value
== 0 && ok
== 0)
1899 fprintf(stderr
, "%s:%s %s\n", file
,
1900 strlen(file
) < 7 ? "\t\t" : "\t", ok
? "OK" : "NOT OK");
1905 /* print a file's info ala --list */
1907 compressed uncompressed ratio uncompressed_name
1908 354841 1679360 78.8% /usr/pkgsrc/distfiles/libglade-2.0.1.tar
1911 print_list(int fd
, off_t out
, const char *outfile
, time_t ts
)
1913 static int first
= 1;
1915 static off_t in_tot
, out_tot
;
1923 printf("method crc date time ");
1926 printf(" compressed uncompressed "
1927 "ratio uncompressed_name\n");
1939 /* read the last 4 bytes - this is the uncompressed size */
1940 rv
= lseek(fd
, (off_t
)(-8), SEEK_END
);
1942 unsigned char buf
[8];
1945 rv
= read(fd
, (char *)buf
, sizeof(buf
));
1947 maybe_warn("read of uncompressed size");
1948 else if (rv
!= sizeof(buf
))
1949 maybe_warnx("read of uncompressed size");
1952 usize
= buf
[4] | buf
[5] << 8 |
1953 buf
[6] << 16 | buf
[7] << 24;
1956 crc
= buf
[0] | buf
[1] << 8 |
1957 buf
[2] << 16 | buf
[3] << 24;
1964 if (vflag
&& fd
== -1)
1967 char *date
= ctime(&ts
);
1969 /* skip the day, 1/100th second, and year */
1972 printf("%5s %08x %11s ", "defla"/*XXX*/, crc
, date
);
1977 printf("%12llu %12llu ", (unsigned long long)out
, (unsigned long long)in
);
1978 print_ratio(in
, out
, stdout
);
1979 printf(" %s\n", outfile
);
1982 /* display the usage of NetBSD gzip */
1987 fprintf(stderr
, "%s\n", gzip_version
);
1990 "usage: %s [-" OPT_LIST
"] [<file> [<file> ...]]\n",
1992 "usage: %s [-123456789acdfhklLNnqrtVv] [-S .suffix] [<file> [<file> ...]]\n"
1993 " -1 --fast fastest (worst) compression\n"
1994 " -2 .. -8 set compression level\n"
1995 " -9 --best best (slowest) compression\n"
1996 " -c --stdout write to stdout, keep original files\n"
1998 " -d --decompress uncompress files\n"
2000 " -f --force force overwriting & compress links\n"
2001 " -h --help display this help\n"
2002 " -k --keep don't delete input files during operation\n"
2003 " -l --list list compressed file contents\n"
2004 " -N --name save or restore original file name and time stamp\n"
2005 " -n --no-name don't save original file name or time stamp\n"
2006 " -q --quiet output no warnings\n"
2007 " -r --recursive recursively compress files in directories\n"
2008 " -S .suf use suffix .suf instead of .gz\n"
2010 " -t --test test compressed file\n"
2011 " -V --version display program version\n"
2012 " -v --verbose print extra statistics\n",
2018 /* display the version of NetBSD gzip */
2020 display_version(void)
2023 fprintf(stderr
, "%s\n", gzip_version
);
2027 #ifndef NO_BZIP2_SUPPORT
2028 #include "unbzip2.c"
2030 #ifndef NO_COMPRESS_SUPPORT
2031 #include "zuncompress.c"
2033 #ifndef NO_PACK_SUPPORT
2038 read_retry(int fd
, void *buf
, size_t sz
)
2041 size_t left
= MIN(sz
, (size_t) SSIZE_MAX
);
2046 ret
= read(fd
, cp
, left
);
2049 } else if (ret
== 0) {