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 /*
27 * This code borrows heavily from "compress" source code, which is
28 * protected by the following copyright. (Clause 3 dropped by request
29 * of the Regents.)
30 */
31
32 /*-
33 * Copyright (c) 1985, 1986, 1992, 1993
34 * The Regents of the University of California. All rights reserved.
35 *
36 * This code is derived from software contributed to Berkeley by
37 * Diomidis Spinellis and James A. Woods, derived from original
38 * work by Spencer Thomas and Joseph Orost.
39 *
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
42 * are met:
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 4. Neither the name of the University nor the names of its contributors
49 * may be used to endorse or promote products derived from this software
50 * without specific prior written permission.
51 *
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * SUCH DAMAGE.
63 */
64
65
66 #include "archive_platform.h"
67 __FBSDID("$FreeBSD$");
68
69 #ifdef HAVE_ERRNO_H
70 #include <errno.h>
71 #endif
72 #ifdef HAVE_STDLIB_H
73 #include <stdlib.h>
74 #endif
75 #ifdef HAVE_STRING_H
76 #include <string.h>
77 #endif
78 #ifdef HAVE_UNISTD_H
79 #include <unistd.h>
80 #endif
81
82 #include "archive.h"
83 #include "archive_private.h"
84 #include "archive_read_private.h"
85
86 /*
87 * Because LZW decompression is pretty simple, I've just implemented
88 * the whole decompressor here (cribbing from "compress" source code,
89 * of course), rather than relying on an external library. I have
90 * made an effort to clarify and simplify the algorithm, so the
91 * names and structure here don't exactly match those used by compress.
92 */
93
94 struct private_data {
95 /* Input variables. */
96 const unsigned char *next_in;
97 size_t avail_in;
98 size_t consume_unnotified;
99 int bit_buffer;
100 int bits_avail;
101 size_t bytes_in_section;
102
103 /* Output variables. */
104 size_t out_block_size;
105 void *out_block;
106
107 /* Decompression status variables. */
108 int use_reset_code;
109 int end_of_stream; /* EOF status. */
110 int maxcode; /* Largest code. */
111 int maxcode_bits; /* Length of largest code. */
112 int section_end_code; /* When to increase bits. */
113 int bits; /* Current code length. */
114 int oldcode; /* Previous code. */
115 int finbyte; /* Last byte of prev code. */
116
117 /* Dictionary. */
118 int free_ent; /* Next dictionary entry. */
119 unsigned char suffix[65536];
120 uint16_t prefix[65536];
121
122 /*
123 * Scratch area for expanding dictionary entries. Note:
124 * "worst" case here comes from compressing /dev/zero: the
125 * last code in the dictionary will code a sequence of
126 * 65536-256 zero bytes. Thus, we need stack space to expand
127 * a 65280-byte dictionary entry. (Of course, 32640:1
128 * compression could also be considered the "best" case. ;-)
129 */
130 unsigned char *stackp;
131 unsigned char stack[65300];
132 };
133
134 static int compress_bidder_bid(struct archive_read_filter_bidder *, struct archive_read_filter *);
135 static int compress_bidder_init(struct archive_read_filter *);
136
137 static ssize_t compress_filter_read(struct archive_read_filter *, const void **);
138 static int compress_filter_close(struct archive_read_filter *);
139
140 static int getbits(struct archive_read_filter *, int n);
141 static int next_code(struct archive_read_filter *);
142
143 #if ARCHIVE_VERSION_NUMBER < 4000000
144 /* Deprecated; remove in libarchive 4.0 */
145 int
archive_read_support_compression_compress(struct archive * a)146 archive_read_support_compression_compress(struct archive *a)
147 {
148 return archive_read_support_filter_compress(a);
149 }
150 #endif
151
152 static const struct archive_read_filter_bidder_vtable
153 compress_bidder_vtable = {
154 .bid = compress_bidder_bid,
155 .init = compress_bidder_init,
156 };
157
158 int
archive_read_support_filter_compress(struct archive * _a)159 archive_read_support_filter_compress(struct archive *_a)
160 {
161 struct archive_read *a = (struct archive_read *)_a;
162
163 return __archive_read_register_bidder(a, NULL, "compress (.Z)",
164 &compress_bidder_vtable);
165 }
166
167 /*
168 * Test whether we can handle this data.
169 * This logic returns zero if any part of the signature fails.
170 */
171 static int
compress_bidder_bid(struct archive_read_filter_bidder * self,struct archive_read_filter * filter)172 compress_bidder_bid(struct archive_read_filter_bidder *self,
173 struct archive_read_filter *filter)
174 {
175 const unsigned char *buffer;
176 ssize_t avail;
177 int bits_checked;
178
179 (void)self; /* UNUSED */
180
181 /* Shortest valid compress file is 3 bytes. */
182 buffer = __archive_read_filter_ahead(filter, 3, &avail);
183
184 if (buffer == NULL)
185 return (0);
186
187 bits_checked = 0;
188 /* First two bytes are the magic value */
189 if (buffer[0] != 0x1F || buffer[1] != 0x9D)
190 return (0);
191 /* Third byte holds compression parameters. */
192 if (buffer[2] & 0x20) /* Reserved bit, must be zero. */
193 return (0);
194 if (buffer[2] & 0x40) /* Reserved bit, must be zero. */
195 return (0);
196 bits_checked += 18;
197
198 return (bits_checked);
199 }
200
201 static const struct archive_read_filter_vtable
202 compress_reader_vtable = {
203 .read = compress_filter_read,
204 .close = compress_filter_close,
205 };
206
207 /*
208 * Setup the callbacks.
209 */
210 static int
compress_bidder_init(struct archive_read_filter * self)211 compress_bidder_init(struct archive_read_filter *self)
212 {
213 struct private_data *state;
214 static const size_t out_block_size = 64 * 1024;
215 void *out_block;
216 int code;
217
218 self->code = ARCHIVE_FILTER_COMPRESS;
219 self->name = "compress (.Z)";
220
221 state = (struct private_data *)calloc(sizeof(*state), 1);
222 out_block = malloc(out_block_size);
223 if (state == NULL || out_block == NULL) {
224 free(out_block);
225 free(state);
226 archive_set_error(&self->archive->archive, ENOMEM,
227 "Can't allocate data for %s decompression",
228 self->name);
229 return (ARCHIVE_FATAL);
230 }
231
232 self->data = state;
233 state->out_block_size = out_block_size;
234 state->out_block = out_block;
235 self->vtable = &compress_reader_vtable;
236
237 /* XXX MOVE THE FOLLOWING OUT OF INIT() XXX */
238
239 (void)getbits(self, 8); /* Skip first signature byte. */
240 (void)getbits(self, 8); /* Skip second signature byte. */
241
242 /* Get compression parameters. */
243 code = getbits(self, 8);
244 if ((code & 0x1f) > 16) {
245 archive_set_error(&self->archive->archive, -1,
246 "Invalid compressed data");
247 return (ARCHIVE_FATAL);
248 }
249 state->maxcode_bits = code & 0x1f;
250 state->maxcode = (1 << state->maxcode_bits);
251 state->use_reset_code = code & 0x80;
252
253 /* Initialize decompressor. */
254 state->free_ent = 256;
255 state->stackp = state->stack;
256 if (state->use_reset_code)
257 state->free_ent++;
258 state->bits = 9;
259 state->section_end_code = (1<<state->bits) - 1;
260 state->oldcode = -1;
261 for (code = 255; code >= 0; code--) {
262 state->prefix[code] = 0;
263 state->suffix[code] = code;
264 }
265 next_code(self);
266
267 return (ARCHIVE_OK);
268 }
269
270 /*
271 * Return a block of data from the decompression buffer. Decompress more
272 * as necessary.
273 */
274 static ssize_t
compress_filter_read(struct archive_read_filter * self,const void ** pblock)275 compress_filter_read(struct archive_read_filter *self, const void **pblock)
276 {
277 struct private_data *state;
278 unsigned char *p, *start, *end;
279 int ret;
280
281 state = (struct private_data *)self->data;
282 if (state->end_of_stream) {
283 *pblock = NULL;
284 return (0);
285 }
286 p = start = (unsigned char *)state->out_block;
287 end = start + state->out_block_size;
288
289 while (p < end && !state->end_of_stream) {
290 if (state->stackp > state->stack) {
291 *p++ = *--state->stackp;
292 } else {
293 ret = next_code(self);
294 if (ret == -1)
295 state->end_of_stream = ret;
296 else if (ret != ARCHIVE_OK)
297 return (ret);
298 }
299 }
300
301 *pblock = start;
302 return (p - start);
303 }
304
305 /*
306 * Close and release the filter.
307 */
308 static int
compress_filter_close(struct archive_read_filter * self)309 compress_filter_close(struct archive_read_filter *self)
310 {
311 struct private_data *state = (struct private_data *)self->data;
312
313 free(state->out_block);
314 free(state);
315 return (ARCHIVE_OK);
316 }
317
318 /*
319 * Process the next code and fill the stack with the expansion
320 * of the code. Returns ARCHIVE_FATAL if there is a fatal I/O or
321 * format error, ARCHIVE_EOF if we hit end of data, ARCHIVE_OK otherwise.
322 */
323 static int
next_code(struct archive_read_filter * self)324 next_code(struct archive_read_filter *self)
325 {
326 struct private_data *state = (struct private_data *)self->data;
327 int code, newcode;
328
329 static int debug_buff[1024];
330 static unsigned debug_index;
331
332 code = newcode = getbits(self, state->bits);
333 if (code < 0)
334 return (code);
335
336 debug_buff[debug_index++] = code;
337 if (debug_index >= sizeof(debug_buff)/sizeof(debug_buff[0]))
338 debug_index = 0;
339
340 /* If it's a reset code, reset the dictionary. */
341 if ((code == 256) && state->use_reset_code) {
342 /*
343 * The original 'compress' implementation blocked its
344 * I/O in a manner that resulted in junk bytes being
345 * inserted after every reset. The next section skips
346 * this junk. (Yes, the number of *bytes* to skip is
347 * a function of the current *bit* length.)
348 */
349 int skip_bytes = state->bits -
350 (state->bytes_in_section % state->bits);
351 skip_bytes %= state->bits;
352 state->bits_avail = 0; /* Discard rest of this byte. */
353 while (skip_bytes-- > 0) {
354 code = getbits(self, 8);
355 if (code < 0)
356 return (code);
357 }
358 /* Now, actually do the reset. */
359 state->bytes_in_section = 0;
360 state->bits = 9;
361 state->section_end_code = (1 << state->bits) - 1;
362 state->free_ent = 257;
363 state->oldcode = -1;
364 return (next_code(self));
365 }
366
367 if (code > state->free_ent
368 || (code == state->free_ent && state->oldcode < 0)) {
369 /* An invalid code is a fatal error. */
370 archive_set_error(&(self->archive->archive), -1,
371 "Invalid compressed data");
372 return (ARCHIVE_FATAL);
373 }
374
375 /* Special case for KwKwK string. */
376 if (code >= state->free_ent) {
377 *state->stackp++ = state->finbyte;
378 code = state->oldcode;
379 }
380
381 /* Generate output characters in reverse order. */
382 while (code >= 256) {
383 *state->stackp++ = state->suffix[code];
384 code = state->prefix[code];
385 }
386 *state->stackp++ = state->finbyte = code;
387
388 /* Generate the new entry. */
389 code = state->free_ent;
390 if (code < state->maxcode && state->oldcode >= 0) {
391 state->prefix[code] = state->oldcode;
392 state->suffix[code] = state->finbyte;
393 ++state->free_ent;
394 }
395 if (state->free_ent > state->section_end_code) {
396 state->bits++;
397 state->bytes_in_section = 0;
398 if (state->bits == state->maxcode_bits)
399 state->section_end_code = state->maxcode;
400 else
401 state->section_end_code = (1 << state->bits) - 1;
402 }
403
404 /* Remember previous code. */
405 state->oldcode = newcode;
406 return (ARCHIVE_OK);
407 }
408
409 /*
410 * Return next 'n' bits from stream.
411 *
412 * -1 indicates end of available data.
413 */
414 static int
getbits(struct archive_read_filter * self,int n)415 getbits(struct archive_read_filter *self, int n)
416 {
417 struct private_data *state = (struct private_data *)self->data;
418 int code;
419 ssize_t ret;
420 static const int mask[] = {
421 0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff,
422 0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff
423 };
424
425 while (state->bits_avail < n) {
426 if (state->avail_in <= 0) {
427 if (state->consume_unnotified) {
428 __archive_read_filter_consume(self->upstream,
429 state->consume_unnotified);
430 state->consume_unnotified = 0;
431 }
432 state->next_in
433 = __archive_read_filter_ahead(self->upstream,
434 1, &ret);
435 if (ret == 0)
436 return (-1);
437 if (ret < 0 || state->next_in == NULL)
438 return (ARCHIVE_FATAL);
439 state->consume_unnotified = state->avail_in = ret;
440 }
441 state->bit_buffer |= *state->next_in++ << state->bits_avail;
442 state->avail_in--;
443 state->bits_avail += 8;
444 state->bytes_in_section++;
445 }
446
447 code = state->bit_buffer;
448 state->bit_buffer >>= n;
449 state->bits_avail -= n;
450
451 return (code & mask[n]);
452 }
453