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$");
29 
30 #ifdef HAVE_ERRNO_H
31 #include <errno.h>
32 #endif
33 #include <stdio.h>
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_BZLIB_H
44 #include <bzlib.h>
45 #endif
46 
47 #include "archive.h"
48 #include "archive_private.h"
49 #include "archive_read_private.h"
50 
51 #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
52 struct private_data {
53 	bz_stream	 stream;
54 	char		*out_block;
55 	size_t		 out_block_size;
56 	char		 valid; /* True = decompressor is initialized */
57 	char		 eof; /* True = found end of compressed data. */
58 };
59 
60 /* Bzip2 filter */
61 static ssize_t	bzip2_filter_read(struct archive_read_filter *, const void **);
62 static int	bzip2_filter_close(struct archive_read_filter *);
63 #endif
64 
65 /*
66  * Note that we can detect bzip2 archives even if we can't decompress
67  * them.  (In fact, we like detecting them because we can give better
68  * error messages.)  So the bid framework here gets compiled even
69  * if bzlib is unavailable.
70  */
71 static int	bzip2_reader_bid(struct archive_read_filter_bidder *, struct archive_read_filter *);
72 static int	bzip2_reader_init(struct archive_read_filter *);
73 static int	bzip2_reader_free(struct archive_read_filter_bidder *);
74 
75 #if ARCHIVE_VERSION_NUMBER < 4000000
76 /* Deprecated; remove in libarchive 4.0 */
77 int
78 archive_read_support_compression_bzip2(struct archive *a)
79 {
80 	return archive_read_support_filter_bzip2(a);
81 }
82 #endif
83 
84 int
85 archive_read_support_filter_bzip2(struct archive *_a)
86 {
87 	struct archive_read *a = (struct archive_read *)_a;
88 	struct archive_read_filter_bidder *reader;
89 
90 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
91 	    ARCHIVE_STATE_NEW, "archive_read_support_filter_bzip2");
92 
93 	if (__archive_read_get_bidder(a, &reader) != ARCHIVE_OK)
94 		return (ARCHIVE_FATAL);
95 
96 	reader->data = NULL;
97 	reader->bid = bzip2_reader_bid;
98 	reader->init = bzip2_reader_init;
99 	reader->options = NULL;
100 	reader->free = bzip2_reader_free;
101 #if defined(HAVE_BZLIB_H) && defined(BZ_CONFIG_ERROR)
102 	return (ARCHIVE_OK);
103 #else
104 	archive_set_error(_a, ARCHIVE_ERRNO_MISC,
105 	    "Using external bunzip2 program");
106 	return (ARCHIVE_WARN);
107 #endif
108 }
109 
110 static int
111 bzip2_reader_free(struct archive_read_filter_bidder *self){
112 	(void)self; /* UNUSED */
113 	return (ARCHIVE_OK);
114 }
115 
116 /*
117  * Test whether we can handle this data.
118  *
119  * This logic returns zero if any part of the signature fails.  It
120  * also tries to Do The Right Thing if a very short buffer prevents us
121  * from verifying as much as we would like.
122  */
123 static int
124 bzip2_reader_bid(struct archive_read_filter_bidder *self, struct archive_read_filter *filter)
125 {
126 	const unsigned char *buffer;
127 	ssize_t avail;
128 	int bits_checked;
129 
130 	(void)self; /* UNUSED */
131 
132 	/* Minimal bzip2 archive is 14 bytes. */
133 	buffer = __archive_read_filter_ahead(filter, 14, &avail);
134 	if (buffer == NULL)
135 		return (0);
136 
137 	/* First three bytes must be "BZh" */
138 	bits_checked = 0;
139 	if (memcmp(buffer, "BZh", 3) != 0)
140 		return (0);
141 	bits_checked += 24;
142 
143 	/* Next follows a compression flag which must be an ASCII digit. */
144 	if (buffer[3] < '1' || buffer[3] > '9')
145 		return (0);
146 	bits_checked += 5;
147 
148 	/* After BZh[1-9], there must be either a data block
149 	 * which begins with 0x314159265359 or an end-of-data
150 	 * marker of 0x177245385090. */
151 	if (memcmp(buffer + 4, "\x31\x41\x59\x26\x53\x59", 6) == 0)
152 		bits_checked += 48;
153 	else if (memcmp(buffer + 4, "\x17\x72\x45\x38\x50\x90", 6) == 0)
154 		bits_checked += 48;
155 	else
156 		return (0);
157 
158 	return (bits_checked);
159 }
160 
161 #if !defined(HAVE_BZLIB_H) || !defined(BZ_CONFIG_ERROR)
162 
163 /*
164  * If we don't have the library on this system, we can't actually do the
165  * decompression.  We can, however, still detect compressed archives
166  * and emit a useful message.
167  */
168 static int
169 bzip2_reader_init(struct archive_read_filter *self)
170 {
171 	int r;
172 
173 	r = __archive_read_program(self, "bunzip2");
174 	/* Note: We set the format here even if __archive_read_program()
175 	 * above fails.  We do, after all, know what the format is
176 	 * even if we weren't able to read it. */
177 	self->code = ARCHIVE_COMPRESSION_BZIP2;
178 	self->name = "bzip2";
179 	return (r);
180 }
181 
182 
183 #else
184 
185 /*
186  * Setup the callbacks.
187  */
188 static int
189 bzip2_reader_init(struct archive_read_filter *self)
190 {
191 	static const size_t out_block_size = 64 * 1024;
192 	void *out_block;
193 	struct private_data *state;
194 
195 	self->code = ARCHIVE_COMPRESSION_BZIP2;
196 	self->name = "bzip2";
197 
198 	state = (struct private_data *)calloc(sizeof(*state), 1);
199 	out_block = (unsigned char *)malloc(out_block_size);
200 	if (state == NULL || out_block == NULL) {
201 		archive_set_error(&self->archive->archive, ENOMEM,
202 		    "Can't allocate data for bzip2 decompression");
203 		free(out_block);
204 		free(state);
205 		return (ARCHIVE_FATAL);
206 	}
207 
208 	self->data = state;
209 	state->out_block_size = out_block_size;
210 	state->out_block = out_block;
211 	self->read = bzip2_filter_read;
212 	self->skip = NULL; /* not supported */
213 	self->close = bzip2_filter_close;
214 
215 	return (ARCHIVE_OK);
216 }
217 
218 /*
219  * Return the next block of decompressed data.
220  */
221 static ssize_t
222 bzip2_filter_read(struct archive_read_filter *self, const void **p)
223 {
224 	struct private_data *state;
225 	size_t decompressed;
226 	const char *read_buf;
227 	ssize_t ret;
228 
229 	state = (struct private_data *)self->data;
230 
231 	if (state->eof) {
232 		*p = NULL;
233 		return (0);
234 	}
235 
236 	/* Empty our output buffer. */
237 	state->stream.next_out = state->out_block;
238 	state->stream.avail_out = state->out_block_size;
239 
240 	/* Try to fill the output buffer. */
241 	for (;;) {
242 		if (!state->valid) {
243 			if (bzip2_reader_bid(self->bidder, self->upstream) == 0) {
244 				state->eof = 1;
245 				*p = state->out_block;
246 				decompressed = state->stream.next_out
247 				    - state->out_block;
248 				return (decompressed);
249 			}
250 			/* Initialize compression library. */
251 			ret = BZ2_bzDecompressInit(&(state->stream),
252 					   0 /* library verbosity */,
253 					   0 /* don't use low-mem algorithm */);
254 
255 			/* If init fails, try low-memory algorithm instead. */
256 			if (ret == BZ_MEM_ERROR)
257 				ret = BZ2_bzDecompressInit(&(state->stream),
258 					   0 /* library verbosity */,
259 					   1 /* do use low-mem algo */);
260 
261 			if (ret != BZ_OK) {
262 				const char *detail = NULL;
263 				int err = ARCHIVE_ERRNO_MISC;
264 				switch (ret) {
265 				case BZ_PARAM_ERROR:
266 					detail = "invalid setup parameter";
267 					break;
268 				case BZ_MEM_ERROR:
269 					err = ENOMEM;
270 					detail = "out of memory";
271 					break;
272 				case BZ_CONFIG_ERROR:
273 					detail = "mis-compiled library";
274 					break;
275 				}
276 				archive_set_error(&self->archive->archive, err,
277 				    "Internal error initializing decompressor%s%s",
278 				    detail == NULL ? "" : ": ",
279 				    detail);
280 				return (ARCHIVE_FATAL);
281 			}
282 			state->valid = 1;
283 		}
284 
285 		/* stream.next_in is really const, but bzlib
286 		 * doesn't declare it so. <sigh> */
287 		read_buf =
288 		    __archive_read_filter_ahead(self->upstream, 1, &ret);
289 		if (read_buf == NULL) {
290 			archive_set_error(&self->archive->archive,
291 			    ARCHIVE_ERRNO_MISC,
292 			    "truncated bzip2 input");
293 			return (ARCHIVE_FATAL);
294 		}
295 		state->stream.next_in = (char *)(uintptr_t)read_buf;
296 		state->stream.avail_in = ret;
297 		/* There is no more data, return whatever we have. */
298 		if (ret == 0) {
299 			state->eof = 1;
300 			*p = state->out_block;
301 			decompressed = state->stream.next_out
302 			    - state->out_block;
303 			return (decompressed);
304 		}
305 
306 		/* Decompress as much as we can in one pass. */
307 		ret = BZ2_bzDecompress(&(state->stream));
308 		__archive_read_filter_consume(self->upstream,
309 		    state->stream.next_in - read_buf);
310 
311 		switch (ret) {
312 		case BZ_STREAM_END: /* Found end of stream. */
313 			switch (BZ2_bzDecompressEnd(&(state->stream))) {
314 			case BZ_OK:
315 				break;
316 			default:
317 				archive_set_error(&(self->archive->archive),
318 					  ARCHIVE_ERRNO_MISC,
319 					  "Failed to clean up decompressor");
320 				return (ARCHIVE_FATAL);
321 			}
322 			state->valid = 0;
323 			/* FALLTHROUGH */
324 		case BZ_OK: /* Decompressor made some progress. */
325 			/* If we filled our buffer, update stats and return. */
326 			if (state->stream.avail_out == 0) {
327 				*p = state->out_block;
328 				decompressed = state->stream.next_out
329 				    - state->out_block;
330 				return (decompressed);
331 			}
332 			break;
333 		default: /* Return an error. */
334 			archive_set_error(&self->archive->archive,
335 			    ARCHIVE_ERRNO_MISC, "bzip decompression failed");
336 			return (ARCHIVE_FATAL);
337 		}
338 	}
339 }
340 
341 /*
342  * Clean up the decompressor.
343  */
344 static int
345 bzip2_filter_close(struct archive_read_filter *self)
346 {
347 	struct private_data *state;
348 	int ret = ARCHIVE_OK;
349 
350 	state = (struct private_data *)self->data;
351 
352 	if (state->valid) {
353 		switch (BZ2_bzDecompressEnd(&state->stream)) {
354 		case BZ_OK:
355 			break;
356 		default:
357 			archive_set_error(&self->archive->archive,
358 					  ARCHIVE_ERRNO_MISC,
359 					  "Failed to clean up decompressor");
360 			ret = ARCHIVE_FATAL;
361 		}
362 		state->valid = 0;
363 	}
364 
365 	free(state->out_block);
366 	free(state);
367 	return (ret);
368 }
369 
370 #endif /* HAVE_BZLIB_H && BZ_CONFIG_ERROR */
371