1 /* minigzip.c -- simulate gzip using the zlib compression library
2 * Copyright (C) 1995-2006, 2010, 2011, 2016 Jean-loup Gailly
3 * For conditions of distribution and use, see copyright notice in zlib.h
7 * minigzip is a minimal implementation of the gzip utility. This is
8 * only an example of using zlib and isn't meant to replace the
9 * full-featured gzip. No attempt is made to deal with file systems
10 * limiting names to 14 or 8+3 characters, etc... Error checking is
11 * very limited. So use minigzip only for testing; use gzip for the
12 * real thing. On MSDOS, use only on file names without extension
27 # include <sys/types.h>
28 # include <sys/mman.h>
29 # include <sys/stat.h>
32 #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
38 # define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
40 # define SET_BINARY_MODE(file)
43 #if defined(_MSC_VER) && _MSC_VER < 1900
44 # define snprintf _snprintf
48 # define unlink delete
49 # define GZ_SUFFIX "-gz"
52 # define unlink remove
53 # define GZ_SUFFIX "-gz"
54 # define fileno(file) file->__file
56 #if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
57 # include <unix.h> /* for fileno */
60 #if !defined(Z_HAVE_UNISTD_H) && !defined(_LARGEFILE64_SOURCE)
61 #ifndef WIN32 /* unlink already in stdio.h for WIN32 */
62 extern int unlink(const char *);
68 # define perror(s) pwinerror(s)
70 /* Map the Windows error number in ERROR to a locale-dependent error
71 message string and return a pointer to it. Typically, the values
72 for ERROR come from GetLastError.
74 The string pointed to shall not be modified by the application,
75 but may be overwritten by a subsequent call to strwinerror
77 The strwinerror function does not change the current setting
80 static char *strwinerror (error)
83 static char buf[1024];
86 DWORD lasterr = GetLastError();
87 DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
88 | FORMAT_MESSAGE_ALLOCATE_BUFFER,
91 0, /* Default language */
96 /* If there is an \r\n appended, zap it. */
98 && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
103 if (chars > sizeof (buf) - 1) {
104 chars = sizeof (buf) - 1;
108 wcstombs(buf, msgbuf, chars + 1);
112 sprintf(buf, "unknown win32 error (%ld)", error);
115 SetLastError(lasterr);
119 static void pwinerror (s)
123 fprintf(stderr, "%s: %s\n", s, strwinerror(GetLastError ()));
125 fprintf(stderr, "%s\n", strwinerror(GetLastError ()));
128 #endif /* UNDER_CE */
131 # define GZ_SUFFIX ".gz"
133 #define SUFFIX_LEN (sizeof(GZ_SUFFIX)-1)
136 #define MAX_NAME_LEN 1024
139 # define local static
140 /* Needed for systems with limitation on stack size. */
146 /* for Z_SOLO, create simplified gz* functions using deflate and inflate */
148 #if defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE)
149 # include <unistd.h> /* for unlink() */
152 static void *myalloc(void *q, unsigned n, unsigned m) {
157 static void myfree(void *q, void *p) {
162 typedef struct gzFile_s {
170 static gzFile gz_open(const char *path, int fd, const char *mode) {
174 gz = malloc(sizeof(struct gzFile_s));
177 gz->write = strchr(mode, 'w') != NULL;
178 gz->strm.zalloc = myalloc;
179 gz->strm.zfree = myfree;
180 gz->strm.opaque = Z_NULL;
182 ret = deflateInit2(&(gz->strm), -1, 8, 15 + 16, 8, 0);
184 gz->strm.next_in = 0;
185 gz->strm.avail_in = Z_NULL;
186 ret = inflateInit2(&(gz->strm), 15 + 16);
192 gz->file = path == NULL ? fdopen(fd, gz->write ? "wb" : "rb") :
193 fopen(path, gz->write ? "wb" : "rb");
194 if (gz->file == NULL) {
195 gz->write ? deflateEnd(&(gz->strm)) : inflateEnd(&(gz->strm));
204 static gzFile gzopen(const char *path, const char *mode) {
205 return gz_open(path, -1, mode);
208 static gzFile gzdopen(int fd, const char *mode) {
209 return gz_open(NULL, fd, mode);
212 static int gzwrite(gzFile gz, const void *buf, unsigned len) {
214 unsigned char out[BUFLEN];
216 if (gz == NULL || !gz->write)
219 strm->next_in = (void *)buf;
220 strm->avail_in = len;
222 strm->next_out = out;
223 strm->avail_out = BUFLEN;
224 (void)deflate(strm, Z_NO_FLUSH);
225 fwrite(out, 1, BUFLEN - strm->avail_out, gz->file);
226 } while (strm->avail_out == 0);
230 static int gzread(gzFile gz, void *buf, unsigned len) {
236 if (gz == NULL || gz->write)
241 strm->next_out = (void *)buf;
242 strm->avail_out = len;
244 got = fread(in, 1, 1, gz->file);
249 ret = inflate(strm, Z_NO_FLUSH);
250 if (ret == Z_DATA_ERROR) {
251 gz->err = Z_DATA_ERROR;
255 if (ret == Z_STREAM_END)
257 } while (strm->avail_out);
258 return len - strm->avail_out;
261 static int gzclose(gzFile gz) {
263 unsigned char out[BUFLEN];
266 return Z_STREAM_ERROR;
269 strm->next_in = Z_NULL;
272 strm->next_out = out;
273 strm->avail_out = BUFLEN;
274 (void)deflate(strm, Z_FINISH);
275 fwrite(out, 1, BUFLEN - strm->avail_out, gz->file);
276 } while (strm->avail_out == 0);
286 static const char *gzerror(gzFile gz, int *err) {
295 /* ===========================================================================
296 * Display error message and exit
298 static void error(const char *msg) {
299 fprintf(stderr, "%s: %s\n", prog, msg);
303 #ifdef USE_MMAP /* MMAP version, Miguel Albrecht <malbrech@eso.org> */
305 /* Try compressing the input file at once using mmap. Return Z_OK if
306 * success, Z_ERRNO otherwise.
308 static int gz_compress_mmap(FILE *in, gzFile out) {
311 int ifd = fileno(in);
312 caddr_t buf; /* mmap'ed buffer for the entire input file */
313 off_t buf_len; /* length of the input file */
316 /* Determine the size of the file, needed for mmap: */
317 if (fstat(ifd, &sb) < 0) return Z_ERRNO;
318 buf_len = sb.st_size;
319 if (buf_len <= 0) return Z_ERRNO;
321 /* Now do the actual mmap: */
322 buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0);
323 if (buf == (caddr_t)(-1)) return Z_ERRNO;
325 /* Compress the whole file at once: */
326 len = gzwrite(out, (char *)buf, (unsigned)buf_len);
328 if (len != (int)buf_len) error(gzerror(out, &err));
330 munmap(buf, buf_len);
332 if (gzclose(out) != Z_OK) error("failed gzclose");
335 #endif /* USE_MMAP */
337 /* ===========================================================================
338 * Compress input to output then close both files.
341 static void gz_compress(FILE *in, gzFile out) {
342 local char buf[BUFLEN];
347 /* Try first compressing with mmap. If mmap fails (minigzip used in a
348 * pipe), use the normal fread loop.
350 if (gz_compress_mmap(in, out) == Z_OK) return;
353 len = (int)fread(buf, 1, sizeof(buf), in);
360 if (gzwrite(out, buf, (unsigned)len) != len) error(gzerror(out, &err));
363 if (gzclose(out) != Z_OK) error("failed gzclose");
366 /* ===========================================================================
367 * Uncompress input to output then close both files.
369 static void gz_uncompress(gzFile in, FILE *out) {
370 local char buf[BUFLEN];
375 len = gzread(in, buf, sizeof(buf));
376 if (len < 0) error (gzerror(in, &err));
379 if ((int)fwrite(buf, 1, (unsigned)len, out) != len) {
380 error("failed fwrite");
383 if (fclose(out)) error("failed fclose");
385 if (gzclose(in) != Z_OK) error("failed gzclose");
389 /* ===========================================================================
390 * Compress the given file: create a corresponding .gz file and remove the
393 static void file_compress(char *file, char *mode) {
394 local char outfile[MAX_NAME_LEN];
398 if (strlen(file) + strlen(GZ_SUFFIX) >= sizeof(outfile)) {
399 fprintf(stderr, "%s: filename too long\n", prog);
403 #if !defined(NO_snprintf) && !defined(NO_vsnprintf)
404 snprintf(outfile, sizeof(outfile), "%s%s", file, GZ_SUFFIX);
406 strcpy(outfile, file);
407 strcat(outfile, GZ_SUFFIX);
410 in = fopen(file, "rb");
415 out = gzopen(outfile, mode);
417 fprintf(stderr, "%s: can't gzopen %s\n", prog, outfile);
420 gz_compress(in, out);
426 /* ===========================================================================
427 * Uncompress the given file and remove the original.
429 static void file_uncompress(char *file) {
430 local char buf[MAX_NAME_LEN];
431 char *infile, *outfile;
434 z_size_t len = strlen(file);
436 if (len + strlen(GZ_SUFFIX) >= sizeof(buf)) {
437 fprintf(stderr, "%s: filename too long\n", prog);
441 #if !defined(NO_snprintf) && !defined(NO_vsnprintf)
442 snprintf(buf, sizeof(buf), "%s", file);
447 if (len > SUFFIX_LEN && strcmp(file+len-SUFFIX_LEN, GZ_SUFFIX) == 0) {
450 outfile[len-3] = '\0';
454 #if !defined(NO_snprintf) && !defined(NO_vsnprintf)
455 snprintf(buf + len, sizeof(buf) - len, "%s", GZ_SUFFIX);
457 strcat(infile, GZ_SUFFIX);
460 in = gzopen(infile, "rb");
462 fprintf(stderr, "%s: can't gzopen %s\n", prog, infile);
465 out = fopen(outfile, "wb");
471 gz_uncompress(in, out);
477 /* ===========================================================================
478 * Usage: minigzip [-c] [-d] [-f] [-h] [-r] [-1 to -9] [files...]
479 * -c : write to standard output
481 * -f : compress with Z_FILTERED
482 * -h : compress with Z_HUFFMAN_ONLY
483 * -r : compress with Z_RLE
484 * -1 to -9 : compression level
487 int main(int argc, char *argv[]) {
491 char *bname, outmode[20];
493 #if !defined(NO_snprintf) && !defined(NO_vsnprintf)
494 snprintf(outmode, sizeof(outmode), "%s", "wb6 ");
496 strcpy(outmode, "wb6 ");
500 bname = strrchr(argv[0], '/');
507 if (!strcmp(bname, "gunzip"))
509 else if (!strcmp(bname, "zcat"))
510 copyout = uncompr = 1;
513 if (strcmp(*argv, "-c") == 0)
515 else if (strcmp(*argv, "-d") == 0)
517 else if (strcmp(*argv, "-f") == 0)
519 else if (strcmp(*argv, "-h") == 0)
521 else if (strcmp(*argv, "-r") == 0)
523 else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' &&
525 outmode[2] = (*argv)[1];
530 if (outmode[3] == ' ')
533 SET_BINARY_MODE(stdin);
534 SET_BINARY_MODE(stdout);
536 file = gzdopen(fileno(stdin), "rb");
537 if (file == NULL) error("can't gzdopen stdin");
538 gz_uncompress(file, stdout);
540 file = gzdopen(fileno(stdout), outmode);
541 if (file == NULL) error("can't gzdopen stdout");
542 gz_compress(stdin, file);
546 SET_BINARY_MODE(stdout);
551 file = gzopen(*argv, "rb");
553 fprintf(stderr, "%s: can't gzopen %s\n", prog, *argv);
555 gz_uncompress(file, stdout);
557 file_uncompress(*argv);
561 FILE * in = fopen(*argv, "rb");
566 file = gzdopen(fileno(stdout), outmode);
567 if (file == NULL) error("can't gzdopen stdout");
569 gz_compress(in, file);
573 file_compress(*argv, outmode);
576 } while (argv++, --argc);