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