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