2 * Copyright (c) 2003-2004 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #include "archive_platform.h"
29 __FBSDID("$FreeBSD$");
41 #include "archive_private.h"
46 unsigned char *uncompressed_buffer;
47 size_t uncompressed_buffer_size;
48 unsigned char *read_next;
54 static int finish(struct archive *);
55 static ssize_t read_ahead(struct archive *, const void **, size_t);
56 static ssize_t read_consume(struct archive *, size_t);
57 static int drive_decompressor(struct archive *a, struct private_data *);
60 /* These two functions are defined even if we lack zlib. See below. */
61 static int bid(const void *, size_t);
62 static int init(struct archive *, const void *, size_t);
65 archive_read_support_compression_gzip(struct archive *a)
67 return (__archive_read_register_compression(a, bid, init));
71 * Test whether we can handle this data.
73 * This logic returns zero if any part of the signature fails. It
74 * also tries to Do The Right Thing if a very short buffer prevents us
75 * from verifying as much as we would like.
78 bid(const void *buff, size_t len)
80 const unsigned char *buffer;
88 if (buffer[0] != 037) /* Verify first ID byte. */
92 return (bits_checked);
94 if (buffer[1] != 0213) /* Verify second ID byte. */
98 return (bits_checked);
100 if (buffer[2] != 8) /* Compression must be 'deflate'. */
104 return (bits_checked);
106 if ((buffer[3] & 0xE0)!= 0) /* No reserved flags set. */
110 return (bits_checked);
113 * TODO: Verify more; in particular, gzip has an optional
114 * header CRC, which would give us 16 more verified bits. We
115 * may also be able to verify certain constraints on other
119 return (bits_checked);
126 * If we don't have zlib on this system, we can't actually do the
127 * decompression. We can, however, still detect gzip-compressed
128 * archives and emit a useful message.
131 init(struct archive *a, const void *buff, size_t n)
133 (void)a; /* UNUSED */
134 (void)buff; /* UNUSED */
135 (void)n; /* UNUSED */
137 archive_set_error(a, -1,
138 "This version of libarchive was compiled without gzip support");
139 return (ARCHIVE_FATAL);
146 * Setup the callbacks.
149 init(struct archive *a, const void *buff, size_t n)
151 struct private_data *state;
154 a->compression_code = ARCHIVE_COMPRESSION_GZIP;
155 a->compression_name = "gzip";
157 state = malloc(sizeof(*state));
159 archive_set_error(a, ENOMEM,
160 "Can't allocate data for %s decompression",
161 a->compression_name);
162 return (ARCHIVE_FATAL);
164 memset(state, 0, sizeof(*state));
166 state->crc = crc32(0L, NULL, 0);
167 state->header_done = 0; /* We've not yet begun to parse header... */
169 state->uncompressed_buffer_size = 64 * 1024;
170 state->uncompressed_buffer = malloc(state->uncompressed_buffer_size);
171 state->stream.next_out = state->uncompressed_buffer;
172 state->read_next = state->uncompressed_buffer;
173 state->stream.avail_out = state->uncompressed_buffer_size;
175 if (state->uncompressed_buffer == NULL) {
176 archive_set_error(a, ENOMEM,
177 "Can't allocate %s decompression buffers",
178 a->compression_name);
180 return (ARCHIVE_FATAL);
184 * A bug in zlib.h: stream.next_in should be marked 'const'
185 * but isn't (the library never alters data through the
186 * next_in pointer, only reads it). The result: this ugly
187 * cast to remove 'const'.
189 state->stream.next_in = (void *)(uintptr_t)(const void *)buff;
190 state->stream.avail_in = n;
192 a->compression_read_ahead = read_ahead;
193 a->compression_read_consume = read_consume;
194 a->compression_skip = NULL; /* not supported */
195 a->compression_finish = finish;
198 * TODO: Do I need to parse the gzip header before calling
199 * inflateInit2()? In particular, one of the header bytes
200 * marks "best compression" or "fastest", which may be
201 * appropriate for setting the second parameter here.
202 * However, I think the only penalty for not setting it
203 * correctly is wasted memory. If this is necessary, it
204 * should probably go into drive_decompressor() below.
207 /* Initialize compression library. */
208 ret = inflateInit2(&(state->stream),
209 -15 /* Don't check for zlib header */);
211 a->compression_data = state;
215 /* Library setup failed: Clean up. */
216 archive_set_error(a, ARCHIVE_ERRNO_MISC,
217 "Internal error initializing %s library", a->compression_name);
218 free(state->uncompressed_buffer);
221 /* Override the error message if we know what really went wrong. */
224 archive_set_error(a, ARCHIVE_ERRNO_MISC,
225 "Internal error initializing compression library: "
226 "invalid setup parameter");
229 archive_set_error(a, ENOMEM,
230 "Internal error initializing compression library: "
233 case Z_VERSION_ERROR:
234 archive_set_error(a, ARCHIVE_ERRNO_MISC,
235 "Internal error initializing compression library: "
236 "invalid library version");
240 return (ARCHIVE_FATAL);
244 * Return a block of data from the decompression buffer. Decompress more
248 read_ahead(struct archive *a, const void **p, size_t min)
250 struct private_data *state;
251 int read_avail, was_avail, ret;
253 state = a->compression_data;
255 if (!a->client_reader) {
256 archive_set_error(a, ARCHIVE_ERRNO_PROGRAMMER,
257 "No read callback is registered? "
258 "This is probably an internal programming error.");
259 return (ARCHIVE_FATAL);
262 read_avail = state->stream.next_out - state->read_next;
264 if (read_avail + state->stream.avail_out < min) {
265 memmove(state->uncompressed_buffer, state->read_next,
267 state->read_next = state->uncompressed_buffer;
268 state->stream.next_out = state->read_next + read_avail;
269 state->stream.avail_out
270 = state->uncompressed_buffer_size - read_avail;
273 while (was_avail < read_avail && /* Made some progress. */
274 read_avail < (int)min && /* Haven't satisfied min. */
275 read_avail < (int)state->uncompressed_buffer_size) { /* !full */
276 if ((ret = drive_decompressor(a, state)) != ARCHIVE_OK)
278 was_avail = read_avail;
279 read_avail = state->stream.next_out - state->read_next;
282 *p = state->read_next;
287 * Mark a previously-returned block of data as read.
290 read_consume(struct archive *a, size_t n)
292 struct private_data *state;
294 state = a->compression_data;
295 a->file_position += n;
296 state->read_next += n;
297 if (state->read_next > state->stream.next_out)
298 __archive_errx(1, "Request to consume too many "
299 "bytes from gzip decompressor");
304 * Clean up the decompressor.
307 finish(struct archive *a)
309 struct private_data *state;
312 state = a->compression_data;
314 switch (inflateEnd(&(state->stream))) {
318 archive_set_error(a, ARCHIVE_ERRNO_MISC,
319 "Failed to clean up %s compressor", a->compression_name);
323 free(state->uncompressed_buffer);
326 a->compression_data = NULL;
327 if (a->client_closer != NULL)
328 (a->client_closer)(a, a->client_data);
334 * Utility function to pull data through decompressor, reading input
335 * blocks as necessary.
338 drive_decompressor(struct archive *a, struct private_data *state)
341 int decompressed, total_decompressed;
342 int count, flags, header_state;
343 unsigned char *output;
349 total_decompressed = 0;
351 if (state->stream.avail_in == 0) {
352 ret = (a->client_reader)(a, a->client_data,
353 (const void **)&state->stream.next_in);
356 * TODO: Find a better way to handle
361 if (ret == 0 && total_decompressed == 0) {
362 archive_set_error(a, EIO,
363 "Premature end of %s compressed data",
364 a->compression_name);
365 return (ARCHIVE_FATAL);
367 a->raw_position += ret;
368 state->stream.avail_in = ret;
371 if (!state->header_done) {
373 * If still parsing the header, interpret the
376 b = *(state->stream.next_in++);
377 state->stream.avail_in--;
380 * Yes, this is somewhat crude, but it works,
381 * GZip format isn't likely to change anytime
382 * in the near future, and header parsing is
383 * certainly not a performance issue, so
384 * there's little point in making this more
385 * elegant. Of course, if you see an easy way
386 * to make this more elegant, please let me
389 switch (header_state) {
390 case 0: /* First byte of signature. */
395 case 1: /* Second byte of signature. */
400 case 2: /* Compression type must be 8. */
405 case 3: /* GZip flags. */
409 case 4: case 5: case 6: case 7: /* Mod time. */
412 case 8: /* Deflate flags. */
418 case 10: /* Optional Extra: First byte of Length. */
420 count = 255 & (int)b;
425 * Fall through if there is no
426 * Optional Extra field.
428 case 11: /* Optional Extra: Second byte of Length. */
430 count = (0xff00 & ((int)b << 8)) | count;
435 * Fall through if there is no
436 * Optional Extra field.
438 case 12: /* Optional Extra Field: counted length. */
441 if (count == 0) header_state = 13;
442 else header_state = 12;
446 * Fall through if there is no
447 * Optional Extra field.
449 case 13: /* Optional Original Filename. */
451 if (b == 0) header_state = 14;
452 else header_state = 13;
456 * Fall through if no Optional
459 case 14: /* Optional Comment. */
461 if (b == 0) header_state = 15;
462 else header_state = 14;
465 /* Fall through if no Optional Comment. */
466 case 15: /* Optional Header CRC: First byte. */
471 /* Fall through if no Optional Header CRC. */
472 case 16: /* Optional Header CRC: Second byte. */
477 /* Fall through if no Optional Header CRC. */
478 case 17: /* First byte of compressed data. */
479 state->header_done = 1; /* done with header */
480 state->stream.avail_in++;
481 state->stream.next_in--;
485 * TODO: Consider moving the inflateInit2 call
486 * here so it can include the compression type
490 output = state->stream.next_out;
492 /* Decompress some data. */
493 ret = inflate(&(state->stream), 0);
494 decompressed = state->stream.next_out - output;
496 /* Accumulate the CRC of the uncompressed data. */
497 state->crc = crc32(state->crc, output, decompressed);
499 /* Accumulate the total bytes of output. */
500 state->total_out += decompressed;
501 total_decompressed += decompressed;
504 case Z_OK: /* Decompressor made some progress. */
505 if (decompressed > 0)
508 case Z_STREAM_END: /* Found end of stream. */
510 * TODO: Verify gzip trailer
511 * (uncompressed length and CRC).
515 /* Any other return value is an error. */
516 archive_set_error(a, ARCHIVE_ERRNO_MISC,
517 "gzip decompression failed (%s)",
525 /* Return a fatal error. */
527 archive_set_error(a, ARCHIVE_ERRNO_MISC, "%s decompression failed",
528 a->compression_name);
529 return (ARCHIVE_FATAL);
532 #endif /* HAVE_ZLIB_H */