Upgrade to libarchive-2.7.0.
[dragonfly.git] / contrib / libarchive / libarchive / archive_read_support_compression_gzip.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
13  *
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.
24  */
25
26 #include "archive_platform.h"
27
28 __FBSDID("$FreeBSD: src/lib/libarchive/archive_read_support_compression_gzip.c,v 1.17 2008/12/06 06:45:15 kientzle Exp $");
29
30
31 #ifdef HAVE_ERRNO_H
32 #include <errno.h>
33 #endif
34 #ifdef HAVE_STDLIB_H
35 #include <stdlib.h>
36 #endif
37 #ifdef HAVE_STRING_H
38 #include <string.h>
39 #endif
40 #ifdef HAVE_UNISTD_H
41 #include <unistd.h>
42 #endif
43 #ifdef HAVE_ZLIB_H
44 #include <zlib.h>
45 #endif
46
47 #include "archive.h"
48 #include "archive_private.h"
49 #include "archive_read_private.h"
50
51 #ifdef HAVE_ZLIB_H
52 struct private_data {
53         z_stream         stream;
54         char             in_stream;
55         unsigned char   *out_block;
56         size_t           out_block_size;
57         int64_t          total_out;
58         unsigned long    crc;
59         char             eof; /* True = found end of compressed data. */
60 };
61
62 /* Gzip Filter. */
63 static ssize_t  gzip_filter_read(struct archive_read_filter *, const void **);
64 static int      gzip_filter_close(struct archive_read_filter *);
65 #endif
66
67 /*
68  * Note that we can detect gzip archives even if we can't decompress
69  * them.  (In fact, we like detecting them because we can give better
70  * error messages.)  So the bid framework here gets compiled even
71  * if zlib is unavailable.
72  *
73  * TODO: If zlib is unavailable, gzip_bidder_init() should
74  * use the compress_program framework to try to fire up an external
75  * gunzip program.
76  */
77 static int      gzip_bidder_bid(struct archive_read_filter_bidder *,
78                     struct archive_read_filter *);
79 static int      gzip_bidder_init(struct archive_read_filter *);
80
81 int
82 archive_read_support_compression_gzip(struct archive *_a)
83 {
84         struct archive_read *a = (struct archive_read *)_a;
85         struct archive_read_filter_bidder *bidder = __archive_read_get_bidder(a);
86
87         if (bidder == NULL)
88                 return (ARCHIVE_FATAL);
89
90         bidder->data = NULL;
91         bidder->bid = gzip_bidder_bid;
92         bidder->init = gzip_bidder_init;
93         bidder->options = NULL;
94         bidder->free = NULL; /* No data, so no cleanup necessary. */
95         /* Signal the extent of gzip support with the return value here. */
96 #if HAVE_ZLIB_H
97         return (ARCHIVE_OK);
98 #else
99         archive_set_error(_a, ARCHIVE_ERRNO_MISC,
100             "Using external gunzip program");
101         return (ARCHIVE_WARN);
102 #endif
103 }
104
105 /*
106  * Read and verify the header.
107  *
108  * Returns zero if the header couldn't be validated, else returns
109  * number of bytes in header.  If pbits is non-NULL, it receives a
110  * count of bits verified, suitable for use by bidder.
111  */
112 static int
113 peek_at_header(struct archive_read_filter *filter, int *pbits)
114 {
115         const unsigned char *p;
116         ssize_t avail, len;
117         int bits = 0;
118         int header_flags;
119
120         /* Start by looking at the first ten bytes of the header, which
121          * is all fixed layout. */
122         len = 10;
123         p = __archive_read_filter_ahead(filter, len, &avail);
124         if (p == NULL || avail == 0)
125                 return (0);
126         if (p[0] != 037)
127                 return (0);
128         bits += 8;
129         if (p[1] != 0213)
130                 return (0);
131         bits += 8;
132         if (p[2] != 8) /* We only support deflation. */
133                 return (0);
134         bits += 8;
135         if ((p[3] & 0xE0)!= 0)  /* No reserved flags set. */
136                 return (0);
137         bits += 3;
138         header_flags = p[3];
139         /* Bytes 4-7 are mod time. */
140         /* Byte 8 is deflate flags. */
141         /* XXXX TODO: return deflate flags back to consume_header for use
142            in initializing the decompressor. */
143         /* Byte 9 is OS. */
144
145         /* Optional extra data:  2 byte length plus variable body. */
146         if (header_flags & 4) {
147                 p = __archive_read_filter_ahead(filter, len + 2, &avail);
148                 if (p == NULL)
149                         return (0);
150                 len += ((int)p[len + 1] << 8) | (int)p[len];
151         }
152
153         /* Null-terminated optional filename. */
154         if (header_flags & 8) {
155                 do {
156                         ++len;
157                         if (avail < len)
158                                 p = __archive_read_filter_ahead(filter,
159                                     len, &avail);
160                         if (p == NULL)
161                                 return (0);
162                 } while (p[len - 1] != 0);
163         }
164
165         /* Null-terminated optional comment. */
166         if (header_flags & 16) {
167                 do {
168                         ++len;
169                         if (avail < len)
170                                 p = __archive_read_filter_ahead(filter,
171                                     len, &avail);
172                         if (p == NULL)
173                                 return (0);
174                 } while (p[len - 1] != 0);
175         }
176
177         /* Optional header CRC */
178         if ((header_flags & 2)) {
179                 p = __archive_read_filter_ahead(filter, len + 2, &avail);
180                 if (p == NULL)
181                         return (0);
182 #if 0
183         int hcrc = ((int)p[len + 1] << 8) | (int)p[len];
184         int crc = /* XXX TODO: Compute header CRC. */;
185         if (crc != hcrc)
186                 return (0);
187         bits += 16;
188 #endif
189                 len += 2;
190         }
191
192         if (pbits != NULL)
193                 *pbits = bits;
194         return (len);
195 }
196
197 /*
198  * Bidder just verifies the header and returns the number of verified bits.
199  */
200 static int
201 gzip_bidder_bid(struct archive_read_filter_bidder *self,
202     struct archive_read_filter *filter)
203 {
204         int bits_checked;
205
206         (void)self; /* UNUSED */
207
208         if (peek_at_header(filter, &bits_checked))
209                 return (bits_checked);
210         return (0);
211 }
212
213
214 #ifndef HAVE_ZLIB_H
215
216 /*
217  * If we don't have the library on this system, we can't do the
218  * decompression directly.  We can, however, try to run gunzip
219  * in case that's available.
220  */
221 static int
222 gzip_bidder_init(struct archive_read_filter *self)
223 {
224         int r;
225
226         r = __archive_read_program(self, "gunzip");
227         /* Note: We set the format here even if __archive_read_program()
228          * above fails.  We do, after all, know what the format is
229          * even if we weren't able to read it. */
230         self->code = ARCHIVE_COMPRESSION_GZIP;
231         self->name = "gzip";
232         return (r);
233 }
234
235 #else
236
237 /*
238  * Initialize the filter object.
239  */
240 static int
241 gzip_bidder_init(struct archive_read_filter *self)
242 {
243         struct private_data *state;
244         static const size_t out_block_size = 64 * 1024;
245         void *out_block;
246
247         self->code = ARCHIVE_COMPRESSION_GZIP;
248         self->name = "gzip";
249
250         state = (struct private_data *)calloc(sizeof(*state), 1);
251         out_block = (unsigned char *)malloc(out_block_size);
252         if (state == NULL || out_block == NULL) {
253                 free(out_block);
254                 free(state);
255                 archive_set_error(&self->archive->archive, ENOMEM,
256                     "Can't allocate data for gzip decompression");
257                 return (ARCHIVE_FATAL);
258         }
259
260         self->data = state;
261         state->out_block_size = out_block_size;
262         state->out_block = out_block;
263         self->read = gzip_filter_read;
264         self->skip = NULL; /* not supported */
265         self->close = gzip_filter_close;
266
267         state->in_stream = 0; /* We're not actually within a stream yet. */
268
269         return (ARCHIVE_OK);
270 }
271
272 static int
273 consume_header(struct archive_read_filter *self)
274 {
275         struct private_data *state;
276         ssize_t avail;
277         size_t len;
278         int ret;
279
280         state = (struct private_data *)self->data;
281
282         /* If this is a real header, consume it. */
283         len = peek_at_header(self->upstream, NULL);
284         if (len == 0)
285                 return (ARCHIVE_EOF);
286         __archive_read_filter_consume(self->upstream, len);
287
288         /* Initialize CRC accumulator. */
289         state->crc = crc32(0L, NULL, 0);
290
291         /* Initialize compression library. */
292         state->stream.next_in = (unsigned char *)(uintptr_t)
293             __archive_read_filter_ahead(self->upstream, 1, &avail);
294         state->stream.avail_in = avail;
295         ret = inflateInit2(&(state->stream),
296             -15 /* Don't check for zlib header */);
297
298         /* Decipher the error code. */
299         switch (ret) {
300         case Z_OK:
301                 state->in_stream = 1;
302                 return (ARCHIVE_OK);
303         case Z_STREAM_ERROR:
304                 archive_set_error(&self->archive->archive,
305                     ARCHIVE_ERRNO_MISC,
306                     "Internal error initializing compression library: "
307                     "invalid setup parameter");
308                 break;
309         case Z_MEM_ERROR:
310                 archive_set_error(&self->archive->archive, ENOMEM,
311                     "Internal error initializing compression library: "
312                     "out of memory");
313                 break;
314         case Z_VERSION_ERROR:
315                 archive_set_error(&self->archive->archive,
316                     ARCHIVE_ERRNO_MISC,
317                     "Internal error initializing compression library: "
318                     "invalid library version");
319                 break;
320         default:
321                 archive_set_error(&self->archive->archive,
322                     ARCHIVE_ERRNO_MISC,
323                     "Internal error initializing compression library: "
324                     " Zlib error %d", ret);
325                 break;
326         }
327         return (ARCHIVE_FATAL);
328 }
329
330 static int
331 consume_trailer(struct archive_read_filter *self)
332 {
333         struct private_data *state;
334         const unsigned char *p;
335         ssize_t avail;
336
337         state = (struct private_data *)self->data;
338
339         state->in_stream = 0;
340         switch (inflateEnd(&(state->stream))) {
341         case Z_OK:
342                 break;
343         default:
344                 archive_set_error(&self->archive->archive,
345                     ARCHIVE_ERRNO_MISC,
346                     "Failed to clean up gzip decompressor");
347                 return (ARCHIVE_FATAL);
348         }
349
350         /* GZip trailer is a fixed 8 byte structure. */
351         p = __archive_read_filter_ahead(self->upstream, 8, &avail);
352         if (p == NULL || avail == 0)
353                 return (ARCHIVE_FATAL);
354
355         /* XXX TODO: Verify the length and CRC. */
356
357         /* We've verified the trailer, so consume it now. */
358         __archive_read_filter_consume(self->upstream, 8);
359
360         return (ARCHIVE_OK);
361 }
362
363 static ssize_t
364 gzip_filter_read(struct archive_read_filter *self, const void **p)
365 {
366         struct private_data *state;
367         size_t decompressed;
368         ssize_t avail_in;
369         int ret;
370
371         state = (struct private_data *)self->data;
372
373         /* Empty our output buffer. */
374         state->stream.next_out = state->out_block;
375         state->stream.avail_out = state->out_block_size;
376
377         /* Try to fill the output buffer. */
378         while (state->stream.avail_out > 0 && !state->eof) {
379                 /* If we're not in a stream, read a header
380                  * and initialize the decompression library. */
381                 if (!state->in_stream) {
382                         ret = consume_header(self);
383                         if (ret == ARCHIVE_EOF) {
384                                 state->eof = 1;
385                                 break;
386                         }
387                         if (ret < ARCHIVE_OK)
388                                 return (ret);
389                 }
390
391                 /* Peek at the next available data. */
392                 /* ZLib treats stream.next_in as const but doesn't declare
393                  * it so, hence this ugly cast. */
394                 state->stream.next_in = (unsigned char *)(uintptr_t)
395                     __archive_read_filter_ahead(self->upstream, 1, &avail_in);
396                 if (state->stream.next_in == NULL)
397                         return (ARCHIVE_FATAL);
398                 state->stream.avail_in = avail_in;
399
400                 /* Decompress and consume some of that data. */
401                 ret = inflate(&(state->stream), 0);
402                 switch (ret) {
403                 case Z_OK: /* Decompressor made some progress. */
404                         __archive_read_filter_consume(self->upstream,
405                             avail_in - state->stream.avail_in);
406                         break;
407                 case Z_STREAM_END: /* Found end of stream. */
408                         __archive_read_filter_consume(self->upstream,
409                             avail_in - state->stream.avail_in);
410                         /* Consume the stream trailer; release the
411                          * decompression library. */
412                         ret = consume_trailer(self);
413                         break;
414                 default:
415                         /* Return an error. */
416                         archive_set_error(&self->archive->archive,
417                             ARCHIVE_ERRNO_MISC,
418                             "gzip decompression failed");
419                         return (ARCHIVE_FATAL);
420                 }
421         }
422
423         /* We've read as much as we can. */
424         decompressed = state->stream.next_out - state->out_block;
425         state->total_out += decompressed;
426         if (decompressed == 0)
427                 *p = NULL;
428         else
429                 *p = state->out_block;
430         return (decompressed);
431 }
432
433 /*
434  * Clean up the decompressor.
435  */
436 static int
437 gzip_filter_close(struct archive_read_filter *self)
438 {
439         struct private_data *state;
440         int ret;
441
442         state = (struct private_data *)self->data;
443         ret = ARCHIVE_OK;
444
445         if (state->in_stream) {
446                 switch (inflateEnd(&(state->stream))) {
447                 case Z_OK:
448                         break;
449                 default:
450                         archive_set_error(&(self->archive->archive),
451                             ARCHIVE_ERRNO_MISC,
452                             "Failed to clean up gzip compressor");
453                         ret = ARCHIVE_FATAL;
454                 }
455         }
456
457         free(state->out_block);
458         free(state);
459         return (ret);
460 }
461
462 #endif /* HAVE_ZLIB_H */