xref: /freebsd/contrib/libarchive/libarchive/archive_read_support_format_cab.c (revision 185becb1e1bd2657c156f78aeb52edac05ba5fb5)
1 /*-
2  * Copyright (c) 2010-2012 Michihiro NAKAJIMA
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 #ifdef HAVE_ERRNO_H
29 #include <errno.h>
30 #endif
31 #ifdef HAVE_LIMITS_H
32 #include <limits.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_ZLIB_H
41 #include <zlib.h>
42 #endif
43 
44 #include "archive.h"
45 #include "archive_entry.h"
46 #include "archive_entry_locale.h"
47 #include "archive_private.h"
48 #include "archive_read_private.h"
49 #include "archive_endian.h"
50 
51 
52 /*
53  * Huffman coding.
54  *
55  * Array representation of a Huffman tree for codes of up to 16 bit lengths.
56  * Lookups are performed through a direct, expanded lookup table.
57  *
58  * An expanded table has as many elements as needed to cover all possible
59  * indices formable with bit patterns of given lookup_bits length.
60  *
61  * If less codes exist, these span multiple entries for all possible
62  * combinations of following bits.
63  *
64  * Example of a Huffman tree with len_size = 3, lookup_bits = 2:
65  *
66  * Symbol | Code
67  * -------+-----
68  *      A | 0b0
69  *      B | 0b10
70  *      C | 0b11
71  *
72  * The bit sequences 0b00 and 0b01 are rightfully not covered by a code,
73  * since code 0b0 already maps to symbol A. The table will contain two
74  * entries for symbol A instead:
75  *
76  *  idx | tbl[idx]
77  * -----+---------
78  * 0b00 |        A
79  * 0b01 |        A
80  * 0b10 |        B
81  * 0b11 |        C
82  *
83  * By using lookup_bits bits as a lookup, it becomes apparent that 0b00 and
84  * 0b01 point to a symbol which actually has the code 0b0. A user of this
85  * data structure must check the code bit length of a retrieved symbol after
86  * the lookup to properly advance the bit stream:
87  *
88  * idx | bitlen[idx]
89  * ----+------------
90  *   A |           1
91  *   B |           2
92  *   C |           2
93  *
94  * Thus, a proper code sequence would be:
95  *
96  * symbol = tbl[read_bits(lookup_bits)]
97  * consume_bits(bitlen[symbol])
98  */
99 struct huffman {
100 	/*
101 	 * Amount of symbols.
102 	 *
103 	 * This implementation keeps track of unused symbols as well,
104 	 * thus symbols start with 0x0000 up to given symbol amount:
105 	 * [0..symbol_count)
106 	 *
107 	 * Used to construct tbl.
108 	 */
109 	uint16_t	 symbol_count;
110 	/*
111 	 * Frequency of code bit lengths.
112 	 *
113 	 * Represents the amount of occurrences of given bit lengths.
114 	 * Index 0 is used for "empty" codes (aka unused symbols),
115 	 * otherwise index represents the bit length
116 	 * (index 1 is bit length 1 and so on).
117 	 *
118 	 * Used to construct tbl.
119 	 */
120 	uint16_t	 freq[17];
121 	/* Map of symbols to their code bit lengths. */
122 	uint8_t		*bitlen;
123 	/* Amount of bits to use for lookup (<= tbl_bits). */
124 	uint8_t		 lookup_bits;
125 	/*
126 	 * Code bit length used for allocation (<= 16).
127 	 *
128 	 * Used to construct tbl.
129 	 */
130 	uint8_t		 tbl_bits;
131 	/* Direct, expanded lookup table. */
132 	uint16_t	*tbl;
133 };
134 
135 /*
136  * Bit stream reader.
137  */
138 struct lzx_br {
139 #define CACHE_TYPE		uint64_t
140 #define CACHE_BITS		(8 * sizeof(CACHE_TYPE))
141 	/* Cache buffer. */
142 	CACHE_TYPE	 cache_buffer;
143 	/* Indicates how many bits avail in cache_buffer. */
144 	size_t		 cache_avail;
145 	uint8_t		 odd;
146 	int		 have_odd;
147 };
148 
149 struct lzx_pos_tbl {
150 	uint32_t	 base;
151 	uint8_t		 footer_bits;
152 };
153 
154 struct lzx_dec {
155 	/* Decoding status. */
156 	int     		 state;
157 #define ST_RD_TRANSLATION	0
158 #define ST_RD_TRANSLATION_SIZE	1
159 #define ST_RD_BLOCK_TYPE	2
160 #define ST_RD_BLOCK_SIZE	3
161 #define ST_RD_ALIGNMENT		4
162 #define ST_RD_R0		5
163 #define ST_RD_R1		6
164 #define ST_RD_R2		7
165 #define ST_COPY_UNCOMP1		8
166 #define ST_COPY_UNCOMP2		9
167 #define ST_RD_ALIGNED_OFFSET	10
168 #define ST_RD_VERBATIM		11
169 #define ST_RD_PRE_MAIN_TREE_256	12
170 #define ST_MAIN_TREE_256	13
171 #define ST_RD_PRE_MAIN_TREE_REM	14
172 #define ST_MAIN_TREE_REM	15
173 #define ST_RD_PRE_LENGTH_TREE	16
174 #define ST_LENGTH_TREE		17
175 #define ST_MAIN			18
176 #define ST_LENGTH		19
177 #define ST_OFFSET		20
178 #define ST_REAL_POS		21
179 #define ST_COPY			22
180 
181 	/*
182 	 * Window to see last decoded data, from 32 KiB to 2 MiB.
183 	 */
184 	size_t			 w_size;
185 	size_t			 w_mask;
186 	/* Window buffer, which is a loop buffer. */
187 	uint8_t			*w_buff;
188 	/* The insert position to the window. */
189 	size_t			 w_pos;
190 	/* The position where we can copy decoded code from the window. */
191 	size_t			 copy_pos;
192 	/* The length how many bytes we can copy decoded code from
193 	 * the window. */
194 	size_t			 copy_len;
195 	/* Translation reversal for x86 processor CALL byte sequence(E8).
196 	 * This is used for LZX only. */
197 	int32_t			 translation_size;
198 	int			 translation;
199 	uint8_t			 block_type;
200 #define VERBATIM_BLOCK		1
201 #define ALIGNED_OFFSET_BLOCK	2
202 #define UNCOMPRESSED_BLOCK	3
203 	size_t			 block_size;
204 	size_t			 block_bytes_avail;
205 	/* Repeated offset. */
206 	size_t			 r0, r1, r2;
207 	uint8_t			 rbytes[4];
208 	size_t			 rbytes_avail;
209 	uint8_t			 length_header;
210 	uint16_t		 position_slot;
211 	uint8_t			 offset_bits;
212 
213 	struct lzx_pos_tbl 	*pos_tbl;
214 	/*
215 	 * Bit stream reader.
216 	 */
217 	struct lzx_br		 br;
218 
219 	/*
220 	 * Huffman coding.
221 	 */
222 	struct huffman		 at;
223 	struct huffman		 lt;
224 	struct huffman		 mt;
225 	struct huffman		 pt;
226 
227 	uint16_t		 loop;
228 	int			 error;
229 };
230 
231 static const size_t slots[] = {
232 	30, 32, 34, 36, 38, 42, 50, 66, 98, 162, 290
233 };
234 #define SLOT_BASE	15
235 #define SLOT_MAX	21/*->25*/
236 
237 struct lzx_stream {
238 	const unsigned char	*next_in;
239 	size_t			 avail_in;
240 	size_t			 total_in;
241 	unsigned char		*next_out;
242 	size_t			 avail_out;
243 	size_t			 total_out;
244 	struct lzx_dec		*ds;
245 };
246 
247 /*
248  * Cabinet file definitions.
249  */
250 /* CFHEADER offset */
251 #define CFHEADER_signature	0
252 #define CFHEADER_cbCabinet	8
253 #define CFHEADER_coffFiles	16
254 #define CFHEADER_versionMinor	24
255 #define CFHEADER_versionMajor	25
256 #define CFHEADER_cFolders	26
257 #define CFHEADER_cFiles		28
258 #define CFHEADER_flags		30
259 #define CFHEADER_setID		32
260 #define CFHEADER_iCabinet	34
261 #define CFHEADER_cbCFHeader	36
262 #define CFHEADER_cbCFFolder	38
263 #define CFHEADER_cbCFData	39
264 
265 /* CFFOLDER offset */
266 #define CFFOLDER_coffCabStart	0
267 #define CFFOLDER_cCFData	4
268 #define CFFOLDER_typeCompress	6
269 #define CFFOLDER_abReserve	8
270 
271 /* CFFILE offset */
272 #define CFFILE_cbFile		0
273 #define CFFILE_uoffFolderStart	4
274 #define CFFILE_iFolder		8
275 #define CFFILE_date_time	10
276 #define CFFILE_attribs		14
277 
278 /* CFDATA offset */
279 #define CFDATA_csum		0
280 #define CFDATA_cbData		4
281 #define CFDATA_cbUncomp		6
282 
283 /* Limits */
284 #define MAX_UNCOMPRESS_SIZE	0x8000
285 #define MAX_FILE_SIZE		(UINT16_MAX * MAX_UNCOMPRESS_SIZE)
286 #define MAX_E8_TRANSLATION	(0x8000 * MAX_UNCOMPRESS_SIZE)
287 
288 static const char * const compression_name[] = {
289 	"NONE",
290 	"MSZIP",
291 	"Quantum",
292 	"LZX",
293 };
294 
295 struct cfdata {
296 	/* Sum value of this CFDATA. */
297 	uint32_t		 sum;
298 	uint16_t		 compressed_size;
299 	uint16_t		 compressed_bytes_remaining;
300 	uint16_t		 uncompressed_size;
301 	uint16_t		 uncompressed_bytes_remaining;
302 	/* To know how many bytes we have decompressed. */
303 	uint16_t		 uncompressed_avail;
304 	/* Offset from the beginning of compressed data of this CFDATA */
305 	uint16_t		 read_offset;
306 	int64_t			 unconsumed;
307 	/* To keep memory image of this CFDATA to compute the sum. */
308 	size_t			 memimage_size;
309 	unsigned char		*memimage;
310 	/* Result of calculation of sum. */
311 	uint32_t		 sum_calculated;
312 	unsigned char		 sum_extra[4];
313 	int			 sum_extra_avail;
314 	const void		*sum_ptr;
315 };
316 
317 struct cffolder {
318 	uint32_t		 cfdata_offset_in_cab;
319 	uint16_t		 cfdata_count;
320 	uint16_t		 comptype;
321 #define COMPTYPE_NONE		0x0000
322 #define COMPTYPE_MSZIP		0x0001
323 #define COMPTYPE_QUANTUM	0x0002
324 #define COMPTYPE_LZX		0x0003
325 	uint16_t		 compdata;
326 	const char		*compname;
327 	/* At the time reading CFDATA */
328 	struct cfdata		 cfdata;
329 	int			 cfdata_index;
330 	/* Flags to mark progress of decompression. */
331 	char			 decompress_init;
332 };
333 
334 struct cffile {
335 	uint32_t		 uncompressed_size;
336 	uint32_t		 offset;
337 	time_t			 mtime;
338 	uint16_t	 	 folder;
339 #define iFoldCONTINUED_FROM_PREV	0xFFFD
340 #define iFoldCONTINUED_TO_NEXT		0xFFFE
341 #define iFoldCONTINUED_PREV_AND_NEXT	0xFFFF
342 	unsigned char		 attr;
343 #define ATTR_RDONLY		0x01
344 #define ATTR_NAME_IS_UTF	0x80
345 	struct archive_string 	 pathname;
346 };
347 
348 struct cfheader {
349 	uint32_t		 files_offset;
350 	uint16_t		 folder_count;
351 	uint16_t		 file_count;
352 	uint16_t		 flags;
353 #define PREV_CABINET	0x0001
354 #define NEXT_CABINET	0x0002
355 #define RESERVE_PRESENT	0x0004
356 	uint16_t		 cabinet;
357 	/* Version number. */
358 	unsigned char		 major;
359 	unsigned char		 minor;
360 	unsigned char		 cffolder;
361 	unsigned char		 cfdata;
362 	/* All folders in a cabinet. */
363 	struct cffolder		*folder_array;
364 	/* All files in a cabinet. */
365 	struct cffile		*file_array;
366 	int			 file_index;
367 };
368 
369 struct cab {
370 	/* entry_bytes_remaining is the number of bytes we expect. */
371 	int64_t			 entry_offset;
372 	int64_t			 entry_bytes_remaining;
373 	int64_t			 entry_unconsumed;
374 	struct cffolder		*entry_cffolder;
375 	struct cffile		*entry_cffile;
376 	struct cfdata		*entry_cfdata;
377 
378 	/* Offset from beginning of a cabinet file. */
379 	int64_t			 cab_offset;
380 	struct cfheader		 cfheader;
381 	struct archive_wstring	 ws;
382 
383 	/* Flag to mark progress that first header of an archive was read.*/
384 	char			 found_header;
385 	char			 end_of_archive;
386 	char			 end_of_entry;
387 	char			 end_of_entry_cleanup;
388 	char			 read_data_invoked;
389 	int64_t			 bytes_skipped;
390 
391 	unsigned char		*uncompressed_buffer;
392 	size_t			 uncompressed_buffer_size;
393 
394 	int			 init_default_conversion;
395 	struct archive_string_conv *sconv;
396 	struct archive_string_conv *sconv_default;
397 	struct archive_string_conv *sconv_utf8;
398 	char			 format_name[64];
399 
400 #ifdef HAVE_ZLIB_H
401 	z_stream		 stream;
402 	char			 stream_valid;
403 #endif
404 	struct lzx_stream	 xstrm;
405 };
406 
407 static int	archive_read_format_cab_bid(struct archive_read *, int);
408 static int	archive_read_format_cab_options(struct archive_read *,
409 		    const char *, const char *);
410 static int	archive_read_format_cab_read_header(struct archive_read *,
411 		    struct archive_entry *);
412 static int	archive_read_format_cab_read_data(struct archive_read *,
413 		    const void **, size_t *, int64_t *);
414 static int	archive_read_format_cab_read_data_skip(struct archive_read *);
415 static int	archive_read_format_cab_cleanup(struct archive_read *);
416 
417 static int	cab_skip_sfx(struct archive_read *);
418 static time_t	cab_dos_time(const char *);
419 static int	cab_read_data(struct archive_read *, const void **,
420 		    size_t *, int64_t *);
421 static int	cab_read_header(struct archive_read *);
422 static uint32_t cab_checksum_cfdata_4(const void *, size_t bytes, uint32_t);
423 static uint32_t cab_checksum_cfdata(const void *, size_t bytes, uint32_t);
424 static void	cab_checksum_update(struct archive_read *, size_t);
425 static int	cab_checksum_finish(struct archive_read *);
426 static int	cab_next_cfdata(struct archive_read *);
427 static const void *cab_read_ahead_cfdata(struct archive_read *, ssize_t *);
428 static const void *cab_read_ahead_cfdata_none(struct archive_read *, ssize_t *);
429 static const void *cab_read_ahead_cfdata_deflate(struct archive_read *,
430 		    ssize_t *);
431 static const void *cab_read_ahead_cfdata_lzx(struct archive_read *,
432 		    ssize_t *);
433 static int64_t	cab_consume_cfdata(struct archive_read *, int64_t);
434 static int64_t	cab_minimum_consume_cfdata(struct archive_read *, int64_t);
435 static int	lzx_decode_init(struct lzx_stream *, int);
436 static int	lzx_read_blocks(struct lzx_stream *, int);
437 static int	lzx_decode_blocks(struct lzx_stream *, int);
438 static void	lzx_decode_free(struct lzx_stream *);
439 static void	lzx_translation(struct lzx_stream *, unsigned char *, size_t, int32_t);
440 static void	lzx_cleanup_bitstream(struct lzx_stream *);
441 static int	lzx_decode(struct lzx_stream *, int);
442 static int	lzx_read_pre_tree(struct lzx_stream *);
443 static int	lzx_read_bitlen(struct lzx_stream *, struct huffman *, uint16_t);
444 static int	lzx_huffman_init(struct huffman *, uint16_t, uint8_t);
445 static void	lzx_huffman_free(struct huffman *);
446 static int	lzx_make_huffman_table(struct huffman *);
447 static uint16_t	lzx_decode_huffman(struct huffman *, uint16_t);
448 
449 
450 int
archive_read_support_format_cab(struct archive * _a)451 archive_read_support_format_cab(struct archive *_a)
452 {
453 	struct archive_read *a = (struct archive_read *)_a;
454 	struct cab *cab;
455 	int r;
456 
457 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
458 	    ARCHIVE_STATE_NEW, "archive_read_support_format_cab");
459 
460 	cab = calloc(1, sizeof(*cab));
461 	if (cab == NULL) {
462 		archive_set_error(&a->archive, ENOMEM,
463 		    "Can't allocate CAB data");
464 		return (ARCHIVE_FATAL);
465 	}
466 	archive_string_init(&cab->ws);
467 	if (archive_wstring_ensure(&cab->ws, 256) == NULL) {
468 		archive_set_error(&a->archive, ENOMEM,
469 		    "Can't allocate memory");
470 		free(cab);
471 		return (ARCHIVE_FATAL);
472 	}
473 
474 	r = __archive_read_register_format(a,
475 	    cab,
476 	    "cab",
477 	    archive_read_format_cab_bid,
478 	    archive_read_format_cab_options,
479 	    archive_read_format_cab_read_header,
480 	    archive_read_format_cab_read_data,
481 	    archive_read_format_cab_read_data_skip,
482 	    NULL,
483 	    archive_read_format_cab_cleanup,
484 	    NULL,
485 	    NULL);
486 
487 	if (r != ARCHIVE_OK) {
488 		archive_wstring_free(&cab->ws);
489 		free(cab);
490 	}
491 	return (ARCHIVE_OK);
492 }
493 
494 static int
find_cab_magic(const char * p)495 find_cab_magic(const char *p)
496 {
497 	switch (p[4]) {
498 	case 0:
499 		/*
500 		 * Note: Self-Extraction program has 'MSCF' string in their
501 		 * program. If we were finding 'MSCF' string only, we got
502 		 * wrong place for Cabinet header, thus, we have to check
503 		 * following four bytes which are reserved and must be set
504 		 * to zero.
505 		 */
506 		if (memcmp(p, "MSCF\0\0\0\0", 8) == 0)
507 			return 0;
508 		return 5;
509 	case 'F': return 1;
510 	case 'C': return 2;
511 	case 'S': return 3;
512 	case 'M': return 4;
513 	default:  return 5;
514 	}
515 }
516 
517 static int
archive_read_format_cab_bid(struct archive_read * a,int best_bid)518 archive_read_format_cab_bid(struct archive_read *a, int best_bid)
519 {
520 	const char *p;
521 	ssize_t bytes_avail, offset, window;
522 
523 	/* If there's already a better bid than we can ever
524 	   make, don't bother testing. */
525 	if (best_bid > 64)
526 		return (-1);
527 
528 	if ((p = __archive_read_ahead(a, 8, NULL)) == NULL)
529 		return (-1);
530 
531 	if (memcmp(p, "MSCF\0\0\0\0", 8) == 0)
532 		return (64);
533 
534 	/*
535 	 * Attempt to handle self-extracting archives
536 	 * by noting a PE header and searching forward
537 	 * up to 128k for an 'MSCF' marker.
538 	 */
539 	if (p[0] == 'M' && p[1] == 'Z') {
540 		offset = 0;
541 		window = 4096;
542 		while (offset < (1024 * 128)) {
543 			const char *h = __archive_read_ahead(a, offset + window,
544 			    &bytes_avail);
545 			if (h == NULL) {
546 				/* Remaining bytes are less than window. */
547 				window >>= 1;
548 				if (window < 128)
549 					return (0);
550 				continue;
551 			}
552 			p = h + offset;
553 			while (p + 8 < h + bytes_avail) {
554 				int next;
555 				if ((next = find_cab_magic(p)) == 0)
556 					return (64);
557 				p += next;
558 			}
559 			offset = p - h;
560 		}
561 	}
562 	return (0);
563 }
564 
565 static int
archive_read_format_cab_options(struct archive_read * a,const char * key,const char * val)566 archive_read_format_cab_options(struct archive_read *a,
567     const char *key, const char *val)
568 {
569 	struct cab *cab = a->format->data;
570 	int ret = ARCHIVE_FAILED;
571 
572 	if (strcmp(key, "hdrcharset")  == 0) {
573 		if (val == NULL || val[0] == 0)
574 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
575 			    "cab: hdrcharset option needs a character-set name");
576 		else {
577 			cab->sconv = archive_string_conversion_from_charset(
578 			    &a->archive, val, 0);
579 			if (cab->sconv != NULL)
580 				ret = ARCHIVE_OK;
581 			else
582 				ret = ARCHIVE_FATAL;
583 		}
584 		return (ret);
585 	}
586 
587 	/* Note: The "warn" return is just to inform the options
588 	 * supervisor that we didn't handle it.  It will generate
589 	 * a suitable error if no one used this option. */
590 	return (ARCHIVE_WARN);
591 }
592 
593 static int
cab_skip_sfx(struct archive_read * a)594 cab_skip_sfx(struct archive_read *a)
595 {
596 	const char *p, *q;
597 	size_t skip;
598 	ssize_t bytes, window;
599 
600 	window = 4096;
601 	for (;;) {
602 		const char *h = __archive_read_ahead(a, window, &bytes);
603 		if (h == NULL) {
604 			/* Remaining size is less than window. */
605 			window >>= 1;
606 			if (window < 128) {
607 				archive_set_error(&a->archive,
608 				    ARCHIVE_ERRNO_FILE_FORMAT,
609 				    "Couldn't find out CAB header");
610 				return (ARCHIVE_FATAL);
611 			}
612 			continue;
613 		}
614 		p = h;
615 		q = p + bytes;
616 
617 		/*
618 		 * Scan ahead until we find something that looks
619 		 * like the cab header.
620 		 */
621 		while (p + 8 < q) {
622 			int next;
623 			if ((next = find_cab_magic(p)) == 0) {
624 				skip = p - h;
625 				__archive_read_consume(a, skip);
626 				return (ARCHIVE_OK);
627 			}
628 			p += next;
629 		}
630 		skip = p - h;
631 		__archive_read_consume(a, skip);
632 	}
633 }
634 
635 static int
truncated_error(struct archive_read * a)636 truncated_error(struct archive_read *a)
637 {
638 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
639 	    "Truncated CAB header");
640 	return (ARCHIVE_FATAL);
641 }
642 
643 #ifdef HAVE_STRNLEN
644 #define cab_strnlen(a,b) strnlen(a,b)
645 #else
646 static size_t
cab_strnlen(const char * p,size_t maxlen)647 cab_strnlen(const char *p, size_t maxlen)
648 {
649 	size_t i;
650 
651 	for (i = 0; i < maxlen; i++) {
652 		if (p[i] == 0)
653 			break;
654 	}
655 	return (i);
656 }
657 #endif
658 
659 /* Read up to max remaining bytes. */
660 static const void *
cab_read_ahead_remaining(struct archive_read * a,size_t max,ssize_t * avail)661 cab_read_ahead_remaining(struct archive_read *a, size_t max, ssize_t *avail)
662 {
663 	const void *p = __archive_read_ahead(a, max, avail);
664 
665 	if (p == NULL && *avail > 0)
666 		p = __archive_read_ahead(a, *avail, avail);
667 	if (p != NULL && (size_t)*avail > max)
668 		*avail = max;
669 
670 	return (p);
671 }
672 
673 /* Convert a path separator '\' -> '/' */
674 static int
cab_convert_path_separator_1(struct archive_string * fn,unsigned char attr)675 cab_convert_path_separator_1(struct archive_string *fn, unsigned char attr)
676 {
677 	size_t i;
678 	int mb;
679 
680 	/* Easy check if we have '\' in multi-byte string. */
681 	mb = 0;
682 	for (i = 0; i < archive_strlen(fn); i++) {
683 		if (fn->s[i] == '\\') {
684 			if (mb) {
685 				/* This may be second byte of multi-byte
686 				 * character. */
687 				break;
688 			}
689 			fn->s[i] = '/';
690 			mb = 0;
691 		} else if ((fn->s[i] & 0x80) && !(attr & ATTR_NAME_IS_UTF))
692 			mb = 1;
693 		else
694 			mb = 0;
695 	}
696 	if (i == archive_strlen(fn))
697 		return (0);
698 	return (-1);
699 }
700 
701 /*
702  * Replace a character '\' with '/' in wide character.
703  */
704 static void
cab_convert_path_separator_2(struct cab * cab,struct archive_entry * entry)705 cab_convert_path_separator_2(struct cab *cab, struct archive_entry *entry)
706 {
707 	const wchar_t *wp;
708 	size_t i;
709 
710 	/* If a conversion to wide character failed, force the replacement. */
711 	if ((wp = archive_entry_pathname_w(entry)) != NULL) {
712 		archive_wstrcpy(&(cab->ws), wp);
713 		for (i = 0; i < archive_strlen(&(cab->ws)); i++) {
714 			if (cab->ws.s[i] == L'\\')
715 				cab->ws.s[i] = L'/';
716 		}
717 		archive_entry_copy_pathname_w(entry, cab->ws.s);
718 	}
719 }
720 
721 /*
722  * Read CFHEADER, CFFOLDER and CFFILE.
723  */
724 static int
cab_read_header(struct archive_read * a)725 cab_read_header(struct archive_read *a)
726 {
727 	struct cab *cab = a->format->data;
728 	const char *p;
729 	struct cfheader *hd;
730 	size_t bytes, len, maxlen, used;
731 	ssize_t avail;
732 	int64_t skip;
733 	int err, i;
734 	int cur_folder, prev_folder;
735 	uint32_t offset32;
736 
737 	a->archive.archive_format = ARCHIVE_FORMAT_CAB;
738 	if (a->archive.archive_format_name == NULL)
739 		a->archive.archive_format_name = "CAB";
740 
741 	if ((p = __archive_read_ahead(a, 42, NULL)) == NULL)
742 		return (truncated_error(a));
743 
744 	if (cab->found_header == 0 &&
745 	    p[0] == 'M' && p[1] == 'Z') {
746 		/* This is an executable?  Must be self-extracting... */
747 		err = cab_skip_sfx(a);
748 		if (err < ARCHIVE_WARN)
749 			return (err);
750 
751 		/* Re-read header after processing the SFX. */
752 		if ((p = __archive_read_ahead(a, 42, NULL)) == NULL)
753 			return (truncated_error(a));
754 	}
755 
756 	cab->cab_offset = 0;
757 	/*
758 	 * Read CFHEADER.
759 	 */
760 	hd = &cab->cfheader;
761 	if (p[CFHEADER_signature+0] != 'M' || p[CFHEADER_signature+1] != 'S' ||
762 	    p[CFHEADER_signature+2] != 'C' || p[CFHEADER_signature+3] != 'F') {
763 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
764 		    "Couldn't find out CAB header");
765 		return (ARCHIVE_FATAL);
766 	}
767 	hd->files_offset = archive_le32dec(p + CFHEADER_coffFiles);
768 	hd->minor = p[CFHEADER_versionMinor];
769 	hd->major = p[CFHEADER_versionMajor];
770 	hd->folder_count = archive_le16dec(p + CFHEADER_cFolders);
771 	if (hd->folder_count == 0)
772 		goto invalid;
773 	hd->file_count = archive_le16dec(p + CFHEADER_cFiles);
774 	if (hd->file_count == 0)
775 		goto invalid;
776 	hd->flags = archive_le16dec(p + CFHEADER_flags);
777 	hd->cabinet = archive_le16dec(p + CFHEADER_iCabinet);
778 	used = CFHEADER_iCabinet + 2;
779 	if (hd->flags & RESERVE_PRESENT) {
780 		uint16_t cfheader;
781 		cfheader = archive_le16dec(p + CFHEADER_cbCFHeader);
782 		if (cfheader > 60000U)
783 			goto invalid;
784 		hd->cffolder = p[CFHEADER_cbCFFolder];
785 		hd->cfdata = p[CFHEADER_cbCFData];
786 		used += 4;/* cbCFHeader, cbCFFolder and cbCFData */
787 		used += cfheader;/* abReserve */
788 	} else
789 		hd->cffolder = 0;/* Avoid compiling warning. */
790 	if (hd->flags & PREV_CABINET) {
791 		/* How many bytes are used for szCabinetPrev. */
792 		if ((p = cab_read_ahead_remaining(a, used + 256,
793 		    &avail)) == NULL || (size_t)avail <= used)
794 			return (truncated_error(a));
795 		maxlen = avail - used;
796 		len = cab_strnlen(p + used, maxlen);
797 		if (len == 0 || len == maxlen) {
798 			goto invalid;
799 		}
800 		used += len + 1;
801 		/* How many bytes are used for szDiskPrev. */
802 		if ((p = cab_read_ahead_remaining(a, used + 256,
803 		    &avail)) == NULL || (size_t)avail <= used)
804 			return (truncated_error(a));
805 		maxlen = avail - used;
806 		len = cab_strnlen(p + used, maxlen);
807 		if (len == maxlen)
808 			goto invalid;
809 		used += len + 1;
810 	}
811 	if (hd->flags & NEXT_CABINET) {
812 		/* How many bytes are used for szCabinetNext. */
813 		if ((p = cab_read_ahead_remaining(a, used + 256,
814 		    &avail)) == NULL || (size_t)avail <= used)
815 			return (truncated_error(a));
816 		maxlen = avail - used;
817 		len = cab_strnlen(p + used, maxlen);
818 		if (len == 0 || len == maxlen)
819 			goto invalid;
820 		used += len + 1;
821 		/* How many bytes are used for szDiskNext. */
822 		if ((p = cab_read_ahead_remaining(a, used + 256,
823 		    &avail)) == NULL || (size_t)avail <= used)
824 			return (truncated_error(a));
825 		maxlen = avail - used;
826 		len = cab_strnlen(p + used, maxlen);
827 		if (len == maxlen)
828 			goto invalid;
829 		used += len + 1;
830 	}
831 	__archive_read_consume(a, used);
832 	cab->cab_offset += used;
833 	used = 0;
834 
835 	/*
836 	 * Read CFFOLDER.
837 	 */
838 	hd->folder_array = calloc(
839 	    hd->folder_count, sizeof(struct cffolder));
840 	if (hd->folder_array == NULL)
841 		goto nomem;
842 
843 	bytes = 8;
844 	if (hd->flags & RESERVE_PRESENT)
845 		bytes += hd->cffolder;
846 	bytes *= hd->folder_count;
847 	if ((p = __archive_read_ahead(a, bytes, NULL)) == NULL)
848 		return (truncated_error(a));
849 	offset32 = 0;
850 	for (i = 0; i < hd->folder_count; i++) {
851 		struct cffolder *folder = &(hd->folder_array[i]);
852 		folder->cfdata_offset_in_cab =
853 		    archive_le32dec(p + CFFOLDER_coffCabStart);
854 		folder->cfdata_count = archive_le16dec(p+CFFOLDER_cCFData);
855 		folder->comptype =
856 		    archive_le16dec(p+CFFOLDER_typeCompress) & 0x0F;
857 		folder->compdata =
858 		    archive_le16dec(p+CFFOLDER_typeCompress) >> 8;
859 		/* Get a compression name. */
860 		if (folder->comptype <
861 		    sizeof(compression_name) / sizeof(compression_name[0]))
862 			folder->compname = compression_name[folder->comptype];
863 		else
864 			folder->compname = "UNKNOWN";
865 		p += 8;
866 		used += 8;
867 		if (hd->flags & RESERVE_PRESENT) {
868 			p += hd->cffolder;/* abReserve */
869 			used += hd->cffolder;
870 		}
871 		/*
872 		 * Sanity check if each data is acceptable.
873 		 */
874 		if (offset32 >= folder->cfdata_offset_in_cab)
875 			goto invalid;
876 		offset32 = folder->cfdata_offset_in_cab;
877 
878 		/* Set a request to initialize zlib for the CFDATA of
879 		 * this folder. */
880 		folder->decompress_init = 0;
881 	}
882 	__archive_read_consume(a, used);
883 	cab->cab_offset += used;
884 
885 	/*
886 	 * Read CFFILE.
887 	 */
888 	/* Seek read pointer to the offset of CFFILE if needed. */
889 	skip = (int64_t)hd->files_offset - cab->cab_offset;
890 	if (skip < 0) {
891 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
892 		    "Invalid offset of CFFILE %jd < %jd",
893 		    (intmax_t)hd->files_offset, (intmax_t)cab->cab_offset);
894 		return (ARCHIVE_FATAL);
895 	}
896 	if (skip) {
897 		if (__archive_read_consume(a, skip) < 0)
898 			return (truncated_error(a));
899 		cab->cab_offset += skip;
900 	}
901 	/* Allocate memory for CFDATA */
902 	hd->file_array = calloc(
903 	    hd->file_count, sizeof(struct cffile));
904 	if (hd->file_array == NULL)
905 		goto nomem;
906 
907 	prev_folder = -1;
908 	for (i = 0; i < hd->file_count; i++) {
909 		struct cffile *file = &(hd->file_array[i]);
910 
911 		if ((p = __archive_read_ahead(a, 16, NULL)) == NULL)
912 			return (truncated_error(a));
913 		file->uncompressed_size = archive_le32dec(p + CFFILE_cbFile);
914 		file->offset = archive_le32dec(p + CFFILE_uoffFolderStart);
915 		file->folder = archive_le16dec(p + CFFILE_iFolder);
916 		file->mtime = cab_dos_time(p + CFFILE_date_time);
917 		file->attr = (uint8_t)archive_le16dec(p + CFFILE_attribs);
918 		__archive_read_consume(a, 16);
919 
920 		cab->cab_offset += 16;
921 		if ((p = cab_read_ahead_remaining(a, 256, &avail)) == NULL)
922 			return (truncated_error(a));
923 		maxlen = avail;
924 		len = cab_strnlen(p, maxlen);
925 		if (len == 0 || len == maxlen)
926 			goto invalid;
927 
928 		/* Copy a pathname.  */
929 		archive_string_init(&(file->pathname));
930 		archive_strncpy(&(file->pathname), p, len);
931 		__archive_read_consume(a, len + 1);
932 		cab->cab_offset += len + 1;
933 
934 		/*
935 		 * Sanity check if each data is acceptable.
936 		 */
937 		if (file->uncompressed_size > MAX_FILE_SIZE)
938 			goto invalid;/* Too large */
939 		if ((int64_t)file->offset + (int64_t)file->uncompressed_size
940 		    > (int64_t)MAX_FILE_SIZE)
941 			goto invalid;/* Too large */
942 		switch (file->folder) {
943 		case iFoldCONTINUED_TO_NEXT:
944 			/* This must be last file in a folder. */
945 			if (i != hd->file_count -1)
946 				goto invalid;
947 			cur_folder = hd->folder_count -1;
948 			break;
949 		case iFoldCONTINUED_PREV_AND_NEXT:
950 			/* This must be only one file in a folder. */
951 			if (hd->file_count != 1)
952 				goto invalid;
953 			/* FALL THROUGH */
954 		case iFoldCONTINUED_FROM_PREV:
955 			/* This must be first file in a folder. */
956 			if (i != 0)
957 				goto invalid;
958 			prev_folder = cur_folder = 0;
959 			offset32 = file->offset;
960 			break;
961 		default:
962 			if (file->folder >= hd->folder_count)
963 				goto invalid;
964 			cur_folder = file->folder;
965 			break;
966 		}
967 		/* Dot not back track. */
968 		if (cur_folder < prev_folder)
969 			goto invalid;
970 		if (cur_folder != prev_folder)
971 			offset32 = 0;
972 		prev_folder = cur_folder;
973 
974 		/* Make sure there are not any blanks from last file
975 		 * contents. */
976 		if (offset32 != file->offset)
977 			goto invalid;
978 		offset32 += file->uncompressed_size;
979 
980 		/* CFDATA is available for file contents. */
981 		if (file->uncompressed_size > 0 &&
982 		    hd->folder_array[cur_folder].cfdata_count == 0)
983 			goto invalid;
984 	}
985 
986 	if (hd->cabinet != 0 || hd->flags & (PREV_CABINET | NEXT_CABINET)) {
987 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
988 		    "Multivolume cabinet file is unsupported");
989 		return (ARCHIVE_WARN);
990 	}
991 	return (ARCHIVE_OK);
992 invalid:
993 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
994 	    "Invalid CAB header");
995 	return (ARCHIVE_FATAL);
996 nomem:
997 	archive_set_error(&a->archive, ENOMEM,
998 	    "Can't allocate memory for CAB data");
999 	return (ARCHIVE_FATAL);
1000 }
1001 
1002 static int
archive_read_format_cab_read_header(struct archive_read * a,struct archive_entry * entry)1003 archive_read_format_cab_read_header(struct archive_read *a,
1004     struct archive_entry *entry)
1005 {
1006 	struct cab *cab = a->format->data;
1007 	struct cfheader *hd;
1008 	struct cffolder *prev_folder;
1009 	struct cffile *file;
1010 	struct archive_string_conv *sconv;
1011 	int err = ARCHIVE_OK, r;
1012 
1013 	if (cab->found_header == 0) {
1014 		err = cab_read_header(a);
1015 		if (err < ARCHIVE_WARN)
1016 			return (err);
1017 		/* We've found the header. */
1018 		cab->found_header = 1;
1019 	}
1020 	hd = &cab->cfheader;
1021 
1022 	if (hd->file_index >= hd->file_count) {
1023 		cab->end_of_archive = 1;
1024 		return (ARCHIVE_EOF);
1025 	}
1026 	file = &hd->file_array[hd->file_index++];
1027 
1028 	cab->end_of_entry = 0;
1029 	cab->end_of_entry_cleanup = 0;
1030 	cab->entry_unconsumed = 0;
1031 	cab->entry_cffile = file;
1032 
1033 	/*
1034 	 * Choose a proper folder.
1035 	 */
1036 	prev_folder = cab->entry_cffolder;
1037 	switch (file->folder) {
1038 	case iFoldCONTINUED_FROM_PREV:
1039 	case iFoldCONTINUED_PREV_AND_NEXT:
1040 		cab->entry_cffolder = &hd->folder_array[0];
1041 		break;
1042 	case iFoldCONTINUED_TO_NEXT:
1043 		cab->entry_cffolder = &hd->folder_array[hd->folder_count-1];
1044 		break;
1045 	default:
1046 		cab->entry_cffolder = &hd->folder_array[file->folder];
1047 		break;
1048 	}
1049 	/* If a cffolder of this file is changed, reset a cfdata to read
1050 	 * file contents from next cfdata. */
1051 	if (prev_folder != cab->entry_cffolder)
1052 		cab->entry_cfdata = NULL;
1053 
1054 	/* If a pathname is UTF-8, prepare a string conversion object
1055 	 * for UTF-8 and use it. */
1056 	if (file->attr & ATTR_NAME_IS_UTF) {
1057 		if (cab->sconv_utf8 == NULL) {
1058 			cab->sconv_utf8 =
1059 			    archive_string_conversion_from_charset(
1060 				&(a->archive), "UTF-8", 1);
1061 			if (cab->sconv_utf8 == NULL)
1062 				return (ARCHIVE_FATAL);
1063 		}
1064 		sconv = cab->sconv_utf8;
1065 	} else if (cab->sconv != NULL) {
1066 		/* Choose the conversion specified by the option. */
1067 		sconv = cab->sconv;
1068 	} else {
1069 		/* Choose the default conversion. */
1070 		if (!cab->init_default_conversion) {
1071 			cab->sconv_default =
1072 			    archive_string_default_conversion_for_read(
1073 			      &(a->archive));
1074 			cab->init_default_conversion = 1;
1075 		}
1076 		sconv = cab->sconv_default;
1077 	}
1078 
1079 	/*
1080 	 * Set a default value and common data
1081 	 */
1082 	r = cab_convert_path_separator_1(&(file->pathname), file->attr);
1083 	if (archive_entry_copy_pathname_l(entry, file->pathname.s,
1084 	    archive_strlen(&(file->pathname)), sconv) != 0) {
1085 		if (errno == ENOMEM) {
1086 			archive_set_error(&a->archive, ENOMEM,
1087 			    "Can't allocate memory for Pathname");
1088 			return (ARCHIVE_FATAL);
1089 		}
1090 		archive_set_error(&a->archive,
1091 		    ARCHIVE_ERRNO_FILE_FORMAT,
1092 		    "Pathname cannot be converted "
1093 		    "from %s to current locale",
1094 		    archive_string_conversion_charset_name(sconv));
1095 		err = ARCHIVE_WARN;
1096 	}
1097 	if (r < 0) {
1098 		/* Convert a path separator '\' -> '/' */
1099 		cab_convert_path_separator_2(cab, entry);
1100 	}
1101 
1102 	archive_entry_set_size(entry, file->uncompressed_size);
1103 	if (file->attr & ATTR_RDONLY)
1104 		archive_entry_set_mode(entry, AE_IFREG | 0555);
1105 	else
1106 		archive_entry_set_mode(entry, AE_IFREG | 0666);
1107 	archive_entry_set_mtime(entry, file->mtime, 0);
1108 
1109 	cab->entry_bytes_remaining = file->uncompressed_size;
1110 	cab->entry_offset = 0;
1111 	/* We don't need compress data. */
1112 	if (file->uncompressed_size == 0)
1113 		cab->end_of_entry_cleanup = cab->end_of_entry = 1;
1114 
1115 	/* Set up a more descriptive format name. */
1116 	snprintf(cab->format_name, sizeof(cab->format_name), "CAB %d.%d (%s)",
1117 	    hd->major, hd->minor, cab->entry_cffolder->compname);
1118 	a->archive.archive_format_name = cab->format_name;
1119 
1120 	return (err);
1121 }
1122 
1123 static int
archive_read_format_cab_read_data(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset)1124 archive_read_format_cab_read_data(struct archive_read *a,
1125     const void **buff, size_t *size, int64_t *offset)
1126 {
1127 	struct cab *cab = a->format->data;
1128 	int r;
1129 
1130 	switch (cab->entry_cffile->folder) {
1131 	case iFoldCONTINUED_FROM_PREV:
1132 	case iFoldCONTINUED_TO_NEXT:
1133 	case iFoldCONTINUED_PREV_AND_NEXT:
1134 		*buff = NULL;
1135 		*size = 0;
1136 		*offset = 0;
1137 		archive_clear_error(&a->archive);
1138 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1139 		    "Cannot restore this file split in multivolume");
1140 		return (ARCHIVE_FAILED);
1141 	default:
1142 		break;
1143 	}
1144 	if (cab->read_data_invoked == 0) {
1145 		if (cab->bytes_skipped) {
1146 			if (cab->entry_cfdata == NULL) {
1147 				r = cab_next_cfdata(a);
1148 				if (r < 0)
1149 					return (r);
1150 			}
1151 			if (cab_consume_cfdata(a, cab->bytes_skipped) < 0)
1152 				return (ARCHIVE_FATAL);
1153 			cab->bytes_skipped = 0;
1154 		}
1155 		cab->read_data_invoked = 1;
1156 	}
1157 	if (cab->entry_unconsumed) {
1158 		/* Consume as much as the compressor actually used. */
1159 		r = (int)cab_consume_cfdata(a, cab->entry_unconsumed);
1160 		cab->entry_unconsumed = 0;
1161 		if (r < 0)
1162 			return (r);
1163 	}
1164 	if (cab->end_of_archive || cab->end_of_entry) {
1165 		if (!cab->end_of_entry_cleanup) {
1166 			/* End-of-entry cleanup done. */
1167 			cab->end_of_entry_cleanup = 1;
1168 		}
1169 		*offset = cab->entry_offset;
1170 		*size = 0;
1171 		*buff = NULL;
1172 		return (ARCHIVE_EOF);
1173 	}
1174 
1175 	return (cab_read_data(a, buff, size, offset));
1176 }
1177 
1178 static uint32_t
cab_checksum_cfdata_4(const void * p,size_t bytes,uint32_t seed)1179 cab_checksum_cfdata_4(const void *p, size_t bytes, uint32_t seed)
1180 {
1181 	const unsigned char *b;
1182 	unsigned u32num;
1183 	uint32_t sum;
1184 
1185 	u32num = (unsigned)bytes / 4;
1186 	sum = seed;
1187 	b = p;
1188 	for (;u32num > 0; --u32num) {
1189 		sum ^= archive_le32dec(b);
1190 		b += 4;
1191 	}
1192 	return (sum);
1193 }
1194 
1195 static uint32_t
cab_checksum_cfdata(const void * p,size_t bytes,uint32_t seed)1196 cab_checksum_cfdata(const void *p, size_t bytes, uint32_t seed)
1197 {
1198 	const unsigned char *b;
1199 	uint32_t sum;
1200 	uint32_t t;
1201 
1202 	sum = cab_checksum_cfdata_4(p, bytes, seed);
1203 	b = p;
1204 	b += bytes & ~3;
1205 	t = 0;
1206 	switch (bytes & 3) {
1207 	case 3:
1208 		t |= ((uint32_t)(*b++)) << 16;
1209 		/* FALL THROUGH */
1210 	case 2:
1211 		t |= ((uint32_t)(*b++)) << 8;
1212 		/* FALL THROUGH */
1213 	case 1:
1214 		t |= *b;
1215 		/* FALL THROUGH */
1216 	default:
1217 		break;
1218 	}
1219 	sum ^= t;
1220 
1221 	return (sum);
1222 }
1223 
1224 static void
cab_checksum_update(struct archive_read * a,size_t bytes)1225 cab_checksum_update(struct archive_read *a, size_t bytes)
1226 {
1227 	struct cab *cab = a->format->data;
1228 	struct cfdata *cfdata = cab->entry_cfdata;
1229 	const unsigned char *p;
1230 	size_t sumbytes;
1231 
1232 	if (cfdata->sum == 0 || cfdata->sum_ptr == NULL)
1233 		return;
1234 	/*
1235 	 * Calculate the sum of this CFDATA.
1236 	 * Make sure CFDATA must be calculated in four bytes.
1237 	 */
1238 	p = cfdata->sum_ptr;
1239 	sumbytes = bytes;
1240 	if (cfdata->sum_extra_avail) {
1241 		while (cfdata->sum_extra_avail < 4 && sumbytes > 0) {
1242 			cfdata->sum_extra[
1243 			    cfdata->sum_extra_avail++] = *p++;
1244 			sumbytes--;
1245 		}
1246 		if (cfdata->sum_extra_avail == 4) {
1247 			cfdata->sum_calculated = cab_checksum_cfdata_4(
1248 			    cfdata->sum_extra, 4, cfdata->sum_calculated);
1249 			cfdata->sum_extra_avail = 0;
1250 		}
1251 	}
1252 	if (sumbytes) {
1253 		int odd = sumbytes & 3;
1254 		if ((int)(sumbytes - odd) > 0)
1255 			cfdata->sum_calculated = cab_checksum_cfdata_4(
1256 			    p, sumbytes - odd, cfdata->sum_calculated);
1257 		if (odd)
1258 			memcpy(cfdata->sum_extra, p + sumbytes - odd, odd);
1259 		cfdata->sum_extra_avail = odd;
1260 	}
1261 	cfdata->sum_ptr = NULL;
1262 }
1263 
1264 static int
cab_checksum_finish(struct archive_read * a)1265 cab_checksum_finish(struct archive_read *a)
1266 {
1267 	struct cab *cab = a->format->data;
1268 	struct cfdata *cfdata = cab->entry_cfdata;
1269 	int l;
1270 
1271 	/* Do not need to compute a sum. */
1272 	if (cfdata->sum == 0)
1273 		return (ARCHIVE_OK);
1274 
1275 	/*
1276 	 * Calculate the sum of remaining CFDATA.
1277 	 */
1278 	if (cfdata->sum_extra_avail) {
1279 		cfdata->sum_calculated =
1280 		    cab_checksum_cfdata(cfdata->sum_extra,
1281 		       cfdata->sum_extra_avail, cfdata->sum_calculated);
1282 		cfdata->sum_extra_avail = 0;
1283 	}
1284 
1285 	l = 4;
1286 	if (cab->cfheader.flags & RESERVE_PRESENT)
1287 		l += cab->cfheader.cfdata;
1288 	if (cfdata->memimage == NULL) {
1289 		return (ARCHIVE_FAILED);
1290 	}
1291 	cfdata->sum_calculated = cab_checksum_cfdata(
1292 	    cfdata->memimage + CFDATA_cbData, l, cfdata->sum_calculated);
1293 	if (cfdata->sum_calculated != cfdata->sum) {
1294 #ifndef DONT_FAIL_ON_CRC_ERROR
1295 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1296 		    "Checksum error CFDATA[%d] %" PRIx32 ":%" PRIx32 " in %d bytes",
1297 		    cab->entry_cffolder->cfdata_index -1,
1298 		    cfdata->sum, cfdata->sum_calculated,
1299 		    cfdata->compressed_size);
1300 		return (ARCHIVE_FAILED);
1301 #endif
1302 	}
1303 	return (ARCHIVE_OK);
1304 }
1305 
1306 /*
1307  * Read CFDATA if needed.
1308  */
1309 static int
cab_next_cfdata(struct archive_read * a)1310 cab_next_cfdata(struct archive_read *a)
1311 {
1312 	struct cab *cab = a->format->data;
1313 	struct cfdata *cfdata = cab->entry_cfdata;
1314 
1315 	/* There are remaining bytes in current CFDATA, use it first. */
1316 	if (cfdata != NULL && cfdata->uncompressed_bytes_remaining > 0)
1317 		return (ARCHIVE_OK);
1318 
1319 	if (cfdata == NULL) {
1320 		int64_t skip;
1321 
1322 		cab->entry_cffolder->cfdata_index = 0;
1323 
1324 		/* Seek read pointer to the offset of CFDATA if needed. */
1325 		skip = cab->entry_cffolder->cfdata_offset_in_cab
1326 			- cab->cab_offset;
1327 		if (skip < 0) {
1328 			int folder_index;
1329 			switch (cab->entry_cffile->folder) {
1330 			case iFoldCONTINUED_FROM_PREV:
1331 			case iFoldCONTINUED_PREV_AND_NEXT:
1332 				folder_index = 0;
1333 				break;
1334 			case iFoldCONTINUED_TO_NEXT:
1335 				folder_index = cab->cfheader.folder_count-1;
1336 				break;
1337 			default:
1338 				folder_index = cab->entry_cffile->folder;
1339 				break;
1340 			}
1341 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1342 			    "Invalid offset of CFDATA in folder(%d) %jd < %jd",
1343 			    folder_index,
1344 			    (intmax_t)cab->entry_cffolder->cfdata_offset_in_cab,
1345 			    (intmax_t)cab->cab_offset);
1346 			return (ARCHIVE_FATAL);
1347 		}
1348 		if (skip > 0) {
1349 			if (__archive_read_consume(a, skip) < 0)
1350 				return (ARCHIVE_FATAL);
1351 			cab->cab_offset =
1352 			    cab->entry_cffolder->cfdata_offset_in_cab;
1353 		}
1354 	}
1355 
1356 	/*
1357 	 * Read a CFDATA.
1358 	 */
1359 	if (cab->entry_cffolder->cfdata_index <
1360 	    cab->entry_cffolder->cfdata_count) {
1361 		const unsigned char *p;
1362 		int l;
1363 
1364 		cfdata = &(cab->entry_cffolder->cfdata);
1365 		cab->entry_cffolder->cfdata_index++;
1366 		cab->entry_cfdata = cfdata;
1367 		cfdata->sum_calculated = 0;
1368 		cfdata->sum_extra_avail = 0;
1369 		cfdata->sum_ptr = NULL;
1370 		l = 8;
1371 		if (cab->cfheader.flags & RESERVE_PRESENT)
1372 			l += cab->cfheader.cfdata;
1373 		if ((p = __archive_read_ahead(a, l, NULL)) == NULL)
1374 			return (truncated_error(a));
1375 		cfdata->sum = archive_le32dec(p + CFDATA_csum);
1376 		cfdata->compressed_size = archive_le16dec(p + CFDATA_cbData);
1377 		cfdata->compressed_bytes_remaining = cfdata->compressed_size;
1378 		cfdata->uncompressed_size =
1379 		    archive_le16dec(p + CFDATA_cbUncomp);
1380 		cfdata->uncompressed_bytes_remaining =
1381 		    cfdata->uncompressed_size;
1382 		cfdata->uncompressed_avail = 0;
1383 		cfdata->read_offset = 0;
1384 		cfdata->unconsumed = 0;
1385 
1386 		/*
1387 		 * Sanity check if data size is acceptable.
1388 		 */
1389 		if (cfdata->compressed_size == 0 ||
1390 		    cfdata->compressed_size > (MAX_UNCOMPRESS_SIZE + 6144))
1391 			goto invalid;
1392 		if (cfdata->uncompressed_size > MAX_UNCOMPRESS_SIZE)
1393 			goto invalid;
1394 		if (cfdata->uncompressed_size == 0) {
1395 			switch (cab->entry_cffile->folder) {
1396 			case iFoldCONTINUED_PREV_AND_NEXT:
1397 			case iFoldCONTINUED_TO_NEXT:
1398 				break;
1399 			case iFoldCONTINUED_FROM_PREV:
1400 			default:
1401 				goto invalid;
1402 			}
1403 		}
1404 		/* If CFDATA is not last in a folder, an uncompressed
1405 		 * size must be 0x8000 (32 KiB) */
1406 		if ((cab->entry_cffolder->cfdata_index <
1407 		     cab->entry_cffolder->cfdata_count) &&
1408 		       cfdata->uncompressed_size != MAX_UNCOMPRESS_SIZE)
1409 			goto invalid;
1410 
1411 		/* A compressed data size and an uncompressed data size must
1412 		 * be the same in no compression mode. */
1413 		if (cab->entry_cffolder->comptype == COMPTYPE_NONE &&
1414 		    cfdata->compressed_size != cfdata->uncompressed_size)
1415 			goto invalid;
1416 
1417 		/*
1418 		 * Save CFDATA image for sum check.
1419 		 */
1420 		if (cfdata->memimage_size < (size_t)l) {
1421 			free(cfdata->memimage);
1422 			cfdata->memimage = malloc(l);
1423 			if (cfdata->memimage == NULL) {
1424 				archive_set_error(&a->archive, ENOMEM,
1425 				    "Can't allocate memory for CAB data");
1426 				return (ARCHIVE_FATAL);
1427 			}
1428 			cfdata->memimage_size = l;
1429 		}
1430 		memcpy(cfdata->memimage, p, l);
1431 
1432 		/* Consume bytes as much as we used. */
1433 		__archive_read_consume(a, l);
1434 		cab->cab_offset += l;
1435 	} else if (cab->entry_cffolder->cfdata_count > 0) {
1436 		/* Run out of all CFDATA in a folder. */
1437 		cfdata->compressed_size = 0;
1438 		cfdata->uncompressed_size = 0;
1439 		cfdata->compressed_bytes_remaining = 0;
1440 		cfdata->uncompressed_bytes_remaining = 0;
1441 	} else {
1442 		/* Current folder does not have any CFDATA. */
1443 		cfdata = &(cab->entry_cffolder->cfdata);
1444 		cab->entry_cfdata = cfdata;
1445 		memset(cfdata, 0, sizeof(*cfdata));
1446 	}
1447 	return (ARCHIVE_OK);
1448 invalid:
1449 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1450 	    "Invalid CFDATA");
1451 	return (ARCHIVE_FATAL);
1452 }
1453 
1454 /*
1455  * Read ahead CFDATA.
1456  */
1457 static const void *
cab_read_ahead_cfdata(struct archive_read * a,ssize_t * avail)1458 cab_read_ahead_cfdata(struct archive_read *a, ssize_t *avail)
1459 {
1460 	struct cab *cab = a->format->data;
1461 	int err;
1462 
1463 	err = cab_next_cfdata(a);
1464 	if (err < ARCHIVE_OK) {
1465 		*avail = err;
1466 		return (NULL);
1467 	}
1468 
1469 	switch (cab->entry_cffolder->comptype) {
1470 	case COMPTYPE_NONE:
1471 		return (cab_read_ahead_cfdata_none(a, avail));
1472 	case COMPTYPE_MSZIP:
1473 		return (cab_read_ahead_cfdata_deflate(a, avail));
1474 	case COMPTYPE_LZX:
1475 		return (cab_read_ahead_cfdata_lzx(a, avail));
1476 	default: /* Unsupported compression. */
1477 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1478 		    "Unsupported CAB compression: %s",
1479 		    cab->entry_cffolder->compname);
1480 		*avail = ARCHIVE_FAILED;
1481 		return (NULL);
1482 	}
1483 }
1484 
1485 /*
1486  * Read ahead CFDATA as uncompressed data.
1487  */
1488 static const void *
cab_read_ahead_cfdata_none(struct archive_read * a,ssize_t * avail)1489 cab_read_ahead_cfdata_none(struct archive_read *a, ssize_t *avail)
1490 {
1491 	struct cab *cab = a->format->data;
1492 	struct cfdata *cfdata;
1493 	const void *d;
1494 
1495 	cfdata = cab->entry_cfdata;
1496 
1497 	/*
1498 	 * Note: '1' here is a performance optimization.
1499 	 * Recall that the decompression layer returns a count of
1500 	 * available bytes; asking for more than that forces the
1501 	 * decompressor to combine reads by copying data.
1502 	 */
1503 	d = __archive_read_ahead(a, 1, avail);
1504 	if (*avail <= 0) {
1505 		*avail = truncated_error(a);
1506 		return (NULL);
1507 	}
1508 	if (*avail > cfdata->uncompressed_bytes_remaining)
1509 		*avail = cfdata->uncompressed_bytes_remaining;
1510 	cfdata->uncompressed_avail = cfdata->uncompressed_size;
1511 	cfdata->unconsumed = *avail;
1512 	cfdata->sum_ptr = d;
1513 	return (d);
1514 }
1515 
1516 /*
1517  * Read ahead CFDATA as deflate data.
1518  */
1519 #ifdef HAVE_ZLIB_H
1520 static const void *
cab_read_ahead_cfdata_deflate(struct archive_read * a,ssize_t * avail)1521 cab_read_ahead_cfdata_deflate(struct archive_read *a, ssize_t *avail)
1522 {
1523 	struct cab *cab = a->format->data;
1524 	struct cfdata *cfdata;
1525 	const void *d;
1526 	int r, mszip;
1527 	uint16_t uavail;
1528 	char eod = 0;
1529 
1530 	cfdata = cab->entry_cfdata;
1531 	/* If the buffer hasn't been allocated, allocate it now. */
1532 	if (cab->uncompressed_buffer == NULL) {
1533 		cab->uncompressed_buffer_size = MAX_UNCOMPRESS_SIZE;
1534 		cab->uncompressed_buffer
1535 		    = malloc(cab->uncompressed_buffer_size);
1536 		if (cab->uncompressed_buffer == NULL) {
1537 			archive_set_error(&a->archive, ENOMEM,
1538 			    "No memory for CAB reader");
1539 			*avail = ARCHIVE_FATAL;
1540 			return (NULL);
1541 		}
1542 	}
1543 
1544 	uavail = cfdata->uncompressed_avail;
1545 	if (uavail == cfdata->uncompressed_size) {
1546 		d = cab->uncompressed_buffer + cfdata->read_offset;
1547 		*avail = uavail - cfdata->read_offset;
1548 		return (d);
1549 	}
1550 
1551 	if (!cab->entry_cffolder->decompress_init) {
1552 		cab->stream.next_in = NULL;
1553 		cab->stream.avail_in = 0;
1554 		cab->stream.total_in = 0;
1555 		cab->stream.next_out = NULL;
1556 		cab->stream.avail_out = 0;
1557 		cab->stream.total_out = 0;
1558 		if (cab->stream_valid)
1559 			r = inflateReset(&cab->stream);
1560 		else
1561 			r = inflateInit2(&cab->stream,
1562 			    -15 /* Don't check for zlib header */);
1563 		if (r != Z_OK) {
1564 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1565 			    "Can't initialize deflate decompression");
1566 			*avail = ARCHIVE_FATAL;
1567 			return (NULL);
1568 		}
1569 		/* Stream structure has been set up. */
1570 		cab->stream_valid = 1;
1571 		/* We've initialized decompression for this stream. */
1572 		cab->entry_cffolder->decompress_init = 1;
1573 	}
1574 
1575 	if (cfdata->compressed_bytes_remaining == cfdata->compressed_size)
1576 		mszip = 2;
1577 	else
1578 		mszip = 0;
1579 	eod = 0;
1580 	cab->stream.total_out = uavail;
1581 	/*
1582 	 * We always uncompress all data in current CFDATA.
1583 	 */
1584 	while (!eod && cab->stream.total_out < cfdata->uncompressed_size) {
1585 		ssize_t bytes_avail;
1586 
1587 		cab->stream.next_out =
1588 		    cab->uncompressed_buffer + cab->stream.total_out;
1589 		cab->stream.avail_out =
1590 		    cfdata->uncompressed_size - cab->stream.total_out;
1591 
1592 		d = __archive_read_ahead(a, 1, &bytes_avail);
1593 		if (bytes_avail <= 0) {
1594 			*avail = truncated_error(a);
1595 			return (NULL);
1596 		}
1597 		if (bytes_avail > cfdata->compressed_bytes_remaining)
1598 			bytes_avail = cfdata->compressed_bytes_remaining;
1599 		/*
1600 		 * A bug in zlib.h: stream.next_in should be marked 'const'
1601 		 * but isn't (the library never alters data through the
1602 		 * next_in pointer, only reads it).  The result: this ugly
1603 		 * cast to remove 'const'.
1604 		 */
1605 		cab->stream.next_in = (Bytef *)(uintptr_t)d;
1606 		cab->stream.avail_in = (uInt)bytes_avail;
1607 		cab->stream.total_in = 0;
1608 
1609 		/* Cut out a tow-byte MSZIP signature(0x43, 0x4b). */
1610 		if (mszip > 0) {
1611 			if (bytes_avail <= 0)
1612 				goto nomszip;
1613 			if (bytes_avail <= mszip) {
1614 				if (mszip == 2) {
1615 					if (cab->stream.next_in[0] != 0x43)
1616 						goto nomszip;
1617 					if (bytes_avail > 1 &&
1618 					    cab->stream.next_in[1] != 0x4b)
1619 						goto nomszip;
1620 				} else if (cab->stream.next_in[0] != 0x4b)
1621 					goto nomszip;
1622 				cfdata->unconsumed = bytes_avail;
1623 				cfdata->sum_ptr = d;
1624 				if (cab_minimum_consume_cfdata(
1625 				    a, cfdata->unconsumed) < 0) {
1626 					*avail = ARCHIVE_FATAL;
1627 					return (NULL);
1628 				}
1629 				mszip -= (int)bytes_avail;
1630 				continue;
1631 			}
1632 			if (mszip == 1 && cab->stream.next_in[0] != 0x4b)
1633 				goto nomszip;
1634 			else if (mszip == 2 && (cab->stream.next_in[0] != 0x43 ||
1635 			    cab->stream.next_in[1] != 0x4b))
1636 				goto nomszip;
1637 			cab->stream.next_in += mszip;
1638 			cab->stream.avail_in -= mszip;
1639 			cab->stream.total_in += mszip;
1640 			mszip = 0;
1641 		}
1642 
1643 		r = inflate(&cab->stream, 0);
1644 		switch (r) {
1645 		case Z_OK:
1646 			break;
1647 		case Z_STREAM_END:
1648 			eod = 1;
1649 			break;
1650 		default:
1651 			goto zlibfailed;
1652 		}
1653 		cfdata->unconsumed = cab->stream.total_in;
1654 		cfdata->sum_ptr = d;
1655 		if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) {
1656 			*avail = ARCHIVE_FATAL;
1657 			return (NULL);
1658 		}
1659 	}
1660 	uavail = (uint16_t)cab->stream.total_out;
1661 
1662 	if (uavail < cfdata->uncompressed_size) {
1663 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1664 		    "Invalid uncompressed size (%d < %d)",
1665 		    uavail, cfdata->uncompressed_size);
1666 		*avail = ARCHIVE_FATAL;
1667 		return (NULL);
1668 	}
1669 
1670 	/*
1671 	 * Note: I suspect there is a bug in makecab.exe because, in rare
1672 	 * case, compressed bytes are still remaining regardless we have
1673 	 * gotten all uncompressed bytes, which size is recorded in CFDATA,
1674 	 * as much as we need, and we have to use the garbage so as to
1675 	 * correctly compute the sum of CFDATA accordingly.
1676 	 */
1677 	if (cfdata->compressed_bytes_remaining > 0) {
1678 		d = __archive_read_ahead(a, cfdata->compressed_bytes_remaining,
1679 		    NULL);
1680 		if (d == NULL) {
1681 			*avail = truncated_error(a);
1682 			return (NULL);
1683 		}
1684 		cfdata->unconsumed = cfdata->compressed_bytes_remaining;
1685 		cfdata->sum_ptr = d;
1686 		if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) {
1687 			*avail = ARCHIVE_FATAL;
1688 			return (NULL);
1689 		}
1690 	}
1691 
1692 	/*
1693 	 * Set dictionary data for decompressing of next CFDATA, which
1694 	 * in the same folder. This is why we always do decompress CFDATA
1695 	 * even if beginning CFDATA or some of CFDATA are not used in
1696 	 * skipping file data.
1697 	 */
1698 	if (cab->entry_cffolder->cfdata_index <
1699 	    cab->entry_cffolder->cfdata_count) {
1700 		r = inflateReset(&cab->stream);
1701 		if (r != Z_OK)
1702 			goto zlibfailed;
1703 		r = inflateSetDictionary(&cab->stream,
1704 		    cab->uncompressed_buffer, cfdata->uncompressed_size);
1705 		if (r != Z_OK)
1706 			goto zlibfailed;
1707 	}
1708 
1709 	d = cab->uncompressed_buffer + cfdata->read_offset;
1710 	*avail = uavail - cfdata->read_offset;
1711 	cfdata->uncompressed_avail = uavail;
1712 
1713 	return (d);
1714 
1715 zlibfailed:
1716 	switch (r) {
1717 	case Z_MEM_ERROR:
1718 		archive_set_error(&a->archive, ENOMEM,
1719 		    "Out of memory for deflate decompression");
1720 		break;
1721 	default:
1722 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1723 		    "Deflate decompression failed (%d)", r);
1724 		break;
1725 	}
1726 	*avail = ARCHIVE_FATAL;
1727 	return (NULL);
1728 nomszip:
1729 	archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1730 	    "CFDATA incorrect(no MSZIP signature)");
1731 	*avail = ARCHIVE_FATAL;
1732 	return (NULL);
1733 }
1734 
1735 #else /* HAVE_ZLIB_H */
1736 
1737 static const void *
cab_read_ahead_cfdata_deflate(struct archive_read * a,ssize_t * avail)1738 cab_read_ahead_cfdata_deflate(struct archive_read *a, ssize_t *avail)
1739 {
1740 	*avail = ARCHIVE_FATAL;
1741 	archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1742 	    "libarchive compiled without deflate support (no libz)");
1743 	return (NULL);
1744 }
1745 
1746 #endif /* HAVE_ZLIB_H */
1747 
1748 static const void *
cab_read_ahead_cfdata_lzx(struct archive_read * a,ssize_t * avail)1749 cab_read_ahead_cfdata_lzx(struct archive_read *a, ssize_t *avail)
1750 {
1751 	struct cab *cab = a->format->data;
1752 	struct cfdata *cfdata;
1753 	const void *d;
1754 	int r;
1755 	uint16_t uavail;
1756 
1757 	cfdata = cab->entry_cfdata;
1758 	/* If the buffer hasn't been allocated, allocate it now. */
1759 	if (cab->uncompressed_buffer == NULL) {
1760 		cab->uncompressed_buffer_size = MAX_UNCOMPRESS_SIZE;
1761 		cab->uncompressed_buffer
1762 		    = malloc(cab->uncompressed_buffer_size);
1763 		if (cab->uncompressed_buffer == NULL) {
1764 			archive_set_error(&a->archive, ENOMEM,
1765 			    "No memory for CAB reader");
1766 			*avail = ARCHIVE_FATAL;
1767 			return (NULL);
1768 		}
1769 	}
1770 
1771 	uavail = cfdata->uncompressed_avail;
1772 	if (uavail == cfdata->uncompressed_size) {
1773 		d = cab->uncompressed_buffer + cfdata->read_offset;
1774 		*avail = uavail - cfdata->read_offset;
1775 		return (d);
1776 	}
1777 
1778 	if (!cab->entry_cffolder->decompress_init) {
1779 		r = lzx_decode_init(&cab->xstrm,
1780 		    cab->entry_cffolder->compdata);
1781 		if (r != ARCHIVE_OK) {
1782 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1783 			    "Can't initialize LZX decompression");
1784 			*avail = ARCHIVE_FATAL;
1785 			return (NULL);
1786 		}
1787 		/* We've initialized decompression for this stream. */
1788 		cab->entry_cffolder->decompress_init = 1;
1789 	}
1790 
1791 	/* Clean up remaining bits of previous CFDATA. */
1792 	lzx_cleanup_bitstream(&cab->xstrm);
1793 	cab->xstrm.total_out = uavail;
1794 	while (cab->xstrm.total_out < cfdata->uncompressed_size) {
1795 		ssize_t bytes_avail;
1796 
1797 		cab->xstrm.next_out =
1798 		    cab->uncompressed_buffer + cab->xstrm.total_out;
1799 		cab->xstrm.avail_out =
1800 		    cfdata->uncompressed_size - cab->xstrm.total_out;
1801 
1802 		d = __archive_read_ahead(a, 1, &bytes_avail);
1803 		if (d == NULL) {
1804 			archive_set_error(&a->archive,
1805 			    ARCHIVE_ERRNO_FILE_FORMAT,
1806 			    "Truncated CAB file data");
1807 			*avail = ARCHIVE_FATAL;
1808 			return (NULL);
1809 		}
1810 		if (bytes_avail > cfdata->compressed_bytes_remaining)
1811 			bytes_avail = cfdata->compressed_bytes_remaining;
1812 
1813 		cab->xstrm.next_in = d;
1814 		cab->xstrm.avail_in = bytes_avail;
1815 		cab->xstrm.total_in = 0;
1816 		r = lzx_decode(&cab->xstrm,
1817 		    cfdata->compressed_bytes_remaining == bytes_avail);
1818 		switch (r) {
1819 		case ARCHIVE_OK:
1820 		case ARCHIVE_EOF:
1821 			break;
1822 		default:
1823 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1824 			    "LZX decompression failed (%d)", r);
1825 			*avail = ARCHIVE_FATAL;
1826 			return (NULL);
1827 		}
1828 		cfdata->unconsumed = cab->xstrm.total_in;
1829 		cfdata->sum_ptr = d;
1830 		if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) {
1831 			*avail = ARCHIVE_FATAL;
1832 			return (NULL);
1833 		}
1834 	}
1835 
1836 	uavail = (uint16_t)cab->xstrm.total_out;
1837 	/*
1838 	 * Make sure a read pointer advances to next CFDATA.
1839 	 */
1840 	if (cfdata->compressed_bytes_remaining > 0) {
1841 		d = __archive_read_ahead(a, cfdata->compressed_bytes_remaining,
1842 		    NULL);
1843 		if (d == NULL) {
1844 			*avail = truncated_error(a);
1845 			return (NULL);
1846 		}
1847 		cfdata->unconsumed = cfdata->compressed_bytes_remaining;
1848 		cfdata->sum_ptr = d;
1849 		if (cab_minimum_consume_cfdata(a, cfdata->unconsumed) < 0) {
1850 			*avail = ARCHIVE_FATAL;
1851 			return (NULL);
1852 		}
1853 	}
1854 
1855 	/*
1856 	 * Translation reversal of x86 processor CALL byte sequence(E8).
1857 	 */
1858 	lzx_translation(&cab->xstrm, cab->uncompressed_buffer,
1859 	    cfdata->uncompressed_size,
1860 	    (cab->entry_cffolder->cfdata_index - 1) * MAX_UNCOMPRESS_SIZE);
1861 
1862 	d = cab->uncompressed_buffer + cfdata->read_offset;
1863 	*avail = uavail - cfdata->read_offset;
1864 	cfdata->uncompressed_avail = uavail;
1865 
1866 	return (d);
1867 }
1868 
1869 /*
1870  * Consume CFDATA.
1871  * We always decompress CFDATA to consume CFDATA as much as we need
1872  * in uncompressed bytes because all CFDATA in a folder are related
1873  * so we do not skip any CFDATA without decompressing.
1874  * Note: If the folder of a CFFILE is iFoldCONTINUED_PREV_AND_NEXT or
1875  * iFoldCONTINUED_FROM_PREV, we won't decompress because a CFDATA for
1876  * the CFFILE is remaining bytes of previous Multivolume CAB file.
1877  */
1878 static int64_t
cab_consume_cfdata(struct archive_read * a,int64_t consumed_bytes)1879 cab_consume_cfdata(struct archive_read *a, int64_t consumed_bytes)
1880 {
1881 	struct cab *cab = a->format->data;
1882 	struct cfdata *cfdata;
1883 	int64_t cbytes, rbytes;
1884 	int err;
1885 
1886 	rbytes = cab_minimum_consume_cfdata(a, consumed_bytes);
1887 	if (rbytes < 0)
1888 		return (ARCHIVE_FATAL);
1889 
1890 	cfdata = cab->entry_cfdata;
1891 	while (rbytes > 0) {
1892 		ssize_t avail;
1893 
1894 		if (cfdata->compressed_size == 0) {
1895 			archive_set_error(&a->archive,
1896 			    ARCHIVE_ERRNO_FILE_FORMAT,
1897 			    "Invalid CFDATA");
1898 			return (ARCHIVE_FATAL);
1899 		}
1900 		cbytes = cfdata->uncompressed_bytes_remaining;
1901 		if (cbytes > rbytes)
1902 			cbytes = rbytes;
1903 		rbytes -= cbytes;
1904 
1905 		if (cfdata->uncompressed_avail == 0 &&
1906 		   (cab->entry_cffile->folder == iFoldCONTINUED_PREV_AND_NEXT ||
1907 		    cab->entry_cffile->folder == iFoldCONTINUED_FROM_PREV)) {
1908 			/* We have not read any data yet. */
1909 			if (cbytes == cfdata->uncompressed_bytes_remaining) {
1910 				/* Skip whole current CFDATA. */
1911 				__archive_read_consume(a,
1912 				    cfdata->compressed_size);
1913 				cab->cab_offset += cfdata->compressed_size;
1914 				cfdata->compressed_bytes_remaining = 0;
1915 				cfdata->uncompressed_bytes_remaining = 0;
1916 				err = cab_next_cfdata(a);
1917 				if (err < 0)
1918 					return (err);
1919 				cfdata = cab->entry_cfdata;
1920 				if (cfdata->uncompressed_size == 0) {
1921 					switch (cab->entry_cffile->folder) {
1922 					case iFoldCONTINUED_PREV_AND_NEXT:
1923 					case iFoldCONTINUED_TO_NEXT:
1924 					case iFoldCONTINUED_FROM_PREV:
1925 						rbytes = 0;
1926 						break;
1927 					default:
1928 						break;
1929 					}
1930 				}
1931 				continue;
1932 			}
1933 			cfdata->read_offset += (uint16_t)cbytes;
1934 			cfdata->uncompressed_bytes_remaining -= (uint16_t)cbytes;
1935 			break;
1936 		} else if (cbytes == 0) {
1937 			err = cab_next_cfdata(a);
1938 			if (err < 0)
1939 				return (err);
1940 			cfdata = cab->entry_cfdata;
1941 			if (cfdata->uncompressed_size == 0) {
1942 				switch (cab->entry_cffile->folder) {
1943 				case iFoldCONTINUED_PREV_AND_NEXT:
1944 				case iFoldCONTINUED_TO_NEXT:
1945 				case iFoldCONTINUED_FROM_PREV:
1946 					return (ARCHIVE_FATAL);
1947 				default:
1948 					break;
1949 				}
1950 			}
1951 			continue;
1952 		}
1953 		while (cbytes > 0) {
1954 			(void)cab_read_ahead_cfdata(a, &avail);
1955 			if (avail <= 0)
1956 				return (ARCHIVE_FATAL);
1957 			if (avail > cbytes)
1958 				avail = (ssize_t)cbytes;
1959 			if (cab_minimum_consume_cfdata(a, avail) < 0)
1960 				return (ARCHIVE_FATAL);
1961 			cbytes -= avail;
1962 		}
1963 	}
1964 	return (consumed_bytes);
1965 }
1966 
1967 /*
1968  * Consume CFDATA as much as we have already gotten and
1969  * compute the sum of CFDATA.
1970  */
1971 static int64_t
cab_minimum_consume_cfdata(struct archive_read * a,int64_t consumed_bytes)1972 cab_minimum_consume_cfdata(struct archive_read *a, int64_t consumed_bytes)
1973 {
1974 	struct cab *cab = a->format->data;
1975 	struct cfdata *cfdata;
1976 	int64_t cbytes, rbytes;
1977 	int err;
1978 
1979 	cfdata = cab->entry_cfdata;
1980 	rbytes = consumed_bytes;
1981 	if (cab->entry_cffolder->comptype == COMPTYPE_NONE) {
1982 		if (consumed_bytes < cfdata->unconsumed)
1983 			cbytes = consumed_bytes;
1984 		else
1985 			cbytes = cfdata->unconsumed;
1986 		rbytes -= cbytes;
1987 		cfdata->read_offset += (uint16_t)cbytes;
1988 		cfdata->uncompressed_bytes_remaining -= (uint16_t)cbytes;
1989 		cfdata->unconsumed -= cbytes;
1990 	} else {
1991 		cbytes = cfdata->uncompressed_avail - cfdata->read_offset;
1992 		if (cbytes > 0) {
1993 			if (consumed_bytes < cbytes)
1994 				cbytes = consumed_bytes;
1995 			rbytes -= cbytes;
1996 			cfdata->read_offset += (uint16_t)cbytes;
1997 			cfdata->uncompressed_bytes_remaining -= (uint16_t)cbytes;
1998 		}
1999 
2000 		if (cfdata->unconsumed) {
2001 			cbytes = cfdata->unconsumed;
2002 			cfdata->unconsumed = 0;
2003 		} else
2004 			cbytes = 0;
2005 	}
2006 	if (cbytes) {
2007 		/* Compute the sum. */
2008 		cab_checksum_update(a, (size_t)cbytes);
2009 
2010 		/* Consume as much as the compressor actually used. */
2011 		__archive_read_consume(a, cbytes);
2012 		cab->cab_offset += cbytes;
2013 		cfdata->compressed_bytes_remaining -= (uint16_t)cbytes;
2014 		if (cfdata->compressed_bytes_remaining == 0) {
2015 			err = cab_checksum_finish(a);
2016 			if (err < 0)
2017 				return (err);
2018 		}
2019 	}
2020 	return (rbytes);
2021 }
2022 
2023 /*
2024  * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
2025  * cab->end_of_entry if it consumes all of the data.
2026  */
2027 static int
cab_read_data(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset)2028 cab_read_data(struct archive_read *a, const void **buff,
2029     size_t *size, int64_t *offset)
2030 {
2031 	struct cab *cab = a->format->data;
2032 	ssize_t bytes_avail;
2033 
2034 	if (cab->entry_bytes_remaining == 0) {
2035 		*buff = NULL;
2036 		*size = 0;
2037 		*offset = cab->entry_offset;
2038 		cab->end_of_entry = 1;
2039 		return (ARCHIVE_OK);
2040 	}
2041 
2042 	*buff = cab_read_ahead_cfdata(a, &bytes_avail);
2043 	if (bytes_avail <= 0) {
2044 		*buff = NULL;
2045 		*size = 0;
2046 		*offset = 0;
2047 		if (bytes_avail == 0 &&
2048 		    cab->entry_cfdata->uncompressed_size == 0) {
2049 			/* All of CFDATA in a folder has been handled. */
2050 			archive_set_error(&a->archive,
2051 			    ARCHIVE_ERRNO_FILE_FORMAT, "Invalid CFDATA");
2052 			return (ARCHIVE_FATAL);
2053 		} else
2054 			return ((int)bytes_avail);
2055 	}
2056 	if (bytes_avail > cab->entry_bytes_remaining)
2057 		bytes_avail = (ssize_t)cab->entry_bytes_remaining;
2058 
2059 	*size = bytes_avail;
2060 	*offset = cab->entry_offset;
2061 	cab->entry_offset += bytes_avail;
2062 	cab->entry_bytes_remaining -= bytes_avail;
2063 	if (cab->entry_bytes_remaining == 0)
2064 		cab->end_of_entry = 1;
2065 	cab->entry_unconsumed = bytes_avail;
2066 	if (cab->entry_cffolder->comptype == COMPTYPE_NONE) {
2067 		/* Don't consume more than current entry used. */
2068 		if (cab->entry_cfdata->unconsumed > cab->entry_unconsumed)
2069 			cab->entry_cfdata->unconsumed = cab->entry_unconsumed;
2070 	}
2071 	return (ARCHIVE_OK);
2072 }
2073 
2074 static int
archive_read_format_cab_read_data_skip(struct archive_read * a)2075 archive_read_format_cab_read_data_skip(struct archive_read *a)
2076 {
2077 	struct cab *cab = a->format->data;
2078 	int64_t bytes_skipped;
2079 	int r;
2080 
2081 	if (cab->end_of_archive)
2082 		return (ARCHIVE_EOF);
2083 
2084 	if (!cab->read_data_invoked) {
2085 		cab->bytes_skipped += cab->entry_bytes_remaining;
2086 		cab->entry_bytes_remaining = 0;
2087 		/* This entry is finished and done. */
2088 		cab->end_of_entry_cleanup = cab->end_of_entry = 1;
2089 		return (ARCHIVE_OK);
2090 	}
2091 
2092 	if (cab->entry_unconsumed) {
2093 		/* Consume as much as the compressor actually used. */
2094 		r = (int)cab_consume_cfdata(a, cab->entry_unconsumed);
2095 		cab->entry_unconsumed = 0;
2096 		if (r < 0)
2097 			return (r);
2098 	} else if (cab->entry_cfdata == NULL) {
2099 		r = cab_next_cfdata(a);
2100 		if (r < 0)
2101 			return (r);
2102 	}
2103 
2104 	/* if we've already read to end of data, we're done. */
2105 	if (cab->end_of_entry_cleanup)
2106 		return (ARCHIVE_OK);
2107 
2108 	/*
2109 	 * If the length is at the beginning, we can skip the
2110 	 * compressed data much more quickly.
2111 	 */
2112 	bytes_skipped = cab_consume_cfdata(a, cab->entry_bytes_remaining);
2113 	if (bytes_skipped < 0)
2114 		return (ARCHIVE_FATAL);
2115 
2116 	/* If the compression type is none(uncompressed), we've already
2117 	 * consumed data as much as the current entry size. */
2118 	if (cab->entry_cffolder->comptype == COMPTYPE_NONE &&
2119 	    cab->entry_cfdata != NULL)
2120 		cab->entry_cfdata->unconsumed = 0;
2121 
2122 	/* This entry is finished and done. */
2123 	cab->end_of_entry_cleanup = cab->end_of_entry = 1;
2124 	return (ARCHIVE_OK);
2125 }
2126 
2127 static int
archive_read_format_cab_cleanup(struct archive_read * a)2128 archive_read_format_cab_cleanup(struct archive_read *a)
2129 {
2130 	struct cab *cab = a->format->data;
2131 	struct cfheader *hd = &cab->cfheader;
2132 	uint16_t i;
2133 
2134 	if (hd->folder_array != NULL) {
2135 		for (i = 0; i < hd->folder_count; i++)
2136 			free(hd->folder_array[i].cfdata.memimage);
2137 		free(hd->folder_array);
2138 	}
2139 	if (hd->file_array != NULL) {
2140 		for (i = 0; i < cab->cfheader.file_count; i++)
2141 			archive_string_free(&(hd->file_array[i].pathname));
2142 		free(hd->file_array);
2143 	}
2144 #ifdef HAVE_ZLIB_H
2145 	if (cab->stream_valid)
2146 		inflateEnd(&cab->stream);
2147 #endif
2148 	lzx_decode_free(&cab->xstrm);
2149 	archive_wstring_free(&cab->ws);
2150 	free(cab->uncompressed_buffer);
2151 	free(cab);
2152 	a->format->data = NULL;
2153 	return (ARCHIVE_OK);
2154 }
2155 
2156 /* Convert an MSDOS-style date/time into Unix-style time. */
2157 static time_t
cab_dos_time(const char * p)2158 cab_dos_time(const char *p)
2159 {
2160 	int msTime, msDate;
2161 	struct tm ts;
2162 
2163 	msDate = archive_le16dec(p);
2164 	msTime = archive_le16dec(p+2);
2165 
2166 	memset(&ts, 0, sizeof(ts));
2167 	ts.tm_year = ((msDate >> 9) & 0x7f) + 80;   /* Years since 1900. */
2168 	ts.tm_mon = ((msDate >> 5) & 0x0f) - 1;     /* Month number.     */
2169 	ts.tm_mday = msDate & 0x1f;		    /* Day of month.     */
2170 	ts.tm_hour = (msTime >> 11) & 0x1f;
2171 	ts.tm_min = (msTime >> 5) & 0x3f;
2172 	ts.tm_sec = (msTime << 1) & 0x3e;
2173 	ts.tm_isdst = -1;
2174 	return (mktime(&ts));
2175 }
2176 
2177 /*****************************************************************
2178  *
2179  * LZX decompression code.
2180  *
2181  *****************************************************************/
2182 
2183 /*
2184  * Initialize LZX decoder.
2185  *
2186  * Returns ARCHIVE_OK if initialization was successful.
2187  * Returns ARCHIVE_FAILED if w_bits has unsupported value.
2188  * Returns ARCHIVE_FATAL if initialization failed; memory allocation
2189  * error occurred.
2190  */
2191 static int
lzx_decode_init(struct lzx_stream * strm,int w_bits)2192 lzx_decode_init(struct lzx_stream *strm, int w_bits)
2193 {
2194 	int base_inc[18];
2195 	struct lzx_dec *ds;
2196 	uint32_t base;
2197 	uint16_t slot, w_size, w_slot;
2198 	uint8_t footer;
2199 
2200 	if (strm->ds == NULL) {
2201 		strm->ds = calloc(1, sizeof(*strm->ds));
2202 		if (strm->ds == NULL)
2203 			return (ARCHIVE_FATAL);
2204 	}
2205 	ds = strm->ds;
2206 	ds->error = ARCHIVE_FAILED;
2207 
2208 	/* Allow bits from 15 (32 KiB) up to 21 (2 MiB) */
2209 	if (w_bits < SLOT_BASE || w_bits > SLOT_MAX)
2210 		return (ARCHIVE_FAILED);
2211 
2212 	ds->error = ARCHIVE_FATAL;
2213 
2214 	/*
2215 	 * Alloc window
2216 	 */
2217 	w_size = ds->w_size;
2218 	w_slot = slots[w_bits - SLOT_BASE];
2219 	ds->w_size = 1U << w_bits;
2220 	ds->w_mask = ds->w_size - 1;
2221 	if (ds->w_buff == NULL || w_size != ds->w_size) {
2222 		free(ds->w_buff);
2223 		ds->w_buff = malloc(ds->w_size);
2224 		if (ds->w_buff == NULL)
2225 			return (ARCHIVE_FATAL);
2226 		free(ds->pos_tbl);
2227 		ds->pos_tbl = malloc(sizeof(ds->pos_tbl[0]) * w_slot);
2228 		if (ds->pos_tbl == NULL)
2229 			return (ARCHIVE_FATAL);
2230 	}
2231 
2232 	for (footer = 0; footer < 18; footer++)
2233 		base_inc[footer] = 1 << footer;
2234 	base = footer = 0;
2235 	for (slot = 0; slot < w_slot; slot++) {
2236 		int n;
2237 		if (footer == 0)
2238 			base = slot;
2239 		else
2240 			base += base_inc[footer];
2241 		if (footer < 17) {
2242 			footer = 0;
2243 			for (n = base; n; n >>= 1)
2244 				footer++;
2245 			if (footer <= 2)
2246 				footer = 0;
2247 			else
2248 				footer -= 2;
2249 		}
2250 		ds->pos_tbl[slot].base = base;
2251 		ds->pos_tbl[slot].footer_bits = footer;
2252 	}
2253 
2254 	ds->w_pos = 0;
2255 	ds->state = ST_RD_TRANSLATION;
2256 	ds->br.cache_buffer = 0;
2257 	ds->br.cache_avail = 0;
2258 	ds->r0 = ds->r1 = ds->r2 = 1;
2259 
2260 	/* Initialize aligned offset tree. */
2261 	if (lzx_huffman_init(&(ds->at), 8, 8) != ARCHIVE_OK)
2262 		return (ARCHIVE_FATAL);
2263 
2264 	/* Initialize pre-tree. */
2265 	if (lzx_huffman_init(&(ds->pt), 20, 10) != ARCHIVE_OK)
2266 		return (ARCHIVE_FATAL);
2267 
2268 	/* Initialize Main tree. */
2269 	if (lzx_huffman_init(&(ds->mt), 256 + (w_slot << 3), 16)
2270 	    != ARCHIVE_OK)
2271 		return (ARCHIVE_FATAL);
2272 
2273 	/* Initialize Length tree. */
2274 	if (lzx_huffman_init(&(ds->lt), 249, 16) != ARCHIVE_OK)
2275 		return (ARCHIVE_FATAL);
2276 
2277 	ds->error = 0;
2278 
2279 	return (ARCHIVE_OK);
2280 }
2281 
2282 /*
2283  * Release LZX decoder.
2284  */
2285 static void
lzx_decode_free(struct lzx_stream * strm)2286 lzx_decode_free(struct lzx_stream *strm)
2287 {
2288 
2289 	if (strm->ds == NULL)
2290 		return;
2291 	free(strm->ds->w_buff);
2292 	free(strm->ds->pos_tbl);
2293 	lzx_huffman_free(&(strm->ds->at));
2294 	lzx_huffman_free(&(strm->ds->pt));
2295 	lzx_huffman_free(&(strm->ds->mt));
2296 	lzx_huffman_free(&(strm->ds->lt));
2297 	free(strm->ds);
2298 	strm->ds = NULL;
2299 }
2300 
2301 /*
2302  * E8 Call Translation reversal.
2303  */
2304 static void
lzx_translation(struct lzx_stream * strm,unsigned char * buffer,size_t size,int32_t offset)2305 lzx_translation(struct lzx_stream *strm, unsigned char *buffer, size_t size,
2306     int32_t offset)
2307 {
2308 	struct lzx_dec *ds = strm->ds;
2309 	unsigned char *p, *end;
2310 
2311 	if (!ds->translation || offset >= MAX_E8_TRANSLATION || size <= 10)
2312 		return;
2313 
2314 	p = buffer;
2315 	end = buffer + size - 10;
2316 
2317 	while (p < end && (p = memchr(p, 0xE8, end - p)) != NULL) {
2318 		int32_t address, position;
2319 
2320 		address = archive_le32dec(p + 1);
2321 		position = offset + (p - buffer);
2322 
2323 		if (address >= -position && address < ds->translation_size) {
2324 			uint32_t relative;
2325 
2326 			if (address >= 0)
2327 				relative = address - position;
2328 			else
2329 				relative = address + ds->translation_size;
2330 
2331 			archive_le32enc(p + 1, relative);
2332 		}
2333 
2334 		p += 5;
2335 	}
2336 }
2337 
2338 /*
2339  * Bit stream reader.
2340  */
2341 /* Check that the cache buffer has enough bits. */
2342 #define lzx_br_has(br, n)	((br)->cache_avail >= n)
2343 /* Get compressed data by bit. */
2344 #define lzx_br_bits(br, n)				\
2345 	(((uint32_t)((br)->cache_buffer >>		\
2346 		((br)->cache_avail - (n)))) & cache_masks[n])
2347 #define lzx_br_bits_forced(br, n)			\
2348 	(((uint32_t)((br)->cache_buffer <<		\
2349 		((n) - (br)->cache_avail))) & cache_masks[n])
2350 /* Read ahead to make sure the cache buffer has enough compressed data we
2351  * will use.
2352  *  True  : completed, there is enough data in the cache buffer.
2353  *  False : we met that strm->next_in is empty, we have to get following
2354  *          bytes. */
2355 #define lzx_br_read_ahead_0(strm, br, n)	\
2356 	(lzx_br_has((br), (n)) || lzx_br_fillup(strm, br) == ARCHIVE_OK)
2357 /*  True  : the cache buffer has some bits as much as we need.
2358  *  False : there are no enough bits in the cache buffer to be used,
2359  *          we have to get following bytes if we could. */
2360 #define lzx_br_read_ahead(strm, br, n)	\
2361 	(lzx_br_read_ahead_0((strm), (br), (n)) || lzx_br_has((br), (n)))
2362 
2363 /* Notify how many bits we consumed. */
2364 #define lzx_br_consume(br, n)	((br)->cache_avail -= (n))
2365 #define lzx_br_consume_unaligned_bits(br) ((br)->cache_avail &= ~0x0f)
2366 
2367 #define lzx_br_is_unaligned(br)	((br)->cache_avail & 0x0f)
2368 
2369 static const uint32_t cache_masks[] = {
2370 	0x00000000, 0x00000001, 0x00000003, 0x00000007,
2371 	0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
2372 	0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF,
2373 	0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF,
2374 	0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF,
2375 	0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,
2376 	0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF,
2377 	0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF,
2378 	0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF
2379 };
2380 
2381 /*
2382  * Shift away used bits in the cache data and fill it up with following bits.
2383  * Call this when cache buffer does not have enough bits you need.
2384  *
2385  * Returns ARCHIVE_OK if the cache buffer is full.
2386  * Returns ARCHIVE_EOF if the cache buffer is not full; input buffer is empty.
2387  */
2388 static int
lzx_br_fillup(struct lzx_stream * strm,struct lzx_br * br)2389 lzx_br_fillup(struct lzx_stream *strm, struct lzx_br *br)
2390 {
2391 /*
2392  * x86 processor family can read misaligned data without an access error.
2393  */
2394 	ssize_t n = CACHE_BITS - br->cache_avail;
2395 
2396 	for (;;) {
2397 		switch (n >> 4) {
2398 		case 4:
2399 			if (strm->avail_in >= 8) {
2400 				br->cache_buffer =
2401 				    ((uint64_t)strm->next_in[1]) << 56 |
2402 				    ((uint64_t)strm->next_in[0]) << 48 |
2403 				    ((uint64_t)strm->next_in[3]) << 40 |
2404 				    ((uint64_t)strm->next_in[2]) << 32 |
2405 				    ((uint32_t)strm->next_in[5]) << 24 |
2406 				    ((uint32_t)strm->next_in[4]) << 16 |
2407 				    ((uint32_t)strm->next_in[7]) << 8 |
2408 				     (uint32_t)strm->next_in[6];
2409 				strm->next_in += 8;
2410 				strm->avail_in -= 8;
2411 				br->cache_avail += 8 * 8;
2412 				return (ARCHIVE_OK);
2413 			}
2414 			break;
2415 		case 3:
2416 			if (strm->avail_in >= 6) {
2417 				br->cache_buffer =
2418 		 		   (br->cache_buffer << 48) |
2419 				    ((uint64_t)strm->next_in[1]) << 40 |
2420 				    ((uint64_t)strm->next_in[0]) << 32 |
2421 				    ((uint64_t)strm->next_in[3]) << 24 |
2422 				    ((uint64_t)strm->next_in[2]) << 16 |
2423 				    ((uint64_t)strm->next_in[5]) << 8 |
2424 				     (uint64_t)strm->next_in[4];
2425 				strm->next_in += 6;
2426 				strm->avail_in -= 6;
2427 				br->cache_avail += 6 * 8;
2428 				return (ARCHIVE_OK);
2429 			}
2430 			break;
2431 		case 0:
2432 			/* We have enough compressed data in
2433 			 * the cache buffer.*/
2434 			return (ARCHIVE_EOF);
2435 		default:
2436 			break;
2437 		}
2438 		if (strm->avail_in < 2) {
2439 			/* There is not enough compressed data to
2440 			 * fill up the cache buffer. */
2441 			if (strm->avail_in == 1) {
2442 				br->odd = *strm->next_in++;
2443 				strm->avail_in--;
2444 				br->have_odd = 1;
2445 			}
2446 			return (ARCHIVE_EOF);
2447 		}
2448 		br->cache_buffer =
2449 		   (br->cache_buffer << 16) |
2450 		    archive_le16dec(strm->next_in);
2451 		strm->next_in += 2;
2452 		strm->avail_in -= 2;
2453 		br->cache_avail += 16;
2454 		n -= 16;
2455 	}
2456 }
2457 
2458 static void
lzx_br_fixup(struct lzx_stream * strm,struct lzx_br * br)2459 lzx_br_fixup(struct lzx_stream *strm, struct lzx_br *br)
2460 {
2461 	ssize_t n = CACHE_BITS - br->cache_avail;
2462 
2463 	if (br->have_odd && n >= 16 && strm->avail_in > 0) {
2464 		br->cache_buffer =
2465 		   (br->cache_buffer << 16) |
2466 		   ((uint16_t)(*strm->next_in)) << 8 | br->odd;
2467 		strm->next_in++;
2468 		strm->avail_in--;
2469 		br->cache_avail += 16;
2470 		br->have_odd = 0;
2471 	}
2472 }
2473 
2474 static void
lzx_cleanup_bitstream(struct lzx_stream * strm)2475 lzx_cleanup_bitstream(struct lzx_stream *strm)
2476 {
2477 	strm->ds->br.cache_avail = 0;
2478 	strm->ds->br.have_odd = 0;
2479 }
2480 
2481 /*
2482  * Decode LZX.
2483  *
2484  * 1. Returns ARCHIVE_OK if output buffer or input buffer are empty.
2485  *    Please set available buffer and call this function again.
2486  * 2. Returns ARCHIVE_EOF if decompression has been completed.
2487  * 3. Returns ARCHIVE_FAILED if an error occurred; compressed data
2488  *    is broken or you do not set 'last' flag properly.
2489  */
2490 static int
lzx_decode(struct lzx_stream * strm,int last)2491 lzx_decode(struct lzx_stream *strm, int last)
2492 {
2493 	struct lzx_dec *ds = strm->ds;
2494 	size_t avail_in;
2495 	int r;
2496 
2497 	if (ds->error)
2498 		return (ds->error);
2499 
2500 	avail_in = strm->avail_in;
2501 	lzx_br_fixup(strm, &(ds->br));
2502 	do {
2503 		if (ds->state < ST_MAIN)
2504 			r = lzx_read_blocks(strm, last);
2505 		else {
2506 			size_t bytes_written = strm->avail_out;
2507 
2508 			r = lzx_decode_blocks(strm, last);
2509 			bytes_written -= strm->avail_out;
2510 			strm->next_out += bytes_written;
2511 			strm->total_out += bytes_written;
2512 		}
2513 	} while (r == 100);
2514 	strm->total_in += avail_in - strm->avail_in;
2515 	return (r);
2516 }
2517 
2518 static int
lzx_read_blocks(struct lzx_stream * strm,int last)2519 lzx_read_blocks(struct lzx_stream *strm, int last)
2520 {
2521 	struct lzx_dec *ds = strm->ds;
2522 	struct lzx_br *br = &(ds->br);
2523 	int r;
2524 	uint16_t i;
2525 
2526 	for (;;) {
2527 		switch (ds->state) {
2528 		case ST_RD_TRANSLATION:
2529 			if (!lzx_br_read_ahead(strm, br, 1)) {
2530 				ds->state = ST_RD_TRANSLATION;
2531 				if (last)
2532 					goto failed;
2533 				return (ARCHIVE_OK);
2534 			}
2535 			ds->translation = lzx_br_bits(br, 1);
2536 			lzx_br_consume(br, 1);
2537 			/* FALL THROUGH */
2538 		case ST_RD_TRANSLATION_SIZE:
2539 			if (ds->translation) {
2540 				uint32_t v;
2541 
2542 				if (!lzx_br_read_ahead(strm, br, 32)) {
2543 					ds->state = ST_RD_TRANSLATION_SIZE;
2544 					if (last)
2545 						goto failed;
2546 					return (ARCHIVE_OK);
2547 				}
2548 				v = lzx_br_bits(br, 16);
2549 				lzx_br_consume(br, 16);
2550 				v <<= 16;
2551 				v |= lzx_br_bits(br, 16);
2552 				if (v > MAX_FILE_SIZE)
2553 					goto failed;
2554 				ds->translation_size = (int32_t)v;
2555 				lzx_br_consume(br, 16);
2556 			}
2557 			/* FALL THROUGH */
2558 		case ST_RD_BLOCK_TYPE:
2559 			if (!lzx_br_read_ahead(strm, br, 3)) {
2560 				ds->state = ST_RD_BLOCK_TYPE;
2561 				if (last)
2562 					goto failed;
2563 				return (ARCHIVE_OK);
2564 			}
2565 			ds->block_type = lzx_br_bits(br, 3);
2566 			lzx_br_consume(br, 3);
2567 			/* Check a block type. */
2568 			switch (ds->block_type) {
2569 			case VERBATIM_BLOCK:
2570 			case ALIGNED_OFFSET_BLOCK:
2571 			case UNCOMPRESSED_BLOCK:
2572 				break;
2573 			default:
2574 				goto failed;/* Invalid */
2575 			}
2576 			/* FALL THROUGH */
2577 		case ST_RD_BLOCK_SIZE:
2578 			if (!lzx_br_read_ahead(strm, br, 24)) {
2579 				ds->state = ST_RD_BLOCK_SIZE;
2580 				if (last)
2581 					goto failed;
2582 				return (ARCHIVE_OK);
2583 			}
2584 			ds->block_size = lzx_br_bits(br, 8);
2585 			lzx_br_consume(br, 8);
2586 			ds->block_size <<= 16;
2587 			ds->block_size |= lzx_br_bits(br, 16);
2588 			lzx_br_consume(br, 16);
2589 			if (ds->block_size == 0)
2590 				goto failed;
2591 			ds->block_bytes_avail = ds->block_size;
2592 			if (ds->block_type != UNCOMPRESSED_BLOCK) {
2593 				if (ds->block_type == VERBATIM_BLOCK)
2594 					ds->state = ST_RD_VERBATIM;
2595 				else
2596 					ds->state = ST_RD_ALIGNED_OFFSET;
2597 				break;
2598 			}
2599 			/* FALL THROUGH */
2600 		case ST_RD_ALIGNMENT:
2601 			/*
2602 			 * Handle an Uncompressed Block.
2603 			 */
2604 			/* Skip padding to align following field on
2605 			 * 16-bit boundary. */
2606 			if (lzx_br_is_unaligned(br))
2607 				lzx_br_consume_unaligned_bits(br);
2608 			else {
2609 				if (lzx_br_read_ahead(strm, br, 16))
2610 					lzx_br_consume(br, 16);
2611 				else {
2612 					ds->state = ST_RD_ALIGNMENT;
2613 					if (last)
2614 						goto failed;
2615 					return (ARCHIVE_OK);
2616 				}
2617 			}
2618 			/* Preparation to read repeated offsets R0,R1 and R2. */
2619 			ds->rbytes_avail = 0;
2620 			ds->state = ST_RD_R0;
2621 			/* FALL THROUGH */
2622 		case ST_RD_R0:
2623 		case ST_RD_R1:
2624 		case ST_RD_R2:
2625 			do {
2626 				uint16_t u16;
2627 				/* Drain bits in the cache buffer of
2628 				 * bit-stream. */
2629 				if (lzx_br_has(br, 32)) {
2630 					u16 = lzx_br_bits(br, 16);
2631 					lzx_br_consume(br, 16);
2632 					archive_le16enc(ds->rbytes, u16);
2633 					u16 = lzx_br_bits(br, 16);
2634 					lzx_br_consume(br, 16);
2635 					archive_le16enc(ds->rbytes+2, u16);
2636 					ds->rbytes_avail = 4;
2637 				} else if (lzx_br_has(br, 16)) {
2638 					u16 = lzx_br_bits(br, 16);
2639 					lzx_br_consume(br, 16);
2640 					archive_le16enc(ds->rbytes, u16);
2641 					ds->rbytes_avail = 2;
2642 				}
2643 				if (ds->rbytes_avail < 4 && ds->br.have_odd) {
2644 					ds->rbytes[ds->rbytes_avail++] =
2645 					    ds->br.odd;
2646 					ds->br.have_odd = 0;
2647 				}
2648 				while (ds->rbytes_avail < 4) {
2649 					if (strm->avail_in <= 0) {
2650 						if (last)
2651 							goto failed;
2652 						return (ARCHIVE_OK);
2653 					}
2654 					ds->rbytes[ds->rbytes_avail++] =
2655 					    *strm->next_in++;
2656 					strm->avail_in--;
2657 				}
2658 				ds->rbytes_avail = 0;
2659 				if (ds->state == ST_RD_R0) {
2660 					ds->r0 = archive_le32dec(ds->rbytes);
2661 					if (ds->r0 > (size_t)INT32_MAX)
2662 						goto failed;
2663 					ds->state = ST_RD_R1;
2664 				} else if (ds->state == ST_RD_R1) {
2665 					ds->r1 = archive_le32dec(ds->rbytes);
2666 					if (ds->r1 > (size_t)INT32_MAX)
2667 						goto failed;
2668 					ds->state = ST_RD_R2;
2669 				} else if (ds->state == ST_RD_R2) {
2670 					ds->r2 = archive_le32dec(ds->rbytes);
2671 					if (ds->r2 > (size_t)INT32_MAX)
2672 						goto failed;
2673 					/* We've gotten all repeated offsets. */
2674 					ds->state = ST_COPY_UNCOMP1;
2675 				}
2676 			} while (ds->state != ST_COPY_UNCOMP1);
2677 			/* FALL THROUGH */
2678 		case ST_COPY_UNCOMP1:
2679 			/*
2680 			 * Copy bytes from next_in to next_out directly.
2681 			 */
2682 			while (ds->block_bytes_avail) {
2683 				size_t l;
2684 
2685 				if (strm->avail_out <= 0)
2686 					/* Output buffer is empty. */
2687 					return (ARCHIVE_OK);
2688 				if (strm->avail_in <= 0) {
2689 					/* Input buffer is empty. */
2690 					if (last)
2691 						goto failed;
2692 					return (ARCHIVE_OK);
2693 				}
2694 				l = ds->block_bytes_avail;
2695 				if (l > ds->w_size - ds->w_pos)
2696 					l = ds->w_size - ds->w_pos;
2697 				if (l > strm->avail_out)
2698 					l = strm->avail_out;
2699 				if (l > strm->avail_in)
2700 					l = strm->avail_in;
2701 				memcpy(strm->next_out, strm->next_in, l);
2702 				memcpy(&(ds->w_buff[ds->w_pos]),
2703 				    strm->next_in, l);
2704 				strm->next_in += l;
2705 				strm->avail_in -= l;
2706 				strm->next_out += l;
2707 				strm->avail_out -= l;
2708 				strm->total_out += l;
2709 				ds->w_pos = (ds->w_pos + l) & ds->w_mask;
2710 				ds->block_bytes_avail -= l;
2711 			}
2712 			/* FALL THROUGH */
2713 		case ST_COPY_UNCOMP2:
2714 			/* Re-align; skip padding byte. */
2715 			if (ds->block_size & 1) {
2716 				if (strm->avail_in <= 0) {
2717 					/* Input buffer is empty. */
2718 					ds->state = ST_COPY_UNCOMP2;
2719 					if (last)
2720 						goto failed;
2721 					return (ARCHIVE_OK);
2722 				}
2723 				strm->next_in++;
2724 				strm->avail_in --;
2725 			}
2726 			/* This block ended. */
2727 			ds->state = ST_RD_BLOCK_TYPE;
2728 			return (ARCHIVE_EOF);
2729 			/********************/
2730 		case ST_RD_ALIGNED_OFFSET:
2731 			/*
2732 			 * Read Aligned offset tree.
2733 			 */
2734 			if (!lzx_br_read_ahead(strm, br, 3 * ds->at.symbol_count)) {
2735 				ds->state = ST_RD_ALIGNED_OFFSET;
2736 				if (last)
2737 					goto failed;
2738 				return (ARCHIVE_OK);
2739 			}
2740 			memset(ds->at.freq, 0, sizeof(ds->at.freq));
2741 			for (i = 0; i < ds->at.symbol_count; i++) {
2742 				ds->at.bitlen[i] = lzx_br_bits(br, 3);
2743 				ds->at.freq[ds->at.bitlen[i]]++;
2744 				lzx_br_consume(br, 3);
2745 			}
2746 			if (lzx_make_huffman_table(&ds->at) < 0)
2747 				goto failed;
2748 			/* FALL THROUGH */
2749 		case ST_RD_VERBATIM:
2750 			ds->loop = 0;
2751 			/* FALL THROUGH */
2752 		case ST_RD_PRE_MAIN_TREE_256:
2753 			/*
2754 			 * Read Pre-tree for first 256 elements of main tree.
2755 			 */
2756 			if (lzx_read_pre_tree(strm) < 0) {
2757 				ds->state = ST_RD_PRE_MAIN_TREE_256;
2758 				if (last)
2759 					goto failed;
2760 				return (ARCHIVE_OK);
2761 			}
2762 			if (lzx_make_huffman_table(&ds->pt) < 0)
2763 				goto failed;
2764 			ds->loop = 0;
2765 			/* FALL THROUGH */
2766 		case ST_MAIN_TREE_256:
2767 			/*
2768 			 * Get path lengths of first 256 elements of main tree.
2769 			 */
2770 			r = lzx_read_bitlen(strm, &ds->mt, 256);
2771 			if (r == ARCHIVE_EOF) {
2772 				ds->state = ST_MAIN_TREE_256;
2773 				if (last)
2774 					goto failed;
2775 				return (ARCHIVE_OK);
2776 			} else if (r < 0)
2777 				goto failed;
2778 			ds->loop = 0;
2779 			/* FALL THROUGH */
2780 		case ST_RD_PRE_MAIN_TREE_REM:
2781 			/*
2782 			 * Read Pre-tree for remaining elements of main tree.
2783 			 */
2784 			if (lzx_read_pre_tree(strm) < 0) {
2785 				ds->state = ST_RD_PRE_MAIN_TREE_REM;
2786 				if (last)
2787 					goto failed;
2788 				return (ARCHIVE_OK);
2789 			}
2790 			if (lzx_make_huffman_table(&ds->pt) < 0)
2791 				goto failed;
2792 			ds->loop = 256;
2793 			/* FALL THROUGH */
2794 		case ST_MAIN_TREE_REM:
2795 			/*
2796 			 * Get path lengths of remaining elements of main tree.
2797 			 */
2798 			r = lzx_read_bitlen(strm, &ds->mt, 0);
2799 			if (r == ARCHIVE_EOF) {
2800 				ds->state = ST_MAIN_TREE_REM;
2801 				if (last)
2802 					goto failed;
2803 				return (ARCHIVE_OK);
2804 			} else if (r < 0)
2805 				goto failed;
2806 			if (lzx_make_huffman_table(&ds->mt) < 0)
2807 				goto failed;
2808 			ds->loop = 0;
2809 			/* FALL THROUGH */
2810 		case ST_RD_PRE_LENGTH_TREE:
2811 			/*
2812 			 * Read Pre-tree for remaining elements of main tree.
2813 			 */
2814 			if (lzx_read_pre_tree(strm) < 0) {
2815 				ds->state = ST_RD_PRE_LENGTH_TREE;
2816 				if (last)
2817 					goto failed;
2818 				return (ARCHIVE_OK);
2819 			}
2820 			if (lzx_make_huffman_table(&ds->pt) < 0)
2821 				goto failed;
2822 			ds->loop = 0;
2823 			/* FALL THROUGH */
2824 		case ST_LENGTH_TREE:
2825 			/*
2826 			 * Get path lengths of remaining elements of main tree.
2827 			 */
2828 			r = lzx_read_bitlen(strm, &ds->lt, 0);
2829 			if (r == ARCHIVE_EOF) {
2830 				ds->state = ST_LENGTH_TREE;
2831 				if (last)
2832 					goto failed;
2833 				return (ARCHIVE_OK);
2834 			} else if (r < 0)
2835 				goto failed;
2836 			if (lzx_make_huffman_table(&ds->lt) < 0)
2837 				goto failed;
2838 			ds->state = ST_MAIN;
2839 			return (100);
2840 		}
2841 	}
2842 failed:
2843 	return (ds->error = ARCHIVE_FAILED);
2844 }
2845 
2846 static int
lzx_decode_blocks(struct lzx_stream * strm,int last)2847 lzx_decode_blocks(struct lzx_stream *strm, int last)
2848 {
2849 	struct lzx_dec *ds = strm->ds;
2850 	struct lzx_br bre = ds->br;
2851 	struct huffman *at = &(ds->at), *lt = &(ds->lt), *mt = &(ds->mt);
2852 	const struct lzx_pos_tbl *pos_tbl = ds->pos_tbl;
2853 	unsigned char *noutp = strm->next_out;
2854 	unsigned char *endp = noutp + strm->avail_out;
2855 	uint8_t *w_buff = ds->w_buff;
2856 	uint8_t *at_bitlen = at->bitlen;
2857 	uint8_t *lt_bitlen = lt->bitlen;
2858 	uint8_t *mt_bitlen = mt->bitlen;
2859 	size_t block_bytes_avail = ds->block_bytes_avail;
2860 	uint8_t at_lookup_bits = at->lookup_bits;
2861 	uint8_t lt_lookup_bits = lt->lookup_bits;
2862 	uint8_t mt_lookup_bits = mt->lookup_bits;
2863 	size_t copy_len = ds->copy_len, copy_pos = ds->copy_pos;
2864 	size_t w_pos = ds->w_pos, w_mask = ds->w_mask, w_size = ds->w_size;
2865 	uint8_t length_header = ds->length_header;
2866 	uint8_t offset_bits = ds->offset_bits;
2867 	uint16_t position_slot = ds->position_slot;
2868 	size_t r0 = ds->r0, r1 = ds->r1, r2 = ds->r2;
2869 	int state = ds->state;
2870 	uint16_t c;
2871 	uint8_t block_type = ds->block_type;
2872 
2873 	for (;;) {
2874 		switch (state) {
2875 		case ST_MAIN:
2876 			for (;;) {
2877 				if (block_bytes_avail == 0) {
2878 					/* This block ended. */
2879 					ds->state = ST_RD_BLOCK_TYPE;
2880 					ds->br = bre;
2881 					ds->block_bytes_avail =
2882 					    block_bytes_avail;
2883 					ds->copy_len = copy_len;
2884 					ds->copy_pos = copy_pos;
2885 					ds->length_header = length_header;
2886 					ds->position_slot = position_slot;
2887 					ds->r0 = r0; ds->r1 = r1; ds->r2 = r2;
2888 					ds->w_pos = w_pos;
2889 					strm->avail_out = endp - noutp;
2890 					return (ARCHIVE_EOF);
2891 				}
2892 				if (noutp >= endp)
2893 					/* Output buffer is empty. */
2894 					goto next_data;
2895 
2896 				if (!lzx_br_read_ahead(strm, &bre,
2897 				    mt_lookup_bits)) {
2898 					if (!last)
2899 						goto next_data;
2900 					/* Remaining bits are less than
2901 					 * maximum bits (mt.lookup_bits) but
2902 					 * maybe it still remains as much as we
2903 					 * need, so we should try to use it
2904 					 * with dummy bits. */
2905 					c = lzx_decode_huffman(mt,
2906 					      lzx_br_bits_forced(
2907 					        &bre, mt_lookup_bits));
2908 					if (!lzx_br_has(&bre, mt_bitlen[c]))
2909 						goto failed;/* Over read. */
2910 					lzx_br_consume(&bre, mt_bitlen[c]);
2911 				} else {
2912 					c = lzx_decode_huffman(mt,
2913 					      lzx_br_bits(&bre, mt_lookup_bits));
2914 					lzx_br_consume(&bre, mt_bitlen[c]);
2915 				}
2916 				if (c > UCHAR_MAX)
2917 					break;
2918 				/*
2919 				 * 'c' is exactly literal code.
2920 				 */
2921 				/* Save a decoded code to reference it
2922 				 * afterward. */
2923 				w_buff[w_pos] = c;
2924 				w_pos = (w_pos + 1) & w_mask;
2925 				/* Store the decoded code to output buffer. */
2926 				*noutp++ = c;
2927 				block_bytes_avail--;
2928 			}
2929 			/*
2930 			 * Get a match code, its length and offset.
2931 			 */
2932 			c -= UCHAR_MAX + 1;
2933 			length_header = c & 7;
2934 			position_slot = c >> 3;
2935 			/* FALL THROUGH */
2936 		case ST_LENGTH:
2937 			/*
2938 			 * Get a length.
2939 			 */
2940 			if (length_header == 7) {
2941 				if (!lzx_br_read_ahead(strm, &bre,
2942 				    lt_lookup_bits)) {
2943 					if (!last) {
2944 						state = ST_LENGTH;
2945 						goto next_data;
2946 					}
2947 					c = lzx_decode_huffman(lt,
2948 					      lzx_br_bits_forced(
2949 					        &bre, lt_lookup_bits));
2950 					if (!lzx_br_has(&bre, lt_bitlen[c]))
2951 						goto failed;/* Over read. */
2952 					lzx_br_consume(&bre, lt_bitlen[c]);
2953 				} else {
2954 					c = lzx_decode_huffman(lt,
2955 					    lzx_br_bits(&bre, lt_lookup_bits));
2956 					lzx_br_consume(&bre, lt_bitlen[c]);
2957 				}
2958 				copy_len = c + 7 + 2;
2959 			} else
2960 				copy_len = length_header + 2;
2961 			if (copy_len > block_bytes_avail)
2962 				goto failed;
2963 			/*
2964 			 * Get an offset.
2965 			 */
2966 			switch (position_slot) {
2967 			case 0: /* Use repeated offset 0. */
2968 				copy_pos = r0;
2969 				state = ST_REAL_POS;
2970 				continue;
2971 			case 1: /* Use repeated offset 1. */
2972 				copy_pos = r1;
2973 				/* Swap repeated offset. */
2974 				r1 = r0;
2975 				r0 = copy_pos;
2976 				state = ST_REAL_POS;
2977 				continue;
2978 			case 2: /* Use repeated offset 2. */
2979 				copy_pos = r2;
2980 				/* Swap repeated offset. */
2981 				r2 = r0;
2982 				r0 = copy_pos;
2983 				state = ST_REAL_POS;
2984 				continue;
2985 			default:
2986 				offset_bits =
2987 				    pos_tbl[position_slot].footer_bits;
2988 				break;
2989 			}
2990 			/* FALL THROUGH */
2991 		case ST_OFFSET:
2992 			/*
2993 			 * Get the offset, which is a distance from
2994 			 * current window position.
2995 			 */
2996 			if (block_type == ALIGNED_OFFSET_BLOCK &&
2997 			    offset_bits >= 3) {
2998 				unsigned offbits = offset_bits - 3;
2999 
3000 				if (!lzx_br_read_ahead(strm, &bre, offbits)) {
3001 					state = ST_OFFSET;
3002 					if (last)
3003 						goto failed;
3004 					goto next_data;
3005 				}
3006 				copy_pos = lzx_br_bits(&bre, offbits) << 3;
3007 
3008 				/* Get an aligned number. */
3009 				if (!lzx_br_read_ahead(strm, &bre,
3010 				    offbits + at_lookup_bits)) {
3011 					if (!last) {
3012 						state = ST_OFFSET;
3013 						goto next_data;
3014 					}
3015 					lzx_br_consume(&bre, offbits);
3016 					c = lzx_decode_huffman(at,
3017 					      lzx_br_bits_forced(&bre,
3018 					        at_lookup_bits));
3019 					if (!lzx_br_has(&bre, at_bitlen[c]))
3020 						goto failed;/* Over read. */
3021 					lzx_br_consume(&bre, at_bitlen[c]);
3022 				} else {
3023 					lzx_br_consume(&bre, offbits);
3024 					c = lzx_decode_huffman(at,
3025 					      lzx_br_bits(&bre, at_lookup_bits));
3026 					lzx_br_consume(&bre, at_bitlen[c]);
3027 				}
3028 				/* Add an aligned number. */
3029 				copy_pos += c;
3030 			} else {
3031 				if (!lzx_br_read_ahead(strm, &bre,
3032 				    offset_bits)) {
3033 					state = ST_OFFSET;
3034 					if (last)
3035 						goto failed;
3036 					goto next_data;
3037 				}
3038 				copy_pos = lzx_br_bits(&bre, offset_bits);
3039 				lzx_br_consume(&bre, offset_bits);
3040 			}
3041 			copy_pos += pos_tbl[position_slot].base - 2;
3042 
3043 			/* Update repeated offset LRU queue. */
3044 			r2 = r1;
3045 			r1 = r0;
3046 			r0 = copy_pos;
3047 			/* FALL THROUGH */
3048 		case ST_REAL_POS:
3049 			/*
3050 			 * Compute a real position in window.
3051 			 */
3052 			copy_pos = (w_pos - copy_pos) & w_mask;
3053 			/* FALL THROUGH */
3054 		case ST_COPY:
3055 			/*
3056 			 * Copy several bytes as extracted data from the window
3057 			 * into the output buffer.
3058 			 */
3059 			for (;;) {
3060 				const uint8_t *s;
3061 				size_t l;
3062 
3063 				l = copy_len;
3064 				if (copy_pos > w_pos) {
3065 					if (l > w_size - copy_pos)
3066 						l = w_size - copy_pos;
3067 				} else {
3068 					if (l > w_size - w_pos)
3069 						l = w_size - w_pos;
3070 				}
3071 				if (noutp + l >= endp)
3072 					l = endp - noutp;
3073 				s = w_buff + copy_pos;
3074 				if (l >= 8 && ((copy_pos + l < w_pos)
3075 				  || (w_pos + l < copy_pos))) {
3076 					memcpy(w_buff + w_pos, s, l);
3077 					memcpy(noutp, s, l);
3078 				} else {
3079 					uint8_t *d;
3080 					size_t li;
3081 
3082 					d = w_buff + w_pos;
3083 					for (li = 0; li < l; li++)
3084 						noutp[li] = d[li] = s[li];
3085 				}
3086 				noutp += l;
3087 				copy_pos = (copy_pos + l) & w_mask;
3088 				w_pos = (w_pos + l) & w_mask;
3089 				block_bytes_avail -= l;
3090 				if (copy_len <= l)
3091 					/* A copy of current pattern ended. */
3092 					break;
3093 				copy_len -= l;
3094 				if (noutp >= endp) {
3095 					/* Output buffer is empty. */
3096 					state = ST_COPY;
3097 					goto next_data;
3098 				}
3099 			}
3100 			state = ST_MAIN;
3101 			break;
3102 		}
3103 	}
3104 failed:
3105 	return (ds->error = ARCHIVE_FAILED);
3106 next_data:
3107 	ds->br = bre;
3108 	ds->block_bytes_avail = block_bytes_avail;
3109 	ds->copy_len = copy_len;
3110 	ds->copy_pos = copy_pos;
3111 	ds->length_header = length_header;
3112 	ds->offset_bits = offset_bits;
3113 	ds->position_slot = position_slot;
3114 	ds->r0 = r0; ds->r1 = r1; ds->r2 = r2;
3115 	ds->state = state;
3116 	ds->w_pos = w_pos;
3117 	strm->avail_out = endp - noutp;
3118 	return (ARCHIVE_OK);
3119 }
3120 
3121 static int
lzx_read_pre_tree(struct lzx_stream * strm)3122 lzx_read_pre_tree(struct lzx_stream *strm)
3123 {
3124 	struct lzx_dec *ds = strm->ds;
3125 	struct lzx_br *br = &(ds->br);
3126 	uint16_t i;
3127 
3128 	if (ds->loop == 0)
3129 		memset(ds->pt.freq, 0, sizeof(ds->pt.freq));
3130 	for (i = ds->loop; i < ds->pt.symbol_count; i++) {
3131 		if (!lzx_br_read_ahead(strm, br, 4)) {
3132 			ds->loop = i;
3133 			return (ARCHIVE_EOF);
3134 		}
3135 		ds->pt.bitlen[i] = lzx_br_bits(br, 4);
3136 		ds->pt.freq[ds->pt.bitlen[i]]++;
3137 		lzx_br_consume(br, 4);
3138 	}
3139 	ds->loop = i;
3140 	return (ARCHIVE_OK);
3141 }
3142 
3143 /*
3144  * Read a bunch of bit-lengths from pre-tree.
3145  */
3146 static int
lzx_read_bitlen(struct lzx_stream * strm,struct huffman * d,uint16_t end)3147 lzx_read_bitlen(struct lzx_stream *strm, struct huffman *d, uint16_t end)
3148 {
3149 	struct lzx_dec *ds = strm->ds;
3150 	struct lzx_br *br = &(ds->br);
3151 	int ret;
3152 	uint16_t c, i, j, rbits, same;
3153 
3154 	i = ds->loop;
3155 	if (i == 0)
3156 		memset(d->freq, 0, sizeof(d->freq));
3157 	ret = ARCHIVE_EOF;
3158 	if (end == 0)
3159 		end = d->symbol_count;
3160 	while (i < end) {
3161 		ds->loop = i;
3162 		if (!lzx_br_read_ahead(strm, br, (unsigned)ds->pt.lookup_bits))
3163 			goto getdata;
3164 		rbits = lzx_br_bits(br, ds->pt.lookup_bits);
3165 		c = lzx_decode_huffman(&(ds->pt), rbits);
3166 		switch (c) {
3167 		case 17:/* several zero lengths, from 4 to 19. */
3168 			if (!lzx_br_read_ahead(strm, br, ds->pt.bitlen[c] + 4U))
3169 				goto getdata;
3170 			lzx_br_consume(br, ds->pt.bitlen[c]);
3171 			same = lzx_br_bits(br, 4) + 4;
3172 			if (same > end - i)
3173 				return (ARCHIVE_FATAL);
3174 			lzx_br_consume(br, 4);
3175 			for (j = 0; j < same; j++)
3176 				d->bitlen[i++] = 0;
3177 			break;
3178 		case 18:/* many zero lengths, from 20 to 51. */
3179 			if (!lzx_br_read_ahead(strm, br, ds->pt.bitlen[c] + 5U))
3180 				goto getdata;
3181 			lzx_br_consume(br, ds->pt.bitlen[c]);
3182 			same = lzx_br_bits(br, 5) + 20;
3183 			if (same > end - i)
3184 				return (ARCHIVE_FATAL);
3185 			lzx_br_consume(br, 5);
3186 			memset(d->bitlen + i, 0, same);
3187 			i += same;
3188 			break;
3189 		case 19:/* a few same lengths. */
3190 			if (!lzx_br_read_ahead(strm, br,
3191 			    ds->pt.bitlen[c] + 1U + ds->pt.lookup_bits))
3192 				goto getdata;
3193 			lzx_br_consume(br, ds->pt.bitlen[c]);
3194 			same = lzx_br_bits(br, 1) + 4;
3195 			if (same > end - i)
3196 				return (ARCHIVE_FATAL);
3197 			lzx_br_consume(br, 1);
3198 			rbits = lzx_br_bits(br, ds->pt.lookup_bits);
3199 			c = lzx_decode_huffman(&(ds->pt), rbits);
3200 			lzx_br_consume(br, ds->pt.bitlen[c]);
3201 			if (c > d->bitlen[i] + 17)
3202 				return (ARCHIVE_FATAL);
3203 			c = (d->bitlen[i] + 17 - c) % 17;
3204 			for (j = 0; j < same; j++)
3205 				d->bitlen[i++] = c;
3206 			d->freq[c] += same;
3207 			break;
3208 		default:
3209 			lzx_br_consume(br, ds->pt.bitlen[c]);
3210 			if (c > d->bitlen[i] + 17)
3211 				return (ARCHIVE_FATAL);
3212 			c = (d->bitlen[i] + 17 - c) % 17;
3213 			d->freq[c]++;
3214 			d->bitlen[i++] = c;
3215 			break;
3216 		}
3217 	}
3218 	ret = ARCHIVE_OK;
3219 getdata:
3220 	ds->loop = i;
3221 	return (ret);
3222 }
3223 
3224 static int
lzx_huffman_init(struct huffman * hf,uint16_t symbol_count,uint8_t tbl_bits)3225 lzx_huffman_init(struct huffman *hf, uint16_t symbol_count, uint8_t tbl_bits)
3226 {
3227 	size_t tbl_size = (size_t)1 << tbl_bits;
3228 
3229 	if (hf->bitlen == NULL || hf->symbol_count != symbol_count) {
3230 		free(hf->bitlen);
3231 		hf->bitlen = calloc(symbol_count, sizeof(hf->bitlen[0]));
3232 		if (hf->bitlen == NULL)
3233 			return (ARCHIVE_FATAL);
3234 		hf->symbol_count = symbol_count;
3235 	} else
3236 		memset(hf->bitlen, 0, symbol_count * sizeof(hf->bitlen[0]));
3237 	if (hf->tbl == NULL) {
3238 		hf->tbl = calloc(tbl_size, sizeof(hf->tbl[0]));
3239 		if (hf->tbl == NULL)
3240 			return (ARCHIVE_FATAL);
3241 		hf->tbl_bits = tbl_bits;
3242 	} else
3243 		memset(hf->tbl, 0, tbl_size * sizeof(hf->bitlen[0]));
3244 	return (ARCHIVE_OK);
3245 }
3246 
3247 static void
lzx_huffman_free(struct huffman * hf)3248 lzx_huffman_free(struct huffman *hf)
3249 {
3250 	free(hf->bitlen);
3251 	free(hf->tbl);
3252 }
3253 
3254 /*
3255  * Create a direct, expanded Huffman lookup table based on
3256  * canonical representation.
3257  */
3258 static int
lzx_make_huffman_table(struct huffman * hf)3259 lzx_make_huffman_table(struct huffman *hf)
3260 {
3261 	uint16_t bitptn[17], weight[17];
3262 	uint16_t *tbl;
3263 	const uint8_t *bitlen;
3264 	uint8_t maxbits = 0;
3265 	uint32_t ptn;
3266 	uint16_t i, symbol_count, w;
3267 
3268 	/*
3269 	 * Initialize bit patterns.
3270 	 *
3271 	 * Each bitptn element represents the smallest possible
3272 	 * code sequence allowed. The weight represents the amount
3273 	 * of lookup bit patterns covered by a code of this length.
3274 	 *
3275 	 * Example of a Huffman tree:
3276 	 *
3277 	 * idx | freq[idx]
3278 	 * ----+----------
3279 	 *   1 |         1
3280 	 *   2 |         2
3281 	 *
3282 	 * The result will be:
3283 	 *
3284 	 * idx | bitptn[idx] | weight[idx]
3285 	 * ----+-------------+------------
3286 	 *   1 |      0x0000 |       32768
3287 	 *   2 |      0x8000 |       16384
3288 	 *
3289 	 * This means that a code with bit length 1 will take 32768
3290 	 * possible combinations starting with 0b0. Since one such code exists
3291 	 * (freq[1] = 1), codes with bit length 2 must start with 0b1. Since
3292 	 * two codes with bit length 2 exist (freq[2] = 2), no more codes can
3293 	 * be added.
3294 	 *
3295 	 * In this example, maxbits will be 2 (longest code length is 2).
3296 	 */
3297 	ptn = 0;
3298 	for (i = 1, w = 1 << 15; i <= 16; i++, w >>= 1) {
3299 		bitptn[i] = ptn;
3300 		weight[i] = w;
3301 		if (hf->freq[i]) {
3302 			ptn += hf->freq[i] * w;
3303 			maxbits = i;
3304 		}
3305 	}
3306 	/* Verify Kraft's inequality. */
3307 	if (ptn != 0 && ptn != 0x10000)
3308 		return (ARCHIVE_FATAL);
3309 
3310 	/*
3311 	 * Shrink codes to smallest size by removing extra bits after
3312 	 * the actual code sequences as good as possible.
3313 	 *
3314 	 * Continuing the example above:
3315 	 *
3316 	 * idx | bitptn[idx] | weight[idx]
3317 	 * ----+-------------+-------------
3318 	 *   1 |      0x0000 |       32768
3319 	 *   2 |      0x8000 |       16384
3320 	 *
3321 	 * As can be seen, a total of 65536 entries must be created even
3322 	 * though 4 would be sufficient (indices 0b00 to 0b11). Right shift
3323 	 * the pattern and divide weight as much as possible:
3324 	 *
3325 	 * idx | bitptn[idx] | weight[idx]
3326 	 * ----+-------------+-------------
3327 	 *   1 |      0x0000 |           2
3328 	 *   2 |      0x0002 |           1
3329 	 *
3330 	 * Thus, the direct, expanded lookup table only needs 4 entries.
3331 	 */
3332 	if (maxbits < 16) {
3333 		uint8_t ebits = 16 - maxbits;
3334 		for (i = 1; i <= maxbits; i++) {
3335 			bitptn[i] >>= ebits;
3336 			weight[i] >>= ebits;
3337 		}
3338 	}
3339 
3340 	/* Grow table if necessary. */
3341 	if (maxbits > hf->tbl_bits) {
3342 		size_t tbl_size;
3343 
3344 		hf->tbl_bits = 16;
3345 		tbl_size = (size_t)1 << hf->tbl_bits;
3346 
3347 		free(hf->tbl);
3348 		hf->tbl = calloc(tbl_size, sizeof(hf->tbl[0]));
3349 		if (hf->tbl == NULL)
3350 			return (ARCHIVE_FATAL);
3351 	}
3352 	hf->lookup_bits = maxbits;
3353 
3354 	/*
3355 	 * Construct the direct, expanded lookup table.
3356 	 *
3357 	 * Store each symbol in table for every possible bit patterns starting
3358 	 * with their code.
3359 	 *
3360 	 * Following the example with len_avail being 4:
3361 	 *
3362 	 * idx | bitlen[idx]
3363 	 * ----+------------
3364 	 *   0 |           0
3365 	 *   1 |           1
3366 	 *   2 |           0
3367 	 *   3 |           2
3368 	 *   4 |           2
3369 	 *
3370 	 * The resulting table contains all used symbols (1, 3, 4) for up to
3371 	 * max_len bit patterns:
3372 	 *
3373 	 *       idx | tbl[idx]
3374 	 * ----------+---------
3375 	 *  0 (0b00) |        1
3376 	 *  1 (0b01) |        1
3377 	 *  2 (0b10) |        3
3378 	 *  3 (0b11) |        4
3379 	 */
3380 	tbl = hf->tbl;
3381 	bitlen = hf->bitlen;
3382 	symbol_count = hf->symbol_count;
3383 	for (i = 0; i < symbol_count; i++) {
3384 		uint16_t *p;
3385 		uint16_t cnt;
3386 		uint8_t len;
3387 
3388 		if (bitlen[i] == 0)
3389 			continue;
3390 		/* Get a bit pattern */
3391 		len = bitlen[i];
3392 		if (len > maxbits)
3393 			return (ARCHIVE_FATAL);
3394 		ptn = bitptn[len];
3395 		cnt = weight[len];
3396 		/* Calculate next bit pattern */
3397 		bitptn[len] = ptn + cnt;
3398 		/* Update the table */
3399 		p = tbl + ptn;
3400 		while (cnt-- > 0)
3401 			*p++ = i;
3402 	}
3403 	return (ARCHIVE_OK);
3404 }
3405 
3406 static uint16_t
lzx_decode_huffman(struct huffman * hf,uint16_t rbits)3407 lzx_decode_huffman(struct huffman *hf, uint16_t rbits)
3408 {
3409 	return hf->tbl[rbits];
3410 }
3411