Chris@4: /* gzappend -- command to append to a gzip file Chris@4: Chris@4: Copyright (C) 2003 Mark Adler, all rights reserved Chris@4: version 1.1, 4 Nov 2003 Chris@4: Chris@4: This software is provided 'as-is', without any express or implied Chris@4: warranty. In no event will the author be held liable for any damages Chris@4: arising from the use of this software. Chris@4: Chris@4: Permission is granted to anyone to use this software for any purpose, Chris@4: including commercial applications, and to alter it and redistribute it Chris@4: freely, subject to the following restrictions: Chris@4: Chris@4: 1. The origin of this software must not be misrepresented; you must not Chris@4: claim that you wrote the original software. If you use this software Chris@4: in a product, an acknowledgment in the product documentation would be Chris@4: appreciated but is not required. Chris@4: 2. Altered source versions must be plainly marked as such, and must not be Chris@4: misrepresented as being the original software. Chris@4: 3. This notice may not be removed or altered from any source distribution. Chris@4: Chris@4: Mark Adler madler@alumni.caltech.edu Chris@4: */ Chris@4: Chris@4: /* Chris@4: * Change history: Chris@4: * Chris@4: * 1.0 19 Oct 2003 - First version Chris@4: * 1.1 4 Nov 2003 - Expand and clarify some comments and notes Chris@4: * - Add version and copyright to help Chris@4: * - Send help to stdout instead of stderr Chris@4: * - Add some preemptive typecasts Chris@4: * - Add L to constants in lseek() calls Chris@4: * - Remove some debugging information in error messages Chris@4: * - Use new data_type definition for zlib 1.2.1 Chris@4: * - Simplfy and unify file operations Chris@4: * - Finish off gzip file in gztack() Chris@4: * - Use deflatePrime() instead of adding empty blocks Chris@4: * - Keep gzip file clean on appended file read errors Chris@4: * - Use in-place rotate instead of auxiliary buffer Chris@4: * (Why you ask? Because it was fun to write!) Chris@4: */ Chris@4: Chris@4: /* Chris@4: gzappend takes a gzip file and appends to it, compressing files from the Chris@4: command line or data from stdin. The gzip file is written to directly, to Chris@4: avoid copying that file, in case it's large. Note that this results in the Chris@4: unfriendly behavior that if gzappend fails, the gzip file is corrupted. Chris@4: Chris@4: This program was written to illustrate the use of the new Z_BLOCK option of Chris@4: zlib 1.2.x's inflate() function. This option returns from inflate() at each Chris@4: block boundary to facilitate locating and modifying the last block bit at Chris@4: the start of the final deflate block. Also whether using Z_BLOCK or not, Chris@4: another required feature of zlib 1.2.x is that inflate() now provides the Chris@4: number of unusued bits in the last input byte used. gzappend will not work Chris@4: with versions of zlib earlier than 1.2.1. Chris@4: Chris@4: gzappend first decompresses the gzip file internally, discarding all but Chris@4: the last 32K of uncompressed data, and noting the location of the last block Chris@4: bit and the number of unused bits in the last byte of the compressed data. Chris@4: The gzip trailer containing the CRC-32 and length of the uncompressed data Chris@4: is verified. This trailer will be later overwritten. Chris@4: Chris@4: Then the last block bit is cleared by seeking back in the file and rewriting Chris@4: the byte that contains it. Seeking forward, the last byte of the compressed Chris@4: data is saved along with the number of unused bits to initialize deflate. Chris@4: Chris@4: A deflate process is initialized, using the last 32K of the uncompressed Chris@4: data from the gzip file to initialize the dictionary. If the total Chris@4: uncompressed data was less than 32K, then all of it is used to initialize Chris@4: the dictionary. The deflate output bit buffer is also initialized with the Chris@4: last bits from the original deflate stream. From here on, the data to Chris@4: append is simply compressed using deflate, and written to the gzip file. Chris@4: When that is complete, the new CRC-32 and uncompressed length are written Chris@4: as the trailer of the gzip file. Chris@4: */ Chris@4: Chris@4: #include Chris@4: #include Chris@4: #include Chris@4: #include Chris@4: #include Chris@4: #include "zlib.h" Chris@4: Chris@4: #define local static Chris@4: #define LGCHUNK 14 Chris@4: #define CHUNK (1U << LGCHUNK) Chris@4: #define DSIZE 32768U Chris@4: Chris@4: /* print an error message and terminate with extreme prejudice */ Chris@4: local void bye(char *msg1, char *msg2) Chris@4: { Chris@4: fprintf(stderr, "gzappend error: %s%s\n", msg1, msg2); Chris@4: exit(1); Chris@4: } Chris@4: Chris@4: /* return the greatest common divisor of a and b using Euclid's algorithm, Chris@4: modified to be fast when one argument much greater than the other, and Chris@4: coded to avoid unnecessary swapping */ Chris@4: local unsigned gcd(unsigned a, unsigned b) Chris@4: { Chris@4: unsigned c; Chris@4: Chris@4: while (a && b) Chris@4: if (a > b) { Chris@4: c = b; Chris@4: while (a - c >= c) Chris@4: c <<= 1; Chris@4: a -= c; Chris@4: } Chris@4: else { Chris@4: c = a; Chris@4: while (b - c >= c) Chris@4: c <<= 1; Chris@4: b -= c; Chris@4: } Chris@4: return a + b; Chris@4: } Chris@4: Chris@4: /* rotate list[0..len-1] left by rot positions, in place */ Chris@4: local void rotate(unsigned char *list, unsigned len, unsigned rot) Chris@4: { Chris@4: unsigned char tmp; Chris@4: unsigned cycles; Chris@4: unsigned char *start, *last, *to, *from; Chris@4: Chris@4: /* normalize rot and handle degenerate cases */ Chris@4: if (len < 2) return; Chris@4: if (rot >= len) rot %= len; Chris@4: if (rot == 0) return; Chris@4: Chris@4: /* pointer to last entry in list */ Chris@4: last = list + (len - 1); Chris@4: Chris@4: /* do simple left shift by one */ Chris@4: if (rot == 1) { Chris@4: tmp = *list; Chris@4: memcpy(list, list + 1, len - 1); Chris@4: *last = tmp; Chris@4: return; Chris@4: } Chris@4: Chris@4: /* do simple right shift by one */ Chris@4: if (rot == len - 1) { Chris@4: tmp = *last; Chris@4: memmove(list + 1, list, len - 1); Chris@4: *list = tmp; Chris@4: return; Chris@4: } Chris@4: Chris@4: /* otherwise do rotate as a set of cycles in place */ Chris@4: cycles = gcd(len, rot); /* number of cycles */ Chris@4: do { Chris@4: start = from = list + cycles; /* start index is arbitrary */ Chris@4: tmp = *from; /* save entry to be overwritten */ Chris@4: for (;;) { Chris@4: to = from; /* next step in cycle */ Chris@4: from += rot; /* go right rot positions */ Chris@4: if (from > last) from -= len; /* (pointer better not wrap) */ Chris@4: if (from == start) break; /* all but one shifted */ Chris@4: *to = *from; /* shift left */ Chris@4: } Chris@4: *to = tmp; /* complete the circle */ Chris@4: } while (--cycles); Chris@4: } Chris@4: Chris@4: /* structure for gzip file read operations */ Chris@4: typedef struct { Chris@4: int fd; /* file descriptor */ Chris@4: int size; /* 1 << size is bytes in buf */ Chris@4: unsigned left; /* bytes available at next */ Chris@4: unsigned char *buf; /* buffer */ Chris@4: unsigned char *next; /* next byte in buffer */ Chris@4: char *name; /* file name for error messages */ Chris@4: } file; Chris@4: Chris@4: /* reload buffer */ Chris@4: local int readin(file *in) Chris@4: { Chris@4: int len; Chris@4: Chris@4: len = read(in->fd, in->buf, 1 << in->size); Chris@4: if (len == -1) bye("error reading ", in->name); Chris@4: in->left = (unsigned)len; Chris@4: in->next = in->buf; Chris@4: return len; Chris@4: } Chris@4: Chris@4: /* read from file in, exit if end-of-file */ Chris@4: local int readmore(file *in) Chris@4: { Chris@4: if (readin(in) == 0) bye("unexpected end of ", in->name); Chris@4: return 0; Chris@4: } Chris@4: Chris@4: #define read1(in) (in->left == 0 ? readmore(in) : 0, \ Chris@4: in->left--, *(in->next)++) Chris@4: Chris@4: /* skip over n bytes of in */ Chris@4: local void skip(file *in, unsigned n) Chris@4: { Chris@4: unsigned bypass; Chris@4: Chris@4: if (n > in->left) { Chris@4: n -= in->left; Chris@4: bypass = n & ~((1U << in->size) - 1); Chris@4: if (bypass) { Chris@4: if (lseek(in->fd, (off_t)bypass, SEEK_CUR) == -1) Chris@4: bye("seeking ", in->name); Chris@4: n -= bypass; Chris@4: } Chris@4: readmore(in); Chris@4: if (n > in->left) Chris@4: bye("unexpected end of ", in->name); Chris@4: } Chris@4: in->left -= n; Chris@4: in->next += n; Chris@4: } Chris@4: Chris@4: /* read a four-byte unsigned integer, little-endian, from in */ Chris@4: unsigned long read4(file *in) Chris@4: { Chris@4: unsigned long val; Chris@4: Chris@4: val = read1(in); Chris@4: val += (unsigned)read1(in) << 8; Chris@4: val += (unsigned long)read1(in) << 16; Chris@4: val += (unsigned long)read1(in) << 24; Chris@4: return val; Chris@4: } Chris@4: Chris@4: /* skip over gzip header */ Chris@4: local void gzheader(file *in) Chris@4: { Chris@4: int flags; Chris@4: unsigned n; Chris@4: Chris@4: if (read1(in) != 31 || read1(in) != 139) bye(in->name, " not a gzip file"); Chris@4: if (read1(in) != 8) bye("unknown compression method in", in->name); Chris@4: flags = read1(in); Chris@4: if (flags & 0xe0) bye("unknown header flags set in", in->name); Chris@4: skip(in, 6); Chris@4: if (flags & 4) { Chris@4: n = read1(in); Chris@4: n += (unsigned)(read1(in)) << 8; Chris@4: skip(in, n); Chris@4: } Chris@4: if (flags & 8) while (read1(in) != 0) ; Chris@4: if (flags & 16) while (read1(in) != 0) ; Chris@4: if (flags & 2) skip(in, 2); Chris@4: } Chris@4: Chris@4: /* decompress gzip file "name", return strm with a deflate stream ready to Chris@4: continue compression of the data in the gzip file, and return a file Chris@4: descriptor pointing to where to write the compressed data -- the deflate Chris@4: stream is initialized to compress using level "level" */ Chris@4: local int gzscan(char *name, z_stream *strm, int level) Chris@4: { Chris@4: int ret, lastbit, left, full; Chris@4: unsigned have; Chris@4: unsigned long crc, tot; Chris@4: unsigned char *window; Chris@4: off_t lastoff, end; Chris@4: file gz; Chris@4: Chris@4: /* open gzip file */ Chris@4: gz.name = name; Chris@4: gz.fd = open(name, O_RDWR, 0); Chris@4: if (gz.fd == -1) bye("cannot open ", name); Chris@4: gz.buf = malloc(CHUNK); Chris@4: if (gz.buf == NULL) bye("out of memory", ""); Chris@4: gz.size = LGCHUNK; Chris@4: gz.left = 0; Chris@4: Chris@4: /* skip gzip header */ Chris@4: gzheader(&gz); Chris@4: Chris@4: /* prepare to decompress */ Chris@4: window = malloc(DSIZE); Chris@4: if (window == NULL) bye("out of memory", ""); Chris@4: strm->zalloc = Z_NULL; Chris@4: strm->zfree = Z_NULL; Chris@4: strm->opaque = Z_NULL; Chris@4: ret = inflateInit2(strm, -15); Chris@4: if (ret != Z_OK) bye("out of memory", " or library mismatch"); Chris@4: Chris@4: /* decompress the deflate stream, saving append information */ Chris@4: lastbit = 0; Chris@4: lastoff = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; Chris@4: left = 0; Chris@4: strm->avail_in = gz.left; Chris@4: strm->next_in = gz.next; Chris@4: crc = crc32(0L, Z_NULL, 0); Chris@4: have = full = 0; Chris@4: do { Chris@4: /* if needed, get more input */ Chris@4: if (strm->avail_in == 0) { Chris@4: readmore(&gz); Chris@4: strm->avail_in = gz.left; Chris@4: strm->next_in = gz.next; Chris@4: } Chris@4: Chris@4: /* set up output to next available section of sliding window */ Chris@4: strm->avail_out = DSIZE - have; Chris@4: strm->next_out = window + have; Chris@4: Chris@4: /* inflate and check for errors */ Chris@4: ret = inflate(strm, Z_BLOCK); Chris@4: if (ret == Z_STREAM_ERROR) bye("internal stream error!", ""); Chris@4: if (ret == Z_MEM_ERROR) bye("out of memory", ""); Chris@4: if (ret == Z_DATA_ERROR) Chris@4: bye("invalid compressed data--format violated in", name); Chris@4: Chris@4: /* update crc and sliding window pointer */ Chris@4: crc = crc32(crc, window + have, DSIZE - have - strm->avail_out); Chris@4: if (strm->avail_out) Chris@4: have = DSIZE - strm->avail_out; Chris@4: else { Chris@4: have = 0; Chris@4: full = 1; Chris@4: } Chris@4: Chris@4: /* process end of block */ Chris@4: if (strm->data_type & 128) { Chris@4: if (strm->data_type & 64) Chris@4: left = strm->data_type & 0x1f; Chris@4: else { Chris@4: lastbit = strm->data_type & 0x1f; Chris@4: lastoff = lseek(gz.fd, 0L, SEEK_CUR) - strm->avail_in; Chris@4: } Chris@4: } Chris@4: } while (ret != Z_STREAM_END); Chris@4: inflateEnd(strm); Chris@4: gz.left = strm->avail_in; Chris@4: gz.next = strm->next_in; Chris@4: Chris@4: /* save the location of the end of the compressed data */ Chris@4: end = lseek(gz.fd, 0L, SEEK_CUR) - gz.left; Chris@4: Chris@4: /* check gzip trailer and save total for deflate */ Chris@4: if (crc != read4(&gz)) Chris@4: bye("invalid compressed data--crc mismatch in ", name); Chris@4: tot = strm->total_out; Chris@4: if ((tot & 0xffffffffUL) != read4(&gz)) Chris@4: bye("invalid compressed data--length mismatch in", name); Chris@4: Chris@4: /* if not at end of file, warn */ Chris@4: if (gz.left || readin(&gz)) Chris@4: fprintf(stderr, Chris@4: "gzappend warning: junk at end of gzip file overwritten\n"); Chris@4: Chris@4: /* clear last block bit */ Chris@4: lseek(gz.fd, lastoff - (lastbit != 0), SEEK_SET); Chris@4: if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); Chris@4: *gz.buf = (unsigned char)(*gz.buf ^ (1 << ((8 - lastbit) & 7))); Chris@4: lseek(gz.fd, -1L, SEEK_CUR); Chris@4: if (write(gz.fd, gz.buf, 1) != 1) bye("writing after seek to ", name); Chris@4: Chris@4: /* if window wrapped, build dictionary from window by rotating */ Chris@4: if (full) { Chris@4: rotate(window, DSIZE, have); Chris@4: have = DSIZE; Chris@4: } Chris@4: Chris@4: /* set up deflate stream with window, crc, total_in, and leftover bits */ Chris@4: ret = deflateInit2(strm, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); Chris@4: if (ret != Z_OK) bye("out of memory", ""); Chris@4: deflateSetDictionary(strm, window, have); Chris@4: strm->adler = crc; Chris@4: strm->total_in = tot; Chris@4: if (left) { Chris@4: lseek(gz.fd, --end, SEEK_SET); Chris@4: if (read(gz.fd, gz.buf, 1) != 1) bye("reading after seek on ", name); Chris@4: deflatePrime(strm, 8 - left, *gz.buf); Chris@4: } Chris@4: lseek(gz.fd, end, SEEK_SET); Chris@4: Chris@4: /* clean up and return */ Chris@4: free(window); Chris@4: free(gz.buf); Chris@4: return gz.fd; Chris@4: } Chris@4: Chris@4: /* append file "name" to gzip file gd using deflate stream strm -- if last Chris@4: is true, then finish off the deflate stream at the end */ Chris@4: local void gztack(char *name, int gd, z_stream *strm, int last) Chris@4: { Chris@4: int fd, len, ret; Chris@4: unsigned left; Chris@4: unsigned char *in, *out; Chris@4: Chris@4: /* open file to compress and append */ Chris@4: fd = 0; Chris@4: if (name != NULL) { Chris@4: fd = open(name, O_RDONLY, 0); Chris@4: if (fd == -1) Chris@4: fprintf(stderr, "gzappend warning: %s not found, skipping ...\n", Chris@4: name); Chris@4: } Chris@4: Chris@4: /* allocate buffers */ Chris@4: in = fd == -1 ? NULL : malloc(CHUNK); Chris@4: out = malloc(CHUNK); Chris@4: if (out == NULL) bye("out of memory", ""); Chris@4: Chris@4: /* compress input file and append to gzip file */ Chris@4: do { Chris@4: /* get more input */ Chris@4: len = fd == -1 ? 0 : read(fd, in, CHUNK); Chris@4: if (len == -1) { Chris@4: fprintf(stderr, Chris@4: "gzappend warning: error reading %s, skipping rest ...\n", Chris@4: name); Chris@4: len = 0; Chris@4: } Chris@4: strm->avail_in = (unsigned)len; Chris@4: strm->next_in = in; Chris@4: if (len) strm->adler = crc32(strm->adler, in, (unsigned)len); Chris@4: Chris@4: /* compress and write all available output */ Chris@4: do { Chris@4: strm->avail_out = CHUNK; Chris@4: strm->next_out = out; Chris@4: ret = deflate(strm, last && len == 0 ? Z_FINISH : Z_NO_FLUSH); Chris@4: left = CHUNK - strm->avail_out; Chris@4: while (left) { Chris@4: len = write(gd, out + CHUNK - strm->avail_out - left, left); Chris@4: if (len == -1) bye("writing gzip file", ""); Chris@4: left -= (unsigned)len; Chris@4: } Chris@4: } while (strm->avail_out == 0 && ret != Z_STREAM_END); Chris@4: } while (len != 0); Chris@4: Chris@4: /* write trailer after last entry */ Chris@4: if (last) { Chris@4: deflateEnd(strm); Chris@4: out[0] = (unsigned char)(strm->adler); Chris@4: out[1] = (unsigned char)(strm->adler >> 8); Chris@4: out[2] = (unsigned char)(strm->adler >> 16); Chris@4: out[3] = (unsigned char)(strm->adler >> 24); Chris@4: out[4] = (unsigned char)(strm->total_in); Chris@4: out[5] = (unsigned char)(strm->total_in >> 8); Chris@4: out[6] = (unsigned char)(strm->total_in >> 16); Chris@4: out[7] = (unsigned char)(strm->total_in >> 24); Chris@4: len = 8; Chris@4: do { Chris@4: ret = write(gd, out + 8 - len, len); Chris@4: if (ret == -1) bye("writing gzip file", ""); Chris@4: len -= ret; Chris@4: } while (len); Chris@4: close(gd); Chris@4: } Chris@4: Chris@4: /* clean up and return */ Chris@4: free(out); Chris@4: if (in != NULL) free(in); Chris@4: if (fd > 0) close(fd); Chris@4: } Chris@4: Chris@4: /* process the compression level option if present, scan the gzip file, and Chris@4: append the specified files, or append the data from stdin if no other file Chris@4: names are provided on the command line -- the gzip file must be writable Chris@4: and seekable */ Chris@4: int main(int argc, char **argv) Chris@4: { Chris@4: int gd, level; Chris@4: z_stream strm; Chris@4: Chris@4: /* ignore command name */ Chris@4: argv++; Chris@4: Chris@4: /* provide usage if no arguments */ Chris@4: if (*argv == NULL) { Chris@4: printf("gzappend 1.1 (4 Nov 2003) Copyright (C) 2003 Mark Adler\n"); Chris@4: printf( Chris@4: "usage: gzappend [-level] file.gz [ addthis [ andthis ... ]]\n"); Chris@4: return 0; Chris@4: } Chris@4: Chris@4: /* set compression level */ Chris@4: level = Z_DEFAULT_COMPRESSION; Chris@4: if (argv[0][0] == '-') { Chris@4: if (argv[0][1] < '0' || argv[0][1] > '9' || argv[0][2] != 0) Chris@4: bye("invalid compression level", ""); Chris@4: level = argv[0][1] - '0'; Chris@4: if (*++argv == NULL) bye("no gzip file name after options", ""); Chris@4: } Chris@4: Chris@4: /* prepare to append to gzip file */ Chris@4: gd = gzscan(*argv++, &strm, level); Chris@4: Chris@4: /* append files on command line, or from stdin if none */ Chris@4: if (*argv == NULL) Chris@4: gztack(NULL, gd, &strm, 1); Chris@4: else Chris@4: do { Chris@4: gztack(*argv, gd, &strm, argv[1] == NULL); Chris@4: } while (*++argv != NULL); Chris@4: return 0; Chris@4: }