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