xref: /freebsd/contrib/libarchive/libarchive/archive_read_support_format_rar5.c (revision 401026e4825a05abba6f945cf1b74b3328876fa2)
1 /*-
2 * Copyright (c) 2018 Grzegorz Antoniak (http://antoniak.org)
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 #include "archive_endian.h"
28 
29 #ifdef HAVE_ERRNO_H
30 #include <errno.h>
31 #endif
32 #include <time.h>
33 #ifdef HAVE_ZLIB_H
34 #include <zlib.h> /* crc32 */
35 #endif
36 #ifdef HAVE_LIMITS_H
37 #include <limits.h>
38 #endif
39 
40 #include "archive.h"
41 #ifndef HAVE_ZLIB_H
42 #include "archive_crc32.h"
43 #endif
44 
45 #include "archive_entry.h"
46 #include "archive_entry_locale.h"
47 #include "archive_ppmd7_private.h"
48 #include "archive_entry_private.h"
49 #include "archive_time_private.h"
50 
51 #ifdef HAVE_BLAKE2_H
52 #include <blake2.h>
53 #else
54 #include "archive_blake2.h"
55 #endif
56 
57 /*#define CHECK_CRC_ON_SOLID_SKIP*/
58 /*#define DONT_FAIL_ON_CRC_ERROR*/
59 /*#define DEBUG*/
60 
61 #define rar5_min(a, b) (((a) > (b)) ? (b) : (a))
62 #define rar5_max(a, b) (((a) > (b)) ? (a) : (b))
63 #define rar5_countof(X) ((const ssize_t) (sizeof(X) / sizeof(*X)))
64 
65 #if defined DEBUG
66 #define DEBUG_CODE if(1)
67 #define LOG(...) do { printf("rar5: " __VA_ARGS__); puts(""); } while(0)
68 #else
69 #define DEBUG_CODE if(0)
70 #endif
71 
72 /* Real RAR5 magic number is:
73  *
74  * 0x52, 0x61, 0x72, 0x21, 0x1a, 0x07, 0x01, 0x00
75  * "Rar!→•☺·\x00"
76  *
77  * Retrieved with `rar5_signature()` by XOR'ing it with 0xA1, because I don't
78  * want to put this magic sequence in each binary that uses libarchive, so
79  * applications that scan through the file for this marker won't trigger on
80  * this "false" one.
81  *
82  * The array itself is decrypted in `rar5_init` function. */
83 
84 static unsigned char rar5_signature_xor[] = { 243, 192, 211, 128, 187, 166, 160, 161 };
85 static const size_t g_unpack_window_size = 0x20000;
86 
87 /* These could have been static const's, but they aren't, because of
88  * Visual Studio. */
89 #define MAX_NAME_IN_CHARS 2048
90 #define MAX_NAME_IN_BYTES (4 * MAX_NAME_IN_CHARS)
91 
92 struct file_header {
93 	ssize_t bytes_remaining;
94 	ssize_t unpacked_size;
95 	int64_t last_offset;         /* Used in sanity checks. */
96 	int64_t last_size;           /* Used in sanity checks. */
97 
98 	uint8_t solid : 1;           /* Is this a solid stream? */
99 	uint8_t service : 1;         /* Is this file a service data? */
100 	uint8_t eof : 1;             /* Did we finish unpacking the file? */
101 	uint8_t dir : 1;             /* Is this file entry a directory? */
102 
103 	/* Optional time fields. */
104 	int64_t e_mtime;
105 	int64_t e_ctime;
106 	int64_t e_atime;
107 	uint32_t e_mtime_ns;
108 	uint32_t e_ctime_ns;
109 	uint32_t e_atime_ns;
110 
111 	/* Optional hash fields. */
112 	uint32_t stored_crc32;
113 	uint32_t calculated_crc32;
114 	uint8_t blake2sp[32];
115 	blake2sp_state b2state;
116 	char has_blake2;
117 
118 	/* Optional redir fields */
119 	uint64_t redir_type;
120 	uint64_t redir_flags;
121 
122 	ssize_t solid_window_size; /* Used in file format check. */
123 };
124 
125 enum EXTRA {
126 	EX_CRYPT = 0x01,
127 	EX_HASH = 0x02,
128 	EX_HTIME = 0x03,
129 	EX_VERSION = 0x04,
130 	EX_REDIR = 0x05,
131 	EX_UOWNER = 0x06,
132 	EX_SUBDATA = 0x07
133 };
134 
135 #define REDIR_SYMLINK_IS_DIR	1
136 
137 enum REDIR_TYPE {
138 	REDIR_TYPE_NONE = 0,
139 	REDIR_TYPE_UNIXSYMLINK = 1,
140 	REDIR_TYPE_WINSYMLINK = 2,
141 	REDIR_TYPE_JUNCTION = 3,
142 	REDIR_TYPE_HARDLINK = 4,
143 	REDIR_TYPE_FILECOPY = 5,
144 };
145 
146 #define	OWNER_USER_NAME		0x01
147 #define	OWNER_GROUP_NAME	0x02
148 #define	OWNER_USER_UID		0x04
149 #define	OWNER_GROUP_GID		0x08
150 #define	OWNER_MAXNAMELEN	256
151 
152 enum FILTER_TYPE {
153 	FILTER_DELTA = 0,   /* Generic pattern. */
154 	FILTER_E8    = 1,   /* Intel x86 code. */
155 	FILTER_E8E9  = 2,   /* Intel x86 code. */
156 	FILTER_ARM   = 3,   /* ARM code. */
157 	FILTER_AUDIO = 4,   /* Audio filter, not used in RARv5. */
158 	FILTER_RGB   = 5,   /* Color palette, not used in RARv5. */
159 	FILTER_ITANIUM = 6, /* Intel's Itanium, not used in RARv5. */
160 	FILTER_PPM   = 7,   /* Predictive pattern matching, not used in
161 			       RARv5. */
162 	FILTER_NONE  = 8,
163 };
164 
165 struct filter_info {
166 	int type;
167 	int channels;
168 	int pos_r;
169 
170 	int64_t block_start;
171 	ssize_t block_length;
172 	uint16_t width;
173 };
174 
175 struct data_ready {
176 	char used;
177 	const uint8_t* buf;
178 	size_t size;
179 	int64_t offset;
180 };
181 
182 struct cdeque {
183 	uint16_t beg_pos;
184 	uint16_t end_pos;
185 	uint16_t cap_mask;
186 	uint16_t size;
187 	size_t* arr;
188 };
189 
190 struct decode_table {
191 	uint32_t size;
192 	int32_t decode_len[16];
193 	uint32_t decode_pos[16];
194 	uint32_t quick_bits;
195 	uint8_t quick_len[1 << 10];
196 	uint16_t quick_num[1 << 10];
197 	uint16_t decode_num[306];
198 };
199 
200 struct comp_state {
201 	/* Flag used to specify if unpacker needs to reinitialize the
202 	   uncompression context. */
203 	uint8_t initialized : 1;
204 
205 	/* Flag used when applying filters. */
206 	uint8_t all_filters_applied : 1;
207 
208 	/* Flag used to skip file context reinitialization, used when unpacker
209 	   is skipping through different multivolume archives. */
210 	uint8_t switch_multivolume : 1;
211 
212 	/* Flag used to specify if unpacker has processed the whole data block
213 	   or just a part of it. */
214 	uint8_t block_parsing_finished : 1;
215 
216 	/* Flag used to indicate that a previous file using this buffer was
217 	   encrypted, meaning no data in the buffer can be trusted */
218 	uint8_t data_encrypted : 1;
219 
220 	signed int notused : 3;
221 
222 	int flags;                   /* Uncompression flags. */
223 	int method;                  /* Uncompression algorithm method. */
224 	int version;                 /* Uncompression algorithm version. */
225 	ssize_t window_size;         /* Size of window_buf. */
226 	uint8_t* window_buf;         /* Circular buffer used during
227 	                                decompression. */
228 	uint8_t* filtered_buf;       /* Buffer used when applying filters. */
229 	const uint8_t* block_buf;    /* Buffer used when merging blocks. */
230 	ssize_t window_mask;         /* Convenience field; window_size - 1. */
231 	int64_t write_ptr;           /* This amount of data has been unpacked
232 					in the window buffer. */
233 	int64_t last_write_ptr;      /* This amount of data has been stored in
234 	                                the output file. */
235 	int64_t last_unstore_ptr;    /* Counter of bytes extracted during
236 	                                unstoring. This is separate from
237 	                                last_write_ptr because of how SERVICE
238 	                                base blocks are handled during skipping
239 	                                in solid multiarchive archives. */
240 	int64_t solid_offset;        /* Additional offset inside the window
241 	                                buffer, used in unpacking solid
242 	                                archives. */
243 	ssize_t cur_block_size;      /* Size of current data block. */
244 	int last_len;                /* Flag used in lzss decompression. */
245 
246 	/* Decode tables used during lzss uncompression. */
247 
248 #define HUFF_BC 20
249 	struct decode_table bd;      /* huffman bit lengths */
250 #define HUFF_NC 306
251 	struct decode_table ld;      /* literals */
252 #define HUFF_DC 64
253 	struct decode_table dd;      /* distances */
254 #define HUFF_LDC 16
255 	struct decode_table ldd;     /* lower bits of distances */
256 #define HUFF_RC 44
257 	struct decode_table rd;      /* repeating distances */
258 #define HUFF_TABLE_SIZE (HUFF_NC + HUFF_DC + HUFF_RC + HUFF_LDC)
259 
260 	/* Circular deque for storing filters. */
261 	struct cdeque filters;
262 	int64_t last_block_start;    /* Used for sanity checking. */
263 	ssize_t last_block_length;   /* Used for sanity checking. */
264 
265 	/* Distance cache used during lzss uncompression. */
266 	int dist_cache[4];
267 
268 	/* Data buffer stack. */
269 	struct data_ready dready[2];
270 };
271 
272 /* Bit reader state. */
273 struct bit_reader {
274 	int8_t bit_addr;    /* Current bit pointer inside current byte. */
275 	int in_addr;        /* Current byte pointer. */
276 };
277 
278 /* RARv5 block header structure. Use bf_* functions to get values from
279  * block_flags_u8 field. I.e. bf_byte_count, etc. */
280 struct compressed_block_header {
281 	/* block_flags_u8 contain fields encoded in little-endian bitfield:
282 	 *
283 	 * - table present flag (shr 7, and 1),
284 	 * - last block flag    (shr 6, and 1),
285 	 * - byte_count         (shr 3, and 7),
286 	 * - bit_size           (shr 0, and 7).
287 	 */
288 	uint8_t block_flags_u8;
289 	uint8_t block_cksum;
290 };
291 
292 /* RARv5 main header structure. */
293 struct main_header {
294 	/* Does the archive contain solid streams? */
295 	uint8_t solid : 1;
296 
297 	/* If this a multi-file archive? */
298 	uint8_t volume : 1;
299 	uint8_t endarc : 1;
300 	uint8_t notused : 5;
301 
302 	unsigned int vol_no;
303 };
304 
305 struct generic_header {
306 	uint8_t split_after : 1;
307 	uint8_t split_before : 1;
308 	uint8_t padding : 6;
309 	int size;
310 	int last_header_id;
311 };
312 
313 struct multivolume {
314 	unsigned int expected_vol_no;
315 	uint8_t* push_buf;
316 };
317 
318 /* Main context structure. */
319 struct rar5 {
320 	int header_initialized;
321 
322 	/* Set to 1 if current file is positioned AFTER the magic value
323 	 * of the archive file. This is used in header reading functions. */
324 	int skipped_magic;
325 
326 	/* Set to not zero if we're in skip mode (either by calling
327 	 * rar5_data_skip function or when skipping over solid streams).
328 	 * Set to 0 when in * extraction mode. This is used during checksum
329 	 * calculation functions. */
330 	int skip_mode;
331 
332 	/* Set to not zero if we're in block merging mode (i.e. when switching
333 	 * to another file in multivolume archive, last block from 1st archive
334 	 * needs to be merged with 1st block from 2nd archive). This flag
335 	 * guards against recursive use of the merging function, which doesn't
336 	 * support recursive calls. */
337 	int merge_mode;
338 
339 	/* An offset to QuickOpen list. This is not supported by this unpacker,
340 	 * because we're focusing on streaming interface. QuickOpen is designed
341 	 * to make things quicker for non-stream interfaces, so it's not our
342 	 * use case. */
343 	uint64_t qlist_offset;
344 
345 	/* An offset to additional Recovery data. This is not supported by this
346 	 * unpacker. Recovery data are additional Reed-Solomon codes that could
347 	 * be used to calculate bytes that are missing in archive or are
348 	 * corrupted. */
349 	uint64_t rr_offset;
350 
351 	/* Various context variables grouped to different structures. */
352 	struct generic_header generic;
353 	struct main_header main;
354 	struct comp_state cstate;
355 	struct file_header file;
356 	struct bit_reader bits;
357 	struct multivolume vol;
358 
359 	/* The header of currently processed RARv5 block. Used in main
360 	 * decompression logic loop. */
361 	struct compressed_block_header last_block_hdr;
362 
363 	/*
364 	 * Custom field to denote that this archive contains encrypted entries
365 	 */
366 	int has_encrypted_entries;
367 	int headers_are_encrypted;
368 };
369 
370 /* Forward function declarations. */
371 
372 static void rar5_signature(char *buf);
373 static int verify_global_checksums(struct archive_read* a);
374 static int rar5_read_data_skip(struct archive_read *a);
375 static int push_data_ready(struct archive_read* a, struct rar5* rar,
376 	const uint8_t* buf, size_t size, int64_t offset);
377 static void clear_data_ready_stack(struct rar5* rar);
378 
379 /* CDE_xxx = Circular Double Ended (Queue) return values. */
380 enum CDE_RETURN_VALUES {
381 	CDE_OK, CDE_ALLOC, CDE_PARAM, CDE_OUT_OF_BOUNDS,
382 };
383 
384 /* Clears the contents of this circular deque. */
cdeque_clear(struct cdeque * d)385 static void cdeque_clear(struct cdeque* d) {
386 	d->size = 0;
387 	d->beg_pos = 0;
388 	d->end_pos = 0;
389 }
390 
391 /* Creates a new circular deque object. Capacity must be power of 2: 8, 16, 32,
392  * 64, 256, etc. When the user will add another item above current capacity,
393  * the circular deque will overwrite the oldest entry. */
cdeque_init(struct cdeque * d,int max_capacity_power_of_2)394 static int cdeque_init(struct cdeque* d, int max_capacity_power_of_2) {
395 	if(d == NULL || max_capacity_power_of_2 == 0)
396 		return CDE_PARAM;
397 
398 	d->cap_mask = max_capacity_power_of_2 - 1;
399 	d->arr = NULL;
400 
401 	if((max_capacity_power_of_2 & d->cap_mask) != 0)
402 		return CDE_PARAM;
403 
404 	cdeque_clear(d);
405 	d->arr = malloc(sizeof(void*) * max_capacity_power_of_2);
406 
407 	return d->arr ? CDE_OK : CDE_ALLOC;
408 }
409 
410 /* Return the current size (not capacity) of circular deque `d`. */
cdeque_size(struct cdeque * d)411 static size_t cdeque_size(struct cdeque* d) {
412 	return d->size;
413 }
414 
415 /* Returns the first element of current circular deque. Note that this function
416  * doesn't perform any bounds checking. If you need bounds checking, use
417  * `cdeque_front()` function instead. */
cdeque_front_fast(struct cdeque * d,void ** value)418 static void cdeque_front_fast(struct cdeque* d, void** value) {
419 	*value = (void*) d->arr[d->beg_pos];
420 }
421 
422 /* Returns the first element of current circular deque. This function
423  * performs bounds checking. */
cdeque_front(struct cdeque * d,void ** value)424 static int cdeque_front(struct cdeque* d, void** value) {
425 	if(d->size > 0) {
426 		cdeque_front_fast(d, value);
427 		return CDE_OK;
428 	} else
429 		return CDE_OUT_OF_BOUNDS;
430 }
431 
432 /* Pushes a new element into the end of this circular deque object. If current
433  * size will exceed capacity, the oldest element will be overwritten. */
cdeque_push_back(struct cdeque * d,void * item)434 static int cdeque_push_back(struct cdeque* d, void* item) {
435 	if(d == NULL)
436 		return CDE_PARAM;
437 
438 	if(d->size == d->cap_mask + 1)
439 		return CDE_OUT_OF_BOUNDS;
440 
441 	d->arr[d->end_pos] = (size_t) item;
442 	d->end_pos = (d->end_pos + 1) & d->cap_mask;
443 	d->size++;
444 
445 	return CDE_OK;
446 }
447 
448 /* Pops a front element of this circular deque object and returns its value.
449  * This function doesn't perform any bounds checking. */
cdeque_pop_front_fast(struct cdeque * d,void ** value)450 static void cdeque_pop_front_fast(struct cdeque* d, void** value) {
451 	*value = (void*) d->arr[d->beg_pos];
452 	d->beg_pos = (d->beg_pos + 1) & d->cap_mask;
453 	d->size--;
454 }
455 
456 /* Pops a front element of this circular deque object and returns its value.
457  * This function performs bounds checking. */
cdeque_pop_front(struct cdeque * d,void ** value)458 static int cdeque_pop_front(struct cdeque* d, void** value) {
459 	if(!d || !value)
460 		return CDE_PARAM;
461 
462 	if(d->size == 0)
463 		return CDE_OUT_OF_BOUNDS;
464 
465 	cdeque_pop_front_fast(d, value);
466 	return CDE_OK;
467 }
468 
469 /* Convenience function to cast filter_info** to void **. */
cdeque_filter_p(struct filter_info ** f)470 static void** cdeque_filter_p(struct filter_info** f) {
471 	return (void**) (size_t) f;
472 }
473 
474 /* Convenience function to cast filter_info* to void *. */
cdeque_filter(struct filter_info * f)475 static void* cdeque_filter(struct filter_info* f) {
476 	return (void**) (size_t) f;
477 }
478 
479 /* Destroys this circular deque object. Deallocates the memory of the
480  * collection buffer, but doesn't deallocate the memory of any pointer passed
481  * to this deque as a value. */
cdeque_free(struct cdeque * d)482 static void cdeque_free(struct cdeque* d) {
483 	if(!d)
484 		return;
485 
486 	if(!d->arr)
487 		return;
488 
489 	free(d->arr);
490 
491 	d->arr = NULL;
492 	d->beg_pos = -1;
493 	d->end_pos = -1;
494 	d->cap_mask = 0;
495 }
496 
497 static inline
bf_bit_size(const struct compressed_block_header * hdr)498 uint8_t bf_bit_size(const struct compressed_block_header* hdr) {
499 	return hdr->block_flags_u8 & 7;
500 }
501 
502 static inline
bf_byte_count(const struct compressed_block_header * hdr)503 uint8_t bf_byte_count(const struct compressed_block_header* hdr) {
504 	return (hdr->block_flags_u8 >> 3) & 7;
505 }
506 
507 static inline
bf_is_table_present(const struct compressed_block_header * hdr)508 uint8_t bf_is_table_present(const struct compressed_block_header* hdr) {
509 	return (hdr->block_flags_u8 >> 7) & 1;
510 }
511 
512 static inline
bf_is_last_block(const struct compressed_block_header * hdr)513 uint8_t bf_is_last_block(const struct compressed_block_header* hdr) {
514 	return (hdr->block_flags_u8 >> 6) & 1;
515 }
516 
get_context(struct archive_read * a)517 static inline struct rar5* get_context(struct archive_read* a) {
518 	return (struct rar5*) a->format->data;
519 }
520 
521 /* Convenience functions used by filter implementations. */
circular_memcpy(uint8_t * dst,uint8_t * window,const ssize_t mask,int64_t start,int64_t end)522 static void circular_memcpy(uint8_t* dst, uint8_t* window, const ssize_t mask,
523     int64_t start, int64_t end)
524 {
525 	if((start & mask) > (end & mask)) {
526 		ssize_t len1 = mask + 1 - (start & mask);
527 		ssize_t len2 = end & mask;
528 
529 		memcpy(dst, &window[start & mask], len1);
530 		memcpy(dst + len1, window, len2);
531 	} else {
532 		memcpy(dst, &window[start & mask], (size_t) (end - start));
533 	}
534 }
535 
read_filter_data(struct rar5 * rar,uint32_t offset)536 static uint32_t read_filter_data(struct rar5* rar, uint32_t offset) {
537 	uint8_t linear_buf[4];
538 	circular_memcpy(linear_buf, rar->cstate.window_buf,
539 	    rar->cstate.window_mask, offset, offset + 4);
540 	return archive_le32dec(linear_buf);
541 }
542 
write_filter_data(struct rar5 * rar,uint32_t offset,uint32_t value)543 static void write_filter_data(struct rar5* rar, uint32_t offset,
544     uint32_t value)
545 {
546 	archive_le32enc(&rar->cstate.filtered_buf[offset], value);
547 }
548 
549 /* Allocates a new filter descriptor and adds it to the filter array. */
add_new_filter(struct rar5 * rar)550 static struct filter_info* add_new_filter(struct rar5* rar) {
551 	struct filter_info* f = calloc(1, sizeof(*f));
552 
553 	if(!f) {
554 		return NULL;
555 	}
556 
557 	cdeque_push_back(&rar->cstate.filters, cdeque_filter(f));
558 	return f;
559 }
560 
run_delta_filter(struct rar5 * rar,struct filter_info * flt)561 static int run_delta_filter(struct rar5* rar, struct filter_info* flt) {
562 	int i;
563 	ssize_t dest_pos, src_pos = 0;
564 
565 	for(i = 0; i < flt->channels; i++) {
566 		uint8_t prev_byte = 0;
567 		for(dest_pos = i;
568 				dest_pos < flt->block_length;
569 				dest_pos += flt->channels)
570 		{
571 			uint8_t byte;
572 
573 			byte = rar->cstate.window_buf[
574 			    (rar->cstate.solid_offset + flt->block_start +
575 			    src_pos) & rar->cstate.window_mask];
576 
577 			prev_byte -= byte;
578 			rar->cstate.filtered_buf[dest_pos] = prev_byte;
579 			src_pos++;
580 		}
581 	}
582 
583 	return ARCHIVE_OK;
584 }
585 
run_e8e9_filter(struct rar5 * rar,struct filter_info * flt,int extended)586 static int run_e8e9_filter(struct rar5* rar, struct filter_info* flt,
587 		int extended)
588 {
589 	const uint32_t file_size = 0x1000000;
590 	ssize_t i;
591 
592 	circular_memcpy(rar->cstate.filtered_buf,
593 	    rar->cstate.window_buf, rar->cstate.window_mask,
594 	    rar->cstate.solid_offset + flt->block_start,
595 	    rar->cstate.solid_offset + flt->block_start + flt->block_length);
596 
597 	for(i = 0; i < flt->block_length - 4;) {
598 		uint8_t b = rar->cstate.window_buf[
599 		    (rar->cstate.solid_offset + flt->block_start +
600 		    i++) & rar->cstate.window_mask];
601 
602 		/*
603 		 * 0xE8 = x86's call <relative_addr_uint32> (function call)
604 		 * 0xE9 = x86's jmp <relative_addr_uint32> (unconditional jump)
605 		 */
606 		if(b == 0xE8 || (extended && b == 0xE9)) {
607 
608 			uint32_t addr;
609 			uint32_t offset = (i + flt->block_start) % file_size;
610 
611 			addr = read_filter_data(rar,
612 			    (uint32_t)(rar->cstate.solid_offset +
613 			    flt->block_start + i) & rar->cstate.window_mask);
614 
615 			if(addr & 0x80000000) {
616 				if(((addr + offset) & 0x80000000) == 0) {
617 					write_filter_data(rar, (uint32_t)i,
618 					    addr + file_size);
619 				}
620 			} else {
621 				if((addr - file_size) & 0x80000000) {
622 					uint32_t naddr = addr - offset;
623 					write_filter_data(rar, (uint32_t)i,
624 					    naddr);
625 				}
626 			}
627 
628 			i += 4;
629 		}
630 	}
631 
632 	return ARCHIVE_OK;
633 }
634 
run_arm_filter(struct rar5 * rar,struct filter_info * flt)635 static int run_arm_filter(struct rar5* rar, struct filter_info* flt) {
636 	ssize_t i = 0;
637 	uint32_t offset;
638 
639 	circular_memcpy(rar->cstate.filtered_buf,
640 	    rar->cstate.window_buf, rar->cstate.window_mask,
641 	    rar->cstate.solid_offset + flt->block_start,
642 	    rar->cstate.solid_offset + flt->block_start + flt->block_length);
643 
644 	for(i = 0; i < flt->block_length - 3; i += 4) {
645 		uint8_t* b = &rar->cstate.window_buf[
646 		    (rar->cstate.solid_offset +
647 		    flt->block_start + i + 3) & rar->cstate.window_mask];
648 
649 		if(*b == 0xEB) {
650 			/* 0xEB = ARM's BL (branch + link) instruction. */
651 			offset = read_filter_data(rar,
652 			    (rar->cstate.solid_offset + flt->block_start + i) &
653 			     (uint32_t)rar->cstate.window_mask) & 0x00ffffff;
654 
655 			offset -= (uint32_t) ((i + flt->block_start) / 4);
656 			offset = (offset & 0x00ffffff) | 0xeb000000;
657 			write_filter_data(rar, (uint32_t)i, offset);
658 		}
659 	}
660 
661 	return ARCHIVE_OK;
662 }
663 
run_filter(struct archive_read * a,struct filter_info * flt)664 static int run_filter(struct archive_read* a, struct filter_info* flt) {
665 	int ret;
666 	struct rar5* rar = get_context(a);
667 
668 	clear_data_ready_stack(rar);
669 	free(rar->cstate.filtered_buf);
670 
671 	rar->cstate.filtered_buf = malloc(flt->block_length);
672 	if(!rar->cstate.filtered_buf) {
673 		archive_set_error(&a->archive, ENOMEM,
674 		    "Can't allocate memory for filter data.");
675 		return ARCHIVE_FATAL;
676 	}
677 
678 	switch(flt->type) {
679 		case FILTER_DELTA:
680 			ret = run_delta_filter(rar, flt);
681 			break;
682 
683 		case FILTER_E8:
684 			/* fallthrough */
685 		case FILTER_E8E9:
686 			ret = run_e8e9_filter(rar, flt,
687 			    flt->type == FILTER_E8E9);
688 			break;
689 
690 		case FILTER_ARM:
691 			ret = run_arm_filter(rar, flt);
692 			break;
693 
694 		default:
695 			archive_set_error(&a->archive,
696 			    ARCHIVE_ERRNO_FILE_FORMAT,
697 			    "Unsupported filter type: 0x%x",
698 			    (unsigned int)flt->type);
699 			return ARCHIVE_FATAL;
700 	}
701 
702 	if(ret != ARCHIVE_OK) {
703 		/* Filter has failed. */
704 		return ret;
705 	}
706 
707 	if(ARCHIVE_OK != push_data_ready(a, rar, rar->cstate.filtered_buf,
708 	    flt->block_length, rar->cstate.last_write_ptr))
709 	{
710 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
711 		    "Stack overflow when submitting unpacked data");
712 
713 		return ARCHIVE_FATAL;
714 	}
715 
716 	rar->cstate.last_write_ptr += flt->block_length;
717 	return ARCHIVE_OK;
718 }
719 
720 /* The `push_data` function submits the selected data range to the user.
721  * Next call of `use_data` will use the pointer, size and offset arguments
722  * that are specified here. These arguments are pushed to the FIFO stack here,
723  * and popped from the stack by the `use_data` function. */
push_data(struct archive_read * a,struct rar5 * rar,const uint8_t * buf,int64_t idx_begin,int64_t idx_end)724 static void push_data(struct archive_read* a, struct rar5* rar,
725     const uint8_t* buf, int64_t idx_begin, int64_t idx_end)
726 {
727 	const ssize_t wmask = rar->cstate.window_mask;
728 	const ssize_t solid_write_ptr = (rar->cstate.solid_offset +
729 	    rar->cstate.last_write_ptr) & wmask;
730 
731 	idx_begin += rar->cstate.solid_offset;
732 	idx_end += rar->cstate.solid_offset;
733 
734 	/* Check if our unpacked data is wrapped inside the window circular
735 	 * buffer.  If it's not wrapped, it can be copied out by using
736 	 * a single memcpy, but when it's wrapped, we need to copy the first
737 	 * part with one memcpy, and the second part with another memcpy. */
738 
739 	if((idx_begin & wmask) > (idx_end & wmask)) {
740 		/* The data is wrapped (begin offset sis bigger than end
741 		 * offset). */
742 		const ssize_t frag1_size = rar->cstate.window_size -
743 		    (idx_begin & wmask);
744 		const ssize_t frag2_size = idx_end & wmask;
745 
746 		/* Copy the first part of the buffer first. */
747 		push_data_ready(a, rar, buf + solid_write_ptr, frag1_size,
748 		    rar->cstate.last_write_ptr);
749 
750 		/* Copy the second part of the buffer. */
751 		push_data_ready(a, rar, buf, frag2_size,
752 		    rar->cstate.last_write_ptr + frag1_size);
753 
754 		rar->cstate.last_write_ptr += frag1_size + frag2_size;
755 	} else {
756 		/* Data is not wrapped, so we can just use one call to copy the
757 		 * data. */
758 		push_data_ready(a, rar,
759 		    buf + solid_write_ptr, (idx_end - idx_begin) & wmask,
760 		    rar->cstate.last_write_ptr);
761 
762 		rar->cstate.last_write_ptr += idx_end - idx_begin;
763 	}
764 }
765 
766 /* Convenience function that submits the data to the user. It uses the
767  * unpack window buffer as a source location. */
push_window_data(struct archive_read * a,struct rar5 * rar,int64_t idx_begin,int64_t idx_end)768 static void push_window_data(struct archive_read* a, struct rar5* rar,
769     int64_t idx_begin, int64_t idx_end)
770 {
771 	push_data(a, rar, rar->cstate.window_buf, idx_begin, idx_end);
772 }
773 
apply_filters(struct archive_read * a)774 static int apply_filters(struct archive_read* a) {
775 	struct filter_info* flt;
776 	struct rar5* rar = get_context(a);
777 	int ret;
778 
779 	rar->cstate.all_filters_applied = 0;
780 
781 	/* Get the first filter that can be applied to our data. The data
782 	 * needs to be fully unpacked before the filter can be run. */
783 	if(CDE_OK == cdeque_front(&rar->cstate.filters,
784 	    cdeque_filter_p(&flt))) {
785 		/* Check if our unpacked data fully covers this filter's
786 		 * range. */
787 		if(rar->cstate.write_ptr > flt->block_start &&
788 		    rar->cstate.write_ptr >= flt->block_start +
789 		    flt->block_length) {
790 			/* Check if we have some data pending to be written
791 			 * right before the filter's start offset. */
792 			if(rar->cstate.last_write_ptr == flt->block_start) {
793 				/* Run the filter specified by descriptor
794 				 * `flt`. */
795 				ret = run_filter(a, flt);
796 				if(ret != ARCHIVE_OK) {
797 					/* Filter failure, return error. */
798 					return ret;
799 				}
800 
801 				/* Filter descriptor won't be needed anymore
802 				 * after it's used, * so remove it from the
803 				 * filter list and free its memory. */
804 				(void) cdeque_pop_front(&rar->cstate.filters,
805 				    cdeque_filter_p(&flt));
806 
807 				free(flt);
808 			} else {
809 				/* We can't run filters yet, dump the memory
810 				 * right before the filter. */
811 				push_window_data(a, rar,
812 				    rar->cstate.last_write_ptr,
813 				    flt->block_start);
814 			}
815 
816 			/* Return 'filter applied or not needed' state to the
817 			 * caller. */
818 			return ARCHIVE_RETRY;
819 		}
820 	}
821 
822 	rar->cstate.all_filters_applied = 1;
823 	return ARCHIVE_OK;
824 }
825 
dist_cache_push(struct rar5 * rar,int value)826 static void dist_cache_push(struct rar5* rar, int value) {
827 	int* q = rar->cstate.dist_cache;
828 
829 	q[3] = q[2];
830 	q[2] = q[1];
831 	q[1] = q[0];
832 	q[0] = value;
833 }
834 
dist_cache_touch(struct rar5 * rar,int idx)835 static int dist_cache_touch(struct rar5* rar, int idx) {
836 	int* q = rar->cstate.dist_cache;
837 	int i, dist = q[idx];
838 
839 	for(i = idx; i > 0; i--)
840 		q[i] = q[i - 1];
841 
842 	q[0] = dist;
843 	return dist;
844 }
845 
free_filters(struct rar5 * rar)846 static void free_filters(struct rar5* rar) {
847 	struct cdeque* d = &rar->cstate.filters;
848 
849 	/* Free any remaining filters. All filters should be naturally
850 	 * consumed by the unpacking function, so remaining filters after
851 	 * unpacking normally mean that unpacking wasn't successful.
852 	 * But still of course we shouldn't leak memory in such case. */
853 
854 	/* cdeque_size() is a fast operation, so we can use it as a loop
855 	 * expression. */
856 	while(cdeque_size(d) > 0) {
857 		struct filter_info* f = NULL;
858 
859 		/* Pop_front will also decrease the collection's size. */
860 		if (CDE_OK == cdeque_pop_front(d, cdeque_filter_p(&f)))
861 			free(f);
862 	}
863 
864 	cdeque_clear(d);
865 
866 	/* Also clear out the variables needed for sanity checking. */
867 	rar->cstate.last_block_start = 0;
868 	rar->cstate.last_block_length = 0;
869 }
870 
reset_file_context(struct rar5 * rar)871 static void reset_file_context(struct rar5* rar) {
872 	memset(&rar->file, 0, sizeof(rar->file));
873 	blake2sp_init(&rar->file.b2state, 32);
874 
875 	if(rar->main.solid) {
876 		rar->cstate.solid_offset += rar->cstate.write_ptr;
877 	} else {
878 		rar->cstate.solid_offset = 0;
879 	}
880 
881 	rar->cstate.write_ptr = 0;
882 	rar->cstate.last_write_ptr = 0;
883 	rar->cstate.last_unstore_ptr = 0;
884 
885 	rar->file.redir_type = REDIR_TYPE_NONE;
886 	rar->file.redir_flags = 0;
887 
888 	free_filters(rar);
889 }
890 
get_archive_read(struct archive * a,struct archive_read ** ar)891 static inline int get_archive_read(struct archive* a,
892     struct archive_read** ar)
893 {
894 	*ar = (struct archive_read*) a;
895 	archive_check_magic(a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
896 	    "archive_read_support_format_rar5");
897 
898 	return ARCHIVE_OK;
899 }
900 
read_ahead(struct archive_read * a,size_t how_many,const uint8_t ** ptr)901 static int read_ahead(struct archive_read* a, size_t how_many,
902     const uint8_t** ptr)
903 {
904 	ssize_t avail = -1;
905 	if(!ptr)
906 		return 0;
907 
908 	*ptr = __archive_read_ahead(a, how_many, &avail);
909 	if(*ptr == NULL) {
910 		return 0;
911 	}
912 
913 	return 1;
914 }
915 
consume(struct archive_read * a,int64_t how_many)916 static int consume(struct archive_read* a, int64_t how_many) {
917 	int ret;
918 
919 	ret = how_many == __archive_read_consume(a, how_many)
920 		? ARCHIVE_OK
921 		: ARCHIVE_FATAL;
922 
923 	return ret;
924 }
925 
926 /**
927  * Read a RAR5 variable sized numeric value. This value will be stored in
928  * `pvalue`. The `pvalue_len` argument points to a variable that will receive
929  * the byte count that was consumed in order to decode the `pvalue` value, plus
930  * one.
931  *
932  * pvalue_len is optional and can be NULL.
933  *
934  * NOTE: if `pvalue_len` is NOT NULL, the caller needs to manually consume
935  * the number of bytes that `pvalue_len` value contains. If the `pvalue_len`
936  * is NULL, this consuming operation is done automatically.
937  *
938  * Returns 1 if *pvalue was successfully read.
939  * Returns 0 if there was an error. In this case, *pvalue contains an
940  *           invalid value.
941  */
942 
read_var(struct archive_read * a,uint64_t * pvalue,uint64_t * pvalue_len)943 static int read_var(struct archive_read* a, uint64_t* pvalue,
944     uint64_t* pvalue_len)
945 {
946 	uint64_t result = 0;
947 	size_t shift, i;
948 	const uint8_t* p;
949 	uint8_t b;
950 
951 	/* We will read maximum of 8 bytes. We don't have to handle the
952 	 * situation to read the RAR5 variable-sized value stored at the end of
953 	 * the file, because such situation will never happen. */
954 	if(!read_ahead(a, 8, &p))
955 		return 0;
956 
957 	for(shift = 0, i = 0; i < 8; i++, shift += 7) {
958 		b = p[i];
959 
960 		/* Strip the MSB from the input byte and add the resulting
961 		 * number to the `result`. */
962 		result += (b & (uint64_t)0x7F) << shift;
963 
964 		/* MSB set to 1 means we need to continue decoding process.
965 		 * MSB set to 0 means we're done.
966 		 *
967 		 * This conditional checks for the second case. */
968 		if((b & 0x80) == 0) {
969 			if(pvalue) {
970 				*pvalue = result;
971 			}
972 
973 			/* If the caller has passed the `pvalue_len` pointer,
974 			 * store the number of consumed bytes in it and do NOT
975 			 * consume those bytes, since the caller has all the
976 			 * information it needs to perform */
977 			if(pvalue_len) {
978 				*pvalue_len = 1 + i;
979 			} else {
980 				/* If the caller did not provide the
981 				 * `pvalue_len` pointer, it will not have the
982 				 * possibility to advance the file pointer,
983 				 * because it will not know how many bytes it
984 				 * needs to consume. This is why we handle
985 				 * such situation here automatically. */
986 				if(ARCHIVE_OK != consume(a, 1 + i)) {
987 					return 0;
988 				}
989 			}
990 
991 			/* End of decoding process, return success. */
992 			return 1;
993 		}
994 	}
995 
996 	/* The decoded value takes the maximum number of 8 bytes.
997 	 * It's a maximum number of bytes, so end decoding process here
998 	 * even if the first bit of last byte is 1. */
999 	if(pvalue) {
1000 		*pvalue = result;
1001 	}
1002 
1003 	if(pvalue_len) {
1004 		*pvalue_len = 9;
1005 	} else {
1006 		if(ARCHIVE_OK != consume(a, 9)) {
1007 			return 0;
1008 		}
1009 	}
1010 
1011 	return 1;
1012 }
1013 
read_var_sized(struct archive_read * a,size_t * pvalue,size_t * pvalue_len)1014 static int read_var_sized(struct archive_read* a, size_t* pvalue,
1015     size_t* pvalue_len)
1016 {
1017 	uint64_t v;
1018 	uint64_t v_size = 0;
1019 
1020 	const int ret = pvalue_len ? read_var(a, &v, &v_size)
1021 				   : read_var(a, &v, NULL);
1022 
1023 	if(ret == 1 && pvalue) {
1024 		*pvalue = (size_t) v;
1025 	}
1026 
1027 	if(pvalue_len) {
1028 		/* Possible data truncation should be safe. */
1029 		*pvalue_len = (size_t) v_size;
1030 	}
1031 
1032 	return ret;
1033 }
1034 
read_bits_32(struct archive_read * a,struct rar5 * rar,const uint8_t * p,uint32_t * value)1035 static int read_bits_32(struct archive_read* a, struct rar5* rar,
1036 	const uint8_t* p, uint32_t* value)
1037 {
1038 	if(rar->bits.in_addr >= rar->cstate.cur_block_size) {
1039 		archive_set_error(&a->archive,
1040 			ARCHIVE_ERRNO_PROGRAMMER,
1041 			"Premature end of stream during extraction of data (#1)");
1042 		return ARCHIVE_FATAL;
1043 	}
1044 
1045 	uint32_t bits = ((uint32_t) p[rar->bits.in_addr]) << 24;
1046 	bits |= p[rar->bits.in_addr + 1] << 16;
1047 	bits |= p[rar->bits.in_addr + 2] << 8;
1048 	bits |= p[rar->bits.in_addr + 3];
1049 	bits <<= rar->bits.bit_addr;
1050 	bits |= p[rar->bits.in_addr + 4] >> (8 - rar->bits.bit_addr);
1051 	*value = bits;
1052 	return ARCHIVE_OK;
1053 }
1054 
read_bits_16(struct archive_read * a,struct rar5 * rar,const uint8_t * p,uint16_t * value)1055 static int read_bits_16(struct archive_read* a, struct rar5* rar,
1056 	const uint8_t* p, uint16_t* value)
1057 {
1058 	if(rar->bits.in_addr >= rar->cstate.cur_block_size) {
1059 		archive_set_error(&a->archive,
1060 			ARCHIVE_ERRNO_PROGRAMMER,
1061 			"Premature end of stream during extraction of data (#2)");
1062 		return ARCHIVE_FATAL;
1063 	}
1064 
1065 	int bits = (int) ((uint32_t) p[rar->bits.in_addr]) << 16;
1066 	bits |= (int) p[rar->bits.in_addr + 1] << 8;
1067 	bits |= (int) p[rar->bits.in_addr + 2];
1068 	bits >>= (8 - rar->bits.bit_addr);
1069 	*value = bits & 0xffff;
1070 	return ARCHIVE_OK;
1071 }
1072 
skip_bits(struct rar5 * rar,int bits)1073 static void skip_bits(struct rar5* rar, int bits) {
1074 	const int new_bits = rar->bits.bit_addr + bits;
1075 	rar->bits.in_addr += new_bits >> 3;
1076 	rar->bits.bit_addr = new_bits & 7;
1077 }
1078 
1079 /* n = up to 16 */
read_consume_bits(struct archive_read * a,struct rar5 * rar,const uint8_t * p,int n,int * value)1080 static int read_consume_bits(struct archive_read* a, struct rar5* rar,
1081 	const uint8_t* p, int n, int* value)
1082 {
1083 	uint16_t v;
1084 	int ret, num;
1085 
1086 	if(n == 0 || n > 16) {
1087 		/* This is a programmer error and should never happen
1088 		 * in runtime. */
1089 		return ARCHIVE_FATAL;
1090 	}
1091 
1092 	ret = read_bits_16(a, rar, p, &v);
1093 	if(ret != ARCHIVE_OK)
1094 		return ret;
1095 
1096 	num = (int) v;
1097 	num >>= 16 - n;
1098 
1099 	skip_bits(rar, n);
1100 
1101 	if(value)
1102 		*value = num;
1103 
1104 	return ARCHIVE_OK;
1105 }
1106 
read_u32(struct archive_read * a,uint32_t * pvalue)1107 static char read_u32(struct archive_read* a, uint32_t* pvalue) {
1108 	const uint8_t* p;
1109 	if(!read_ahead(a, 4, &p))
1110 		return 0;
1111 
1112 	*pvalue = archive_le32dec(p);
1113 	return ARCHIVE_OK == consume(a, 4);
1114 }
1115 
read_u64(struct archive_read * a,uint64_t * pvalue)1116 static char read_u64(struct archive_read* a, uint64_t* pvalue) {
1117 	const uint8_t* p;
1118 	if(!read_ahead(a, 8, &p))
1119 		return 0;
1120 
1121 	*pvalue = archive_le64dec(p);
1122 	return ARCHIVE_OK == consume(a, 8);
1123 }
1124 
bid_standard(struct archive_read * a)1125 static int bid_standard(struct archive_read* a) {
1126 	const uint8_t* p;
1127 	char signature[sizeof(rar5_signature_xor)];
1128 
1129 	rar5_signature(signature);
1130 
1131 	if(!read_ahead(a, sizeof(rar5_signature_xor), &p))
1132 		return -1;
1133 
1134 	if(!memcmp(signature, p, sizeof(rar5_signature_xor)))
1135 		return 30;
1136 
1137 	return -1;
1138 }
1139 
bid_sfx(struct archive_read * a)1140 static int bid_sfx(struct archive_read *a)
1141 {
1142 	const char *p;
1143 
1144 	if ((p = __archive_read_ahead(a, 7, NULL)) == NULL)
1145 		return -1;
1146 
1147 	if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) {
1148 		/* This is a PE file */
1149 		char signature[sizeof(rar5_signature_xor)];
1150 		ssize_t offset = 0x10000;
1151 		ssize_t window = 4096;
1152 		ssize_t bytes_avail;
1153 
1154 		rar5_signature(signature);
1155 
1156 		while (offset + window <= (1024 * 512)) {
1157 			const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail);
1158 			if (buff == NULL) {
1159 				/* Remaining bytes are less than window. */
1160 				window >>= 1;
1161 				if (window < 0x40)
1162 					return 0;
1163 				continue;
1164 			}
1165 			p = buff + offset;
1166 			while (p + 8 < buff + bytes_avail) {
1167 				if (memcmp(p, signature, sizeof(signature)) == 0)
1168 					return 30;
1169 				p += 0x10;
1170 			}
1171 			offset = p - buff;
1172 		}
1173 	}
1174 
1175 	return 0;
1176 }
1177 
rar5_bid(struct archive_read * a,int best_bid)1178 static int rar5_bid(struct archive_read* a, int best_bid) {
1179 	int my_bid;
1180 
1181 	if(best_bid > 30)
1182 		return -1;
1183 
1184 	my_bid = bid_standard(a);
1185 	if(my_bid > -1) {
1186 		return my_bid;
1187 	}
1188 	my_bid = bid_sfx(a);
1189 	if (my_bid > -1) {
1190 		return my_bid;
1191 	}
1192 
1193 	return -1;
1194 }
1195 
rar5_options(struct archive_read * a,const char * key,const char * val)1196 static int rar5_options(struct archive_read *a, const char *key,
1197     const char *val) {
1198 	(void) a;
1199 	(void) key;
1200 	(void) val;
1201 
1202 	/* No options supported in this version. Return the ARCHIVE_WARN code
1203 	 * to signal the options supervisor that the unpacker didn't handle
1204 	 * setting this option. */
1205 
1206 	return ARCHIVE_WARN;
1207 }
1208 
init_header(struct archive_read * a)1209 static void init_header(struct archive_read* a) {
1210 	a->archive.archive_format = ARCHIVE_FORMAT_RAR_V5;
1211 	a->archive.archive_format_name = "RAR5";
1212 }
1213 
init_window_mask(struct rar5 * rar)1214 static void init_window_mask(struct rar5* rar) {
1215 	if (rar->cstate.window_size)
1216 		rar->cstate.window_mask = rar->cstate.window_size - 1;
1217 	else
1218 		rar->cstate.window_mask = 0;
1219 }
1220 
1221 enum HEADER_FLAGS {
1222 	HFL_EXTRA_DATA = 0x0001,
1223 	HFL_DATA = 0x0002,
1224 	HFL_SKIP_IF_UNKNOWN = 0x0004,
1225 	HFL_SPLIT_BEFORE = 0x0008,
1226 	HFL_SPLIT_AFTER = 0x0010,
1227 	HFL_CHILD = 0x0020,
1228 	HFL_INHERITED = 0x0040
1229 };
1230 
process_main_locator_extra_block(struct archive_read * a,struct rar5 * rar)1231 static int process_main_locator_extra_block(struct archive_read* a,
1232     struct rar5* rar)
1233 {
1234 	uint64_t locator_flags;
1235 
1236 	enum LOCATOR_FLAGS {
1237 		QLIST = 0x01, RECOVERY = 0x02,
1238 	};
1239 
1240 	if(!read_var(a, &locator_flags, NULL)) {
1241 		return ARCHIVE_EOF;
1242 	}
1243 
1244 	if(locator_flags & QLIST) {
1245 		if(!read_var(a, &rar->qlist_offset, NULL)) {
1246 			return ARCHIVE_EOF;
1247 		}
1248 
1249 		/* qlist is not used */
1250 	}
1251 
1252 	if(locator_flags & RECOVERY) {
1253 		if(!read_var(a, &rar->rr_offset, NULL)) {
1254 			return ARCHIVE_EOF;
1255 		}
1256 
1257 		/* rr is not used */
1258 	}
1259 
1260 	return ARCHIVE_OK;
1261 }
1262 
parse_file_extra_hash(struct archive_read * a,struct rar5 * rar,int64_t * extra_data_size)1263 static int parse_file_extra_hash(struct archive_read* a, struct rar5* rar,
1264     int64_t* extra_data_size)
1265 {
1266 	size_t hash_type = 0;
1267 	size_t value_len;
1268 
1269 	enum HASH_TYPE {
1270 		BLAKE2sp = 0x00
1271 	};
1272 
1273 	if(!read_var_sized(a, &hash_type, &value_len))
1274 		return ARCHIVE_EOF;
1275 
1276 	*extra_data_size -= value_len;
1277 	if(ARCHIVE_OK != consume(a, value_len)) {
1278 		return ARCHIVE_EOF;
1279 	}
1280 
1281 	/* The file uses BLAKE2sp checksum algorithm instead of plain old
1282 	 * CRC32. */
1283 	if(hash_type == BLAKE2sp) {
1284 		const uint8_t* p;
1285 		const int hash_size = sizeof(rar->file.blake2sp);
1286 
1287 		if(!read_ahead(a, hash_size, &p))
1288 			return ARCHIVE_EOF;
1289 
1290 		rar->file.has_blake2 = 1;
1291 		memcpy(&rar->file.blake2sp, p, hash_size);
1292 
1293 		if(ARCHIVE_OK != consume(a, hash_size)) {
1294 			return ARCHIVE_EOF;
1295 		}
1296 
1297 		*extra_data_size -= hash_size;
1298 	} else {
1299 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1300 		    "Unsupported hash type (0x%jx)", (uintmax_t)hash_type);
1301 		return ARCHIVE_FATAL;
1302 	}
1303 
1304 	return ARCHIVE_OK;
1305 }
1306 
parse_htime_item(struct archive_read * a,char unix_time,int64_t * sec,uint32_t * nsec,int64_t * extra_data_size)1307 static int parse_htime_item(struct archive_read* a, char unix_time,
1308     int64_t* sec, uint32_t* nsec, int64_t* extra_data_size)
1309 {
1310 	if(unix_time) {
1311 		uint32_t time_val;
1312 		if(!read_u32(a, &time_val))
1313 			return ARCHIVE_EOF;
1314 
1315 		*extra_data_size -= 4;
1316 		*sec = (int64_t) time_val;
1317 	} else {
1318 		uint64_t windows_time;
1319 		if(!read_u64(a, &windows_time))
1320 			return ARCHIVE_EOF;
1321 
1322 		ntfs_to_unix(windows_time, sec, nsec);
1323 		*extra_data_size -= 8;
1324 	}
1325 
1326 	return ARCHIVE_OK;
1327 }
1328 
parse_file_extra_version(struct archive_read * a,struct archive_entry * e,int64_t * extra_data_size)1329 static int parse_file_extra_version(struct archive_read* a,
1330     struct archive_entry* e, int64_t* extra_data_size)
1331 {
1332 	size_t flags = 0;
1333 	size_t version = 0;
1334 	size_t value_len = 0;
1335 	struct archive_string version_string;
1336 	struct archive_string name_utf8_string;
1337 	const char* cur_filename;
1338 
1339 	/* Flags are ignored. */
1340 	if(!read_var_sized(a, &flags, &value_len))
1341 		return ARCHIVE_EOF;
1342 
1343 	*extra_data_size -= value_len;
1344 	if(ARCHIVE_OK != consume(a, value_len))
1345 		return ARCHIVE_EOF;
1346 
1347 	if(!read_var_sized(a, &version, &value_len))
1348 		return ARCHIVE_EOF;
1349 
1350 	*extra_data_size -= value_len;
1351 	if(ARCHIVE_OK != consume(a, value_len))
1352 		return ARCHIVE_EOF;
1353 
1354 	/* extra_data_size should be zero here. */
1355 
1356 	cur_filename = archive_entry_pathname_utf8(e);
1357 	if(cur_filename == NULL) {
1358 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1359 		    "Version entry without file name");
1360 		return ARCHIVE_FATAL;
1361 	}
1362 
1363 	archive_string_init(&version_string);
1364 	archive_string_init(&name_utf8_string);
1365 
1366 	/* Prepare a ;123 suffix for the filename, where '123' is the version
1367 	 * value of this file. */
1368 	archive_string_sprintf(&version_string, ";%zu", version);
1369 
1370 	/* Build the new filename. */
1371 	archive_strcat(&name_utf8_string, cur_filename);
1372 	archive_strcat(&name_utf8_string, version_string.s);
1373 
1374 	/* Apply the new filename into this file's context. */
1375 	archive_entry_update_pathname_utf8(e, name_utf8_string.s);
1376 
1377 	/* Free buffers. */
1378 	archive_string_free(&version_string);
1379 	archive_string_free(&name_utf8_string);
1380 	return ARCHIVE_OK;
1381 }
1382 
parse_file_extra_htime(struct archive_read * a,struct archive_entry * e,struct rar5 * rar,int64_t * extra_data_size)1383 static int parse_file_extra_htime(struct archive_read* a,
1384     struct archive_entry* e, struct rar5* rar, int64_t* extra_data_size)
1385 {
1386 	char unix_time, has_unix_ns, has_mtime, has_ctime, has_atime;
1387 	size_t flags = 0;
1388 	size_t value_len;
1389 
1390 	enum HTIME_FLAGS {
1391 		IS_UNIX       = 0x01,
1392 		HAS_MTIME     = 0x02,
1393 		HAS_CTIME     = 0x04,
1394 		HAS_ATIME     = 0x08,
1395 		HAS_UNIX_NS   = 0x10,
1396 	};
1397 
1398 	if(!read_var_sized(a, &flags, &value_len))
1399 		return ARCHIVE_EOF;
1400 
1401 	*extra_data_size -= value_len;
1402 	if(ARCHIVE_OK != consume(a, value_len)) {
1403 		return ARCHIVE_EOF;
1404 	}
1405 
1406 	unix_time = flags & IS_UNIX;
1407 	has_unix_ns = unix_time && (flags & HAS_UNIX_NS);
1408 	has_mtime = flags & HAS_MTIME;
1409 	has_atime = flags & HAS_ATIME;
1410 	has_ctime = flags & HAS_CTIME;
1411 	rar->file.e_atime_ns = rar->file.e_ctime_ns = rar->file.e_mtime_ns = 0;
1412 
1413 	if(has_mtime) {
1414 		parse_htime_item(a, unix_time, &rar->file.e_mtime,
1415 		    &rar->file.e_mtime_ns, extra_data_size);
1416 	}
1417 
1418 	if(has_ctime) {
1419 		parse_htime_item(a, unix_time, &rar->file.e_ctime,
1420 		    &rar->file.e_ctime_ns, extra_data_size);
1421 	}
1422 
1423 	if(has_atime) {
1424 		parse_htime_item(a, unix_time, &rar->file.e_atime,
1425 		    &rar->file.e_atime_ns, extra_data_size);
1426 	}
1427 
1428 	if(has_mtime && has_unix_ns) {
1429 		if(!read_u32(a, &rar->file.e_mtime_ns))
1430 			return ARCHIVE_EOF;
1431 
1432 		*extra_data_size -= 4;
1433 	}
1434 
1435 	if(has_ctime && has_unix_ns) {
1436 		if(!read_u32(a, &rar->file.e_ctime_ns))
1437 			return ARCHIVE_EOF;
1438 
1439 		*extra_data_size -= 4;
1440 	}
1441 
1442 	if(has_atime && has_unix_ns) {
1443 		if(!read_u32(a, &rar->file.e_atime_ns))
1444 			return ARCHIVE_EOF;
1445 
1446 		*extra_data_size -= 4;
1447 	}
1448 
1449 	/* The seconds and nanoseconds are either together, or separated in two
1450 	 * fields so we parse them, then set the archive_entry's times. */
1451 	if(has_mtime) {
1452 		archive_entry_set_mtime(e, rar->file.e_mtime, rar->file.e_mtime_ns);
1453 	}
1454 
1455 	if(has_ctime) {
1456 		archive_entry_set_ctime(e, rar->file.e_ctime, rar->file.e_ctime_ns);
1457 	}
1458 
1459 	if(has_atime) {
1460 		archive_entry_set_atime(e, rar->file.e_atime, rar->file.e_atime_ns);
1461 	}
1462 
1463 	return ARCHIVE_OK;
1464 }
1465 
parse_file_extra_redir(struct archive_read * a,struct archive_entry * e,struct rar5 * rar,int64_t * extra_data_size)1466 static int parse_file_extra_redir(struct archive_read* a,
1467     struct archive_entry* e, struct rar5* rar, int64_t* extra_data_size)
1468 {
1469 	uint64_t value_size = 0;
1470 	size_t target_size = 0;
1471 	char target_utf8_buf[MAX_NAME_IN_BYTES];
1472 	const uint8_t* p;
1473 
1474 	if(!read_var(a, &rar->file.redir_type, &value_size))
1475 		return ARCHIVE_EOF;
1476 	if(ARCHIVE_OK != consume(a, (int64_t)value_size))
1477 		return ARCHIVE_EOF;
1478 	*extra_data_size -= value_size;
1479 
1480 	if(!read_var(a, &rar->file.redir_flags, &value_size))
1481 		return ARCHIVE_EOF;
1482 	if(ARCHIVE_OK != consume(a, (int64_t)value_size))
1483 		return ARCHIVE_EOF;
1484 	*extra_data_size -= value_size;
1485 
1486 	if(!read_var_sized(a, &target_size, NULL))
1487 		return ARCHIVE_EOF;
1488 	*extra_data_size -= target_size + 1;
1489 
1490 	if(target_size > (MAX_NAME_IN_CHARS - 1)) {
1491 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1492 		    "Link target is too long");
1493 		return ARCHIVE_FATAL;
1494 	}
1495 
1496 	if(target_size == 0) {
1497 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1498 		    "No link target specified");
1499 		return ARCHIVE_FATAL;
1500 	}
1501 
1502 	if(!read_ahead(a, target_size, &p))
1503 		return ARCHIVE_EOF;
1504 
1505 	memcpy(target_utf8_buf, p, target_size);
1506 	target_utf8_buf[target_size] = 0;
1507 
1508 	if(ARCHIVE_OK != consume(a, (int64_t)target_size))
1509 		return ARCHIVE_EOF;
1510 
1511 	switch(rar->file.redir_type) {
1512 		case REDIR_TYPE_UNIXSYMLINK:
1513 		case REDIR_TYPE_WINSYMLINK:
1514 			archive_entry_set_filetype(e, AE_IFLNK);
1515 			archive_entry_update_symlink_utf8(e, target_utf8_buf);
1516 			if (rar->file.redir_flags & REDIR_SYMLINK_IS_DIR) {
1517 				archive_entry_set_symlink_type(e,
1518 					AE_SYMLINK_TYPE_DIRECTORY);
1519 			} else {
1520 				archive_entry_set_symlink_type(e,
1521 				AE_SYMLINK_TYPE_FILE);
1522 			}
1523 			break;
1524 
1525 		case REDIR_TYPE_HARDLINK:
1526 			archive_entry_set_filetype(e, AE_IFREG);
1527 			archive_entry_update_hardlink_utf8(e, target_utf8_buf);
1528 			break;
1529 
1530 		default:
1531 			/* Unknown redir type, skip it. */
1532 			break;
1533 	}
1534 	return ARCHIVE_OK;
1535 }
1536 
parse_file_extra_owner(struct archive_read * a,struct archive_entry * e,int64_t * extra_data_size)1537 static int parse_file_extra_owner(struct archive_read* a,
1538     struct archive_entry* e, int64_t* extra_data_size)
1539 {
1540 	uint64_t flags = 0;
1541 	uint64_t value_size = 0;
1542 	uint64_t id = 0;
1543 	size_t name_len = 0;
1544 	size_t name_size = 0;
1545 	char namebuf[OWNER_MAXNAMELEN];
1546 	const uint8_t* p;
1547 
1548 	if(!read_var(a, &flags, &value_size))
1549 		return ARCHIVE_EOF;
1550 	if(ARCHIVE_OK != consume(a, (int64_t)value_size))
1551 		return ARCHIVE_EOF;
1552 	*extra_data_size -= value_size;
1553 
1554 	if ((flags & OWNER_USER_NAME) != 0) {
1555 		if(!read_var_sized(a, &name_size, NULL))
1556 			return ARCHIVE_EOF;
1557 		*extra_data_size -= name_size + 1;
1558 
1559 		if(!read_ahead(a, name_size, &p))
1560 			return ARCHIVE_EOF;
1561 
1562 		if (name_size >= OWNER_MAXNAMELEN) {
1563 			name_len = OWNER_MAXNAMELEN - 1;
1564 		} else {
1565 			name_len = name_size;
1566 		}
1567 
1568 		memcpy(namebuf, p, name_len);
1569 		namebuf[name_len] = 0;
1570 		if(ARCHIVE_OK != consume(a, (int64_t)name_size))
1571 			return ARCHIVE_EOF;
1572 
1573 		archive_entry_set_uname(e, namebuf);
1574 	}
1575 	if ((flags & OWNER_GROUP_NAME) != 0) {
1576 		if(!read_var_sized(a, &name_size, NULL))
1577 			return ARCHIVE_EOF;
1578 		*extra_data_size -= name_size + 1;
1579 
1580 		if(!read_ahead(a, name_size, &p))
1581 			return ARCHIVE_EOF;
1582 
1583 		if (name_size >= OWNER_MAXNAMELEN) {
1584 			name_len = OWNER_MAXNAMELEN - 1;
1585 		} else {
1586 			name_len = name_size;
1587 		}
1588 
1589 		memcpy(namebuf, p, name_len);
1590 		namebuf[name_len] = 0;
1591 		if(ARCHIVE_OK != consume(a, (int64_t)name_size))
1592 			return ARCHIVE_EOF;
1593 
1594 		archive_entry_set_gname(e, namebuf);
1595 	}
1596 	if ((flags & OWNER_USER_UID) != 0) {
1597 		if(!read_var(a, &id, &value_size))
1598 			return ARCHIVE_EOF;
1599 		if(ARCHIVE_OK != consume(a, (int64_t)value_size))
1600 			return ARCHIVE_EOF;
1601 		*extra_data_size -= value_size;
1602 
1603 		archive_entry_set_uid(e, (la_int64_t)id);
1604 	}
1605 	if ((flags & OWNER_GROUP_GID) != 0) {
1606 		if(!read_var(a, &id, &value_size))
1607 			return ARCHIVE_EOF;
1608 		if(ARCHIVE_OK != consume(a, (int64_t)value_size))
1609 			return ARCHIVE_EOF;
1610 		*extra_data_size -= value_size;
1611 
1612 		archive_entry_set_gid(e, (la_int64_t)id);
1613 	}
1614 	return ARCHIVE_OK;
1615 }
1616 
process_head_file_extra(struct archive_read * a,struct archive_entry * e,struct rar5 * rar,int64_t extra_data_size)1617 static int process_head_file_extra(struct archive_read* a,
1618     struct archive_entry* e, struct rar5* rar, int64_t extra_data_size)
1619 {
1620 	uint64_t extra_field_size;
1621 	uint64_t extra_field_id = 0;
1622 	uint64_t var_size;
1623 
1624 	while(extra_data_size > 0) {
1625 		/* Make sure we won't fail if the file declares only unsupported
1626 		attributes. */
1627 		int ret = ARCHIVE_OK;
1628 
1629 		if(!read_var(a, &extra_field_size, &var_size))
1630 			return ARCHIVE_EOF;
1631 
1632 		extra_data_size -= var_size;
1633 		if(ARCHIVE_OK != consume(a, var_size)) {
1634 			return ARCHIVE_EOF;
1635 		}
1636 
1637 		if(!read_var(a, &extra_field_id, &var_size))
1638 			return ARCHIVE_EOF;
1639 
1640 		extra_field_size -= var_size;
1641 		extra_data_size -= var_size;
1642 		if(ARCHIVE_OK != consume(a, var_size)) {
1643 			return ARCHIVE_EOF;
1644 		}
1645 
1646 		switch(extra_field_id) {
1647 			case EX_HASH:
1648 				ret = parse_file_extra_hash(a, rar,
1649 				    &extra_data_size);
1650 				break;
1651 			case EX_HTIME:
1652 				ret = parse_file_extra_htime(a, e, rar,
1653 				    &extra_data_size);
1654 				break;
1655 			case EX_REDIR:
1656 				ret = parse_file_extra_redir(a, e, rar,
1657 				    &extra_data_size);
1658 				break;
1659 			case EX_UOWNER:
1660 				ret = parse_file_extra_owner(a, e,
1661 				    &extra_data_size);
1662 				break;
1663 			case EX_VERSION:
1664 				ret = parse_file_extra_version(a, e,
1665 				    &extra_data_size);
1666 				break;
1667 			case EX_CRYPT:
1668 				/* Mark the entry as encrypted */
1669 				archive_entry_set_is_data_encrypted(e, 1);
1670 				rar->has_encrypted_entries = 1;
1671 				rar->cstate.data_encrypted = 1;
1672 				/* fallthrough */
1673 			case EX_SUBDATA:
1674 				/* fallthrough */
1675 			default:
1676 				/* Skip unsupported entry. */
1677 				extra_data_size -= extra_field_size;
1678 				if (ARCHIVE_OK != consume(a, extra_field_size)) {
1679 					return ARCHIVE_EOF;
1680 				}
1681 
1682 				/* Don't fail on unsupported attribute -- we've handled it
1683 				   by skipping over it. */
1684 				ret = ARCHIVE_OK;
1685 		}
1686 
1687 		if (ret != ARCHIVE_OK) {
1688 			/* Forward any errors signalled by the attribute parsing
1689 			   functions. */
1690 			return ret;
1691 		}
1692 	}
1693 
1694 	if (extra_data_size != 0) {
1695 		/* We didn't skip everything, or we skipped too much; either way,
1696 		   there's an error in this parsing function. */
1697 
1698 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1699 				"unsupported structure of file header extra data");
1700 		return ARCHIVE_FATAL;
1701 	}
1702 
1703 	return ARCHIVE_OK;
1704 }
1705 
file_entry_sanity_checks(struct archive_read * a,size_t block_flags,uint8_t is_dir,uint64_t unpacked_size,size_t packed_size)1706 static int file_entry_sanity_checks(struct archive_read* a,
1707 	size_t block_flags, uint8_t is_dir, uint64_t unpacked_size,
1708 	size_t packed_size)
1709 {
1710 	if (is_dir) {
1711 		const int declares_data_size =
1712 			(int) (unpacked_size != 0 || packed_size != 0);
1713 
1714 		/* FILE entries for directories still declare HFL_DATA in block flags,
1715 		   even though attaching data to such blocks doesn't make much sense. */
1716 		if (declares_data_size) {
1717 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1718 				"directory entries cannot have any data");
1719 			return ARCHIVE_FATAL;
1720 		}
1721 	} else {
1722 		const int declares_hfl_data = (int) ((block_flags & HFL_DATA) != 0);
1723 		if (!declares_hfl_data) {
1724 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1725 					"no data found in file/service block");
1726 			return ARCHIVE_FATAL;
1727 		}
1728 	}
1729 
1730 	return ARCHIVE_OK;
1731 }
1732 
process_head_file(struct archive_read * a,struct rar5 * rar,struct archive_entry * entry,size_t block_flags)1733 static int process_head_file(struct archive_read* a, struct rar5* rar,
1734     struct archive_entry* entry, size_t block_flags)
1735 {
1736 	int64_t extra_data_size = 0;
1737 	size_t data_size = 0;
1738 	size_t file_flags = 0;
1739 	size_t file_attr = 0;
1740 	size_t compression_info = 0;
1741 	size_t host_os = 0;
1742 	size_t name_size = 0;
1743 	uint64_t unpacked_size, window_size;
1744 	uint32_t mtime = 0, crc = 0;
1745 	int c_method = 0, c_version = 0;
1746 	char name_utf8_buf[MAX_NAME_IN_BYTES];
1747 	const uint8_t* p;
1748 	int sanity_ret;
1749 
1750 	enum FILE_FLAGS {
1751 		DIRECTORY = 0x0001, UTIME = 0x0002, CRC32 = 0x0004,
1752 		UNKNOWN_UNPACKED_SIZE = 0x0008,
1753 	};
1754 
1755 	enum FILE_ATTRS {
1756 		ATTR_READONLY = 0x1, ATTR_HIDDEN = 0x2, ATTR_SYSTEM = 0x4,
1757 		ATTR_DIRECTORY = 0x10,
1758 	};
1759 
1760 	enum COMP_INFO_FLAGS {
1761 		SOLID = 0x0040,
1762 	};
1763 
1764 	enum HOST_OS {
1765 		HOST_WINDOWS = 0,
1766 		HOST_UNIX = 1,
1767 	};
1768 
1769 	archive_entry_clear(entry);
1770 
1771 	/* Do not reset file context if we're switching archives. */
1772 	if(!rar->cstate.switch_multivolume) {
1773 		reset_file_context(rar);
1774 	}
1775 
1776 	if(block_flags & HFL_EXTRA_DATA) {
1777 		uint64_t edata_size = 0;
1778 		if(!read_var(a, &edata_size, NULL))
1779 			return ARCHIVE_EOF;
1780 
1781 		/* Intentional type cast from unsigned to signed. */
1782 		extra_data_size = (int64_t) edata_size;
1783 	}
1784 
1785 	if(block_flags & HFL_DATA) {
1786 		if(!read_var_sized(a, &data_size, NULL))
1787 			return ARCHIVE_EOF;
1788 
1789 		rar->file.bytes_remaining = data_size;
1790 	} else {
1791 		rar->file.bytes_remaining = 0;
1792 	}
1793 
1794 	if(!read_var_sized(a, &file_flags, NULL))
1795 		return ARCHIVE_EOF;
1796 
1797 	if(!read_var(a, &unpacked_size, NULL))
1798 		return ARCHIVE_EOF;
1799 
1800 	if(file_flags & UNKNOWN_UNPACKED_SIZE) {
1801 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1802 		    "Files with unknown unpacked size are not supported");
1803 		return ARCHIVE_FATAL;
1804 	}
1805 
1806 	rar->file.dir = (uint8_t) ((file_flags & DIRECTORY) > 0);
1807 
1808 	sanity_ret = file_entry_sanity_checks(a, block_flags, rar->file.dir,
1809 		unpacked_size, data_size);
1810 
1811 	if (sanity_ret != ARCHIVE_OK) {
1812 		return sanity_ret;
1813 	}
1814 
1815 	if(!read_var_sized(a, &file_attr, NULL))
1816 		return ARCHIVE_EOF;
1817 
1818 	if(file_flags & UTIME) {
1819 		if(!read_u32(a, &mtime))
1820 			return ARCHIVE_EOF;
1821 	}
1822 
1823 	if(file_flags & CRC32) {
1824 		if(!read_u32(a, &crc))
1825 			return ARCHIVE_EOF;
1826 	}
1827 
1828 	if(!read_var_sized(a, &compression_info, NULL))
1829 		return ARCHIVE_EOF;
1830 
1831 	c_method = (int) (compression_info >> 7) & 0x7;
1832 	c_version = (int) (compression_info & 0x3f);
1833 
1834 	/* RAR5 seems to limit the dictionary size to 64MB. */
1835 	window_size = (rar->file.dir > 0) ?
1836 		0 :
1837 		g_unpack_window_size << ((compression_info >> 10) & 15);
1838 	rar->cstate.method = c_method;
1839 	rar->cstate.version = c_version + 50;
1840 	rar->file.solid = (compression_info & SOLID) > 0;
1841 
1842 	/* Archives which declare solid files without initializing the window
1843 	 * buffer first are invalid, unless previous data was encrypted, in
1844 	 * which case we may never have had the chance */
1845 
1846 	if(rar->file.solid > 0 && rar->cstate.data_encrypted == 0 &&
1847 	    rar->cstate.window_buf == NULL) {
1848 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1849 				  "Declared solid file, but no window buffer "
1850 				  "initialized yet.");
1851 		return ARCHIVE_FATAL;
1852 	}
1853 
1854 	/* Check if window_size is a sane value. Also, if the file is not
1855 	 * declared as a directory, disallow window_size == 0. */
1856 	if(window_size > (64 * 1024 * 1024) ||
1857 	    (rar->file.dir == 0 && window_size == 0))
1858 	{
1859 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1860 		    "Declared dictionary size is not supported.");
1861 		return ARCHIVE_FATAL;
1862 	}
1863 
1864 	if(rar->file.solid > 0) {
1865 		/* Re-check if current window size is the same as previous
1866 		 * window size (for solid files only). */
1867 		if(rar->file.solid_window_size > 0 &&
1868 		    rar->file.solid_window_size != (ssize_t) window_size)
1869 		{
1870 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1871 			    "Window size for this solid file doesn't match "
1872 			    "the window size used in previous solid file. ");
1873 			return ARCHIVE_FATAL;
1874 		}
1875 	}
1876 	else
1877 		rar->cstate.data_encrypted = 0; /* Reset for new buffer */
1878 
1879 	if(rar->cstate.window_size < (ssize_t) window_size &&
1880 	    rar->cstate.window_buf)
1881 	{
1882 		/* The `data_ready` stack contains pointers to the `window_buf` or
1883 		 * `filtered_buf` buffers.  Since we're about to reallocate the first
1884 		 * buffer, some of those pointers could become invalid. Therefore, we
1885 		 * need to dispose of all entries from the stack before attempting the
1886 		 * realloc. */
1887 		clear_data_ready_stack(rar);
1888 
1889 		/* If window_buf has been allocated before, reallocate it, so
1890 		 * that its size will match new window_size. */
1891 
1892 		uint8_t* new_window_buf =
1893 			realloc(rar->cstate.window_buf, (size_t) window_size);
1894 
1895 		if(!new_window_buf) {
1896 			archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1897 				"Not enough memory when trying to realloc the window "
1898 				"buffer.");
1899 			return ARCHIVE_FATAL;
1900 		}
1901 
1902 		rar->cstate.window_buf = new_window_buf;
1903 	}
1904 
1905 	/* Values up to 64M should fit into ssize_t on every
1906 	 * architecture. */
1907 	rar->cstate.window_size = (ssize_t) window_size;
1908 
1909 	if(rar->file.solid > 0 && rar->file.solid_window_size == 0) {
1910 		/* Solid files have to have the same window_size across
1911 		   whole archive. Remember the window_size parameter
1912 		   for first solid file found. */
1913 		rar->file.solid_window_size = rar->cstate.window_size;
1914 	}
1915 
1916 	init_window_mask(rar);
1917 
1918 	rar->file.service = 0;
1919 
1920 	if(!read_var_sized(a, &host_os, NULL))
1921 		return ARCHIVE_EOF;
1922 
1923 	if(host_os == HOST_WINDOWS) {
1924 		/* Host OS is Windows */
1925 
1926 		__LA_MODE_T mode;
1927 
1928 		if(file_attr & ATTR_DIRECTORY) {
1929 			if (file_attr & ATTR_READONLY) {
1930 				mode = 0555 | AE_IFDIR;
1931 			} else {
1932 				mode = 0755 | AE_IFDIR;
1933 			}
1934 		} else {
1935 			if (file_attr & ATTR_READONLY) {
1936 				mode = 0444 | AE_IFREG;
1937 			} else {
1938 				mode = 0644 | AE_IFREG;
1939 			}
1940 		}
1941 
1942 		archive_entry_set_mode(entry, mode);
1943 
1944 		if (file_attr & (ATTR_READONLY | ATTR_HIDDEN | ATTR_SYSTEM)) {
1945 			char *fflags_text, *ptr;
1946 			/* allocate for ",rdonly,hidden,system" */
1947 			fflags_text = malloc(22 * sizeof(*fflags_text));
1948 			if (fflags_text != NULL) {
1949 				ptr = fflags_text;
1950 				if (file_attr & ATTR_READONLY) {
1951 					strcpy(ptr, ",rdonly");
1952 					ptr = ptr + 7;
1953 				}
1954 				if (file_attr & ATTR_HIDDEN) {
1955 					strcpy(ptr, ",hidden");
1956 					ptr = ptr + 7;
1957 				}
1958 				if (file_attr & ATTR_SYSTEM) {
1959 					strcpy(ptr, ",system");
1960 					ptr = ptr + 7;
1961 				}
1962 				if (ptr > fflags_text) {
1963 					archive_entry_copy_fflags_text(entry,
1964 					    fflags_text + 1);
1965 				}
1966 				free(fflags_text);
1967 			}
1968 		}
1969 	} else if(host_os == HOST_UNIX) {
1970 		/* Host OS is Unix */
1971 		archive_entry_set_mode(entry, (__LA_MODE_T) file_attr);
1972 	} else {
1973 		/* Unknown host OS */
1974 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1975 				"Unsupported Host OS: 0x%jx",
1976 				(uintmax_t)host_os);
1977 
1978 		return ARCHIVE_FATAL;
1979 	}
1980 
1981 	if(!read_var_sized(a, &name_size, NULL))
1982 		return ARCHIVE_EOF;
1983 
1984 	if(name_size > (MAX_NAME_IN_CHARS - 1)) {
1985 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1986 				"Filename is too long");
1987 
1988 		return ARCHIVE_FATAL;
1989 	}
1990 
1991 	if(name_size == 0) {
1992 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1993 				"No filename specified");
1994 
1995 		return ARCHIVE_FATAL;
1996 	}
1997 
1998 	if(!read_ahead(a, name_size, &p))
1999 		return ARCHIVE_EOF;
2000 
2001 	memcpy(name_utf8_buf, p, name_size);
2002 	name_utf8_buf[name_size] = 0;
2003 	if(ARCHIVE_OK != consume(a, name_size)) {
2004 		return ARCHIVE_EOF;
2005 	}
2006 
2007 	archive_entry_update_pathname_utf8(entry, name_utf8_buf);
2008 
2009 	if(extra_data_size > 0) {
2010 		int ret = process_head_file_extra(a, entry, rar,
2011 		    extra_data_size);
2012 
2013 		/*
2014 		 * TODO: rewrite or remove useless sanity check
2015 		 *       as extra_data_size is not passed as a pointer
2016 		 *
2017 		if(extra_data_size < 0) {
2018 			archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
2019 			    "File extra data size is not zero");
2020 			return ARCHIVE_FATAL;
2021 		}
2022 		 */
2023 
2024 		if(ret != ARCHIVE_OK)
2025 			return ret;
2026 	}
2027 
2028 	if((file_flags & UNKNOWN_UNPACKED_SIZE) == 0) {
2029 		rar->file.unpacked_size = (ssize_t) unpacked_size;
2030 		if(rar->file.redir_type == REDIR_TYPE_NONE)
2031 			archive_entry_set_size(entry, unpacked_size);
2032 	}
2033 
2034 	if(file_flags & UTIME) {
2035 		archive_entry_set_mtime(entry, (time_t) mtime, 0);
2036 	}
2037 
2038 	if(file_flags & CRC32) {
2039 		rar->file.stored_crc32 = crc;
2040 	}
2041 
2042 	if(!rar->cstate.switch_multivolume) {
2043 		/* Do not reinitialize unpacking state if we're switching
2044 		 * archives. */
2045 		rar->cstate.block_parsing_finished = 1;
2046 		rar->cstate.all_filters_applied = 1;
2047 		rar->cstate.initialized = 0;
2048 	}
2049 
2050 	if(rar->generic.split_before > 0) {
2051 		/* If now we're standing on a header that has a 'split before'
2052 		 * mark, it means we're standing on a 'continuation' file
2053 		 * header. Signal the caller that if it wants to move to
2054 		 * another file, it must call rar5_read_header() function
2055 		 * again. */
2056 
2057 		return ARCHIVE_RETRY;
2058 	} else {
2059 		return ARCHIVE_OK;
2060 	}
2061 }
2062 
process_head_service(struct archive_read * a,struct rar5 * rar,struct archive_entry * entry,size_t block_flags)2063 static int process_head_service(struct archive_read* a, struct rar5* rar,
2064     struct archive_entry* entry, size_t block_flags)
2065 {
2066 	/* Process this SERVICE block the same way as FILE blocks. */
2067 	int ret = process_head_file(a, rar, entry, block_flags);
2068 	if(ret != ARCHIVE_OK)
2069 		return ret;
2070 
2071 	rar->file.service = 1;
2072 
2073 	/* But skip the data part automatically. It's no use for the user
2074 	 * anyway.  It contains only service data, not even needed to
2075 	 * properly unpack the file. */
2076 	ret = rar5_read_data_skip(a);
2077 	if(ret != ARCHIVE_OK)
2078 		return ret;
2079 
2080 	/* After skipping, try parsing another block automatically. */
2081 	return ARCHIVE_RETRY;
2082 }
2083 
process_head_main(struct archive_read * a,struct rar5 * rar,struct archive_entry * entry,size_t block_flags)2084 static int process_head_main(struct archive_read* a, struct rar5* rar,
2085     struct archive_entry* entry, size_t block_flags)
2086 {
2087 	int ret;
2088 	uint64_t extra_data_size = 0;
2089 	size_t extra_field_size = 0;
2090 	size_t extra_field_id = 0;
2091 	size_t archive_flags = 0;
2092 
2093 	enum MAIN_FLAGS {
2094 		VOLUME = 0x0001,         /* multi-volume archive */
2095 		VOLUME_NUMBER = 0x0002,  /* volume number, first vol doesn't
2096 					  * have it */
2097 		SOLID = 0x0004,          /* solid archive */
2098 		PROTECT = 0x0008,        /* contains Recovery info */
2099 		LOCK = 0x0010,           /* readonly flag, not used */
2100 	};
2101 
2102 	enum MAIN_EXTRA {
2103 		// Just one attribute here.
2104 		LOCATOR = 0x01,
2105 	};
2106 
2107 	(void) entry;
2108 
2109 	if(block_flags & HFL_EXTRA_DATA) {
2110 		if(!read_var(a, &extra_data_size, NULL))
2111 			return ARCHIVE_EOF;
2112 	} else {
2113 		extra_data_size = 0;
2114 	}
2115 
2116 	if(!read_var_sized(a, &archive_flags, NULL)) {
2117 		return ARCHIVE_EOF;
2118 	}
2119 
2120 	rar->main.volume = (archive_flags & VOLUME) > 0;
2121 	rar->main.solid = (archive_flags & SOLID) > 0;
2122 
2123 	if(archive_flags & VOLUME_NUMBER) {
2124 		size_t v = 0;
2125 		if(!read_var_sized(a, &v, NULL)) {
2126 			return ARCHIVE_EOF;
2127 		}
2128 
2129 		if (v > UINT_MAX) {
2130 			archive_set_error(&a->archive,
2131 			    ARCHIVE_ERRNO_FILE_FORMAT,
2132 			    "Invalid volume number");
2133 			return ARCHIVE_FATAL;
2134 		}
2135 
2136 		rar->main.vol_no = (unsigned int) v;
2137 	} else {
2138 		rar->main.vol_no = 0;
2139 	}
2140 
2141 	if(rar->vol.expected_vol_no > 0 &&
2142 		rar->main.vol_no != rar->vol.expected_vol_no)
2143 	{
2144 		/* Returning EOF instead of FATAL because of strange
2145 		 * libarchive behavior. When opening multiple files via
2146 		 * archive_read_open_filenames(), after reading up the whole
2147 		 * last file, the __archive_read_ahead function wraps up to
2148 		 * the first archive instead of returning EOF. */
2149 		return ARCHIVE_EOF;
2150 	}
2151 
2152 	if(extra_data_size == 0) {
2153 		/* Early return. */
2154 		return ARCHIVE_OK;
2155 	}
2156 
2157 	if(!read_var_sized(a, &extra_field_size, NULL)) {
2158 		return ARCHIVE_EOF;
2159 	}
2160 
2161 	if(!read_var_sized(a, &extra_field_id, NULL)) {
2162 		return ARCHIVE_EOF;
2163 	}
2164 
2165 	if(extra_field_size == 0) {
2166 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2167 		    "Invalid extra field size");
2168 		return ARCHIVE_FATAL;
2169 	}
2170 
2171 	switch(extra_field_id) {
2172 		case LOCATOR:
2173 			ret = process_main_locator_extra_block(a, rar);
2174 			if(ret != ARCHIVE_OK) {
2175 				/* Error while parsing main locator extra
2176 				 * block. */
2177 				return ret;
2178 			}
2179 
2180 			break;
2181 		default:
2182 			archive_set_error(&a->archive,
2183 			    ARCHIVE_ERRNO_FILE_FORMAT,
2184 			    "Unsupported extra type (0x%jx)",
2185 			    (uintmax_t)extra_field_id);
2186 			return ARCHIVE_FATAL;
2187 	}
2188 
2189 	return ARCHIVE_OK;
2190 }
2191 
skip_unprocessed_bytes(struct archive_read * a)2192 static int skip_unprocessed_bytes(struct archive_read* a) {
2193 	struct rar5* rar = get_context(a);
2194 	int ret;
2195 
2196 	if(rar->file.bytes_remaining) {
2197 		/* Use different skipping method in block merging mode than in
2198 		 * normal mode. If merge mode is active, rar5_read_data_skip
2199 		 * can't be used, because it could allow recursive use of
2200 		 * merge_block() * function, and this function doesn't support
2201 		 * recursive use. */
2202 		if(rar->merge_mode) {
2203 			/* Discard whole merged block. This is valid in solid
2204 			 * mode as well, because the code will discard blocks
2205 			 * only if those blocks are safe to discard (i.e.
2206 			 * they're not FILE blocks).  */
2207 			ret = consume(a, rar->file.bytes_remaining);
2208 			if(ret != ARCHIVE_OK) {
2209 				return ret;
2210 			}
2211 			rar->file.bytes_remaining = 0;
2212 		} else {
2213 			/* If we're not in merge mode, use safe skipping code.
2214 			 * This will ensure we'll handle solid archives
2215 			 * properly. */
2216 			ret = rar5_read_data_skip(a);
2217 			if(ret != ARCHIVE_OK) {
2218 				return ret;
2219 			}
2220 		}
2221 	}
2222 
2223 	return ARCHIVE_OK;
2224 }
2225 
2226 static int scan_for_signature(struct archive_read* a);
2227 
2228 /* Base block processing function. A 'base block' is a RARv5 header block
2229  * that tells the reader what kind of data is stored inside the block.
2230  *
2231  * From the birds-eye view a RAR file looks file this:
2232  *
2233  * <magic><base_block_1><base_block_2>...<base_block_n>
2234  *
2235  * There are a few types of base blocks. Those types are specified inside
2236  * the 'switch' statement in this function. For example purposes, I'll write
2237  * how a standard RARv5 file could look like here:
2238  *
2239  * <magic><MAIN><FILE><FILE><FILE><SERVICE><ENDARC>
2240  *
2241  * The structure above could describe an archive file with 3 files in it,
2242  * one service "QuickOpen" block (that is ignored by this parser), and an
2243  * end of file base block marker.
2244  *
2245  * If the file is stored in multiple archive files ("multiarchive"), it might
2246  * look like this:
2247  *
2248  * .part01.rar: <magic><MAIN><FILE><ENDARC>
2249  * .part02.rar: <magic><MAIN><FILE><ENDARC>
2250  * .part03.rar: <magic><MAIN><FILE><ENDARC>
2251  *
2252  * This example could describe 3 RAR files that contain ONE archived file.
2253  * Or it could describe 3 RAR files that contain 3 different files. Or 3
2254  * RAR files than contain 2 files. It all depends what metadata is stored in
2255  * the headers of <FILE> blocks.
2256  *
2257  * Each <FILE> block contains info about its size, the name of the file it's
2258  * storing inside, and whether this FILE block is a continuation block of
2259  * previous archive ('split before'), and is this FILE block should be
2260  * continued in another archive ('split after'). By parsing the 'split before'
2261  * and 'split after' flags, we're able to tell if multiple <FILE> base blocks
2262  * are describing one file, or multiple files (with the same filename, for
2263  * example).
2264  *
2265  * One thing to note is that if we're parsing the first <FILE> block, and
2266  * we see 'split after' flag, then we need to jump over to another <FILE>
2267  * block to be able to decompress rest of the data. To do this, we need
2268  * to skip the <ENDARC> block, then switch to another file, then skip the
2269  * <magic> block, <MAIN> block, and then we're standing on the proper
2270  * <FILE> block.
2271  */
2272 
process_base_block(struct archive_read * a,struct archive_entry * entry)2273 static int process_base_block(struct archive_read* a,
2274     struct archive_entry* entry)
2275 {
2276 	const size_t SMALLEST_RAR5_BLOCK_SIZE = 3;
2277 
2278 	struct rar5* rar = get_context(a);
2279 	uint32_t hdr_crc, computed_crc;
2280 	size_t raw_hdr_size = 0, hdr_size_len, hdr_size;
2281 	size_t header_id = 0;
2282 	size_t header_flags = 0;
2283 	const uint8_t* p;
2284 	int ret;
2285 
2286 	enum HEADER_TYPE {
2287 		HEAD_MARK    = 0x00, HEAD_MAIN  = 0x01, HEAD_FILE   = 0x02,
2288 		HEAD_SERVICE = 0x03, HEAD_CRYPT = 0x04, HEAD_ENDARC = 0x05,
2289 		HEAD_UNKNOWN = 0xff,
2290 	};
2291 
2292 	/* Skip any unprocessed data for this file. */
2293 	ret = skip_unprocessed_bytes(a);
2294 	if(ret != ARCHIVE_OK)
2295 		return ret;
2296 
2297 	/* Read the expected CRC32 checksum. */
2298 	if(!read_u32(a, &hdr_crc)) {
2299 		return ARCHIVE_EOF;
2300 	}
2301 
2302 	/* Read header size. */
2303 	if(!read_var_sized(a, &raw_hdr_size, &hdr_size_len)) {
2304 		return ARCHIVE_EOF;
2305 	}
2306 
2307 	hdr_size = raw_hdr_size + hdr_size_len;
2308 
2309 	/* Sanity check, maximum header size for RAR5 is 2MB. */
2310 	if(hdr_size > (2 * 1024 * 1024)) {
2311 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2312 		    "Base block header is too large");
2313 
2314 		return ARCHIVE_FATAL;
2315 	}
2316 
2317 	/* Additional sanity checks to weed out invalid files. */
2318 	if(raw_hdr_size == 0 || hdr_size_len == 0 ||
2319 		hdr_size < SMALLEST_RAR5_BLOCK_SIZE)
2320 	{
2321 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2322 		    "Too small block encountered (%zu bytes)",
2323 		    raw_hdr_size);
2324 
2325 		return ARCHIVE_FATAL;
2326 	}
2327 
2328 	/* Read the whole header data into memory, maximum memory use here is
2329 	 * 2MB. */
2330 	if(!read_ahead(a, hdr_size, &p)) {
2331 		return ARCHIVE_EOF;
2332 	}
2333 
2334 	/* Verify the CRC32 of the header data. */
2335 	computed_crc = (uint32_t) crc32(0, p, (int) hdr_size);
2336 	if(computed_crc != hdr_crc) {
2337 #ifndef DONT_FAIL_ON_CRC_ERROR
2338 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2339 		    "Header CRC error");
2340 
2341 		return ARCHIVE_FATAL;
2342 #endif
2343 	}
2344 
2345 	/* If the checksum is OK, we proceed with parsing. */
2346 	if(ARCHIVE_OK != consume(a, hdr_size_len)) {
2347 		return ARCHIVE_EOF;
2348 	}
2349 
2350 	if(!read_var_sized(a, &header_id, NULL))
2351 		return ARCHIVE_EOF;
2352 
2353 	if(!read_var_sized(a, &header_flags, NULL))
2354 		return ARCHIVE_EOF;
2355 
2356 	rar->generic.split_after = (header_flags & HFL_SPLIT_AFTER) > 0;
2357 	rar->generic.split_before = (header_flags & HFL_SPLIT_BEFORE) > 0;
2358 	rar->generic.size = (int)hdr_size;
2359 	rar->generic.last_header_id = (int)header_id;
2360 	rar->main.endarc = 0;
2361 
2362 	/* Those are possible header ids in RARv5. */
2363 	switch(header_id) {
2364 		case HEAD_MAIN:
2365 			ret = process_head_main(a, rar, entry, header_flags);
2366 
2367 			/* Main header doesn't have any files in it, so it's
2368 			 * pointless to return to the caller. Retry to next
2369 			 * header, which should be HEAD_FILE/HEAD_SERVICE. */
2370 			if(ret == ARCHIVE_OK)
2371 				return ARCHIVE_RETRY;
2372 
2373 			return ret;
2374 		case HEAD_SERVICE:
2375 			ret = process_head_service(a, rar, entry, header_flags);
2376 			return ret;
2377 		case HEAD_FILE:
2378 			ret = process_head_file(a, rar, entry, header_flags);
2379 			return ret;
2380 		case HEAD_CRYPT:
2381 			archive_entry_set_is_metadata_encrypted(entry, 1);
2382 			archive_entry_set_is_data_encrypted(entry, 1);
2383 			rar->has_encrypted_entries = 1;
2384 			rar->headers_are_encrypted = 1;
2385 			archive_set_error(&a->archive,
2386 			    ARCHIVE_ERRNO_FILE_FORMAT,
2387 			    "Encryption is not supported");
2388 			return ARCHIVE_FATAL;
2389 		case HEAD_ENDARC:
2390 			rar->main.endarc = 1;
2391 
2392 			/* After encountering an end of file marker, we need
2393 			 * to take into consideration if this archive is
2394 			 * continued in another file (i.e. is it part01.rar:
2395 			 * is there a part02.rar?) */
2396 			if(rar->main.volume) {
2397 				/* In case there is part02.rar, position the
2398 				 * read pointer in a proper place, so we can
2399 				 * resume parsing. */
2400 				ret = scan_for_signature(a);
2401 				if(ret == ARCHIVE_FATAL) {
2402 					return ARCHIVE_EOF;
2403 				} else {
2404 					if(rar->vol.expected_vol_no ==
2405 					    UINT_MAX) {
2406 						archive_set_error(&a->archive,
2407 						    ARCHIVE_ERRNO_FILE_FORMAT,
2408 						    "Header error");
2409 							return ARCHIVE_FATAL;
2410 					}
2411 
2412 					rar->vol.expected_vol_no =
2413 					    rar->main.vol_no + 1;
2414 					return ARCHIVE_OK;
2415 				}
2416 			} else {
2417 				return ARCHIVE_EOF;
2418 			}
2419 		case HEAD_MARK:
2420 			return ARCHIVE_EOF;
2421 		default:
2422 			if((header_flags & HFL_SKIP_IF_UNKNOWN) == 0) {
2423 				archive_set_error(&a->archive,
2424 				    ARCHIVE_ERRNO_FILE_FORMAT,
2425 				    "Header type error");
2426 				return ARCHIVE_FATAL;
2427 			} else {
2428 				/* If the block is marked as 'skip if unknown',
2429 				 * do as the flag says: skip the block
2430 				 * instead on failing on it. */
2431 				return ARCHIVE_RETRY;
2432 			}
2433 	}
2434 
2435 #if !defined WIN32
2436 	// Not reached.
2437 	archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
2438 	    "Internal unpacker error");
2439 	return ARCHIVE_FATAL;
2440 #endif
2441 }
2442 
skip_base_block(struct archive_read * a)2443 static int skip_base_block(struct archive_read* a) {
2444 	int ret;
2445 	struct rar5* rar = get_context(a);
2446 
2447 	/* Create a new local archive_entry structure that will be operated on
2448 	 * by header reader; operations on this archive_entry will be discarded.
2449 	 */
2450 	struct archive_entry* entry = archive_entry_new();
2451 	ret = process_base_block(a, entry);
2452 
2453 	/* Discard operations on this archive_entry structure. */
2454 	archive_entry_free(entry);
2455 	if(ret == ARCHIVE_FATAL)
2456 		return ret;
2457 
2458 	if(rar->generic.last_header_id == 2 && rar->generic.split_before > 0)
2459 		return ARCHIVE_OK;
2460 
2461 	if(ret == ARCHIVE_OK)
2462 		return ARCHIVE_RETRY;
2463 	else
2464 		return ret;
2465 }
2466 
try_skip_sfx(struct archive_read * a)2467 static int try_skip_sfx(struct archive_read *a)
2468 {
2469 	const char *p;
2470 
2471 	if ((p = __archive_read_ahead(a, 7, NULL)) == NULL)
2472 		return ARCHIVE_EOF;
2473 
2474 	if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)
2475 	{
2476 		char signature[sizeof(rar5_signature_xor)];
2477 		const void *h;
2478 		const char *q;
2479 		size_t skip, total = 0;
2480 		ssize_t bytes, window = 4096;
2481 
2482 		rar5_signature(signature);
2483 
2484 		while (total + window <= (1024 * 512)) {
2485 			h = __archive_read_ahead(a, window, &bytes);
2486 			if (h == NULL) {
2487 				/* Remaining bytes are less than window. */
2488 				window >>= 1;
2489 				if (window < 0x40)
2490 					goto fatal;
2491 				continue;
2492 			}
2493 			if (bytes < 0x40)
2494 				goto fatal;
2495 			p = h;
2496 			q = p + bytes;
2497 
2498 			/*
2499 			 * Scan ahead until we find something that looks
2500 			 * like the RAR header.
2501 			 */
2502 			while (p + 8 < q) {
2503 				if (memcmp(p, signature, sizeof(signature)) == 0) {
2504 					skip = p - (const char *)h;
2505 					__archive_read_consume(a, skip);
2506 					return (ARCHIVE_OK);
2507 				}
2508 				p += 0x10;
2509 			}
2510 			skip = p - (const char *)h;
2511 			__archive_read_consume(a, skip);
2512 			total += skip;
2513 		}
2514 	}
2515 
2516 	return ARCHIVE_OK;
2517 fatal:
2518 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2519 			"Couldn't find out RAR header");
2520 	return (ARCHIVE_FATAL);
2521 }
2522 
rar5_read_header(struct archive_read * a,struct archive_entry * entry)2523 static int rar5_read_header(struct archive_read *a,
2524     struct archive_entry *entry)
2525 {
2526 	struct rar5* rar = get_context(a);
2527 	int ret;
2528 
2529 	/*
2530 	 * It should be sufficient to call archive_read_next_header() for
2531 	 * a reader to determine if an entry is encrypted or not.
2532 	 */
2533 	if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2534 		rar->has_encrypted_entries = 0;
2535 	}
2536 
2537 	if(rar->header_initialized == 0) {
2538 		init_header(a);
2539 		if ((ret = try_skip_sfx(a)) < ARCHIVE_WARN)
2540 			return ret;
2541 		rar->header_initialized = 1;
2542 	}
2543 
2544 	if(rar->skipped_magic == 0) {
2545 		if(ARCHIVE_OK != consume(a, sizeof(rar5_signature_xor))) {
2546 			return ARCHIVE_EOF;
2547 		}
2548 
2549 		rar->skipped_magic = 1;
2550 	}
2551 
2552 	do {
2553 		ret = process_base_block(a, entry);
2554 	} while(ret == ARCHIVE_RETRY ||
2555 			(rar->main.endarc > 0 && ret == ARCHIVE_OK));
2556 
2557 	return ret;
2558 }
2559 
init_unpack(struct rar5 * rar)2560 static void init_unpack(struct rar5* rar) {
2561 	rar->file.calculated_crc32 = 0;
2562 	init_window_mask(rar);
2563 
2564 	free(rar->cstate.window_buf);
2565 	free(rar->cstate.filtered_buf);
2566 
2567 	if(rar->cstate.window_size > 0) {
2568 		rar->cstate.window_buf = calloc(1, rar->cstate.window_size);
2569 		rar->cstate.filtered_buf = calloc(1, rar->cstate.window_size);
2570 	} else {
2571 		rar->cstate.window_buf = NULL;
2572 		rar->cstate.filtered_buf = NULL;
2573 	}
2574 
2575 	clear_data_ready_stack(rar);
2576 
2577 	rar->cstate.write_ptr = 0;
2578 	rar->cstate.last_write_ptr = 0;
2579 
2580 	memset(&rar->cstate.bd, 0, sizeof(rar->cstate.bd));
2581 	memset(&rar->cstate.ld, 0, sizeof(rar->cstate.ld));
2582 	memset(&rar->cstate.dd, 0, sizeof(rar->cstate.dd));
2583 	memset(&rar->cstate.ldd, 0, sizeof(rar->cstate.ldd));
2584 	memset(&rar->cstate.rd, 0, sizeof(rar->cstate.rd));
2585 }
2586 
update_crc(struct rar5 * rar,const uint8_t * p,size_t to_read)2587 static void update_crc(struct rar5* rar, const uint8_t* p, size_t to_read) {
2588     int verify_crc;
2589 
2590 	if(rar->skip_mode) {
2591 #if defined CHECK_CRC_ON_SOLID_SKIP
2592 		verify_crc = 1;
2593 #else
2594 		verify_crc = 0;
2595 #endif
2596 	} else
2597 		verify_crc = 1;
2598 
2599 	if(verify_crc) {
2600 		/* Don't update CRC32 if the file doesn't have the
2601 		 * `stored_crc32` info filled in. */
2602 		if(rar->file.stored_crc32 > 0) {
2603 			rar->file.calculated_crc32 =
2604 				crc32(rar->file.calculated_crc32, p, (unsigned int)to_read);
2605 		}
2606 
2607 		/* Check if the file uses an optional BLAKE2sp checksum
2608 		 * algorithm. */
2609 		if(rar->file.has_blake2 > 0) {
2610 			/* Return value of the `update` function is always 0,
2611 			 * so we can explicitly ignore it here. */
2612 			(void) blake2sp_update(&rar->file.b2state, p, to_read);
2613 		}
2614 	}
2615 }
2616 
create_decode_tables(uint8_t * bit_length,struct decode_table * table,int size)2617 static int create_decode_tables(uint8_t* bit_length,
2618     struct decode_table* table, int size)
2619 {
2620 	int code, upper_limit = 0, i, lc[16];
2621 	uint32_t decode_pos_clone[rar5_countof(table->decode_pos)];
2622 	ssize_t cur_len, quick_data_size;
2623 
2624 	memset(&lc, 0, sizeof(lc));
2625 	memset(table->decode_num, 0, sizeof(table->decode_num));
2626 	table->size = size;
2627 	table->quick_bits = size == HUFF_NC ? 10 : 7;
2628 
2629 	for(i = 0; i < size; i++) {
2630 		lc[bit_length[i] & 15]++;
2631 	}
2632 
2633 	lc[0] = 0;
2634 	table->decode_pos[0] = 0;
2635 	table->decode_len[0] = 0;
2636 
2637 	for(i = 1; i < 16; i++) {
2638 		upper_limit += lc[i];
2639 
2640 		table->decode_len[i] = upper_limit << (16 - i);
2641 		table->decode_pos[i] = table->decode_pos[i - 1] + lc[i - 1];
2642 
2643 		upper_limit <<= 1;
2644 	}
2645 
2646 	memcpy(decode_pos_clone, table->decode_pos, sizeof(decode_pos_clone));
2647 
2648 	for(i = 0; i < size; i++) {
2649 		uint8_t clen = bit_length[i] & 15;
2650 		if(clen > 0) {
2651 			int last_pos = decode_pos_clone[clen];
2652 			table->decode_num[last_pos] = i;
2653 			decode_pos_clone[clen]++;
2654 		}
2655 	}
2656 
2657 	quick_data_size = (int64_t)1 << table->quick_bits;
2658 	cur_len = 1;
2659 	for(code = 0; code < quick_data_size; code++) {
2660 		int bit_field = code << (16 - table->quick_bits);
2661 		int dist, pos;
2662 
2663 		while(cur_len < rar5_countof(table->decode_len) &&
2664 				bit_field >= table->decode_len[cur_len]) {
2665 			cur_len++;
2666 		}
2667 
2668 		table->quick_len[code] = (uint8_t) cur_len;
2669 
2670 		dist = bit_field - table->decode_len[cur_len - 1];
2671 		dist >>= (16 - cur_len);
2672 
2673 		pos = table->decode_pos[cur_len & 15] + dist;
2674 		if(cur_len < rar5_countof(table->decode_pos) && pos < size) {
2675 			table->quick_num[code] = table->decode_num[pos];
2676 		} else {
2677 			table->quick_num[code] = 0;
2678 		}
2679 	}
2680 
2681 	return ARCHIVE_OK;
2682 }
2683 
decode_number(struct archive_read * a,struct decode_table * table,const uint8_t * p,uint16_t * num)2684 static int decode_number(struct archive_read* a, struct decode_table* table,
2685     const uint8_t* p, uint16_t* num)
2686 {
2687 	int i, bits, dist, ret;
2688 	uint16_t bitfield;
2689 	uint32_t pos;
2690 	struct rar5* rar = get_context(a);
2691 
2692 	if(ARCHIVE_OK != (ret = read_bits_16(a, rar, p, &bitfield))) {
2693 		return ret;
2694 	}
2695 
2696 	bitfield &= 0xfffe;
2697 
2698 	if(bitfield < table->decode_len[table->quick_bits]) {
2699 		int code = bitfield >> (16 - table->quick_bits);
2700 		skip_bits(rar, table->quick_len[code]);
2701 		*num = table->quick_num[code];
2702 		return ARCHIVE_OK;
2703 	}
2704 
2705 	bits = 15;
2706 
2707 	for(i = table->quick_bits + 1; i < 15; i++) {
2708 		if(bitfield < table->decode_len[i]) {
2709 			bits = i;
2710 			break;
2711 		}
2712 	}
2713 
2714 	skip_bits(rar, bits);
2715 
2716 	dist = bitfield - table->decode_len[bits - 1];
2717 	dist >>= (16 - bits);
2718 	pos = table->decode_pos[bits] + dist;
2719 
2720 	if(pos >= table->size)
2721 		pos = 0;
2722 
2723 	*num = table->decode_num[pos];
2724 	return ARCHIVE_OK;
2725 }
2726 
2727 /* Reads and parses Huffman tables from the beginning of the block. */
parse_tables(struct archive_read * a,struct rar5 * rar,const uint8_t * p)2728 static int parse_tables(struct archive_read* a, struct rar5* rar,
2729     const uint8_t* p)
2730 {
2731 	int ret, value, i, w, idx = 0;
2732 	uint8_t bit_length[HUFF_BC],
2733 		table[HUFF_TABLE_SIZE],
2734 		nibble_mask = 0xF0,
2735 		nibble_shift = 4;
2736 
2737 	enum { ESCAPE = 15 };
2738 
2739 	/* The data for table generation is compressed using a simple RLE-like
2740 	 * algorithm when storing zeroes, so we need to unpack it first. */
2741 	for(w = 0, i = 0; w < HUFF_BC;) {
2742 		if(i >= rar->cstate.cur_block_size) {
2743 			/* Truncated data, can't continue. */
2744 			archive_set_error(&a->archive,
2745 			    ARCHIVE_ERRNO_FILE_FORMAT,
2746 			    "Truncated data in huffman tables");
2747 			return ARCHIVE_FATAL;
2748 		}
2749 
2750 		value = (p[i] & nibble_mask) >> nibble_shift;
2751 
2752 		if(nibble_mask == 0x0F)
2753 			++i;
2754 
2755 		nibble_mask ^= 0xFF;
2756 		nibble_shift ^= 4;
2757 
2758 		/* Values smaller than 15 is data, so we write it directly.
2759 		 * Value 15 is a flag telling us that we need to unpack more
2760 		 * bytes. */
2761 		if(value == ESCAPE) {
2762 			value = (p[i] & nibble_mask) >> nibble_shift;
2763 			if(nibble_mask == 0x0F)
2764 				++i;
2765 			nibble_mask ^= 0xFF;
2766 			nibble_shift ^= 4;
2767 
2768 			if(value == 0) {
2769 				/* We sometimes need to write the actual value
2770 				 * of 15, so this case handles that. */
2771 				bit_length[w++] = ESCAPE;
2772 			} else {
2773 				int k;
2774 
2775 				/* Fill zeroes. */
2776 				for(k = 0; (k < value + 2) && (w < HUFF_BC);
2777 				    k++) {
2778 					bit_length[w++] = 0;
2779 				}
2780 			}
2781 		} else {
2782 			bit_length[w++] = value;
2783 		}
2784 	}
2785 
2786 	rar->bits.in_addr = i;
2787 	rar->bits.bit_addr = nibble_shift ^ 4;
2788 
2789 	ret = create_decode_tables(bit_length, &rar->cstate.bd, HUFF_BC);
2790 	if(ret != ARCHIVE_OK) {
2791 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2792 		    "Decoding huffman tables failed");
2793 		return ARCHIVE_FATAL;
2794 	}
2795 
2796 	for(i = 0; i < HUFF_TABLE_SIZE;) {
2797 		uint16_t num;
2798 
2799 		ret = decode_number(a, &rar->cstate.bd, p, &num);
2800 		if(ret != ARCHIVE_OK) {
2801 			archive_set_error(&a->archive,
2802 			    ARCHIVE_ERRNO_FILE_FORMAT,
2803 			    "Decoding huffman tables failed");
2804 			return ARCHIVE_FATAL;
2805 		}
2806 
2807 		if(num < 16) {
2808 			/* 0..15: store directly */
2809 			table[i] = (uint8_t) num;
2810 			i++;
2811 		} else if(num < 18) {
2812 			/* 16..17: repeat previous code */
2813 			uint16_t n;
2814 
2815 			if(ARCHIVE_OK != (ret = read_bits_16(a, rar, p, &n)))
2816 				return ret;
2817 
2818 			if(num == 16) {
2819 				n >>= 13;
2820 				n += 3;
2821 				skip_bits(rar, 3);
2822 			} else {
2823 				n >>= 9;
2824 				n += 11;
2825 				skip_bits(rar, 7);
2826 			}
2827 
2828 			if(i > 0) {
2829 				while(n-- > 0 && i < HUFF_TABLE_SIZE) {
2830 					table[i] = table[i - 1];
2831 					i++;
2832 				}
2833 			} else {
2834 				archive_set_error(&a->archive,
2835 				    ARCHIVE_ERRNO_FILE_FORMAT,
2836 				    "Unexpected error when decoding "
2837 				    "huffman tables");
2838 				return ARCHIVE_FATAL;
2839 			}
2840 		} else {
2841 			/* other codes: fill with zeroes `n` times */
2842 			uint16_t n;
2843 
2844 			if(ARCHIVE_OK != (ret = read_bits_16(a, rar, p, &n)))
2845 				return ret;
2846 
2847 			if(num == 18) {
2848 				n >>= 13;
2849 				n += 3;
2850 				skip_bits(rar, 3);
2851 			} else {
2852 				n >>= 9;
2853 				n += 11;
2854 				skip_bits(rar, 7);
2855 			}
2856 
2857 			while(n-- > 0 && i < HUFF_TABLE_SIZE)
2858 				table[i++] = 0;
2859 		}
2860 	}
2861 
2862 	ret = create_decode_tables(&table[idx], &rar->cstate.ld, HUFF_NC);
2863 	if(ret != ARCHIVE_OK) {
2864 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2865 		     "Failed to create literal table");
2866 		return ARCHIVE_FATAL;
2867 	}
2868 
2869 	idx += HUFF_NC;
2870 
2871 	ret = create_decode_tables(&table[idx], &rar->cstate.dd, HUFF_DC);
2872 	if(ret != ARCHIVE_OK) {
2873 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2874 		    "Failed to create distance table");
2875 		return ARCHIVE_FATAL;
2876 	}
2877 
2878 	idx += HUFF_DC;
2879 
2880 	ret = create_decode_tables(&table[idx], &rar->cstate.ldd, HUFF_LDC);
2881 	if(ret != ARCHIVE_OK) {
2882 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2883 		    "Failed to create lower bits of distances table");
2884 		return ARCHIVE_FATAL;
2885 	}
2886 
2887 	idx += HUFF_LDC;
2888 
2889 	ret = create_decode_tables(&table[idx], &rar->cstate.rd, HUFF_RC);
2890 	if(ret != ARCHIVE_OK) {
2891 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2892 		    "Failed to create repeating distances table");
2893 		return ARCHIVE_FATAL;
2894 	}
2895 
2896 	return ARCHIVE_OK;
2897 }
2898 
2899 /* Parses the block header, verifies its CRC byte, and saves the header
2900  * fields inside the `hdr` pointer. */
parse_block_header(struct archive_read * a,const uint8_t * p,ssize_t * block_size,struct compressed_block_header * hdr)2901 static int parse_block_header(struct archive_read* a, const uint8_t* p,
2902     ssize_t* block_size, struct compressed_block_header* hdr)
2903 {
2904 	uint8_t calculated_cksum;
2905 	memcpy(hdr, p, sizeof(struct compressed_block_header));
2906 
2907 	if(bf_byte_count(hdr) > 2) {
2908 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2909 		    "Unsupported block header size (was %d, max is 2)",
2910 		    bf_byte_count(hdr));
2911 		return ARCHIVE_FATAL;
2912 	}
2913 
2914 	/* This should probably use bit reader interface in order to be more
2915 	 * future-proof. */
2916 	*block_size = 0;
2917 	switch(bf_byte_count(hdr)) {
2918 		/* 1-byte block size */
2919 		case 0:
2920 			*block_size = *(const uint8_t*) &p[2];
2921 			break;
2922 
2923 		/* 2-byte block size */
2924 		case 1:
2925 			*block_size = archive_le16dec(&p[2]);
2926 			break;
2927 
2928 		/* 3-byte block size */
2929 		case 2:
2930 			*block_size = archive_le32dec(&p[2]);
2931 			*block_size &= 0x00FFFFFF;
2932 			break;
2933 
2934 		/* Other block sizes are not supported. This case is not
2935 		 * reached, because we have an 'if' guard before the switch
2936 		 * that makes sure of it. */
2937 		default:
2938 			return ARCHIVE_FATAL;
2939 	}
2940 
2941 	/* Verify the block header checksum. 0x5A is a magic value and is
2942 	 * always * constant. */
2943 	calculated_cksum = 0x5A
2944 	    ^ (uint8_t) hdr->block_flags_u8
2945 	    ^ (uint8_t) *block_size
2946 	    ^ (uint8_t) (*block_size >> 8)
2947 	    ^ (uint8_t) (*block_size >> 16);
2948 
2949 	if(calculated_cksum != hdr->block_cksum) {
2950 #ifndef DONT_FAIL_ON_CRC_ERROR
2951 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2952 		    "Block checksum error: got 0x%x, expected 0x%x",
2953 		    hdr->block_cksum, calculated_cksum);
2954 
2955 		return ARCHIVE_FATAL;
2956 #endif
2957 	}
2958 
2959 	return ARCHIVE_OK;
2960 }
2961 
2962 /* Convenience function used during filter processing. */
parse_filter_data(struct archive_read * a,struct rar5 * rar,const uint8_t * p,uint32_t * filter_data)2963 static int parse_filter_data(struct archive_read* a, struct rar5* rar,
2964 	const uint8_t* p, uint32_t* filter_data)
2965 {
2966 	int i, bytes, ret;
2967 	uint32_t data = 0;
2968 
2969 	if(ARCHIVE_OK != (ret = read_consume_bits(a, rar, p, 2, &bytes)))
2970 		return ret;
2971 
2972 	bytes++;
2973 
2974 	for(i = 0; i < bytes; i++) {
2975 		uint16_t byte;
2976 
2977 		if(ARCHIVE_OK != (ret = read_bits_16(a, rar, p, &byte))) {
2978 			return ret;
2979 		}
2980 
2981 		/* Cast to uint32_t will ensure the shift operation will not
2982 		 * produce undefined result. */
2983 		data += ((uint32_t) byte >> 8) << (i * 8);
2984 		skip_bits(rar, 8);
2985 	}
2986 
2987 	*filter_data = data;
2988 	return ARCHIVE_OK;
2989 }
2990 
2991 /* Function is used during sanity checking. */
is_valid_filter_block_start(struct rar5 * rar,uint32_t start)2992 static int is_valid_filter_block_start(struct rar5* rar,
2993     uint32_t start)
2994 {
2995 	const int64_t block_start = (ssize_t) start + rar->cstate.write_ptr;
2996 	const int64_t last_bs = rar->cstate.last_block_start;
2997 	const ssize_t last_bl = rar->cstate.last_block_length;
2998 
2999 	if(last_bs == 0 || last_bl == 0) {
3000 		/* We didn't have any filters yet, so accept this offset. */
3001 		return 1;
3002 	}
3003 
3004 	if(block_start >= last_bs + last_bl) {
3005 		/* Current offset is bigger than last block's end offset, so
3006 		 * accept current offset. */
3007 		return 1;
3008 	}
3009 
3010 	/* Any other case is not a normal situation and we should fail. */
3011 	return 0;
3012 }
3013 
3014 /* The function will create a new filter, read its parameters from the input
3015  * stream and add it to the filter collection. */
parse_filter(struct archive_read * ar,const uint8_t * p)3016 static int parse_filter(struct archive_read* ar, const uint8_t* p) {
3017 	uint32_t block_start, block_length;
3018 	uint16_t filter_type;
3019 	struct filter_info* filt = NULL;
3020 	struct rar5* rar = get_context(ar);
3021 	int ret;
3022 
3023 	/* Read the parameters from the input stream. */
3024 	if(ARCHIVE_OK != (ret = parse_filter_data(ar, rar, p, &block_start)))
3025 		return ret;
3026 
3027 	if(ARCHIVE_OK != (ret = parse_filter_data(ar, rar, p, &block_length)))
3028 		return ret;
3029 
3030 	if(ARCHIVE_OK != (ret = read_bits_16(ar, rar, p, &filter_type)))
3031 		return ret;
3032 
3033 	filter_type >>= 13;
3034 	skip_bits(rar, 3);
3035 
3036 	/* Perform some sanity checks on this filter parameters. Note that we
3037 	 * allow only DELTA, E8/E9 and ARM filters here, because rest of
3038 	 * filters are not used in RARv5. */
3039 
3040 	if(block_length < 4 ||
3041 	    block_length > 0x400000 ||
3042 	    filter_type > FILTER_ARM ||
3043 	    !is_valid_filter_block_start(rar, block_start))
3044 	{
3045 		archive_set_error(&ar->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3046 		    "Invalid filter encountered");
3047 		return ARCHIVE_FATAL;
3048 	}
3049 
3050 	/* Allocate a new filter. */
3051 	filt = add_new_filter(rar);
3052 	if(filt == NULL) {
3053 		archive_set_error(&ar->archive, ENOMEM,
3054 		    "Can't allocate memory for a filter descriptor.");
3055 		return ARCHIVE_FATAL;
3056 	}
3057 
3058 	filt->type = filter_type;
3059 	filt->block_start = rar->cstate.write_ptr + block_start;
3060 	filt->block_length = block_length;
3061 
3062 	rar->cstate.last_block_start = filt->block_start;
3063 	rar->cstate.last_block_length = filt->block_length;
3064 
3065 	/* Read some more data in case this is a DELTA filter. Other filter
3066 	 * types don't require any additional data over what was already
3067 	 * read. */
3068 	if(filter_type == FILTER_DELTA) {
3069 		int channels;
3070 
3071 		if(ARCHIVE_OK != (ret = read_consume_bits(ar, rar, p, 5, &channels)))
3072 			return ret;
3073 
3074 		filt->channels = channels + 1;
3075 	}
3076 
3077 	return ARCHIVE_OK;
3078 }
3079 
decode_code_length(struct archive_read * a,struct rar5 * rar,const uint8_t * p,uint16_t code)3080 static int decode_code_length(struct archive_read* a, struct rar5* rar,
3081 	const uint8_t* p, uint16_t code)
3082 {
3083 	int lbits, length = 2;
3084 
3085 	if(code < 8) {
3086 		lbits = 0;
3087 		length += code;
3088 	} else {
3089 		lbits = code / 4 - 1;
3090 		length += (4 | (code & 3)) << lbits;
3091 	}
3092 
3093 	if(lbits > 0) {
3094 		int add;
3095 
3096 		if(ARCHIVE_OK != read_consume_bits(a, rar, p, lbits, &add))
3097 			return -1;
3098 
3099 		length += add;
3100 	}
3101 
3102 	return length;
3103 }
3104 
copy_string(struct archive_read * a,int len,int dist)3105 static int copy_string(struct archive_read* a, int len, int dist) {
3106 	struct rar5* rar = get_context(a);
3107 	const ssize_t cmask = rar->cstate.window_mask;
3108 	const uint64_t write_ptr = rar->cstate.write_ptr +
3109 	    rar->cstate.solid_offset;
3110 	int i;
3111 
3112 	if (rar->cstate.window_buf == NULL)
3113 		return ARCHIVE_FATAL;
3114 
3115 	/* The unpacker spends most of the time in this function. It would be
3116 	 * a good idea to introduce some optimizations here.
3117 	 *
3118 	 * Just remember that this loop treats buffers that overlap differently
3119 	 * than buffers that do not overlap. This is why a simple memcpy(3)
3120 	 * call will not be enough. */
3121 
3122 	for(i = 0; i < len; i++) {
3123 		const ssize_t write_idx = (write_ptr + i) & cmask;
3124 		const ssize_t read_idx = (write_ptr + i - dist) & cmask;
3125 		rar->cstate.window_buf[write_idx] =
3126 		    rar->cstate.window_buf[read_idx];
3127 	}
3128 
3129 	rar->cstate.write_ptr += len;
3130 	return ARCHIVE_OK;
3131 }
3132 
do_uncompress_block(struct archive_read * a,const uint8_t * p)3133 static int do_uncompress_block(struct archive_read* a, const uint8_t* p) {
3134 	struct rar5* rar = get_context(a);
3135 	uint16_t num;
3136 	int ret;
3137 
3138 	const uint64_t cmask = rar->cstate.window_mask;
3139 	const struct compressed_block_header* hdr = &rar->last_block_hdr;
3140 	const uint8_t bit_size = 1 + bf_bit_size(hdr);
3141 
3142 	while(1) {
3143 		if(rar->cstate.write_ptr - rar->cstate.last_write_ptr >
3144 		    (rar->cstate.window_size >> 1)) {
3145 			/* Don't allow growing data by more than half of the
3146 			 * window size at a time. In such case, break the loop;
3147 			 *  next call to this function will continue processing
3148 			 *  from this moment. */
3149 			break;
3150 		}
3151 
3152 		if(rar->bits.in_addr > rar->cstate.cur_block_size - 1 ||
3153 		    (rar->bits.in_addr == rar->cstate.cur_block_size - 1 &&
3154 		    rar->bits.bit_addr >= bit_size))
3155 		{
3156 			/* If the program counter is here, it means the
3157 			 * function has finished processing the block. */
3158 			rar->cstate.block_parsing_finished = 1;
3159 			break;
3160 		}
3161 
3162 		/* Decode the next literal. */
3163 		if(ARCHIVE_OK != decode_number(a, &rar->cstate.ld, p, &num)) {
3164 			return ARCHIVE_EOF;
3165 		}
3166 
3167 		/* Num holds a decompression literal, or 'command code'.
3168 		 *
3169 		 * - Values lower than 256 are just bytes. Those codes
3170 		 *   can be stored in the output buffer directly.
3171 		 *
3172 		 * - Code 256 defines a new filter, which is later used to
3173 		 *   transform the data block accordingly to the filter type.
3174 		 *   The data block needs to be fully uncompressed first.
3175 		 *
3176 		 * - Code bigger than 257 and smaller than 262 define
3177 		 *   a repetition pattern that should be copied from
3178 		 *   an already uncompressed chunk of data.
3179 		 */
3180 
3181 		if(num < 256) {
3182 			/* Directly store the byte. */
3183 			int64_t write_idx = rar->cstate.solid_offset +
3184 			    rar->cstate.write_ptr++;
3185 
3186 			rar->cstate.window_buf[write_idx & cmask] =
3187 			    (uint8_t) num;
3188 			continue;
3189 		} else if(num >= 262) {
3190 			uint16_t dist_slot;
3191 			int len = decode_code_length(a, rar, p, num - 262),
3192 				dbits,
3193 				dist = 1;
3194 
3195 			if(len == -1) {
3196 				archive_set_error(&a->archive,
3197 				    ARCHIVE_ERRNO_PROGRAMMER,
3198 				    "Failed to decode the code length");
3199 
3200 				return ARCHIVE_FATAL;
3201 			}
3202 
3203 			if(ARCHIVE_OK != decode_number(a, &rar->cstate.dd, p,
3204 			    &dist_slot))
3205 			{
3206 				archive_set_error(&a->archive,
3207 				    ARCHIVE_ERRNO_PROGRAMMER,
3208 				    "Failed to decode the distance slot");
3209 
3210 				return ARCHIVE_FATAL;
3211 			}
3212 
3213 			if(dist_slot < 4) {
3214 				dbits = 0;
3215 				dist += dist_slot;
3216 			} else {
3217 				dbits = dist_slot / 2 - 1;
3218 
3219 				/* Cast to uint32_t will make sure the shift
3220 				 * left operation won't produce undefined
3221 				 * result. Then, the uint32_t type will
3222 				 * be implicitly casted to int. */
3223 				dist += (uint32_t) (2 |
3224 				    (dist_slot & 1)) << dbits;
3225 			}
3226 
3227 			if(dbits > 0) {
3228 				if(dbits >= 4) {
3229 					uint32_t add = 0;
3230 					uint16_t low_dist;
3231 
3232 					if(dbits > 4) {
3233 						if(ARCHIVE_OK != (ret = read_bits_32(
3234 						    a, rar, p, &add))) {
3235 							/* Return EOF if we
3236 							 * can't read more
3237 							 * data. */
3238 							return ret;
3239 						}
3240 
3241 						skip_bits(rar, dbits - 4);
3242 						add = (add >> (
3243 						    36 - dbits)) << 4;
3244 						dist += add;
3245 					}
3246 
3247 					if(ARCHIVE_OK != decode_number(a,
3248 					    &rar->cstate.ldd, p, &low_dist))
3249 					{
3250 						archive_set_error(&a->archive,
3251 						    ARCHIVE_ERRNO_PROGRAMMER,
3252 						    "Failed to decode the "
3253 						    "distance slot");
3254 
3255 						return ARCHIVE_FATAL;
3256 					}
3257 
3258 					if(dist >= INT_MAX - low_dist - 1) {
3259 						/* This only happens in
3260 						 * invalid archives. */
3261 						archive_set_error(&a->archive,
3262 						    ARCHIVE_ERRNO_FILE_FORMAT,
3263 						    "Distance pointer "
3264 						    "overflow");
3265 						return ARCHIVE_FATAL;
3266 					}
3267 
3268 					dist += low_dist;
3269 				} else {
3270 					/* dbits is one of [0,1,2,3] */
3271 					int add;
3272 
3273 					if(ARCHIVE_OK != (ret = read_consume_bits(a, rar,
3274 					     p, dbits, &add))) {
3275 						/* Return EOF if we can't read
3276 						 * more data. */
3277 						return ret;
3278 					}
3279 
3280 					dist += add;
3281 				}
3282 			}
3283 
3284 			if(dist > 0x100) {
3285 				len++;
3286 
3287 				if(dist > 0x2000) {
3288 					len++;
3289 
3290 					if(dist > 0x40000) {
3291 						len++;
3292 					}
3293 				}
3294 			}
3295 
3296 			dist_cache_push(rar, dist);
3297 			rar->cstate.last_len = len;
3298 
3299 			if(ARCHIVE_OK != copy_string(a, len, dist))
3300 				return ARCHIVE_FATAL;
3301 
3302 			continue;
3303 		} else if(num == 256) {
3304 			/* Create a filter. */
3305 			ret = parse_filter(a, p);
3306 			if(ret != ARCHIVE_OK)
3307 				return ret;
3308 
3309 			continue;
3310 		} else if(num == 257) {
3311 			if(rar->cstate.last_len != 0) {
3312 				if(ARCHIVE_OK != copy_string(a,
3313 				    rar->cstate.last_len,
3314 				    rar->cstate.dist_cache[0]))
3315 				{
3316 					return ARCHIVE_FATAL;
3317 				}
3318 			}
3319 
3320 			continue;
3321 		} else {
3322 			/* num < 262 */
3323 			const int idx = num - 258;
3324 			const int dist = dist_cache_touch(rar, idx);
3325 
3326 			uint16_t len_slot;
3327 			int len;
3328 
3329 			if(ARCHIVE_OK != decode_number(a, &rar->cstate.rd, p,
3330 			    &len_slot)) {
3331 				return ARCHIVE_FATAL;
3332 			}
3333 
3334 			len = decode_code_length(a, rar, p, len_slot);
3335 			if (len == -1) {
3336 				return ARCHIVE_FATAL;
3337 			}
3338 
3339 			rar->cstate.last_len = len;
3340 
3341 			if(ARCHIVE_OK != copy_string(a, len, dist))
3342 				return ARCHIVE_FATAL;
3343 
3344 			continue;
3345 		}
3346 	}
3347 
3348 	return ARCHIVE_OK;
3349 }
3350 
3351 /* Binary search for the RARv5 signature. */
scan_for_signature(struct archive_read * a)3352 static int scan_for_signature(struct archive_read* a) {
3353 	const uint8_t* p;
3354 	const int chunk_size = 512;
3355 	ssize_t i;
3356 	char signature[sizeof(rar5_signature_xor)];
3357 
3358 	/* If we're here, it means we're on an 'unknown territory' data.
3359 	 * There's no indication what kind of data we're reading here.
3360 	 * It could be some text comment, any kind of binary data,
3361 	 * digital sign, dragons, etc.
3362 	 *
3363 	 * We want to find a valid RARv5 magic header inside this unknown
3364 	 * data. */
3365 
3366 	/* Is it possible in libarchive to just skip everything until the
3367 	 * end of the file? If so, it would be a better approach than the
3368 	 * current implementation of this function. */
3369 
3370 	rar5_signature(signature);
3371 
3372 	while(1) {
3373 		if(!read_ahead(a, chunk_size, &p))
3374 			return ARCHIVE_EOF;
3375 
3376 		for(i = 0; i < chunk_size - (int)sizeof(rar5_signature_xor);
3377 		    i++) {
3378 			if(memcmp(&p[i], signature,
3379 			    sizeof(rar5_signature_xor)) == 0) {
3380 				/* Consume the number of bytes we've used to
3381 				 * search for the signature, as well as the
3382 				 * number of bytes used by the signature
3383 				 * itself. After this we should be standing
3384 				 * on a valid base block header. */
3385 				(void) consume(a,
3386 				    i + sizeof(rar5_signature_xor));
3387 				return ARCHIVE_OK;
3388 			}
3389 		}
3390 
3391 		consume(a, chunk_size);
3392 	}
3393 
3394 	return ARCHIVE_FATAL;
3395 }
3396 
3397 /* This function will switch the multivolume archive file to another file,
3398  * i.e. from part03 to part 04. */
advance_multivolume(struct archive_read * a)3399 static int advance_multivolume(struct archive_read* a) {
3400 	int lret;
3401 	struct rar5* rar = get_context(a);
3402 
3403 	/* A small state machine that will skip unnecessary data, needed to
3404 	 * switch from one multivolume to another. Such skipping is needed if
3405 	 * we want to be an stream-oriented (instead of file-oriented)
3406 	 * unpacker.
3407 	 *
3408 	 * The state machine starts with `rar->main.endarc` == 0. It also
3409 	 * assumes that current stream pointer points to some base block
3410 	 * header.
3411 	 *
3412 	 * The `endarc` field is being set when the base block parsing
3413 	 * function encounters the 'end of archive' marker.
3414 	 */
3415 
3416 	while(1) {
3417 		if(rar->main.endarc == 1) {
3418 			int looping = 1;
3419 
3420 			rar->main.endarc = 0;
3421 
3422 			while(looping) {
3423 				lret = skip_base_block(a);
3424 				switch(lret) {
3425 					case ARCHIVE_RETRY:
3426 						/* Continue looping. */
3427 						break;
3428 					case ARCHIVE_OK:
3429 						/* Break loop. */
3430 						looping = 0;
3431 						break;
3432 					default:
3433 						/* Forward any errors to the
3434 						 * caller. */
3435 						return lret;
3436 				}
3437 			}
3438 
3439 			break;
3440 		} else {
3441 			/* Skip current base block. In order to properly skip
3442 			 * it, we really need to simply parse it and discard
3443 			 * the results. */
3444 
3445 			lret = skip_base_block(a);
3446 			if(lret == ARCHIVE_FATAL || lret == ARCHIVE_FAILED)
3447 				return lret;
3448 
3449 			/* The `skip_base_block` function tells us if we
3450 			 * should continue with skipping, or we should stop
3451 			 * skipping. We're trying to skip everything up to
3452 			 * a base FILE block. */
3453 
3454 			if(lret != ARCHIVE_RETRY) {
3455 				/* If there was an error during skipping, or we
3456 				 * have just skipped a FILE base block... */
3457 
3458 				if(rar->main.endarc == 0) {
3459 					return lret;
3460 				} else {
3461 					continue;
3462 				}
3463 			}
3464 		}
3465 	}
3466 
3467 	return ARCHIVE_OK;
3468 }
3469 
3470 /* Merges the partial block from the first multivolume archive file, and
3471  * partial block from the second multivolume archive file. The result is
3472  * a chunk of memory containing the whole block, and the stream pointer
3473  * is advanced to the next block in the second multivolume archive file. */
merge_block(struct archive_read * a,ssize_t block_size,const uint8_t ** p)3474 static int merge_block(struct archive_read* a, ssize_t block_size,
3475     const uint8_t** p)
3476 {
3477 	struct rar5* rar = get_context(a);
3478 	ssize_t cur_block_size, partial_offset = 0;
3479 	const uint8_t* lp;
3480 	int ret;
3481 
3482 	if(rar->merge_mode) {
3483 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
3484 		    "Recursive merge is not allowed");
3485 
3486 		return ARCHIVE_FATAL;
3487 	}
3488 
3489 	/* Set a flag that we're in the switching mode. */
3490 	rar->cstate.switch_multivolume = 1;
3491 
3492 	/* Reallocate the memory which will hold the whole block. */
3493 	if(rar->vol.push_buf)
3494 		free((void*) rar->vol.push_buf);
3495 
3496 	/* Increasing the allocation block by 8 is due to bit reading functions,
3497 	 * which are using additional 2 or 4 bytes. Allocating the block size
3498 	 * by exact value would make bit reader perform reads from invalid
3499 	 * memory block when reading the last byte from the buffer. */
3500 	rar->vol.push_buf = malloc(block_size + 8);
3501 	if(!rar->vol.push_buf) {
3502 		archive_set_error(&a->archive, ENOMEM,
3503 		    "Can't allocate memory for a merge block buffer.");
3504 		return ARCHIVE_FATAL;
3505 	}
3506 
3507 	/* Valgrind complains if the extension block for bit reader is not
3508 	 * initialized, so initialize it. */
3509 	memset(&rar->vol.push_buf[block_size], 0, 8);
3510 
3511 	/* A single block can span across multiple multivolume archive files,
3512 	 * so we use a loop here. This loop will consume enough multivolume
3513 	 * archive files until the whole block is read. */
3514 
3515 	while(1) {
3516 		/* Get the size of current block chunk in this multivolume
3517 		 * archive file and read it. */
3518 		cur_block_size = rar5_min(rar->file.bytes_remaining,
3519 		    block_size - partial_offset);
3520 
3521 		if(cur_block_size == 0) {
3522 			archive_set_error(&a->archive,
3523 			    ARCHIVE_ERRNO_FILE_FORMAT,
3524 			    "Encountered block size == 0 during block merge");
3525 			return ARCHIVE_FATAL;
3526 		}
3527 
3528 		if(!read_ahead(a, cur_block_size, &lp))
3529 			return ARCHIVE_EOF;
3530 
3531 		/* Sanity check; there should never be a situation where this
3532 		 * function reads more data than the block's size. */
3533 		if(partial_offset + cur_block_size > block_size) {
3534 			archive_set_error(&a->archive,
3535 			    ARCHIVE_ERRNO_PROGRAMMER,
3536 			    "Consumed too much data when merging blocks.");
3537 			return ARCHIVE_FATAL;
3538 		}
3539 
3540 		/* Merge previous block chunk with current block chunk,
3541 		 * or create first block chunk if this is our first
3542 		 * iteration. */
3543 		memcpy(&rar->vol.push_buf[partial_offset], lp, cur_block_size);
3544 
3545 		/* Advance the stream read pointer by this block chunk size. */
3546 		if(ARCHIVE_OK != consume(a, cur_block_size))
3547 			return ARCHIVE_EOF;
3548 
3549 		/* Update the pointers. `partial_offset` contains information
3550 		 * about the sum of merged block chunks. */
3551 		partial_offset += cur_block_size;
3552 		rar->file.bytes_remaining -= cur_block_size;
3553 
3554 		/* If `partial_offset` is the same as `block_size`, this means
3555 		 * we've merged all block chunks and we have a valid full
3556 		 * block. */
3557 		if(partial_offset == block_size) {
3558 			break;
3559 		}
3560 
3561 		/* If we don't have any bytes to read, this means we should
3562 		 * switch to another multivolume archive file. */
3563 		if(rar->file.bytes_remaining == 0) {
3564 			rar->merge_mode++;
3565 			ret = advance_multivolume(a);
3566 			rar->merge_mode--;
3567 			if(ret != ARCHIVE_OK) {
3568 				return ret;
3569 			}
3570 		}
3571 	}
3572 
3573 	*p = rar->vol.push_buf;
3574 
3575 	/* If we're here, we can resume unpacking by processing the block
3576 	 * pointed to by the `*p` memory pointer. */
3577 
3578 	return ARCHIVE_OK;
3579 }
3580 
process_block(struct archive_read * a)3581 static int process_block(struct archive_read* a) {
3582 	const uint8_t* p;
3583 	struct rar5* rar = get_context(a);
3584 	int ret;
3585 
3586 	/* If we don't have any data to be processed, this most probably means
3587 	 * we need to switch to the next volume. */
3588 	if(rar->main.volume && rar->file.bytes_remaining == 0) {
3589 		ret = advance_multivolume(a);
3590 		if(ret != ARCHIVE_OK)
3591 			return ret;
3592 	}
3593 
3594 	if(rar->cstate.block_parsing_finished) {
3595 		ssize_t block_size;
3596 		ssize_t to_skip;
3597 		ssize_t cur_block_size;
3598 
3599 		/* The header size won't be bigger than 6 bytes. */
3600 		if(!read_ahead(a, 6, &p)) {
3601 			/* Failed to prefetch data block header. */
3602 			return ARCHIVE_EOF;
3603 		}
3604 
3605 		/*
3606 		 * Read block_size by parsing block header. Validate the header
3607 		 * by calculating CRC byte stored inside the header. Size of
3608 		 * the header is not constant (block size can be stored either
3609 		 * in 1 or 2 bytes), that's why block size is left out from the
3610 		 * `compressed_block_header` structure and returned by
3611 		 * `parse_block_header` as the second argument. */
3612 
3613 		ret = parse_block_header(a, p, &block_size,
3614 		    &rar->last_block_hdr);
3615 		if(ret != ARCHIVE_OK) {
3616 			return ret;
3617 		}
3618 
3619 		/* Skip block header. Next data is huffman tables,
3620 		 * if present. */
3621 		to_skip = sizeof(struct compressed_block_header) +
3622 			bf_byte_count(&rar->last_block_hdr) + 1;
3623 
3624 		if(ARCHIVE_OK != consume(a, to_skip))
3625 			return ARCHIVE_EOF;
3626 
3627 		rar->file.bytes_remaining -= to_skip;
3628 
3629 		/* The block size gives information about the whole block size,
3630 		 * but the block could be stored in split form when using
3631 		 * multi-volume archives. In this case, the block size will be
3632 		 * bigger than the actual data stored in this file. Remaining
3633 		 * part of the data will be in another file. */
3634 
3635 		cur_block_size =
3636 			rar5_min(rar->file.bytes_remaining, block_size);
3637 
3638 		if(block_size > rar->file.bytes_remaining) {
3639 			/* If current blocks' size is bigger than our data
3640 			 * size, this means we have a multivolume archive.
3641 			 * In this case, skip all base headers until the end
3642 			 * of the file, proceed to next "partXXX.rar" volume,
3643 			 * find its signature, skip all headers up to the first
3644 			 * FILE base header, and continue from there.
3645 			 *
3646 			 * Note that `merge_block` will update the `rar`
3647 			 * context structure quite extensively. */
3648 
3649 			ret = merge_block(a, block_size, &p);
3650 			if(ret != ARCHIVE_OK) {
3651 				return ret;
3652 			}
3653 
3654 			cur_block_size = block_size;
3655 
3656 			/* Current stream pointer should be now directly
3657 			 * *after* the block that spanned through multiple
3658 			 * archive files. `p` pointer should have the data of
3659 			 * the *whole* block (merged from partial blocks
3660 			 * stored in multiple archives files). */
3661 		} else {
3662 			rar->cstate.switch_multivolume = 0;
3663 
3664 			/* Read the whole block size into memory. This can take
3665 			 * up to  8 megabytes of memory in theoretical cases.
3666 			 * Might be worth to optimize this and use a standard
3667 			 * chunk of 4kb's. */
3668 			if(!read_ahead(a, 4 + cur_block_size, &p)) {
3669 				/* Failed to prefetch block data. */
3670 				return ARCHIVE_EOF;
3671 			}
3672 		}
3673 
3674 		rar->cstate.block_buf = p;
3675 		rar->cstate.cur_block_size = cur_block_size;
3676 		rar->cstate.block_parsing_finished = 0;
3677 
3678 		rar->bits.in_addr = 0;
3679 		rar->bits.bit_addr = 0;
3680 
3681 		if(bf_is_table_present(&rar->last_block_hdr)) {
3682 			/* Load Huffman tables. */
3683 			ret = parse_tables(a, rar, p);
3684 			if(ret != ARCHIVE_OK) {
3685 				/* Error during decompression of Huffman
3686 				 * tables. */
3687 				return ret;
3688 			}
3689 		}
3690 	} else {
3691 		/* Block parsing not finished, reuse previous memory buffer. */
3692 		p = rar->cstate.block_buf;
3693 	}
3694 
3695 	/* Uncompress the block, or a part of it, depending on how many bytes
3696 	 * will be generated by uncompressing the block.
3697 	 *
3698 	 * In case too many bytes will be generated, calling this function
3699 	 * again will resume the uncompression operation. */
3700 	ret = do_uncompress_block(a, p);
3701 	if(ret != ARCHIVE_OK) {
3702 		return ret;
3703 	}
3704 
3705 	if(rar->cstate.block_parsing_finished &&
3706 	    rar->cstate.switch_multivolume == 0 &&
3707 	    rar->cstate.cur_block_size > 0)
3708 	{
3709 		/* If we're processing a normal block, consume the whole
3710 		 * block. We can do this because we've already read the whole
3711 		 * block to memory. */
3712 		if(ARCHIVE_OK != consume(a, rar->cstate.cur_block_size))
3713 			return ARCHIVE_FATAL;
3714 
3715 		rar->file.bytes_remaining -= rar->cstate.cur_block_size;
3716 	} else if(rar->cstate.switch_multivolume) {
3717 		/* Don't consume the block if we're doing multivolume
3718 		 * processing. The volume switching function will consume
3719 		 * the proper count of bytes instead. */
3720 		rar->cstate.switch_multivolume = 0;
3721 	}
3722 
3723 	return ARCHIVE_OK;
3724 }
3725 
3726 /* Pops the `buf`, `size` and `offset` from the "data ready" stack.
3727  *
3728  * Returns ARCHIVE_OK when those arguments can be used, ARCHIVE_RETRY
3729  * when there is no data on the stack. */
use_data(struct rar5 * rar,const void ** buf,size_t * size,int64_t * offset)3730 static int use_data(struct rar5* rar, const void** buf, size_t* size,
3731     int64_t* offset)
3732 {
3733 	int i;
3734 
3735 	for(i = 0; i < rar5_countof(rar->cstate.dready); i++) {
3736 		struct data_ready *d = &rar->cstate.dready[i];
3737 
3738 		if(d->used) {
3739 			if(buf)    *buf = d->buf;
3740 			if(size)   *size = d->size;
3741 			if(offset) *offset = d->offset;
3742 
3743 			d->used = 0;
3744 			return ARCHIVE_OK;
3745 		}
3746 	}
3747 
3748 	return ARCHIVE_RETRY;
3749 }
3750 
clear_data_ready_stack(struct rar5 * rar)3751 static void clear_data_ready_stack(struct rar5* rar) {
3752 	memset(&rar->cstate.dready, 0, sizeof(rar->cstate.dready));
3753 }
3754 
3755 /* Pushes the `buf`, `size` and `offset` arguments to the rar->cstate.dready
3756  * FIFO stack. Those values will be popped from this stack by the `use_data`
3757  * function. */
push_data_ready(struct archive_read * a,struct rar5 * rar,const uint8_t * buf,size_t size,int64_t offset)3758 static int push_data_ready(struct archive_read* a, struct rar5* rar,
3759     const uint8_t* buf, size_t size, int64_t offset)
3760 {
3761 	int i;
3762 
3763 	/* Don't push if we're in skip mode. This is needed because solid
3764 	 * streams need full processing even if we're skipping data. After
3765 	 * fully processing the stream, we need to discard the generated bytes,
3766 	 * because we're interested only in the side effect: building up the
3767 	 * internal window circular buffer. This window buffer will be used
3768 	 * later during unpacking of requested data. */
3769 	if(rar->skip_mode)
3770 		return ARCHIVE_OK;
3771 
3772 	/* Sanity check. */
3773 	if(offset != rar->file.last_offset + rar->file.last_size) {
3774 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
3775 		    "Sanity check error: output stream is not continuous");
3776 		return ARCHIVE_FATAL;
3777 	}
3778 
3779 	for(i = 0; i < rar5_countof(rar->cstate.dready); i++) {
3780 		struct data_ready* d = &rar->cstate.dready[i];
3781 		if(!d->used) {
3782 			d->used = 1;
3783 			d->buf = buf;
3784 			d->size = size;
3785 			d->offset = offset;
3786 
3787 			/* These fields are used only in sanity checking. */
3788 			rar->file.last_offset = offset;
3789 			rar->file.last_size = size;
3790 
3791 			/* Calculate the checksum of this new block before
3792 			 * submitting data to libarchive's engine. */
3793 			update_crc(rar, d->buf, d->size);
3794 
3795 			return ARCHIVE_OK;
3796 		}
3797 	}
3798 
3799 	/* Program counter will reach this code if the `rar->cstate.data_ready`
3800 	 * stack will be filled up so that no new entries will be allowed. The
3801 	 * code shouldn't allow such situation to occur. So we treat this case
3802 	 * as an internal error. */
3803 
3804 	archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
3805 	    "Error: premature end of data_ready stack");
3806 	return ARCHIVE_FATAL;
3807 }
3808 
3809 /* This function uncompresses the data that is stored in the <FILE> base
3810  * block.
3811  *
3812  * The FILE base block looks like this:
3813  *
3814  * <header><huffman tables><block_1><block_2>...<block_n>
3815  *
3816  * The <header> is a block header, that is parsed in parse_block_header().
3817  * It's a "compressed_block_header" structure, containing metadata needed
3818  * to know when we should stop looking for more <block_n> blocks.
3819  *
3820  * <huffman tables> contain data needed to set up the huffman tables, needed
3821  * for the actual decompression.
3822  *
3823  * Each <block_n> consists of series of literals:
3824  *
3825  * <literal><literal><literal>...<literal>
3826  *
3827  * Those literals generate the uncompression data. They operate on a circular
3828  * buffer, sometimes writing raw data into it, sometimes referencing
3829  * some previous data inside this buffer, and sometimes declaring a filter
3830  * that will need to be executed on the data stored in the circular buffer.
3831  * It all depends on the literal that is used.
3832  *
3833  * Sometimes blocks produce output data, sometimes they don't. For example, for
3834  * some huge files that use lots of filters, sometimes a block is filled with
3835  * only filter declaration literals. Such blocks won't produce any data in the
3836  * circular buffer.
3837  *
3838  * Sometimes blocks will produce 4 bytes of data, and sometimes 1 megabyte,
3839  * because a literal can reference previously decompressed data. For example,
3840  * there can be a literal that says: 'append a byte 0xFE here', and after
3841  * it another literal can say 'append 1 megabyte of data from circular buffer
3842  * offset 0x12345'. This is how RAR format handles compressing repeated
3843  * patterns.
3844  *
3845  * The RAR compressor creates those literals and the actual efficiency of
3846  * compression depends on what those literals are. The literals can also
3847  * be seen as a kind of a non-turing-complete virtual machine that simply
3848  * tells the decompressor what it should do.
3849  * */
3850 
do_uncompress_file(struct archive_read * a)3851 static int do_uncompress_file(struct archive_read* a) {
3852 	struct rar5* rar = get_context(a);
3853 	int ret;
3854 	int64_t max_end_pos;
3855 
3856 	if(!rar->cstate.initialized) {
3857 		/* Don't perform full context reinitialization if we're
3858 		 * processing a solid archive. */
3859 		if(!rar->main.solid || !rar->cstate.window_buf) {
3860 			init_unpack(rar);
3861 		}
3862 
3863 		rar->cstate.initialized = 1;
3864 	}
3865 
3866 	/* Don't allow extraction if window_size is invalid. */
3867 	if(rar->cstate.window_size == 0) {
3868 		archive_set_error(&a->archive,
3869 			ARCHIVE_ERRNO_FILE_FORMAT,
3870 			"Invalid window size declaration in this file");
3871 
3872 		/* This should never happen in valid files. */
3873 		return ARCHIVE_FATAL;
3874 	}
3875 
3876 	if(rar->cstate.all_filters_applied == 1) {
3877 		/* We use while(1) here, but standard case allows for just 1
3878 		 * iteration. The loop will iterate if process_block() didn't
3879 		 * generate any data at all. This can happen if the block
3880 		 * contains only filter definitions (this is common in big
3881 		 * files). */
3882 		while(1) {
3883 			ret = process_block(a);
3884 			if(ret == ARCHIVE_EOF || ret == ARCHIVE_FATAL)
3885 				return ret;
3886 
3887 			if(rar->cstate.last_write_ptr ==
3888 			    rar->cstate.write_ptr) {
3889 				/* The block didn't generate any new data,
3890 				 * so just process a new block if this one
3891 				 * wasn't the last block in the file. */
3892 				if (bf_is_last_block(&rar->last_block_hdr)) {
3893 					return ARCHIVE_EOF;
3894 				}
3895 
3896 				continue;
3897 			}
3898 
3899 			/* The block has generated some new data, so break
3900 			 * the loop. */
3901 			break;
3902 		}
3903 	}
3904 
3905 	/* Try to run filters. If filters won't be applied, it means that
3906 	 * insufficient data was generated. */
3907 	ret = apply_filters(a);
3908 	if(ret == ARCHIVE_RETRY) {
3909 		return ARCHIVE_OK;
3910 	} else if(ret == ARCHIVE_FATAL) {
3911 		return ARCHIVE_FATAL;
3912 	}
3913 
3914 	/* If apply_filters() will return ARCHIVE_OK, we can continue here. */
3915 
3916 	if(cdeque_size(&rar->cstate.filters) > 0) {
3917 		/* Check if we can write something before hitting first
3918 		 * filter. */
3919 		struct filter_info* flt;
3920 
3921 		/* Get the block_start offset from the first filter. */
3922 		if(CDE_OK != cdeque_front(&rar->cstate.filters,
3923 		    cdeque_filter_p(&flt)))
3924 		{
3925 			archive_set_error(&a->archive,
3926 			    ARCHIVE_ERRNO_PROGRAMMER,
3927 			    "Can't read first filter");
3928 			return ARCHIVE_FATAL;
3929 		}
3930 
3931 		max_end_pos = rar5_min(flt->block_start,
3932 		    rar->cstate.write_ptr);
3933 	} else {
3934 		/* There are no filters defined, or all filters were applied.
3935 		 * This means we can just store the data without any
3936 		 * postprocessing. */
3937 		max_end_pos = rar->cstate.write_ptr;
3938 	}
3939 
3940 	if(max_end_pos == rar->cstate.last_write_ptr) {
3941 		/* We can't write anything yet. The block uncompression
3942 		 * function did not generate enough data, and no filter can be
3943 		 * applied. At the same time we don't have any data that can be
3944 		 *  stored without filter postprocessing. This means we need to
3945 		 *  wait for more data to be generated, so we can apply the
3946 		 * filters.
3947 		 *
3948 		 * Signal the caller that we need more data to be able to do
3949 		 * anything.
3950 		 */
3951 		return ARCHIVE_RETRY;
3952 	} else {
3953 		/* We can write the data before hitting the first filter.
3954 		 * So let's do it. The push_window_data() function will
3955 		 * effectively return the selected data block to the user
3956 		 * application. */
3957 		push_window_data(a, rar, rar->cstate.last_write_ptr,
3958 		    max_end_pos);
3959 		rar->cstate.last_write_ptr = max_end_pos;
3960 	}
3961 
3962 	return ARCHIVE_OK;
3963 }
3964 
uncompress_file(struct archive_read * a)3965 static int uncompress_file(struct archive_read* a) {
3966 	int ret;
3967 
3968 	while(1) {
3969 		/* Sometimes the uncompression function will return a
3970 		 * 'retry' signal. If this will happen, we have to retry
3971 		 * the function. */
3972 		ret = do_uncompress_file(a);
3973 		if(ret != ARCHIVE_RETRY)
3974 			return ret;
3975 	}
3976 }
3977 
3978 
do_unstore_file(struct archive_read * a,struct rar5 * rar,const void ** buf,size_t * size,int64_t * offset)3979 static int do_unstore_file(struct archive_read* a,
3980     struct rar5* rar, const void** buf, size_t* size, int64_t* offset)
3981 {
3982 	size_t to_read;
3983 	const uint8_t* p;
3984 
3985 	if(rar->file.bytes_remaining == 0 && rar->main.volume > 0 &&
3986 	    rar->generic.split_after > 0)
3987 	{
3988 		int ret;
3989 
3990 		rar->cstate.switch_multivolume = 1;
3991 		ret = advance_multivolume(a);
3992 		rar->cstate.switch_multivolume = 0;
3993 
3994 		if(ret != ARCHIVE_OK) {
3995 			/* Failed to advance to next multivolume archive
3996 			 * file. */
3997 			return ret;
3998 		}
3999 	}
4000 
4001 	to_read = rar5_min(rar->file.bytes_remaining, 64 * 1024);
4002 	if(to_read == 0) {
4003 		return ARCHIVE_EOF;
4004 	}
4005 
4006 	if(!read_ahead(a, to_read, &p)) {
4007 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4008 		    "I/O error when unstoring file");
4009 		return ARCHIVE_FATAL;
4010 	}
4011 
4012 	if(ARCHIVE_OK != consume(a, to_read)) {
4013 		return ARCHIVE_EOF;
4014 	}
4015 
4016 	if(buf)    *buf = p;
4017 	if(size)   *size = to_read;
4018 	if(offset) *offset = rar->cstate.last_unstore_ptr;
4019 
4020 	rar->file.bytes_remaining -= to_read;
4021 	rar->cstate.last_unstore_ptr += to_read;
4022 
4023 	update_crc(rar, p, to_read);
4024 	return ARCHIVE_OK;
4025 }
4026 
do_unpack(struct archive_read * a,struct rar5 * rar,const void ** buf,size_t * size,int64_t * offset)4027 static int do_unpack(struct archive_read* a, struct rar5* rar,
4028     const void** buf, size_t* size, int64_t* offset)
4029 {
4030 	enum COMPRESSION_METHOD {
4031 		STORE = 0, FASTEST = 1, FAST = 2, NORMAL = 3, GOOD = 4,
4032 		BEST = 5
4033 	};
4034 
4035 	if(rar->file.service > 0) {
4036 		return do_unstore_file(a, rar, buf, size, offset);
4037 	} else {
4038 		switch(rar->cstate.method) {
4039 			case STORE:
4040 				return do_unstore_file(a, rar, buf, size,
4041 				    offset);
4042 			case FASTEST:
4043 				/* fallthrough */
4044 			case FAST:
4045 				/* fallthrough */
4046 			case NORMAL:
4047 				/* fallthrough */
4048 			case GOOD:
4049 				/* fallthrough */
4050 			case BEST:
4051 				/* No data is returned here. But because a sparse-file aware
4052 				 * caller (like archive_read_data_into_fd) may treat zero-size
4053 				 * as a sparse file block, we need to update the offset
4054 				 * accordingly. At this point the decoder doesn't have any
4055 				 * pending uncompressed data blocks, so the current position in
4056 				 * the output file should be last_write_ptr. */
4057 				if (offset) *offset = rar->cstate.last_write_ptr;
4058 				return uncompress_file(a);
4059 			default:
4060 				archive_set_error(&a->archive,
4061 				    ARCHIVE_ERRNO_FILE_FORMAT,
4062 				    "Compression method not supported: 0x%x",
4063 				    (unsigned int)rar->cstate.method);
4064 
4065 				return ARCHIVE_FATAL;
4066 		}
4067 	}
4068 
4069 #if !defined WIN32
4070 	/* Not reached. */
4071 	return ARCHIVE_OK;
4072 #endif
4073 }
4074 
verify_checksums(struct archive_read * a)4075 static int verify_checksums(struct archive_read* a) {
4076 	int verify_crc;
4077 	struct rar5* rar = get_context(a);
4078 
4079 	/* Check checksums only when actually unpacking the data. There's no
4080 	 * need to calculate checksum when we're skipping data in solid archives
4081 	 * (skipping in solid archives is the same thing as unpacking compressed
4082 	 * data and discarding the result). */
4083 
4084 	if(!rar->skip_mode) {
4085 		/* Always check checksums if we're not in skip mode */
4086 		verify_crc = 1;
4087 	} else {
4088 		/* We can override the logic above with a compile-time option
4089 		 * NO_CRC_ON_SOLID_SKIP. This option is used during debugging,
4090 		 * and it will check checksums of unpacked data even when
4091 		 * we're skipping it. */
4092 
4093 #if defined CHECK_CRC_ON_SOLID_SKIP
4094 		/* Debug case */
4095 		verify_crc = 1;
4096 #else
4097 		/* Normal case */
4098 		verify_crc = 0;
4099 #endif
4100 	}
4101 
4102 	if(verify_crc) {
4103 		/* During unpacking, on each unpacked block we're calling the
4104 		 * update_crc() function. Since we are here, the unpacking
4105 		 * process is already over and we can check if calculated
4106 		 * checksum (CRC32 or BLAKE2sp) is the same as what is stored
4107 		 * in the archive. */
4108 		if(rar->file.stored_crc32 > 0) {
4109 			/* Check CRC32 only when the file contains a CRC32
4110 			 * value for this file. */
4111 
4112 			if(rar->file.calculated_crc32 !=
4113 			    rar->file.stored_crc32) {
4114 				/* Checksums do not match; the unpacked file
4115 				 * is corrupted. */
4116 
4117 				DEBUG_CODE {
4118 					printf("Checksum error: CRC32 "
4119 					    "(was: %08" PRIx32 ", expected: %08" PRIx32 ")\n",
4120 					    rar->file.calculated_crc32,
4121 					    rar->file.stored_crc32);
4122 				}
4123 
4124 #ifndef DONT_FAIL_ON_CRC_ERROR
4125 				archive_set_error(&a->archive,
4126 				    ARCHIVE_ERRNO_FILE_FORMAT,
4127 				    "Checksum error: CRC32");
4128 				return ARCHIVE_FATAL;
4129 #endif
4130 			} else {
4131 				DEBUG_CODE {
4132 					printf("Checksum OK: CRC32 "
4133 					    "(%08" PRIx32 "/%08" PRIx32 ")\n",
4134 					    rar->file.stored_crc32,
4135 					    rar->file.calculated_crc32);
4136 				}
4137 			}
4138 		}
4139 
4140 		if(rar->file.has_blake2 > 0) {
4141 			/* BLAKE2sp is an optional checksum algorithm that is
4142 			 * added to RARv5 archives when using the `-htb` switch
4143 			 *  during creation of archive.
4144 			 *
4145 			 * We now finalize the hash calculation by calling the
4146 			 * `final` function. This will generate the final hash
4147 			 * value we can use to compare it with the BLAKE2sp
4148 			 * checksum that is stored in the archive.
4149 			 *
4150 			 * The return value of this `final` function is not
4151 			 * very helpful, as it guards only against improper use.
4152  			 * This is why we're explicitly ignoring it. */
4153 
4154 			uint8_t b2_buf[32];
4155 			(void) blake2sp_final(&rar->file.b2state, b2_buf, 32);
4156 
4157 			if(memcmp(&rar->file.blake2sp, b2_buf, 32) != 0) {
4158 #ifndef DONT_FAIL_ON_CRC_ERROR
4159 				archive_set_error(&a->archive,
4160 				    ARCHIVE_ERRNO_FILE_FORMAT,
4161 				    "Checksum error: BLAKE2");
4162 
4163 				return ARCHIVE_FATAL;
4164 #endif
4165 			}
4166 		}
4167 	}
4168 
4169 	/* Finalization for this file has been successfully completed. */
4170 	return ARCHIVE_OK;
4171 }
4172 
verify_global_checksums(struct archive_read * a)4173 static int verify_global_checksums(struct archive_read* a) {
4174 	return verify_checksums(a);
4175 }
4176 
4177 /*
4178  * Decryption function for the magic signature pattern. Check the comment near
4179  * the `rar5_signature_xor` symbol to read the rationale behind this.
4180  */
rar5_signature(char * buf)4181 static void rar5_signature(char *buf) {
4182 		size_t i;
4183 
4184 		for(i = 0; i < sizeof(rar5_signature_xor); i++) {
4185 			buf[i] = rar5_signature_xor[i] ^ 0xA1;
4186 		}
4187 }
4188 
rar5_read_data(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset)4189 static int rar5_read_data(struct archive_read *a, const void **buff,
4190     size_t *size, int64_t *offset) {
4191 	int ret;
4192 	struct rar5* rar = get_context(a);
4193 
4194 	if (size)
4195 		*size = 0;
4196 
4197 	if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
4198 		rar->has_encrypted_entries = 0;
4199 	}
4200 
4201 	if (rar->headers_are_encrypted || rar->cstate.data_encrypted) {
4202 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4203 		    "Reading encrypted data is not currently supported");
4204 		return ARCHIVE_FATAL;
4205 	}
4206 
4207 	if(rar->file.dir > 0) {
4208 		/* Don't process any data if this file entry was declared
4209 		 * as a directory. This is needed, because entries marked as
4210 		 * directory doesn't have any dictionary buffer allocated, so
4211 		 * it's impossible to perform any decompression. */
4212 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4213 		    "Can't decompress an entry marked as a directory");
4214 		return ARCHIVE_FATAL;
4215 	}
4216 
4217 	if(!rar->skip_mode && (rar->cstate.last_write_ptr > rar->file.unpacked_size)) {
4218 		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
4219 		    "Unpacker has written too many bytes");
4220 		return ARCHIVE_FATAL;
4221 	}
4222 
4223 	ret = use_data(rar, buff, size, offset);
4224 	if(ret == ARCHIVE_OK) {
4225 		return ret;
4226 	}
4227 
4228 	if(rar->file.eof == 1) {
4229 		return ARCHIVE_EOF;
4230 	}
4231 
4232 	ret = do_unpack(a, rar, buff, size, offset);
4233 	if(ret != ARCHIVE_OK) {
4234 		return ret;
4235 	}
4236 
4237 	if(rar->file.bytes_remaining == 0 &&
4238 			rar->cstate.last_write_ptr == rar->file.unpacked_size)
4239 	{
4240 		/* If all bytes of current file were processed, run
4241 		 * finalization.
4242 		 *
4243 		 * Finalization will check checksum against proper values. If
4244 		 * some of the checksums will not match, we'll return an error
4245 		 * value in the last `archive_read_data` call to signal an error
4246 		 * to the user. */
4247 
4248 		rar->file.eof = 1;
4249 		return verify_global_checksums(a);
4250 	}
4251 
4252 	return ARCHIVE_OK;
4253 }
4254 
rar5_read_data_skip(struct archive_read * a)4255 static int rar5_read_data_skip(struct archive_read *a) {
4256 	struct rar5* rar = get_context(a);
4257 
4258 	if(rar->main.solid && (rar->cstate.data_encrypted == 0)) {
4259 		/* In solid archives, instead of skipping the data, we need to
4260 		 * extract it, and dispose the result. The side effect of this
4261 		 * operation will be setting up the initial window buffer state
4262 		 * needed to be able to extract the selected file. Note that
4263 		 * this is only possible when data withing this solid block is
4264 		 * not encrypted, in which case we'll skip and fail if the user
4265 		 * tries to read data. */
4266 
4267 		int ret;
4268 
4269 		/* Make sure to process all blocks in the compressed stream. */
4270 		while(rar->file.bytes_remaining > 0) {
4271 			/* Setting the "skip mode" will allow us to skip
4272 			 * checksum checks during data skipping. Checking the
4273 			 * checksum of skipped data isn't really necessary and
4274 			 * it's only slowing things down.
4275 			 *
4276 			 * This is incremented instead of setting to 1 because
4277 			 * this data skipping function can be called
4278 			 * recursively. */
4279 			rar->skip_mode++;
4280 
4281 			/* We're disposing 1 block of data, so we use triple
4282 			 * NULLs in arguments. */
4283 			ret = rar5_read_data(a, NULL, NULL, NULL);
4284 
4285 			/* Turn off "skip mode". */
4286 			rar->skip_mode--;
4287 
4288 			if(ret < 0 || ret == ARCHIVE_EOF) {
4289 				/* Propagate any potential error conditions
4290 				 * to the caller. */
4291 				return ret;
4292 			}
4293 		}
4294 	} else {
4295 		/* In standard archives, we can just jump over the compressed
4296 		 * stream. Each file in non-solid archives starts from an empty
4297 		 * window buffer. */
4298 
4299 		if(ARCHIVE_OK != consume(a, rar->file.bytes_remaining)) {
4300 			return ARCHIVE_FATAL;
4301 		}
4302 
4303 		rar->file.bytes_remaining = 0;
4304 	}
4305 
4306 	return ARCHIVE_OK;
4307 }
4308 
rar5_seek_data(struct archive_read * a,int64_t offset,int whence)4309 static int64_t rar5_seek_data(struct archive_read *a, int64_t offset,
4310     int whence)
4311 {
4312 	(void) a;
4313 	(void) offset;
4314 	(void) whence;
4315 
4316 	/* We're a streaming unpacker, and we don't support seeking. */
4317 
4318 	return ARCHIVE_FATAL;
4319 }
4320 
rar5_cleanup(struct archive_read * a)4321 static int rar5_cleanup(struct archive_read *a) {
4322 	struct rar5* rar = get_context(a);
4323 
4324 	free(rar->cstate.window_buf);
4325 	free(rar->cstate.filtered_buf);
4326 	clear_data_ready_stack(rar);
4327 
4328 	free(rar->vol.push_buf);
4329 
4330 	free_filters(rar);
4331 	cdeque_free(&rar->cstate.filters);
4332 
4333 	free(rar);
4334 	a->format->data = NULL;
4335 
4336 	return ARCHIVE_OK;
4337 }
4338 
rar5_capabilities(struct archive_read * a)4339 static int rar5_capabilities(struct archive_read * a) {
4340 	(void) a;
4341 	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA
4342 			| ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
4343 }
4344 
rar5_has_encrypted_entries(struct archive_read * _a)4345 static int rar5_has_encrypted_entries(struct archive_read *_a) {
4346 	if (_a && _a->format) {
4347 		struct rar5 *rar = (struct rar5 *)_a->format->data;
4348 		if (rar) {
4349 			return rar->has_encrypted_entries;
4350 		}
4351 	}
4352 
4353 	return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4354 }
4355 
rar5_init(struct rar5 * rar)4356 static int rar5_init(struct rar5* rar) {
4357 	memset(rar, 0, sizeof(struct rar5));
4358 
4359 	if(CDE_OK != cdeque_init(&rar->cstate.filters, 8192))
4360 		return ARCHIVE_FATAL;
4361 
4362 	/*
4363 	 * Until enough data has been read, we cannot tell about
4364 	 * any encrypted entries yet.
4365 	 */
4366 	rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4367 
4368 	return ARCHIVE_OK;
4369 }
4370 
archive_read_support_format_rar5(struct archive * _a)4371 int archive_read_support_format_rar5(struct archive *_a) {
4372 	struct archive_read* ar;
4373 	int ret;
4374 	struct rar5* rar;
4375 
4376 	if(ARCHIVE_OK != (ret = get_archive_read(_a, &ar)))
4377 		return ret;
4378 
4379 	rar = malloc(sizeof(*rar));
4380 	if(rar == NULL) {
4381 		archive_set_error(&ar->archive, ENOMEM,
4382 		    "Can't allocate rar5 data");
4383 		return ARCHIVE_FATAL;
4384 	}
4385 
4386 	if(ARCHIVE_OK != rar5_init(rar)) {
4387 		archive_set_error(&ar->archive, ENOMEM,
4388 		    "Can't allocate rar5 filter buffer");
4389 		free(rar);
4390 		return ARCHIVE_FATAL;
4391 	}
4392 
4393 	ret = __archive_read_register_format(ar,
4394 	    rar,
4395 	    "rar5",
4396 	    rar5_bid,
4397 	    rar5_options,
4398 	    rar5_read_header,
4399 	    rar5_read_data,
4400 	    rar5_read_data_skip,
4401 	    rar5_seek_data,
4402 	    rar5_cleanup,
4403 	    rar5_capabilities,
4404 	    rar5_has_encrypted_entries);
4405 
4406 	if(ret != ARCHIVE_OK) {
4407 		(void) rar5_cleanup(ar);
4408 	}
4409 
4410 	return ret;
4411 }
4412