2 * Copyright (c) 2003-2007 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 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 #include "archive_platform.h"
28 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_compression_gzip.c,v 1.13 2007/03/03 07:37:36 kientzle Exp $");
48 #include "archive_private.h"
49 #include "archive_read_private.h"
54 unsigned char *uncompressed_buffer;
55 size_t uncompressed_buffer_size;
56 unsigned char *read_next;
62 static int finish(struct archive_read *);
63 static ssize_t read_ahead(struct archive_read *, const void **, size_t);
64 static ssize_t read_consume(struct archive_read *, size_t);
65 static int drive_decompressor(struct archive_read *a, struct private_data *);
68 /* These two functions are defined even if we lack zlib. See below. */
69 static int bid(const void *, size_t);
70 static int init(struct archive_read *, const void *, size_t);
73 archive_read_support_compression_gzip(struct archive *_a)
75 struct archive_read *a = (struct archive_read *)_a;
76 return (__archive_read_register_compression(a, bid, init));
80 * Test whether we can handle this data.
82 * This logic returns zero if any part of the signature fails. It
83 * also tries to Do The Right Thing if a very short buffer prevents us
84 * from verifying as much as we would like.
87 bid(const void *buff, size_t len)
89 const unsigned char *buffer;
95 buffer = (const unsigned char *)buff;
97 if (buffer[0] != 037) /* Verify first ID byte. */
101 return (bits_checked);
103 if (buffer[1] != 0213) /* Verify second ID byte. */
107 return (bits_checked);
109 if (buffer[2] != 8) /* Compression must be 'deflate'. */
113 return (bits_checked);
115 if ((buffer[3] & 0xE0)!= 0) /* No reserved flags set. */
119 return (bits_checked);
122 * TODO: Verify more; in particular, gzip has an optional
123 * header CRC, which would give us 16 more verified bits. We
124 * may also be able to verify certain constraints on other
128 return (bits_checked);
135 * If we don't have zlib on this system, we can't actually do the
136 * decompression. We can, however, still detect gzip-compressed
137 * archives and emit a useful message.
140 init(struct archive_read *a, const void *buff, size_t n)
142 (void)a; /* UNUSED */
143 (void)buff; /* UNUSED */
144 (void)n; /* UNUSED */
146 archive_set_error(a, -1,
147 "This version of libarchive was compiled without gzip support");
148 return (ARCHIVE_FATAL);
155 * Setup the callbacks.
158 init(struct archive_read *a, const void *buff, size_t n)
160 struct private_data *state;
163 a->archive.compression_code = ARCHIVE_COMPRESSION_GZIP;
164 a->archive.compression_name = "gzip";
166 state = (struct private_data *)malloc(sizeof(*state));
168 archive_set_error(&a->archive, ENOMEM,
169 "Can't allocate data for %s decompression",
170 a->archive.compression_name);
171 return (ARCHIVE_FATAL);
173 memset(state, 0, sizeof(*state));
175 state->crc = crc32(0L, NULL, 0);
176 state->header_done = 0; /* We've not yet begun to parse header... */
178 state->uncompressed_buffer_size = 64 * 1024;
179 state->uncompressed_buffer = (unsigned char *)malloc(state->uncompressed_buffer_size);
180 state->stream.next_out = state->uncompressed_buffer;
181 state->read_next = state->uncompressed_buffer;
182 state->stream.avail_out = state->uncompressed_buffer_size;
184 if (state->uncompressed_buffer == NULL) {
185 archive_set_error(&a->archive, ENOMEM,
186 "Can't allocate %s decompression buffers",
187 a->archive.compression_name);
189 return (ARCHIVE_FATAL);
193 * A bug in zlib.h: stream.next_in should be marked 'const'
194 * but isn't (the library never alters data through the
195 * next_in pointer, only reads it). The result: this ugly
196 * cast to remove 'const'.
198 state->stream.next_in = (Bytef *)(uintptr_t)(const void *)buff;
199 state->stream.avail_in = n;
201 a->compression_read_ahead = read_ahead;
202 a->compression_read_consume = read_consume;
203 a->compression_skip = NULL; /* not supported */
204 a->compression_finish = finish;
207 * TODO: Do I need to parse the gzip header before calling
208 * inflateInit2()? In particular, one of the header bytes
209 * marks "best compression" or "fastest", which may be
210 * appropriate for setting the second parameter here.
211 * However, I think the only penalty for not setting it
212 * correctly is wasted memory. If this is necessary, it
213 * should probably go into drive_decompressor() below.
216 /* Initialize compression library. */
217 ret = inflateInit2(&(state->stream),
218 -15 /* Don't check for zlib header */);
220 a->compression_data = state;
224 /* Library setup failed: Clean up. */
225 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
226 "Internal error initializing %s library",
227 a->archive.compression_name);
228 free(state->uncompressed_buffer);
231 /* Override the error message if we know what really went wrong. */
234 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
235 "Internal error initializing compression library: "
236 "invalid setup parameter");
239 archive_set_error(&a->archive, ENOMEM,
240 "Internal error initializing compression library: "
243 case Z_VERSION_ERROR:
244 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
245 "Internal error initializing compression library: "
246 "invalid library version");
250 return (ARCHIVE_FATAL);
254 * Return a block of data from the decompression buffer. Decompress more
258 read_ahead(struct archive_read *a, const void **p, size_t min)
260 struct private_data *state;
261 int read_avail, was_avail, ret;
263 state = (struct private_data *)a->compression_data;
265 if (!a->client_reader) {
266 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
267 "No read callback is registered? "
268 "This is probably an internal programming error.");
269 return (ARCHIVE_FATAL);
272 read_avail = state->stream.next_out - state->read_next;
274 if (read_avail + state->stream.avail_out < min) {
275 memmove(state->uncompressed_buffer, state->read_next,
277 state->read_next = state->uncompressed_buffer;
278 state->stream.next_out = state->read_next + read_avail;
279 state->stream.avail_out
280 = state->uncompressed_buffer_size - read_avail;
283 while (was_avail < read_avail && /* Made some progress. */
284 read_avail < (int)min && /* Haven't satisfied min. */
285 read_avail < (int)state->uncompressed_buffer_size) { /* !full */
286 if ((ret = drive_decompressor(a, state)) != ARCHIVE_OK)
288 was_avail = read_avail;
289 read_avail = state->stream.next_out - state->read_next;
292 *p = state->read_next;
297 * Mark a previously-returned block of data as read.
300 read_consume(struct archive_read *a, size_t n)
302 struct private_data *state;
304 state = (struct private_data *)a->compression_data;
305 a->archive.file_position += n;
306 state->read_next += n;
307 if (state->read_next > state->stream.next_out)
308 __archive_errx(1, "Request to consume too many "
309 "bytes from gzip decompressor");
314 * Clean up the decompressor.
317 finish(struct archive_read *a)
319 struct private_data *state;
322 state = (struct private_data *)a->compression_data;
324 switch (inflateEnd(&(state->stream))) {
328 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
329 "Failed to clean up %s compressor",
330 a->archive.compression_name);
334 free(state->uncompressed_buffer);
337 a->compression_data = NULL;
338 if (a->client_closer != NULL)
339 (a->client_closer)(&a->archive, a->client_data);
345 * Utility function to pull data through decompressor, reading input
346 * blocks as necessary.
349 drive_decompressor(struct archive_read *a, struct private_data *state)
352 int decompressed, total_decompressed;
353 int count, flags, header_state;
354 unsigned char *output;
360 total_decompressed = 0;
362 if (state->stream.avail_in == 0) {
363 ret = (a->client_reader)(&a->archive, a->client_data,
364 (const void **)&state->stream.next_in);
367 * TODO: Find a better way to handle
372 if (ret == 0 && total_decompressed == 0) {
373 archive_set_error(&a->archive, EIO,
374 "Premature end of %s compressed data",
375 a->archive.compression_name);
376 return (ARCHIVE_FATAL);
378 a->archive.raw_position += ret;
379 state->stream.avail_in = ret;
382 if (!state->header_done) {
384 * If still parsing the header, interpret the
387 b = *(state->stream.next_in++);
388 state->stream.avail_in--;
391 * Yes, this is somewhat crude, but it works,
392 * GZip format isn't likely to change anytime
393 * in the near future, and header parsing is
394 * certainly not a performance issue, so
395 * there's little point in making this more
396 * elegant. Of course, if you see an easy way
397 * to make this more elegant, please let me
400 switch (header_state) {
401 case 0: /* First byte of signature. */
406 case 1: /* Second byte of signature. */
411 case 2: /* Compression type must be 8. */
416 case 3: /* GZip flags. */
420 case 4: case 5: case 6: case 7: /* Mod time. */
423 case 8: /* Deflate flags. */
429 case 10: /* Optional Extra: First byte of Length. */
431 count = 255 & (int)b;
436 * Fall through if there is no
437 * Optional Extra field.
439 case 11: /* Optional Extra: Second byte of Length. */
441 count = (0xff00 & ((int)b << 8)) | count;
446 * Fall through if there is no
447 * Optional Extra field.
449 case 12: /* Optional Extra Field: counted length. */
452 if (count == 0) header_state = 13;
453 else header_state = 12;
457 * Fall through if there is no
458 * Optional Extra field.
460 case 13: /* Optional Original Filename. */
462 if (b == 0) header_state = 14;
463 else header_state = 13;
467 * Fall through if no Optional
470 case 14: /* Optional Comment. */
472 if (b == 0) header_state = 15;
473 else header_state = 14;
476 /* Fall through if no Optional Comment. */
477 case 15: /* Optional Header CRC: First byte. */
482 /* Fall through if no Optional Header CRC. */
483 case 16: /* Optional Header CRC: Second byte. */
488 /* Fall through if no Optional Header CRC. */
489 case 17: /* First byte of compressed data. */
490 state->header_done = 1; /* done with header */
491 state->stream.avail_in++;
492 state->stream.next_in--;
496 * TODO: Consider moving the inflateInit2 call
497 * here so it can include the compression type
501 output = state->stream.next_out;
503 /* Decompress some data. */
504 ret = inflate(&(state->stream), 0);
505 decompressed = state->stream.next_out - output;
507 /* Accumulate the CRC of the uncompressed data. */
508 state->crc = crc32(state->crc, output, decompressed);
510 /* Accumulate the total bytes of output. */
511 state->total_out += decompressed;
512 total_decompressed += decompressed;
515 case Z_OK: /* Decompressor made some progress. */
516 if (decompressed > 0)
519 case Z_STREAM_END: /* Found end of stream. */
521 * TODO: Verify gzip trailer
522 * (uncompressed length and CRC).
526 /* Any other return value is an error. */
527 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
528 "gzip decompression failed (%s)",
536 /* Return a fatal error. */
538 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
539 "%s decompression failed", a->archive.compression_name);
540 return (ARCHIVE_FATAL);
543 #endif /* HAVE_ZLIB_H */