xref: /freebsd/contrib/libarchive/libarchive/archive_read_support_format_rar.c (revision eb5165bb491138f60d9004bc4c781490016d9288)
1 /*-
2 * Copyright (c) 2003-2007 Tim Kientzle
3 * Copyright (c) 2011 Andres Mejia
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 *    notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26 
27 #include "archive_platform.h"
28 
29 #ifdef HAVE_ERRNO_H
30 #include <errno.h>
31 #endif
32 #include <time.h>
33 #include <limits.h>
34 #ifdef HAVE_ZLIB_H
35 #include <zlib.h> /* crc32 */
36 #endif
37 
38 #include "archive.h"
39 #ifndef HAVE_ZLIB_H
40 #include "archive_crc32.h"
41 #endif
42 #include "archive_endian.h"
43 #include "archive_entry.h"
44 #include "archive_entry_locale.h"
45 #include "archive_ppmd7_private.h"
46 #include "archive_private.h"
47 #include "archive_read_private.h"
48 
49 /* RAR signature, also known as the mark header */
50 #define RAR_SIGNATURE "\x52\x61\x72\x21\x1A\x07\x00"
51 
52 /* Header types */
53 #define MARK_HEAD    0x72
54 #define MAIN_HEAD    0x73
55 #define FILE_HEAD    0x74
56 #define COMM_HEAD    0x75
57 #define AV_HEAD      0x76
58 #define SUB_HEAD     0x77
59 #define PROTECT_HEAD 0x78
60 #define SIGN_HEAD    0x79
61 #define NEWSUB_HEAD  0x7a
62 #define ENDARC_HEAD  0x7b
63 
64 /* Main Header Flags */
65 #define MHD_VOLUME       0x0001
66 #define MHD_COMMENT      0x0002
67 #define MHD_LOCK         0x0004
68 #define MHD_SOLID        0x0008
69 #define MHD_NEWNUMBERING 0x0010
70 #define MHD_AV           0x0020
71 #define MHD_PROTECT      0x0040
72 #define MHD_PASSWORD     0x0080
73 #define MHD_FIRSTVOLUME  0x0100
74 #define MHD_ENCRYPTVER   0x0200
75 
76 /* Flags common to all headers */
77 #define HD_MARKDELETION     0x4000
78 #define HD_ADD_SIZE_PRESENT 0x8000
79 
80 /* File Header Flags */
81 #define FHD_SPLIT_BEFORE 0x0001
82 #define FHD_SPLIT_AFTER  0x0002
83 #define FHD_PASSWORD     0x0004
84 #define FHD_COMMENT      0x0008
85 #define FHD_SOLID        0x0010
86 #define FHD_LARGE        0x0100
87 #define FHD_UNICODE      0x0200
88 #define FHD_SALT         0x0400
89 #define FHD_VERSION      0x0800
90 #define FHD_EXTTIME      0x1000
91 #define FHD_EXTFLAGS     0x2000
92 
93 /* File dictionary sizes */
94 #define DICTIONARY_SIZE_64   0x00
95 #define DICTIONARY_SIZE_128  0x20
96 #define DICTIONARY_SIZE_256  0x40
97 #define DICTIONARY_SIZE_512  0x60
98 #define DICTIONARY_SIZE_1024 0x80
99 #define DICTIONARY_SIZE_2048 0xA0
100 #define DICTIONARY_SIZE_4096 0xC0
101 #define FILE_IS_DIRECTORY    0xE0
102 #define DICTIONARY_MASK      FILE_IS_DIRECTORY
103 
104 /* OS Flags */
105 #define OS_MSDOS  0
106 #define OS_OS2    1
107 #define OS_WIN32  2
108 #define OS_UNIX   3
109 #define OS_MAC_OS 4
110 #define OS_BEOS   5
111 
112 /* Compression Methods */
113 #define COMPRESS_METHOD_STORE   0x30
114 /* LZSS */
115 #define COMPRESS_METHOD_FASTEST 0x31
116 #define COMPRESS_METHOD_FAST    0x32
117 #define COMPRESS_METHOD_NORMAL  0x33
118 /* PPMd Variant H */
119 #define COMPRESS_METHOD_GOOD    0x34
120 #define COMPRESS_METHOD_BEST    0x35
121 
122 #define CRC_POLYNOMIAL 0xEDB88320
123 
124 #define NS_UNIT 10000000
125 
126 #define DICTIONARY_MAX_SIZE 0x400000
127 
128 #define MAINCODE_SIZE      299
129 #define OFFSETCODE_SIZE    60
130 #define LOWOFFSETCODE_SIZE 17
131 #define LENGTHCODE_SIZE    28
132 #define HUFFMAN_TABLE_SIZE \
133   MAINCODE_SIZE + OFFSETCODE_SIZE + LOWOFFSETCODE_SIZE + LENGTHCODE_SIZE
134 
135 #define MAX_SYMBOL_LENGTH 0xF
136 #define MAX_SYMBOLS       20
137 
138 /* Virtual Machine Properties */
139 #define VM_MEMORY_SIZE 0x40000
140 #define VM_MEMORY_MASK (VM_MEMORY_SIZE - 1)
141 #define PROGRAM_WORK_SIZE 0x3C000
142 #define PROGRAM_GLOBAL_SIZE 0x2000
143 #define PROGRAM_SYSTEM_GLOBAL_ADDRESS PROGRAM_WORK_SIZE
144 #define PROGRAM_SYSTEM_GLOBAL_SIZE 0x40
145 #define PROGRAM_USER_GLOBAL_ADDRESS (PROGRAM_SYSTEM_GLOBAL_ADDRESS + PROGRAM_SYSTEM_GLOBAL_SIZE)
146 #define PROGRAM_USER_GLOBAL_SIZE (PROGRAM_GLOBAL_SIZE - PROGRAM_SYSTEM_GLOBAL_SIZE)
147 
148 /*
149  * Considering L1,L2 cache miss and a calling of write system-call,
150  * the best size of the output buffer(uncompressed buffer) is 128K.
151  * If the structure of extracting process is changed, this value
152  * might be researched again.
153  */
154 #define UNP_BUFFER_SIZE   (128 * 1024)
155 
156 /* Define this here for non-Windows platforms */
157 #if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__))
158 #define FILE_ATTRIBUTE_DIRECTORY 0x10
159 #endif
160 
161 #undef minimum
162 #define minimum(a, b)	((a)<(b)?(a):(b))
163 
164 /* Stack overflow check */
165 #define MAX_COMPRESS_DEPTH 1024
166 
167 /* Fields common to all headers */
168 struct rar_header
169 {
170   char crc[2];
171   char type;
172   char flags[2];
173   char size[2];
174 };
175 
176 /* Fields common to all file headers */
177 struct rar_file_header
178 {
179   char pack_size[4];
180   char unp_size[4];
181   char host_os;
182   char file_crc[4];
183   char file_time[4];
184   char unp_ver;
185   char method;
186   char name_size[2];
187   char file_attr[4];
188 };
189 
190 struct huffman_tree_node
191 {
192   int branches[2];
193 };
194 
195 struct huffman_table_entry
196 {
197   unsigned int length;
198   int value;
199 };
200 
201 struct huffman_code
202 {
203   struct huffman_tree_node *tree;
204   int numentries;
205   int numallocatedentries;
206   int minlength;
207   int maxlength;
208   int tablesize;
209   struct huffman_table_entry *table;
210 };
211 
212 struct lzss
213 {
214   unsigned char *window;
215   int mask;
216   int64_t position;
217 };
218 
219 struct data_block_offsets
220 {
221   int64_t header_size;
222   int64_t start_offset;
223   int64_t end_offset;
224 };
225 
226 struct rar_program_code
227 {
228   uint8_t *staticdata;
229   uint32_t staticdatalen;
230   uint8_t *globalbackup;
231   uint32_t globalbackuplen;
232   uint64_t fingerprint;
233   uint32_t usagecount;
234   uint32_t oldfilterlength;
235   struct rar_program_code *next;
236 };
237 
238 struct rar_filter
239 {
240   struct rar_program_code *prog;
241   uint32_t initialregisters[8];
242   uint8_t *globaldata;
243   uint32_t globaldatalen;
244   size_t blockstartpos;
245   uint32_t blocklength;
246   uint32_t filteredblockaddress;
247   uint32_t filteredblocklength;
248   struct rar_filter *next;
249 };
250 
251 struct memory_bit_reader
252 {
253   const uint8_t *bytes;
254   size_t length;
255   size_t offset;
256   uint64_t bits;
257   int available;
258   int at_eof;
259 };
260 
261 struct rar_virtual_machine
262 {
263   uint32_t registers[8];
264   uint8_t memory[VM_MEMORY_SIZE + sizeof(uint32_t)];
265 };
266 
267 struct rar_filters
268 {
269   struct rar_virtual_machine *vm;
270   struct rar_program_code *progs;
271   struct rar_filter *stack;
272   int64_t filterstart;
273   uint32_t lastfilternum;
274   int64_t lastend;
275   uint8_t *bytes;
276   size_t bytes_ready;
277 };
278 
279 struct audio_state
280 {
281   int8_t weight[5];
282   int16_t delta[4];
283   int8_t lastdelta;
284   int error[11];
285   int count;
286   uint8_t lastbyte;
287 };
288 
289 struct rar
290 {
291   /* Entries from main RAR header */
292   unsigned main_flags;
293   unsigned long file_crc;
294   char reserved1[2];
295   char reserved2[4];
296   char encryptver;
297 
298   /* File header entries */
299   char compression_method;
300   unsigned file_flags;
301   int64_t packed_size;
302   int64_t unp_size;
303   time_t mtime;
304   long mnsec;
305   mode_t mode;
306   char *filename;
307   char *filename_save;
308   size_t filename_save_size;
309   size_t filename_allocated;
310 
311   /* File header optional entries */
312   char salt[8];
313   time_t atime;
314   long ansec;
315   time_t ctime;
316   long cnsec;
317   time_t arctime;
318   long arcnsec;
319 
320   /* Fields to help with tracking decompression of files. */
321   int64_t bytes_unconsumed;
322   int64_t bytes_remaining;
323   int64_t bytes_uncopied;
324   int64_t offset;
325   int64_t offset_outgoing;
326   int64_t offset_seek;
327   char valid;
328   unsigned int unp_offset;
329   unsigned int unp_buffer_size;
330   unsigned char *unp_buffer;
331   unsigned int dictionary_size;
332   char start_new_block;
333   char entry_eof;
334   unsigned long crc_calculated;
335   int found_first_header;
336   char has_endarc_header;
337   struct data_block_offsets *dbo;
338   size_t cursor;
339   size_t nodes;
340   char filename_must_match;
341 
342   /* LZSS members */
343   struct huffman_code maincode;
344   struct huffman_code offsetcode;
345   struct huffman_code lowoffsetcode;
346   struct huffman_code lengthcode;
347   unsigned char lengthtable[HUFFMAN_TABLE_SIZE];
348   struct lzss lzss;
349   unsigned int lastlength;
350   unsigned int lastoffset;
351   unsigned int oldoffset[4];
352   unsigned int lastlowoffset;
353   unsigned int numlowoffsetrepeats;
354   char start_new_table;
355 
356   /* Filters */
357   struct rar_filters filters;
358 
359   /* PPMd Variant H members */
360   char ppmd_valid;
361   char ppmd_eod;
362   char is_ppmd_block;
363   int ppmd_escape;
364   CPpmd7 ppmd7_context;
365   CPpmd7z_RangeDec range_dec;
366   IByteIn bytein;
367 
368   /*
369    * String conversion object.
370    */
371   int init_default_conversion;
372   struct archive_string_conv *sconv_default;
373   struct archive_string_conv *opt_sconv;
374   struct archive_string_conv *sconv_utf8;
375   struct archive_string_conv *sconv_utf16be;
376 
377   /*
378    * Bit stream reader.
379    */
380   struct rar_br {
381 #define CACHE_TYPE	uint64_t
382 #define CACHE_BITS	(8 * sizeof(CACHE_TYPE))
383     /* Cache buffer. */
384     CACHE_TYPE		 cache_buffer;
385     /* Indicates how many bits avail in cache_buffer. */
386     int			 cache_avail;
387     ssize_t		 avail_in;
388     const unsigned char *next_in;
389   } br;
390 
391   /*
392    * Custom field to denote that this archive contains encrypted entries
393    */
394   int has_encrypted_entries;
395 };
396 
397 static int archive_read_support_format_rar_capabilities(struct archive_read *);
398 static int archive_read_format_rar_has_encrypted_entries(struct archive_read *);
399 static int archive_read_format_rar_bid(struct archive_read *, int);
400 static int archive_read_format_rar_options(struct archive_read *,
401     const char *, const char *);
402 static int archive_read_format_rar_read_header(struct archive_read *,
403     struct archive_entry *);
404 static int archive_read_format_rar_read_data(struct archive_read *,
405     const void **, size_t *, int64_t *);
406 static int archive_read_format_rar_read_data_skip(struct archive_read *a);
407 static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t,
408     int);
409 static int archive_read_format_rar_cleanup(struct archive_read *);
410 
411 /* Support functions */
412 static int read_header(struct archive_read *, struct archive_entry *, char);
413 static time_t get_time(int);
414 static int read_exttime(const char *, struct rar *, const char *);
415 static int read_symlink_stored(struct archive_read *, struct archive_entry *,
416                                struct archive_string_conv *);
417 static int read_data_stored(struct archive_read *, const void **, size_t *,
418                             int64_t *);
419 static int read_data_compressed(struct archive_read *, const void **, size_t *,
420                                 int64_t *, size_t);
421 static int rar_br_preparation(struct archive_read *, struct rar_br *);
422 static int parse_codes(struct archive_read *);
423 static void free_codes(struct archive_read *);
424 static int read_next_symbol(struct archive_read *, struct huffman_code *);
425 static int create_code(struct archive_read *, struct huffman_code *,
426                        unsigned char *, int, char);
427 static int add_value(struct archive_read *, struct huffman_code *, int, int,
428                      int);
429 static int new_node(struct huffman_code *);
430 static int make_table(struct archive_read *, struct huffman_code *);
431 static int make_table_recurse(struct archive_read *, struct huffman_code *, int,
432                               struct huffman_table_entry *, int, int);
433 static int expand(struct archive_read *, int64_t *);
434 static int copy_from_lzss_window_to_unp(struct archive_read *, const void **,
435                                         int64_t, size_t);
436 static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *);
437 static int parse_filter(struct archive_read *, const uint8_t *, uint16_t,
438                         uint8_t);
439 static int run_filters(struct archive_read *);
440 static void clear_filters(struct rar_filters *);
441 static struct rar_filter *create_filter(struct rar_program_code *,
442                                         const uint8_t *, uint32_t,
443                                         uint32_t[8], size_t, uint32_t);
444 static void delete_filter(struct rar_filter *filter);
445 static struct rar_program_code *compile_program(const uint8_t *, size_t);
446 static void delete_program_code(struct rar_program_code *prog);
447 static uint32_t membr_next_rarvm_number(struct memory_bit_reader *br);
448 static inline uint32_t membr_bits(struct memory_bit_reader *br, int bits);
449 static int membr_fill(struct memory_bit_reader *br, int bits);
450 static int read_filter(struct archive_read *, int64_t *);
451 static int rar_decode_byte(struct archive_read*, uint8_t *);
452 static int execute_filter(struct archive_read*, struct rar_filter *,
453                           struct rar_virtual_machine *, size_t);
454 static int copy_from_lzss_window(struct archive_read *, uint8_t *, int64_t, int);
455 static inline void vm_write_32(struct rar_virtual_machine*, size_t, uint32_t);
456 static inline uint32_t vm_read_32(struct rar_virtual_machine*, size_t);
457 
458 /*
459  * Bit stream reader.
460  */
461 /* Check that the cache buffer has enough bits. */
462 #define rar_br_has(br, n) ((br)->cache_avail >= n)
463 /* Get compressed data by bit. */
464 #define rar_br_bits(br, n)        \
465   (((uint32_t)((br)->cache_buffer >>    \
466     ((br)->cache_avail - (n)))) & cache_masks[n])
467 #define rar_br_bits_forced(br, n)     \
468   (((uint32_t)((br)->cache_buffer <<    \
469     ((n) - (br)->cache_avail))) & cache_masks[n])
470 /* Read ahead to make sure the cache buffer has enough compressed data we
471  * will use.
472  *  True  : completed, there is enough data in the cache buffer.
473  *  False : there is no data in the stream. */
474 #define rar_br_read_ahead(a, br, n) \
475   ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n)))
476 /* Notify how many bits we consumed. */
477 #define rar_br_consume(br, n) ((br)->cache_avail -= (n))
478 #define rar_br_consume_unaligned_bits(br) ((br)->cache_avail &= ~7)
479 
480 static const uint32_t cache_masks[] = {
481   0x00000000, 0x00000001, 0x00000003, 0x00000007,
482   0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
483   0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF,
484   0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF,
485   0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF,
486   0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,
487   0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF,
488   0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF,
489   0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF
490 };
491 
492 /*
493  * Shift away used bits in the cache data and fill it up with following bits.
494  * Call this when cache buffer does not have enough bits you need.
495  *
496  * Returns 1 if the cache buffer is full.
497  * Returns 0 if the cache buffer is not full; input buffer is empty.
498  */
499 static int
rar_br_fillup(struct archive_read * a,struct rar_br * br)500 rar_br_fillup(struct archive_read *a, struct rar_br *br)
501 {
502   struct rar *rar = (struct rar *)(a->format->data);
503   int n = CACHE_BITS - br->cache_avail;
504 
505   for (;;) {
506     switch (n >> 3) {
507     case 8:
508       if (br->avail_in >= 8) {
509         br->cache_buffer =
510             ((uint64_t)br->next_in[0]) << 56 |
511             ((uint64_t)br->next_in[1]) << 48 |
512             ((uint64_t)br->next_in[2]) << 40 |
513             ((uint64_t)br->next_in[3]) << 32 |
514             ((uint32_t)br->next_in[4]) << 24 |
515             ((uint32_t)br->next_in[5]) << 16 |
516             ((uint32_t)br->next_in[6]) << 8 |
517              (uint32_t)br->next_in[7];
518         br->next_in += 8;
519         br->avail_in -= 8;
520         br->cache_avail += 8 * 8;
521         rar->bytes_unconsumed += 8;
522         rar->bytes_remaining -= 8;
523         return (1);
524       }
525       break;
526     case 7:
527       if (br->avail_in >= 7) {
528         br->cache_buffer =
529            (br->cache_buffer << 56) |
530             ((uint64_t)br->next_in[0]) << 48 |
531             ((uint64_t)br->next_in[1]) << 40 |
532             ((uint64_t)br->next_in[2]) << 32 |
533             ((uint32_t)br->next_in[3]) << 24 |
534             ((uint32_t)br->next_in[4]) << 16 |
535             ((uint32_t)br->next_in[5]) << 8 |
536              (uint32_t)br->next_in[6];
537         br->next_in += 7;
538         br->avail_in -= 7;
539         br->cache_avail += 7 * 8;
540         rar->bytes_unconsumed += 7;
541         rar->bytes_remaining -= 7;
542         return (1);
543       }
544       break;
545     case 6:
546       if (br->avail_in >= 6) {
547         br->cache_buffer =
548            (br->cache_buffer << 48) |
549             ((uint64_t)br->next_in[0]) << 40 |
550             ((uint64_t)br->next_in[1]) << 32 |
551             ((uint32_t)br->next_in[2]) << 24 |
552             ((uint32_t)br->next_in[3]) << 16 |
553             ((uint32_t)br->next_in[4]) << 8 |
554              (uint32_t)br->next_in[5];
555         br->next_in += 6;
556         br->avail_in -= 6;
557         br->cache_avail += 6 * 8;
558         rar->bytes_unconsumed += 6;
559         rar->bytes_remaining -= 6;
560         return (1);
561       }
562       break;
563     case 0:
564       /* We have enough compressed data in
565        * the cache buffer.*/
566       return (1);
567     default:
568       break;
569     }
570     if (br->avail_in <= 0) {
571 
572       if (rar->bytes_unconsumed > 0) {
573         /* Consume as much as the decompressor
574          * actually used. */
575         __archive_read_consume(a, rar->bytes_unconsumed);
576         rar->bytes_unconsumed = 0;
577       }
578       br->next_in = rar_read_ahead(a, 1, &(br->avail_in));
579       if (br->next_in == NULL)
580         return (0);
581       if (br->avail_in == 0)
582         return (0);
583     }
584     br->cache_buffer =
585        (br->cache_buffer << 8) | *br->next_in++;
586     br->avail_in--;
587     br->cache_avail += 8;
588     n -= 8;
589     rar->bytes_unconsumed++;
590     rar->bytes_remaining--;
591   }
592 }
593 
594 static int
rar_br_preparation(struct archive_read * a,struct rar_br * br)595 rar_br_preparation(struct archive_read *a, struct rar_br *br)
596 {
597   struct rar *rar = (struct rar *)(a->format->data);
598 
599   if (rar->bytes_remaining > 0) {
600     br->next_in = rar_read_ahead(a, 1, &(br->avail_in));
601     if (br->next_in == NULL) {
602       archive_set_error(&a->archive,
603           ARCHIVE_ERRNO_FILE_FORMAT,
604           "Truncated RAR file data");
605       return (ARCHIVE_FATAL);
606     }
607     if (br->cache_avail == 0)
608       (void)rar_br_fillup(a, br);
609   }
610   return (ARCHIVE_OK);
611 }
612 
613 /* Find last bit set */
614 static inline int
rar_fls(unsigned int word)615 rar_fls(unsigned int word)
616 {
617   word |= (word >>  1);
618   word |= (word >>  2);
619   word |= (word >>  4);
620   word |= (word >>  8);
621   word |= (word >> 16);
622   return word - (word >> 1);
623 }
624 
625 /* LZSS functions */
626 static inline int64_t
lzss_position(struct lzss * lzss)627 lzss_position(struct lzss *lzss)
628 {
629   return lzss->position;
630 }
631 
632 static inline int
lzss_mask(struct lzss * lzss)633 lzss_mask(struct lzss *lzss)
634 {
635   return lzss->mask;
636 }
637 
638 static inline int
lzss_size(struct lzss * lzss)639 lzss_size(struct lzss *lzss)
640 {
641   return lzss->mask + 1;
642 }
643 
644 static inline int
lzss_offset_for_position(struct lzss * lzss,int64_t pos)645 lzss_offset_for_position(struct lzss *lzss, int64_t pos)
646 {
647   return (int)(pos & lzss->mask);
648 }
649 
650 static inline unsigned char *
lzss_pointer_for_position(struct lzss * lzss,int64_t pos)651 lzss_pointer_for_position(struct lzss *lzss, int64_t pos)
652 {
653   return &lzss->window[lzss_offset_for_position(lzss, pos)];
654 }
655 
656 static inline int
lzss_current_offset(struct lzss * lzss)657 lzss_current_offset(struct lzss *lzss)
658 {
659   return lzss_offset_for_position(lzss, lzss->position);
660 }
661 
662 static inline uint8_t *
lzss_current_pointer(struct lzss * lzss)663 lzss_current_pointer(struct lzss *lzss)
664 {
665   return lzss_pointer_for_position(lzss, lzss->position);
666 }
667 
668 static inline void
lzss_emit_literal(struct rar * rar,uint8_t literal)669 lzss_emit_literal(struct rar *rar, uint8_t literal)
670 {
671   *lzss_current_pointer(&rar->lzss) = literal;
672   rar->lzss.position++;
673 }
674 
675 static inline void
lzss_emit_match(struct rar * rar,int offset,int length)676 lzss_emit_match(struct rar *rar, int offset, int length)
677 {
678   int dstoffs = lzss_current_offset(&rar->lzss);
679   int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss);
680   int l, li, remaining;
681   unsigned char *d, *s;
682 
683   remaining = length;
684   while (remaining > 0) {
685     l = remaining;
686     if (dstoffs > srcoffs) {
687       if (l > lzss_size(&rar->lzss) - dstoffs)
688         l = lzss_size(&rar->lzss) - dstoffs;
689     } else {
690       if (l > lzss_size(&rar->lzss) - srcoffs)
691         l = lzss_size(&rar->lzss) - srcoffs;
692     }
693     d = &(rar->lzss.window[dstoffs]);
694     s = &(rar->lzss.window[srcoffs]);
695     if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs))
696       memcpy(d, s, l);
697     else {
698       for (li = 0; li < l; li++)
699         d[li] = s[li];
700     }
701     remaining -= l;
702     dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss));
703     srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss));
704   }
705   rar->lzss.position += length;
706 }
707 
708 static Byte
ppmd_read(void * p)709 ppmd_read(void *p)
710 {
711   struct archive_read *a = ((IByteIn*)p)->a;
712   struct rar *rar = (struct rar *)(a->format->data);
713   struct rar_br *br = &(rar->br);
714   Byte b;
715   if (!rar_br_read_ahead(a, br, 8))
716   {
717     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
718                       "Truncated RAR file data");
719     rar->valid = 0;
720     return 0;
721   }
722   b = rar_br_bits(br, 8);
723   rar_br_consume(br, 8);
724   return b;
725 }
726 
727 int
archive_read_support_format_rar(struct archive * _a)728 archive_read_support_format_rar(struct archive *_a)
729 {
730   struct archive_read *a = (struct archive_read *)_a;
731   struct rar *rar;
732   int r;
733 
734   archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
735                       "archive_read_support_format_rar");
736 
737   rar = calloc(1, sizeof(*rar));
738   if (rar == NULL)
739   {
740     archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data");
741     return (ARCHIVE_FATAL);
742   }
743 
744   /*
745    * Until enough data has been read, we cannot tell about
746    * any encrypted entries yet.
747    */
748   rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
749 
750   r = __archive_read_register_format(a,
751                                      rar,
752                                      "rar",
753                                      archive_read_format_rar_bid,
754                                      archive_read_format_rar_options,
755                                      archive_read_format_rar_read_header,
756                                      archive_read_format_rar_read_data,
757                                      archive_read_format_rar_read_data_skip,
758                                      archive_read_format_rar_seek_data,
759                                      archive_read_format_rar_cleanup,
760                                      archive_read_support_format_rar_capabilities,
761                                      archive_read_format_rar_has_encrypted_entries);
762 
763   if (r != ARCHIVE_OK)
764     free(rar);
765   return (r);
766 }
767 
768 static int
archive_read_support_format_rar_capabilities(struct archive_read * a)769 archive_read_support_format_rar_capabilities(struct archive_read * a)
770 {
771   (void)a; /* UNUSED */
772   return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA
773     | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
774 }
775 
776 static int
archive_read_format_rar_has_encrypted_entries(struct archive_read * _a)777 archive_read_format_rar_has_encrypted_entries(struct archive_read *_a)
778 {
779   if (_a && _a->format) {
780     struct rar * rar = (struct rar *)_a->format->data;
781     if (rar) {
782       return rar->has_encrypted_entries;
783     }
784   }
785   return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
786 }
787 
788 
789 static int
archive_read_format_rar_bid(struct archive_read * a,int best_bid)790 archive_read_format_rar_bid(struct archive_read *a, int best_bid)
791 {
792   const char *p;
793 
794   /* If there's already a bid > 30, we'll never win. */
795   if (best_bid > 30)
796     return (-1);
797 
798   if ((p = __archive_read_ahead(a, 7, NULL)) == NULL)
799     return (-1);
800 
801   if (memcmp(p, RAR_SIGNATURE, 7) == 0)
802     return (30);
803 
804   if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) {
805     /* This is a PE file */
806     ssize_t offset = 0x10000;
807     ssize_t window = 4096;
808     ssize_t bytes_avail;
809     while (offset + window <= (1024 * 128)) {
810       const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail);
811       if (buff == NULL) {
812         /* Remaining bytes are less than window. */
813         window >>= 1;
814         if (window < 0x40)
815           return (0);
816         continue;
817       }
818       p = buff + offset;
819       while (p + 7 < buff + bytes_avail) {
820         if (memcmp(p, RAR_SIGNATURE, 7) == 0)
821           return (30);
822         p += 0x10;
823       }
824       offset = p - buff;
825     }
826   }
827   return (0);
828 }
829 
830 static int
skip_sfx(struct archive_read * a)831 skip_sfx(struct archive_read *a)
832 {
833   const void *h;
834   const char *p, *q;
835   size_t skip, total;
836   ssize_t bytes, window;
837 
838   total = 0;
839   window = 4096;
840   while (total + window <= (1024 * 128)) {
841     h = __archive_read_ahead(a, window, &bytes);
842     if (h == NULL) {
843       /* Remaining bytes are less than window. */
844       window >>= 1;
845       if (window < 0x40)
846       	goto fatal;
847       continue;
848     }
849     if (bytes < 0x40)
850       goto fatal;
851     p = h;
852     q = p + bytes;
853 
854     /*
855      * Scan ahead until we find something that looks
856      * like the RAR header.
857      */
858     while (p + 7 < q) {
859       if (memcmp(p, RAR_SIGNATURE, 7) == 0) {
860       	skip = p - (const char *)h;
861       	__archive_read_consume(a, skip);
862       	return (ARCHIVE_OK);
863       }
864       p += 0x10;
865     }
866     skip = p - (const char *)h;
867     __archive_read_consume(a, skip);
868     total += skip;
869   }
870 fatal:
871   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
872       "Couldn't find out RAR header");
873   return (ARCHIVE_FATAL);
874 }
875 
876 static int
archive_read_format_rar_options(struct archive_read * a,const char * key,const char * val)877 archive_read_format_rar_options(struct archive_read *a,
878     const char *key, const char *val)
879 {
880   struct rar *rar;
881   int ret = ARCHIVE_FAILED;
882 
883   rar = (struct rar *)(a->format->data);
884   if (strcmp(key, "hdrcharset")  == 0) {
885     if (val == NULL || val[0] == 0)
886       archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
887           "rar: hdrcharset option needs a character-set name");
888     else {
889       rar->opt_sconv =
890           archive_string_conversion_from_charset(
891               &a->archive, val, 0);
892       if (rar->opt_sconv != NULL)
893         ret = ARCHIVE_OK;
894       else
895         ret = ARCHIVE_FATAL;
896     }
897     return (ret);
898   }
899 
900   /* Note: The "warn" return is just to inform the options
901    * supervisor that we didn't handle it.  It will generate
902    * a suitable error if no one used this option. */
903   return (ARCHIVE_WARN);
904 }
905 
906 static int
archive_read_format_rar_read_header(struct archive_read * a,struct archive_entry * entry)907 archive_read_format_rar_read_header(struct archive_read *a,
908                                     struct archive_entry *entry)
909 {
910   const void *h;
911   const char *p;
912   struct rar *rar;
913   int64_t skip;
914   char head_type;
915   int ret;
916   unsigned flags;
917   unsigned long crc32_expected;
918 
919   a->archive.archive_format = ARCHIVE_FORMAT_RAR;
920   if (a->archive.archive_format_name == NULL)
921     a->archive.archive_format_name = "RAR";
922 
923   rar = (struct rar *)(a->format->data);
924 
925   /*
926    * It should be sufficient to call archive_read_next_header() for
927    * a reader to determine if an entry is encrypted or not. If the
928    * encryption of an entry is only detectable when calling
929    * archive_read_data(), so be it. We'll do the same check there
930    * as well.
931    */
932   if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
933     rar->has_encrypted_entries = 0;
934   }
935 
936   /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if
937   * this fails.
938   */
939   if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
940     return (ARCHIVE_EOF);
941 
942   p = h;
943   if (rar->found_first_header == 0 &&
944      ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) {
945     /* This is an executable ? Must be self-extracting... */
946     ret = skip_sfx(a);
947     if (ret < ARCHIVE_WARN)
948       return (ret);
949   }
950   rar->found_first_header = 1;
951 
952   while (1)
953   {
954     unsigned long crc32_val;
955 
956     if ((h = __archive_read_ahead(a, 7, NULL)) == NULL) {
957       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
958                         "Failed to read next header");
959       return (ARCHIVE_FATAL);
960     }
961     p = h;
962 
963     head_type = p[2];
964     switch(head_type)
965     {
966     case MARK_HEAD:
967       if (memcmp(p, RAR_SIGNATURE, 7) != 0) {
968         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
969           "Invalid marker header");
970         return (ARCHIVE_FATAL);
971       }
972       __archive_read_consume(a, 7);
973       break;
974 
975     case MAIN_HEAD:
976       rar->main_flags = archive_le16dec(p + 3);
977       skip = archive_le16dec(p + 5);
978       if ((size_t)skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) {
979         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
980           "Invalid header size");
981         return (ARCHIVE_FATAL);
982       }
983       if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
984         return (ARCHIVE_FATAL);
985       p = h;
986       memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1));
987       memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1),
988              sizeof(rar->reserved2));
989       if (rar->main_flags & MHD_ENCRYPTVER) {
990         if ((size_t)skip <
991             7 + sizeof(rar->reserved1) + sizeof(rar->reserved2) + 1) {
992           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
993             "Invalid header size");
994           return (ARCHIVE_FATAL);
995         }
996         rar->encryptver = *(p + 7 + sizeof(rar->reserved1) +
997                             sizeof(rar->reserved2));
998       }
999 
1000       /* Main header is password encrypted, so we cannot read any
1001          file names or any other info about files from the header. */
1002       if (rar->main_flags & MHD_PASSWORD)
1003       {
1004         archive_entry_set_is_metadata_encrypted(entry, 1);
1005         archive_entry_set_is_data_encrypted(entry, 1);
1006         rar->has_encrypted_entries = 1;
1007          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1008                           "RAR encryption support unavailable");
1009         return (ARCHIVE_FATAL);
1010       }
1011 
1012       crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2);
1013       if ((crc32_val & 0xffff) != archive_le16dec(p)) {
1014 #ifndef DONT_FAIL_ON_CRC_ERROR
1015         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1016           "Header CRC error");
1017         return (ARCHIVE_FATAL);
1018 #endif
1019       }
1020       __archive_read_consume(a, skip);
1021       break;
1022 
1023     case FILE_HEAD:
1024       return read_header(a, entry, head_type);
1025 
1026     case COMM_HEAD:
1027     case AV_HEAD:
1028     case SUB_HEAD:
1029     case PROTECT_HEAD:
1030     case SIGN_HEAD:
1031     case ENDARC_HEAD:
1032       flags = archive_le16dec(p + 3);
1033       skip = archive_le16dec(p + 5);
1034       if (skip < 7) {
1035         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1036           "Invalid header size too small");
1037         return (ARCHIVE_FATAL);
1038       }
1039       if (flags & HD_ADD_SIZE_PRESENT)
1040       {
1041         if (skip < 7 + 4) {
1042           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1043             "Invalid header size too small");
1044           return (ARCHIVE_FATAL);
1045         }
1046         if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
1047           return (ARCHIVE_FATAL);
1048         p = h;
1049         skip += archive_le32dec(p + 7);
1050       }
1051 
1052       /* Skip over the 2-byte CRC at the beginning of the header. */
1053       crc32_expected = archive_le16dec(p);
1054       __archive_read_consume(a, 2);
1055       skip -= 2;
1056 
1057       /* Skim the entire header and compute the CRC. */
1058       crc32_val = 0;
1059       while (skip > 0) {
1060         unsigned to_read;
1061         if (skip > 32 * 1024)
1062           to_read = 32 * 1024;
1063         else
1064           to_read = (unsigned)skip;
1065         if ((h = __archive_read_ahead(a, to_read, NULL)) == NULL) {
1066           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1067             "Bad RAR file");
1068           return (ARCHIVE_FATAL);
1069         }
1070         p = h;
1071         crc32_val = crc32(crc32_val, (const unsigned char *)p, to_read);
1072         __archive_read_consume(a, to_read);
1073         skip -= to_read;
1074       }
1075       if ((crc32_val & 0xffff) != crc32_expected) {
1076 #ifndef DONT_FAIL_ON_CRC_ERROR
1077         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1078           "Header CRC error");
1079         return (ARCHIVE_FATAL);
1080 #endif
1081       }
1082       if (head_type == ENDARC_HEAD)
1083         return (ARCHIVE_EOF);
1084       break;
1085 
1086     case NEWSUB_HEAD:
1087       if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN)
1088         return ret;
1089       break;
1090 
1091     default:
1092       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1093                         "Bad RAR file");
1094       return (ARCHIVE_FATAL);
1095     }
1096   }
1097 }
1098 
1099 static int
archive_read_format_rar_read_data(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset)1100 archive_read_format_rar_read_data(struct archive_read *a, const void **buff,
1101                                   size_t *size, int64_t *offset)
1102 {
1103   struct rar *rar = (struct rar *)(a->format->data);
1104   int ret;
1105 
1106   if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
1107     rar->has_encrypted_entries = 0;
1108   }
1109 
1110   if (rar->bytes_unconsumed > 0) {
1111       /* Consume as much as the decompressor actually used. */
1112       __archive_read_consume(a, rar->bytes_unconsumed);
1113       rar->bytes_unconsumed = 0;
1114   }
1115 
1116   *buff = NULL;
1117   if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {
1118     *size = 0;
1119     *offset = rar->offset;
1120     return (ARCHIVE_EOF);
1121   }
1122 
1123   switch (rar->compression_method)
1124   {
1125   case COMPRESS_METHOD_STORE:
1126     ret = read_data_stored(a, buff, size, offset);
1127     break;
1128 
1129   case COMPRESS_METHOD_FASTEST:
1130   case COMPRESS_METHOD_FAST:
1131   case COMPRESS_METHOD_NORMAL:
1132   case COMPRESS_METHOD_GOOD:
1133   case COMPRESS_METHOD_BEST:
1134     ret = read_data_compressed(a, buff, size, offset, 0);
1135     if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) {
1136       __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
1137       rar->start_new_table = 1;
1138       rar->ppmd_valid = 0;
1139     }
1140     break;
1141 
1142   default:
1143     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1144                       "Unsupported compression method for RAR file");
1145     ret = ARCHIVE_FATAL;
1146     break;
1147   }
1148   return (ret);
1149 }
1150 
1151 static int
archive_read_format_rar_read_data_skip(struct archive_read * a)1152 archive_read_format_rar_read_data_skip(struct archive_read *a)
1153 {
1154   struct rar *rar;
1155   int64_t bytes_skipped;
1156   int ret;
1157 
1158   rar = (struct rar *)(a->format->data);
1159 
1160   if (rar->bytes_unconsumed > 0) {
1161       /* Consume as much as the decompressor actually used. */
1162       __archive_read_consume(a, rar->bytes_unconsumed);
1163       rar->bytes_unconsumed = 0;
1164   }
1165 
1166   if (rar->bytes_remaining > 0) {
1167     bytes_skipped = __archive_read_consume(a, rar->bytes_remaining);
1168     if (bytes_skipped < 0)
1169       return (ARCHIVE_FATAL);
1170   }
1171 
1172   /* Compressed data to skip must be read from each header in a multivolume
1173    * archive.
1174    */
1175   if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)
1176   {
1177     ret = archive_read_format_rar_read_header(a, a->entry);
1178     if (ret == (ARCHIVE_EOF))
1179       ret = archive_read_format_rar_read_header(a, a->entry);
1180     if (ret != (ARCHIVE_OK))
1181       return ret;
1182     return archive_read_format_rar_read_data_skip(a);
1183   }
1184 
1185   return (ARCHIVE_OK);
1186 }
1187 
1188 static int64_t
archive_read_format_rar_seek_data(struct archive_read * a,int64_t offset,int whence)1189 archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset,
1190     int whence)
1191 {
1192   int64_t client_offset, ret;
1193   size_t i;
1194   struct rar *rar = (struct rar *)(a->format->data);
1195 
1196   if (rar->compression_method == COMPRESS_METHOD_STORE)
1197   {
1198     /* Modify the offset for use with SEEK_SET */
1199     switch (whence)
1200     {
1201       case SEEK_CUR:
1202         client_offset = rar->offset_seek;
1203         break;
1204       case SEEK_END:
1205         client_offset = rar->unp_size;
1206         break;
1207       case SEEK_SET:
1208       default:
1209         client_offset = 0;
1210     }
1211     client_offset += offset;
1212     if (client_offset < 0)
1213     {
1214       /* Can't seek past beginning of data block */
1215       return -1;
1216     }
1217     else if (client_offset > rar->unp_size)
1218     {
1219       /*
1220        * Set the returned offset but only seek to the end of
1221        * the data block.
1222        */
1223       rar->offset_seek = client_offset;
1224       client_offset = rar->unp_size;
1225     }
1226 
1227     client_offset += rar->dbo[0].start_offset;
1228     i = 0;
1229     while (i < rar->cursor)
1230     {
1231       i++;
1232       client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset;
1233     }
1234     if (rar->main_flags & MHD_VOLUME)
1235     {
1236       /* Find the appropriate offset among the multivolume archive */
1237       while (1)
1238       {
1239         if (client_offset < rar->dbo[rar->cursor].start_offset &&
1240           rar->file_flags & FHD_SPLIT_BEFORE)
1241         {
1242           /* Search backwards for the correct data block */
1243           if (rar->cursor == 0)
1244           {
1245             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1246               "Attempt to seek past beginning of RAR data block");
1247             return (ARCHIVE_FAILED);
1248           }
1249           rar->cursor--;
1250           client_offset -= rar->dbo[rar->cursor+1].start_offset -
1251             rar->dbo[rar->cursor].end_offset;
1252           if (client_offset < rar->dbo[rar->cursor].start_offset)
1253             continue;
1254           ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset -
1255             rar->dbo[rar->cursor].header_size, SEEK_SET);
1256           if (ret < (ARCHIVE_OK))
1257             return ret;
1258           ret = archive_read_format_rar_read_header(a, a->entry);
1259           if (ret != (ARCHIVE_OK))
1260           {
1261             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1262               "Error during seek of RAR file");
1263             return (ARCHIVE_FAILED);
1264           }
1265           rar->cursor--;
1266           break;
1267         }
1268         else if (client_offset > rar->dbo[rar->cursor].end_offset &&
1269           rar->file_flags & FHD_SPLIT_AFTER)
1270         {
1271           /* Search forward for the correct data block */
1272           rar->cursor++;
1273           if (rar->cursor < rar->nodes &&
1274             client_offset > rar->dbo[rar->cursor].end_offset)
1275           {
1276             client_offset += rar->dbo[rar->cursor].start_offset -
1277               rar->dbo[rar->cursor-1].end_offset;
1278             continue;
1279           }
1280           rar->cursor--;
1281           ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset,
1282                                     SEEK_SET);
1283           if (ret < (ARCHIVE_OK))
1284             return ret;
1285           ret = archive_read_format_rar_read_header(a, a->entry);
1286           if (ret == (ARCHIVE_EOF))
1287           {
1288             rar->has_endarc_header = 1;
1289             ret = archive_read_format_rar_read_header(a, a->entry);
1290           }
1291           if (ret != (ARCHIVE_OK))
1292           {
1293             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1294               "Error during seek of RAR file");
1295             return (ARCHIVE_FAILED);
1296           }
1297           client_offset += rar->dbo[rar->cursor].start_offset -
1298             rar->dbo[rar->cursor-1].end_offset;
1299           continue;
1300         }
1301         break;
1302       }
1303     }
1304 
1305     ret = __archive_read_seek(a, client_offset, SEEK_SET);
1306     if (ret < (ARCHIVE_OK))
1307       return ret;
1308     rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret;
1309     i = rar->cursor;
1310     while (i > 0)
1311     {
1312       i--;
1313       ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset;
1314     }
1315     ret -= rar->dbo[0].start_offset;
1316 
1317     /* Always restart reading the file after a seek */
1318     __archive_reset_read_data(&a->archive);
1319 
1320     rar->bytes_unconsumed = 0;
1321     rar->offset = 0;
1322 
1323     /*
1324      * If a seek past the end of file was requested, return the requested
1325      * offset.
1326      */
1327     if (ret == rar->unp_size && rar->offset_seek > rar->unp_size)
1328       return rar->offset_seek;
1329 
1330     /* Return the new offset */
1331     rar->offset_seek = ret;
1332     return rar->offset_seek;
1333   }
1334   else
1335   {
1336     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1337       "Seeking of compressed RAR files is unsupported");
1338   }
1339   return (ARCHIVE_FAILED);
1340 }
1341 
1342 static int
archive_read_format_rar_cleanup(struct archive_read * a)1343 archive_read_format_rar_cleanup(struct archive_read *a)
1344 {
1345   struct rar *rar;
1346 
1347   rar = (struct rar *)(a->format->data);
1348   free_codes(a);
1349   clear_filters(&rar->filters);
1350   free(rar->filename);
1351   free(rar->filename_save);
1352   free(rar->dbo);
1353   free(rar->unp_buffer);
1354   free(rar->lzss.window);
1355   __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
1356   free(rar);
1357   (a->format->data) = NULL;
1358   return (ARCHIVE_OK);
1359 }
1360 
1361 static int
read_header(struct archive_read * a,struct archive_entry * entry,char head_type)1362 read_header(struct archive_read *a, struct archive_entry *entry,
1363             char head_type)
1364 {
1365   const void *h;
1366   const char *p, *endp;
1367   struct rar *rar;
1368   struct rar_header rar_header;
1369   struct rar_file_header file_header;
1370   int64_t header_size;
1371   unsigned filename_size, end;
1372   char *filename;
1373   char *strp;
1374   char packed_size[8];
1375   char unp_size[8];
1376   int ttime;
1377   struct archive_string_conv *sconv, *fn_sconv;
1378   uint32_t crc32_computed, crc32_read;
1379   int ret = (ARCHIVE_OK), ret2;
1380   char *newptr;
1381   size_t newsize;
1382 
1383   rar = (struct rar *)(a->format->data);
1384 
1385   /* Setup a string conversion object for non-rar-unicode filenames. */
1386   sconv = rar->opt_sconv;
1387   if (sconv == NULL) {
1388     if (!rar->init_default_conversion) {
1389       rar->sconv_default =
1390           archive_string_default_conversion_for_read(
1391             &(a->archive));
1392       rar->init_default_conversion = 1;
1393     }
1394     sconv = rar->sconv_default;
1395   }
1396 
1397 
1398   if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
1399     return (ARCHIVE_FATAL);
1400   p = h;
1401   memcpy(&rar_header, p, sizeof(rar_header));
1402   rar->file_flags = archive_le16dec(rar_header.flags);
1403   header_size = archive_le16dec(rar_header.size);
1404   if (header_size < (int64_t)sizeof(file_header) + 7) {
1405     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1406       "Invalid header size");
1407     return (ARCHIVE_FATAL);
1408   }
1409   crc32_computed = crc32(0, (const unsigned char *)p + 2, 7 - 2);
1410   __archive_read_consume(a, 7);
1411 
1412   if (!(rar->file_flags & FHD_SOLID))
1413   {
1414     rar->compression_method = 0;
1415     rar->packed_size = 0;
1416     rar->unp_size = 0;
1417     rar->mtime = 0;
1418     rar->ctime = 0;
1419     rar->atime = 0;
1420     rar->arctime = 0;
1421     rar->mode = 0;
1422     memset(&rar->salt, 0, sizeof(rar->salt));
1423     rar->atime = 0;
1424     rar->ansec = 0;
1425     rar->ctime = 0;
1426     rar->cnsec = 0;
1427     rar->mtime = 0;
1428     rar->mnsec = 0;
1429     rar->arctime = 0;
1430     rar->arcnsec = 0;
1431   }
1432   else
1433   {
1434     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1435                       "RAR solid archive support unavailable");
1436     return (ARCHIVE_FATAL);
1437   }
1438 
1439   if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
1440   {
1441     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1442                       "Failed to read full header content");
1443     return (ARCHIVE_FATAL);
1444   }
1445 
1446   /* File Header CRC check. */
1447   crc32_computed = crc32(crc32_computed, h, (unsigned)(header_size - 7));
1448   crc32_read = archive_le16dec(rar_header.crc);
1449   if ((crc32_computed & 0xffff) != crc32_read) {
1450 #ifndef DONT_FAIL_ON_CRC_ERROR
1451     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1452       "Header CRC error");
1453     return (ARCHIVE_FATAL);
1454 #endif
1455   }
1456   /* If no CRC error, go on parsing File Header. */
1457   p = h;
1458   endp = p + header_size - 7;
1459   memcpy(&file_header, p, sizeof(file_header));
1460   p += sizeof(file_header);
1461 
1462   rar->compression_method = file_header.method;
1463 
1464   ttime = archive_le32dec(file_header.file_time);
1465   rar->mtime = get_time(ttime);
1466 
1467   rar->file_crc = archive_le32dec(file_header.file_crc);
1468 
1469   if (rar->file_flags & FHD_PASSWORD)
1470   {
1471     archive_entry_set_is_data_encrypted(entry, 1);
1472     rar->has_encrypted_entries = 1;
1473     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1474                       "RAR encryption support unavailable");
1475     /* Since it is only the data part itself that is encrypted we can at least
1476        extract information about the currently processed entry and don't need
1477        to return ARCHIVE_FATAL here. */
1478     /*return (ARCHIVE_FATAL);*/
1479   }
1480 
1481   if (rar->file_flags & FHD_LARGE)
1482   {
1483     if (p + 8 > endp) {
1484       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1485                         "Invalid header size");
1486       return (ARCHIVE_FATAL);
1487     }
1488     memcpy(packed_size, file_header.pack_size, 4);
1489     memcpy(packed_size + 4, p, 4); /* High pack size */
1490     p += 4;
1491     memcpy(unp_size, file_header.unp_size, 4);
1492     memcpy(unp_size + 4, p, 4); /* High unpack size */
1493     p += 4;
1494     rar->packed_size = archive_le64dec(&packed_size);
1495     rar->unp_size = archive_le64dec(&unp_size);
1496   }
1497   else
1498   {
1499     rar->packed_size = archive_le32dec(file_header.pack_size);
1500     rar->unp_size = archive_le32dec(file_header.unp_size);
1501   }
1502 
1503   if (rar->packed_size < 0 || rar->unp_size < 0)
1504   {
1505     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1506                       "Invalid sizes specified");
1507     return (ARCHIVE_FATAL);
1508   }
1509 
1510   rar->bytes_remaining = rar->packed_size;
1511 
1512   /* TODO: RARv3 subblocks contain comments. For now the complete block is
1513    * consumed at the end.
1514    */
1515   if (head_type == NEWSUB_HEAD) {
1516     size_t distance = p - (const char *)h;
1517     if (rar->packed_size > INT64_MAX - header_size) {
1518       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1519                         "Extended header size too large");
1520       return (ARCHIVE_FATAL);
1521     }
1522     header_size += rar->packed_size;
1523     if ((uintmax_t)header_size > SIZE_MAX) {
1524       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1525                         "Unable to read extended header data");
1526       return (ARCHIVE_FATAL);
1527     }
1528     /* Make sure we have the extended data. */
1529     if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) {
1530       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1531                         "Failed to read extended header data");
1532       return (ARCHIVE_FATAL);
1533     }
1534     p = h;
1535     endp = p + header_size - 7;
1536     p += distance;
1537   }
1538 
1539   filename_size = archive_le16dec(file_header.name_size);
1540   if (p + filename_size > endp) {
1541     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1542       "Invalid filename size");
1543     return (ARCHIVE_FATAL);
1544   }
1545   if (rar->filename_allocated < filename_size * 2 + 2) {
1546     newsize = filename_size * 2 + 2;
1547     newptr = realloc(rar->filename, newsize);
1548     if (newptr == NULL) {
1549       archive_set_error(&a->archive, ENOMEM,
1550                         "Couldn't allocate memory");
1551       return (ARCHIVE_FATAL);
1552     }
1553     rar->filename = newptr;
1554     rar->filename_allocated = newsize;
1555   }
1556   filename = rar->filename;
1557   memcpy(filename, p, filename_size);
1558   filename[filename_size] = '\0';
1559   if (rar->file_flags & FHD_UNICODE)
1560   {
1561     if (filename_size != strlen(filename))
1562     {
1563       unsigned char highbyte, flagbits, flagbyte;
1564       unsigned fn_end, offset;
1565 
1566       end = filename_size;
1567       fn_end = filename_size * 2;
1568       filename_size = 0;
1569       offset = (unsigned)strlen(filename) + 1;
1570       highbyte = offset >= end ? 0 : *(p + offset++);
1571       flagbits = 0;
1572       flagbyte = 0;
1573       while (offset < end && filename_size < fn_end)
1574       {
1575         if (!flagbits)
1576         {
1577           flagbyte = *(p + offset++);
1578           flagbits = 8;
1579         }
1580 
1581         flagbits -= 2;
1582         switch((flagbyte >> flagbits) & 3)
1583         {
1584           case 0:
1585             if (offset >= end)
1586               continue;
1587             filename[filename_size++] = '\0';
1588             filename[filename_size++] = *(p + offset++);
1589             break;
1590           case 1:
1591             if (offset >= end)
1592               continue;
1593             filename[filename_size++] = highbyte;
1594             filename[filename_size++] = *(p + offset++);
1595             break;
1596           case 2:
1597             if (offset >= end - 1) {
1598               offset = end;
1599               continue;
1600             }
1601             filename[filename_size++] = *(p + offset + 1);
1602             filename[filename_size++] = *(p + offset);
1603             offset += 2;
1604             break;
1605           case 3:
1606           {
1607             char extra, high;
1608             uint8_t length;
1609 
1610             if (offset >= end)
1611               continue;
1612 
1613             length = *(p + offset++);
1614             if (length & 0x80) {
1615               if (offset >= end)
1616                 continue;
1617               extra = *(p + offset++);
1618               high = (char)highbyte;
1619             } else
1620               extra = high = 0;
1621             length = (length & 0x7f) + 2;
1622             while (length && filename_size < fn_end) {
1623               unsigned cp = filename_size >> 1;
1624               filename[filename_size++] = high;
1625               filename[filename_size++] = p[cp] + extra;
1626               length--;
1627             }
1628           }
1629           break;
1630         }
1631       }
1632       if (filename_size > fn_end) {
1633         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1634           "Invalid filename");
1635         return (ARCHIVE_FATAL);
1636       }
1637       filename[filename_size++] = '\0';
1638       /*
1639        * Do not increment filename_size here as the computations below
1640        * add the space for the terminating NUL explicitly.
1641        */
1642       filename[filename_size] = '\0';
1643 
1644       /* Decoded unicode form is UTF-16BE, so we have to update a string
1645        * conversion object for it. */
1646       if (rar->sconv_utf16be == NULL) {
1647         rar->sconv_utf16be = archive_string_conversion_from_charset(
1648            &a->archive, "UTF-16BE", 1);
1649         if (rar->sconv_utf16be == NULL)
1650           return (ARCHIVE_FATAL);
1651       }
1652       fn_sconv = rar->sconv_utf16be;
1653 
1654       strp = filename;
1655       while (memcmp(strp, "\x00\x00", 2))
1656       {
1657         if (!memcmp(strp, "\x00\\", 2))
1658           *(strp + 1) = '/';
1659         strp += 2;
1660       }
1661       p += offset;
1662     } else {
1663       /*
1664        * If FHD_UNICODE is set but no unicode data, this file name form
1665        * is UTF-8, so we have to update a string conversion object for
1666        * it accordingly.
1667        */
1668       if (rar->sconv_utf8 == NULL) {
1669         rar->sconv_utf8 = archive_string_conversion_from_charset(
1670            &a->archive, "UTF-8", 1);
1671         if (rar->sconv_utf8 == NULL)
1672           return (ARCHIVE_FATAL);
1673       }
1674       fn_sconv = rar->sconv_utf8;
1675       while ((strp = strchr(filename, '\\')) != NULL)
1676         *strp = '/';
1677       p += filename_size;
1678     }
1679   }
1680   else
1681   {
1682     fn_sconv = sconv;
1683     while ((strp = strchr(filename, '\\')) != NULL)
1684       *strp = '/';
1685     p += filename_size;
1686   }
1687 
1688   /* Split file in multivolume RAR. No more need to process header. */
1689   if (rar->filename_save &&
1690     filename_size == rar->filename_save_size &&
1691     !memcmp(rar->filename, rar->filename_save, filename_size + 1))
1692   {
1693     __archive_read_consume(a, header_size - 7);
1694     rar->br.avail_in = 0;
1695     rar->br.next_in = NULL;
1696     rar->cursor++;
1697     if (rar->cursor >= rar->nodes)
1698     {
1699       struct data_block_offsets *newdbo;
1700 
1701       newsize = sizeof(*rar->dbo) * (rar->nodes + 1);
1702       if ((newdbo = realloc(rar->dbo, newsize)) == NULL)
1703       {
1704         archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory");
1705         return (ARCHIVE_FATAL);
1706       }
1707       rar->dbo = newdbo;
1708       rar->nodes++;
1709       rar->dbo[rar->cursor].header_size = header_size;
1710       rar->dbo[rar->cursor].start_offset = -1;
1711       rar->dbo[rar->cursor].end_offset = -1;
1712     }
1713     if (rar->dbo[rar->cursor].start_offset < 0)
1714     {
1715       if (rar->packed_size > INT64_MAX - a->filter->position)
1716       {
1717         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1718                           "Unable to store offsets");
1719         return (ARCHIVE_FATAL);
1720       }
1721       rar->dbo[rar->cursor].start_offset = a->filter->position;
1722       rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset +
1723         rar->packed_size;
1724     }
1725     return ret;
1726   }
1727   else if (rar->filename_must_match)
1728   {
1729     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1730       "Mismatch of file parts split across multi-volume archive");
1731     return (ARCHIVE_FATAL);
1732   }
1733 
1734   newsize = filename_size + 1;
1735   if ((newptr = realloc(rar->filename_save, newsize)) == NULL)
1736   {
1737     archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory");
1738     return (ARCHIVE_FATAL);
1739   }
1740   rar->filename_save = newptr;
1741   memcpy(rar->filename_save, rar->filename, newsize);
1742   rar->filename_save_size = filename_size;
1743 
1744   /* Set info for seeking */
1745   free(rar->dbo);
1746   if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL)
1747   {
1748     archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory");
1749     return (ARCHIVE_FATAL);
1750   }
1751   rar->dbo[0].header_size = header_size;
1752   rar->dbo[0].start_offset = -1;
1753   rar->dbo[0].end_offset = -1;
1754   rar->cursor = 0;
1755   rar->nodes = 1;
1756 
1757   if (rar->file_flags & FHD_SALT)
1758   {
1759     if (p + 8 > endp) {
1760       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1761         "Invalid header size");
1762       return (ARCHIVE_FATAL);
1763     }
1764     memcpy(rar->salt, p, 8);
1765     p += 8;
1766   }
1767 
1768   if (rar->file_flags & FHD_EXTTIME) {
1769     if (read_exttime(p, rar, endp) < 0) {
1770       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1771         "Invalid header size");
1772       return (ARCHIVE_FATAL);
1773     }
1774   }
1775 
1776   __archive_read_consume(a, header_size - 7);
1777   if (rar->packed_size > INT64_MAX - a->filter->position) {
1778     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1779                       "Unable to store offsets");
1780     return (ARCHIVE_FATAL);
1781   }
1782   rar->dbo[0].start_offset = a->filter->position;
1783   rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size;
1784 
1785   switch(file_header.host_os)
1786   {
1787   case OS_MSDOS:
1788   case OS_OS2:
1789   case OS_WIN32:
1790     rar->mode = (__LA_MODE_T)archive_le32dec(file_header.file_attr);
1791     if (rar->mode & FILE_ATTRIBUTE_DIRECTORY)
1792       rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
1793     else
1794       rar->mode = AE_IFREG;
1795     rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
1796     break;
1797 
1798   case OS_UNIX:
1799   case OS_MAC_OS:
1800   case OS_BEOS:
1801     rar->mode = (__LA_MODE_T)archive_le32dec(file_header.file_attr);
1802     break;
1803 
1804   default:
1805     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1806                       "Unknown file attributes from RAR file's host OS");
1807     return (ARCHIVE_FATAL);
1808   }
1809 
1810   rar->bytes_uncopied = rar->bytes_unconsumed = 0;
1811   rar->lzss.position = rar->offset = 0;
1812   rar->offset_seek = 0;
1813   rar->dictionary_size = 0;
1814   rar->offset_outgoing = 0;
1815   rar->br.cache_avail = 0;
1816   rar->br.avail_in = 0;
1817   rar->br.next_in = NULL;
1818   rar->crc_calculated = 0;
1819   rar->entry_eof = 0;
1820   rar->valid = 1;
1821   rar->is_ppmd_block = 0;
1822   rar->start_new_table = 1;
1823   free(rar->unp_buffer);
1824   rar->unp_buffer = NULL;
1825   rar->unp_offset = 0;
1826   rar->unp_buffer_size = UNP_BUFFER_SIZE;
1827   memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
1828   __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
1829   rar->ppmd_valid = rar->ppmd_eod = 0;
1830   rar->filters.filterstart = INT64_MAX;
1831 
1832   /* Don't set any archive entries for non-file header types */
1833   if (head_type == NEWSUB_HEAD)
1834     return ret;
1835 
1836   archive_entry_set_mtime(entry, rar->mtime, rar->mnsec);
1837   archive_entry_set_ctime(entry, rar->ctime, rar->cnsec);
1838   archive_entry_set_atime(entry, rar->atime, rar->ansec);
1839   archive_entry_set_size(entry, rar->unp_size);
1840   archive_entry_set_mode(entry, rar->mode);
1841 
1842   if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv))
1843   {
1844     if (errno == ENOMEM)
1845     {
1846       archive_set_error(&a->archive, ENOMEM,
1847                         "Can't allocate memory for Pathname");
1848       return (ARCHIVE_FATAL);
1849     }
1850     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1851                       "Pathname cannot be converted from %s to current locale",
1852                       archive_string_conversion_charset_name(fn_sconv));
1853     ret = (ARCHIVE_WARN);
1854   }
1855 
1856   if (((rar->mode) & AE_IFMT) == AE_IFLNK)
1857   {
1858     /* Make sure a symbolic-link file does not have its body. */
1859     rar->bytes_remaining = 0;
1860     archive_entry_set_size(entry, 0);
1861 
1862     /* Read a symbolic-link name. */
1863     if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN))
1864       return ret2;
1865     if (ret > ret2)
1866       ret = ret2;
1867   }
1868 
1869   if (rar->bytes_remaining == 0)
1870     rar->entry_eof = 1;
1871 
1872   return ret;
1873 }
1874 
1875 static time_t
get_time(int ttime)1876 get_time(int ttime)
1877 {
1878   struct tm tm;
1879   tm.tm_sec = 2 * (ttime & 0x1f);
1880   tm.tm_min = (ttime >> 5) & 0x3f;
1881   tm.tm_hour = (ttime >> 11) & 0x1f;
1882   tm.tm_mday = (ttime >> 16) & 0x1f;
1883   tm.tm_mon = ((ttime >> 21) & 0x0f) - 1;
1884   tm.tm_year = ((ttime >> 25) & 0x7f) + 80;
1885   tm.tm_isdst = -1;
1886   return mktime(&tm);
1887 }
1888 
1889 static int
read_exttime(const char * p,struct rar * rar,const char * endp)1890 read_exttime(const char *p, struct rar *rar, const char *endp)
1891 {
1892   unsigned rmode, flags, rem, j, count;
1893   int ttime, i;
1894   struct tm *tm;
1895   time_t t;
1896   long nsec;
1897 #if defined(HAVE_LOCALTIME_R) || defined(HAVE_LOCALTIME_S)
1898   struct tm tmbuf;
1899 #endif
1900 
1901   if (p + 2 > endp)
1902     return (-1);
1903   flags = archive_le16dec(p);
1904   p += 2;
1905 
1906   for (i = 3; i >= 0; i--)
1907   {
1908     t = 0;
1909     if (i == 3)
1910       t = rar->mtime;
1911     rmode = flags >> i * 4;
1912     if (rmode & 8)
1913     {
1914       if (!t)
1915       {
1916         if (p + 4 > endp)
1917           return (-1);
1918         ttime = archive_le32dec(p);
1919         t = get_time(ttime);
1920         p += 4;
1921       }
1922       rem = 0;
1923       count = rmode & 3;
1924       if (p + count > endp)
1925         return (-1);
1926       for (j = 0; j < count; j++)
1927       {
1928         rem = (((unsigned)(unsigned char)*p) << 16) | (rem >> 8);
1929         p++;
1930       }
1931 #if defined(HAVE_LOCALTIME_S)
1932       tm = localtime_s(&tmbuf, &t) ? NULL : &tmbuf;
1933 #elif defined(HAVE_LOCALTIME_R)
1934       tm = localtime_r(&t, &tmbuf);
1935 #else
1936       tm = localtime(&t);
1937 #endif
1938       nsec = tm->tm_sec + rem / NS_UNIT;
1939       if (rmode & 4)
1940       {
1941         tm->tm_sec++;
1942         t = mktime(tm);
1943       }
1944       if (i == 3)
1945       {
1946         rar->mtime = t;
1947         rar->mnsec = nsec;
1948       }
1949       else if (i == 2)
1950       {
1951         rar->ctime = t;
1952         rar->cnsec = nsec;
1953       }
1954       else if (i == 1)
1955       {
1956         rar->atime = t;
1957         rar->ansec = nsec;
1958       }
1959       else
1960       {
1961         rar->arctime = t;
1962         rar->arcnsec = nsec;
1963       }
1964     }
1965   }
1966   return (0);
1967 }
1968 
1969 static int
read_symlink_stored(struct archive_read * a,struct archive_entry * entry,struct archive_string_conv * sconv)1970 read_symlink_stored(struct archive_read *a, struct archive_entry *entry,
1971                     struct archive_string_conv *sconv)
1972 {
1973   const void *h;
1974   const char *p;
1975   struct rar *rar;
1976   int ret = (ARCHIVE_OK);
1977 
1978   rar = (struct rar *)(a->format->data);
1979   if ((uintmax_t)rar->packed_size > SIZE_MAX)
1980   {
1981     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1982                       "Unable to read link");
1983     return (ARCHIVE_FATAL);
1984   }
1985   if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL)
1986   {
1987     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1988                       "Failed to read link");
1989     return (ARCHIVE_FATAL);
1990   }
1991   p = h;
1992 
1993   if (archive_entry_copy_symlink_l(entry,
1994       p, (size_t)rar->packed_size, sconv))
1995   {
1996     if (errno == ENOMEM)
1997     {
1998       archive_set_error(&a->archive, ENOMEM,
1999                         "Can't allocate memory for link");
2000       return (ARCHIVE_FATAL);
2001     }
2002     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2003                       "link cannot be converted from %s to current locale",
2004                       archive_string_conversion_charset_name(sconv));
2005     ret = (ARCHIVE_WARN);
2006   }
2007   __archive_read_consume(a, rar->packed_size);
2008   return ret;
2009 }
2010 
2011 static int
read_data_stored(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset)2012 read_data_stored(struct archive_read *a, const void **buff, size_t *size,
2013                  int64_t *offset)
2014 {
2015   struct rar *rar;
2016   ssize_t bytes_avail;
2017 
2018   rar = (struct rar *)(a->format->data);
2019   if (rar->bytes_remaining == 0 &&
2020     !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER))
2021   {
2022     *buff = NULL;
2023     *size = 0;
2024     *offset = rar->offset;
2025     if (rar->file_crc != rar->crc_calculated) {
2026 #ifndef DONT_FAIL_ON_CRC_ERROR
2027       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2028                         "File CRC error");
2029       return (ARCHIVE_FATAL);
2030 #endif
2031     }
2032     rar->entry_eof = 1;
2033     return (ARCHIVE_EOF);
2034   }
2035 
2036   *buff = rar_read_ahead(a, 1, &bytes_avail);
2037   if (bytes_avail <= 0)
2038   {
2039     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2040                       "Truncated RAR file data");
2041     return (ARCHIVE_FATAL);
2042   }
2043 
2044   *size = bytes_avail;
2045   *offset = rar->offset;
2046   rar->offset += bytes_avail;
2047   rar->offset_seek += bytes_avail;
2048   rar->bytes_remaining -= bytes_avail;
2049   rar->bytes_unconsumed = bytes_avail;
2050   /* Calculate File CRC. */
2051   rar->crc_calculated = crc32(rar->crc_calculated, *buff,
2052     (unsigned)bytes_avail);
2053   return (ARCHIVE_OK);
2054 }
2055 
2056 static int
read_data_compressed(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset,size_t looper)2057 read_data_compressed(struct archive_read *a, const void **buff, size_t *size,
2058                      int64_t *offset, size_t looper)
2059 {
2060   if (looper++ > MAX_COMPRESS_DEPTH)
2061     return (ARCHIVE_FATAL);
2062 
2063   struct rar *rar;
2064   int64_t start, end;
2065   size_t bs;
2066   int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i;
2067 
2068   rar = (struct rar *)(a->format->data);
2069 
2070   do {
2071     if (!rar->valid)
2072       return (ARCHIVE_FATAL);
2073 
2074     if (rar->filters.bytes_ready > 0)
2075     {
2076       /* Flush unp_buffer first */
2077       if (rar->unp_offset > 0)
2078       {
2079         *buff = rar->unp_buffer;
2080         *size = rar->unp_offset;
2081         rar->unp_offset = 0;
2082         *offset = rar->offset_outgoing;
2083         rar->offset_outgoing += *size;
2084       }
2085       else
2086       {
2087         *buff = rar->filters.bytes;
2088         *size = rar->filters.bytes_ready;
2089 
2090         rar->offset += *size;
2091         *offset = rar->offset_outgoing;
2092         rar->offset_outgoing += *size;
2093 
2094         rar->filters.bytes_ready -= *size;
2095         rar->filters.bytes += *size;
2096       }
2097       goto ending_block;
2098     }
2099 
2100     if (rar->ppmd_eod ||
2101        (rar->dictionary_size && rar->offset >= rar->unp_size))
2102     {
2103       if (rar->unp_offset > 0) {
2104         /*
2105          * We have unprocessed extracted data. write it out.
2106          */
2107         *buff = rar->unp_buffer;
2108         *size = rar->unp_offset;
2109         *offset = rar->offset_outgoing;
2110         rar->offset_outgoing += *size;
2111         /* Calculate File CRC. */
2112         rar->crc_calculated = crc32(rar->crc_calculated, *buff,
2113           (unsigned)*size);
2114         rar->unp_offset = 0;
2115         return (ARCHIVE_OK);
2116       }
2117       *buff = NULL;
2118       *size = 0;
2119       *offset = rar->offset;
2120       if (rar->file_crc != rar->crc_calculated) {
2121 #ifndef DONT_FAIL_ON_CRC_ERROR
2122         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2123                           "File CRC error");
2124         return (ARCHIVE_FATAL);
2125 #endif
2126       }
2127       rar->entry_eof = 1;
2128       return (ARCHIVE_EOF);
2129     }
2130 
2131     if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0)
2132     {
2133       if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
2134         bs = rar->unp_buffer_size - rar->unp_offset;
2135       else
2136         bs = (size_t)rar->bytes_uncopied;
2137       ret = copy_from_lzss_window_to_unp(a, buff, rar->offset, bs);
2138       if (ret != ARCHIVE_OK)
2139         return (ret);
2140       rar->offset += bs;
2141       rar->bytes_uncopied -= bs;
2142       if (*buff != NULL) {
2143         rar->unp_offset = 0;
2144         *size = rar->unp_buffer_size;
2145         *offset = rar->offset_outgoing;
2146         rar->offset_outgoing += *size;
2147         /* Calculate File CRC. */
2148         rar->crc_calculated = crc32(rar->crc_calculated, *buff,
2149           (unsigned)*size);
2150         return (ret);
2151       }
2152       continue;
2153     }
2154 
2155     if (rar->filters.lastend == rar->filters.filterstart)
2156     {
2157       if (!run_filters(a))
2158         return (ARCHIVE_FATAL);
2159       continue;
2160     }
2161 
2162     if (!rar->br.next_in &&
2163       (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN)
2164       return (ret);
2165     if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN)))
2166       return (ret);
2167 
2168     if (rar->is_ppmd_block)
2169     {
2170       if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2171         &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2172       {
2173         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2174                           "Invalid symbol");
2175         return (ARCHIVE_FATAL);
2176       }
2177       if(sym != rar->ppmd_escape)
2178       {
2179         lzss_emit_literal(rar, sym);
2180         rar->bytes_uncopied++;
2181       }
2182       else
2183       {
2184         if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2185           &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2186         {
2187           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2188                             "Invalid symbol");
2189           return (ARCHIVE_FATAL);
2190         }
2191 
2192         switch(code)
2193         {
2194           case 0:
2195             rar->start_new_table = 1;
2196             return read_data_compressed(a, buff, size, offset, looper);
2197 
2198           case 2:
2199             rar->ppmd_eod = 1;/* End Of ppmd Data. */
2200             continue;
2201 
2202           case 3:
2203             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2204                               "Parsing filters is unsupported");
2205             return (ARCHIVE_FAILED);
2206 
2207           case 4:
2208             lzss_offset = 0;
2209             for (i = 2; i >= 0; i--)
2210             {
2211               if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2212                 &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2213               {
2214                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2215                                   "Invalid symbol");
2216                 return (ARCHIVE_FATAL);
2217               }
2218               lzss_offset |= code << (i * 8);
2219             }
2220             if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2221               &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2222             {
2223               archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2224                                 "Invalid symbol");
2225               return (ARCHIVE_FATAL);
2226             }
2227             lzss_emit_match(rar, lzss_offset + 2, length + 32);
2228             rar->bytes_uncopied += length + 32;
2229             break;
2230 
2231           case 5:
2232             if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2233               &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2234             {
2235               archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2236                                 "Invalid symbol");
2237               return (ARCHIVE_FATAL);
2238             }
2239             lzss_emit_match(rar, 1, length + 4);
2240             rar->bytes_uncopied += length + 4;
2241             break;
2242 
2243          default:
2244            lzss_emit_literal(rar, sym);
2245            rar->bytes_uncopied++;
2246         }
2247       }
2248     }
2249     else
2250     {
2251       start = rar->offset;
2252       end = start + rar->dictionary_size;
2253 
2254       /* We don't want to overflow the window and overwrite data that we write
2255        * at 'start'. Therefore, reduce the end length by the maximum match size,
2256        * which is 260 bytes. You can compute this maximum by looking at the
2257        * definition of 'expand', in particular when 'symbol >= 271'. */
2258       /* NOTE: It's possible for 'dictionary_size' to be less than this 260
2259        * value, however that will only be the case when 'unp_size' is small,
2260        * which should only happen when the entry size is small and there's no
2261        * risk of overflowing the buffer */
2262       if (rar->dictionary_size > 260) {
2263         end -= 260;
2264       }
2265 
2266       if (rar->filters.filterstart < end) {
2267         end = rar->filters.filterstart;
2268       }
2269 
2270       ret = expand(a, &end);
2271       if (ret != ARCHIVE_OK)
2272         return (ret);
2273 
2274       rar->bytes_uncopied = end - start;
2275       rar->filters.lastend = end;
2276       if (rar->filters.lastend != rar->filters.filterstart && rar->bytes_uncopied == 0) {
2277           /* Broken RAR files cause this case.
2278           * NOTE: If this case were possible on a normal RAR file
2279           * we would find out where it was actually bad and
2280           * what we would do to solve it. */
2281           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2282                             "Internal error extracting RAR file");
2283           return (ARCHIVE_FATAL);
2284       }
2285     }
2286     if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
2287       bs = rar->unp_buffer_size - rar->unp_offset;
2288     else
2289       bs = (size_t)rar->bytes_uncopied;
2290     ret = copy_from_lzss_window_to_unp(a, buff, rar->offset, bs);
2291     if (ret != ARCHIVE_OK)
2292       return (ret);
2293     rar->offset += bs;
2294     rar->bytes_uncopied -= bs;
2295     /*
2296      * If *buff is NULL, it means unp_buffer is not full.
2297      * So we have to continue extracting a RAR file.
2298      */
2299   } while (*buff == NULL);
2300 
2301   rar->unp_offset = 0;
2302   *size = rar->unp_buffer_size;
2303   *offset = rar->offset_outgoing;
2304   rar->offset_outgoing += *size;
2305 ending_block:
2306   /* Calculate File CRC. */
2307   rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size);
2308   return ret;
2309 }
2310 
2311 static int
parse_codes(struct archive_read * a)2312 parse_codes(struct archive_read *a)
2313 {
2314   int i, j, val, n, r;
2315   unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags;
2316   unsigned int maxorder;
2317   struct huffman_code precode;
2318   struct rar *rar = (struct rar *)(a->format->data);
2319   struct rar_br *br = &(rar->br);
2320 
2321   free_codes(a);
2322 
2323   /* Skip to the next byte */
2324   rar_br_consume_unaligned_bits(br);
2325 
2326   /* PPMd block flag */
2327   if (!rar_br_read_ahead(a, br, 1))
2328     goto truncated_data;
2329   if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0)
2330   {
2331     rar_br_consume(br, 1);
2332     if (!rar_br_read_ahead(a, br, 7))
2333       goto truncated_data;
2334     ppmd_flags = rar_br_bits(br, 7);
2335     rar_br_consume(br, 7);
2336 
2337     /* Memory is allocated in MB */
2338     if (ppmd_flags & 0x20)
2339     {
2340       if (!rar_br_read_ahead(a, br, 8))
2341         goto truncated_data;
2342       rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20;
2343       rar_br_consume(br, 8);
2344     }
2345 
2346     if (ppmd_flags & 0x40)
2347     {
2348       if (!rar_br_read_ahead(a, br, 8))
2349         goto truncated_data;
2350       rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8);
2351       rar_br_consume(br, 8);
2352     }
2353     else
2354       rar->ppmd_escape = 2;
2355 
2356     if (ppmd_flags & 0x20)
2357     {
2358       maxorder = (ppmd_flags & 0x1F) + 1;
2359       if(maxorder > 16)
2360         maxorder = 16 + (maxorder - 16) * 3;
2361 
2362       if (maxorder == 1)
2363       {
2364         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2365                           "Truncated RAR file data");
2366         return (ARCHIVE_FATAL);
2367       }
2368 
2369       /* Make sure ppmd7_context is freed before Ppmd7_Construct
2370        * because reading a broken file causes this abnormal sequence. */
2371       __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
2372 
2373       rar->bytein.a = a;
2374       rar->bytein.Read = &ppmd_read;
2375       __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec);
2376       rar->range_dec.Stream = &rar->bytein;
2377       __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context);
2378 
2379       if (rar->dictionary_size == 0) {
2380         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2381                           "Invalid zero dictionary size");
2382         return (ARCHIVE_FATAL);
2383       }
2384 
2385       if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context,
2386         rar->dictionary_size))
2387       {
2388         archive_set_error(&a->archive, ENOMEM,
2389                           "Out of memory");
2390         return (ARCHIVE_FATAL);
2391       }
2392       if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
2393       {
2394         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2395                           "Unable to initialize PPMd range decoder");
2396         return (ARCHIVE_FATAL);
2397       }
2398       __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder);
2399       rar->ppmd_valid = 1;
2400     }
2401     else
2402     {
2403       if (!rar->ppmd_valid) {
2404         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2405                           "Invalid PPMd sequence");
2406         return (ARCHIVE_FATAL);
2407       }
2408       if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
2409       {
2410         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2411                           "Unable to initialize PPMd range decoder");
2412         return (ARCHIVE_FATAL);
2413       }
2414     }
2415   }
2416   else
2417   {
2418     rar_br_consume(br, 1);
2419 
2420     /* Keep existing table flag */
2421     if (!rar_br_read_ahead(a, br, 1))
2422       goto truncated_data;
2423     if (!rar_br_bits(br, 1))
2424       memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
2425     rar_br_consume(br, 1);
2426 
2427     memset(&bitlengths, 0, sizeof(bitlengths));
2428     for (i = 0; i < MAX_SYMBOLS;)
2429     {
2430       if (!rar_br_read_ahead(a, br, 4))
2431         goto truncated_data;
2432       bitlengths[i++] = rar_br_bits(br, 4);
2433       rar_br_consume(br, 4);
2434       if (bitlengths[i-1] == 0xF)
2435       {
2436         if (!rar_br_read_ahead(a, br, 4))
2437           goto truncated_data;
2438         zerocount = rar_br_bits(br, 4);
2439         rar_br_consume(br, 4);
2440         if (zerocount)
2441         {
2442           i--;
2443           for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++)
2444             bitlengths[i++] = 0;
2445         }
2446       }
2447     }
2448 
2449     memset(&precode, 0, sizeof(precode));
2450     r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH);
2451     if (r != ARCHIVE_OK) {
2452       free(precode.tree);
2453       free(precode.table);
2454       return (r);
2455     }
2456 
2457     for (i = 0; i < HUFFMAN_TABLE_SIZE;)
2458     {
2459       if ((val = read_next_symbol(a, &precode)) < 0) {
2460         free(precode.tree);
2461         free(precode.table);
2462         return (ARCHIVE_FATAL);
2463       }
2464       if (val < 16)
2465       {
2466         rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF;
2467         i++;
2468       }
2469       else if (val < 18)
2470       {
2471         if (i == 0)
2472         {
2473           free(precode.tree);
2474           free(precode.table);
2475           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2476                             "Internal error extracting RAR file");
2477           return (ARCHIVE_FATAL);
2478         }
2479 
2480         if(val == 16) {
2481           if (!rar_br_read_ahead(a, br, 3)) {
2482             free(precode.tree);
2483             free(precode.table);
2484             goto truncated_data;
2485           }
2486           n = rar_br_bits(br, 3) + 3;
2487           rar_br_consume(br, 3);
2488         } else {
2489           if (!rar_br_read_ahead(a, br, 7)) {
2490             free(precode.tree);
2491             free(precode.table);
2492             goto truncated_data;
2493           }
2494           n = rar_br_bits(br, 7) + 11;
2495           rar_br_consume(br, 7);
2496         }
2497 
2498         for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
2499         {
2500           rar->lengthtable[i] = rar->lengthtable[i-1];
2501           i++;
2502         }
2503       }
2504       else
2505       {
2506         if(val == 18) {
2507           if (!rar_br_read_ahead(a, br, 3)) {
2508             free(precode.tree);
2509             free(precode.table);
2510             goto truncated_data;
2511           }
2512           n = rar_br_bits(br, 3) + 3;
2513           rar_br_consume(br, 3);
2514         } else {
2515           if (!rar_br_read_ahead(a, br, 7)) {
2516             free(precode.tree);
2517             free(precode.table);
2518             goto truncated_data;
2519           }
2520           n = rar_br_bits(br, 7) + 11;
2521           rar_br_consume(br, 7);
2522         }
2523 
2524         for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
2525           rar->lengthtable[i++] = 0;
2526       }
2527     }
2528     free(precode.tree);
2529     free(precode.table);
2530 
2531     r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE,
2532                 MAX_SYMBOL_LENGTH);
2533     if (r != ARCHIVE_OK)
2534       return (r);
2535     r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE],
2536                 OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
2537     if (r != ARCHIVE_OK)
2538       return (r);
2539     r = create_code(a, &rar->lowoffsetcode,
2540                 &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE],
2541                 LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
2542     if (r != ARCHIVE_OK)
2543       return (r);
2544     r = create_code(a, &rar->lengthcode,
2545                 &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE +
2546                 LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH);
2547     if (r != ARCHIVE_OK)
2548       return (r);
2549   }
2550 
2551   if (!rar->dictionary_size || !rar->lzss.window ||
2552       (unsigned int)(rar->lzss.mask + 1) < rar->dictionary_size)
2553   {
2554     /* Seems as though dictionary sizes are not used. Even so, minimize
2555      * memory usage as much as possible.
2556      */
2557     void *new_window;
2558     unsigned int new_size;
2559 
2560     if (rar->unp_size >= DICTIONARY_MAX_SIZE)
2561       new_size = DICTIONARY_MAX_SIZE;
2562     else
2563       new_size = rar_fls((unsigned int)rar->unp_size) << 1;
2564     if (new_size == 0) {
2565       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2566                         "Zero window size is invalid");
2567       return (ARCHIVE_FATAL);
2568     }
2569     new_window = realloc(rar->lzss.window, new_size);
2570     if (new_window == NULL) {
2571       archive_set_error(&a->archive, ENOMEM,
2572                         "Unable to allocate memory for uncompressed data");
2573       return (ARCHIVE_FATAL);
2574     }
2575     rar->lzss.window = (unsigned char *)new_window;
2576     rar->dictionary_size = new_size;
2577     memset(rar->lzss.window, 0, rar->dictionary_size);
2578     rar->lzss.mask = rar->dictionary_size - 1;
2579   }
2580 
2581   rar->start_new_table = 0;
2582   return (ARCHIVE_OK);
2583 truncated_data:
2584   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2585                     "Truncated RAR file data");
2586   rar->valid = 0;
2587   return (ARCHIVE_FATAL);
2588 }
2589 
2590 static void
free_codes(struct archive_read * a)2591 free_codes(struct archive_read *a)
2592 {
2593   struct rar *rar = (struct rar *)(a->format->data);
2594   free(rar->maincode.tree);
2595   free(rar->offsetcode.tree);
2596   free(rar->lowoffsetcode.tree);
2597   free(rar->lengthcode.tree);
2598   free(rar->maincode.table);
2599   free(rar->offsetcode.table);
2600   free(rar->lowoffsetcode.table);
2601   free(rar->lengthcode.table);
2602   memset(&rar->maincode, 0, sizeof(rar->maincode));
2603   memset(&rar->offsetcode, 0, sizeof(rar->offsetcode));
2604   memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode));
2605   memset(&rar->lengthcode, 0, sizeof(rar->lengthcode));
2606 }
2607 
2608 
2609 static int
read_next_symbol(struct archive_read * a,struct huffman_code * code)2610 read_next_symbol(struct archive_read *a, struct huffman_code *code)
2611 {
2612   unsigned char bit;
2613   unsigned int bits;
2614   int length, value, node;
2615   struct rar *rar;
2616   struct rar_br *br;
2617 
2618   if (!code->table)
2619   {
2620     if (make_table(a, code) != (ARCHIVE_OK))
2621       return -1;
2622   }
2623 
2624   rar = (struct rar *)(a->format->data);
2625   br = &(rar->br);
2626 
2627   /* Look ahead (peek) at bits */
2628   if (!rar_br_read_ahead(a, br, code->tablesize)) {
2629     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2630                       "Truncated RAR file data");
2631     rar->valid = 0;
2632     return -1;
2633   }
2634   bits = rar_br_bits(br, code->tablesize);
2635 
2636   length = code->table[bits].length;
2637   value = code->table[bits].value;
2638 
2639   if (length < 0)
2640   {
2641     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2642                       "Invalid prefix code in bitstream");
2643     return -1;
2644   }
2645 
2646   if (length <= code->tablesize)
2647   {
2648     /* Skip length bits */
2649     rar_br_consume(br, length);
2650     return value;
2651   }
2652 
2653   /* Skip tablesize bits */
2654   rar_br_consume(br, code->tablesize);
2655 
2656   node = value;
2657   while (code->tree[node].branches[0] != code->tree[node].branches[1])
2658   {
2659     if (!rar_br_read_ahead(a, br, 1)) {
2660       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2661                         "Truncated RAR file data");
2662       rar->valid = 0;
2663       return -1;
2664     }
2665     bit = rar_br_bits(br, 1);
2666     rar_br_consume(br, 1);
2667 
2668     if (code->tree[node].branches[bit] < 0)
2669     {
2670       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2671                         "Invalid prefix code in bitstream");
2672       return -1;
2673     }
2674     node = code->tree[node].branches[bit];
2675   }
2676 
2677   return code->tree[node].branches[0];
2678 }
2679 
2680 static int
create_code(struct archive_read * a,struct huffman_code * code,unsigned char * lengths,int numsymbols,char maxlength)2681 create_code(struct archive_read *a, struct huffman_code *code,
2682             unsigned char *lengths, int numsymbols, char maxlength)
2683 {
2684   int i, j, codebits = 0, symbolsleft = numsymbols;
2685 
2686   code->numentries = 0;
2687   code->numallocatedentries = 0;
2688   if (new_node(code) < 0) {
2689     archive_set_error(&a->archive, ENOMEM,
2690                       "Unable to allocate memory for node data");
2691     return (ARCHIVE_FATAL);
2692   }
2693   code->numentries = 1;
2694   code->minlength = INT_MAX;
2695   code->maxlength = INT_MIN;
2696   codebits = 0;
2697   for(i = 1; i <= maxlength; i++)
2698   {
2699     for(j = 0; j < numsymbols; j++)
2700     {
2701       if (lengths[j] != i) continue;
2702       if (add_value(a, code, j, codebits, i) != ARCHIVE_OK)
2703         return (ARCHIVE_FATAL);
2704       codebits++;
2705       if (--symbolsleft <= 0)
2706         break;
2707     }
2708     if (symbolsleft <= 0)
2709       break;
2710     codebits <<= 1;
2711   }
2712   return (ARCHIVE_OK);
2713 }
2714 
2715 static int
add_value(struct archive_read * a,struct huffman_code * code,int value,int codebits,int length)2716 add_value(struct archive_read *a, struct huffman_code *code, int value,
2717           int codebits, int length)
2718 {
2719   int lastnode, bitpos, bit;
2720   /* int repeatpos, repeatnode, nextnode; */
2721 
2722   free(code->table);
2723   code->table = NULL;
2724 
2725   if(length > code->maxlength)
2726     code->maxlength = length;
2727   if(length < code->minlength)
2728     code->minlength = length;
2729 
2730   /*
2731    * Dead code, repeatpos was is -1
2732    *
2733   repeatpos = -1;
2734   if (repeatpos == 0 || (repeatpos >= 0
2735     && (((codebits >> (repeatpos - 1)) & 3) == 0
2736     || ((codebits >> (repeatpos - 1)) & 3) == 3)))
2737   {
2738     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2739                       "Invalid repeat position");
2740     return (ARCHIVE_FATAL);
2741   }
2742   */
2743 
2744   lastnode = 0;
2745   for (bitpos = length - 1; bitpos >= 0; bitpos--)
2746   {
2747     bit = (codebits >> bitpos) & 1;
2748 
2749     /* Leaf node check */
2750     if (code->tree[lastnode].branches[0] ==
2751       code->tree[lastnode].branches[1])
2752     {
2753       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2754                         "Prefix found");
2755       return (ARCHIVE_FATAL);
2756     }
2757 
2758     /*
2759      * Dead code, repeatpos was -1, bitpos >=0
2760      *
2761     if (bitpos == repeatpos)
2762     {
2763       * Open branch check *
2764       if (!(code->tree[lastnode].branches[bit] < 0))
2765       {
2766         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2767                           "Invalid repeating code");
2768         return (ARCHIVE_FATAL);
2769       }
2770 
2771       if ((repeatnode = new_node(code)) < 0) {
2772         archive_set_error(&a->archive, ENOMEM,
2773                           "Unable to allocate memory for node data");
2774         return (ARCHIVE_FATAL);
2775       }
2776       if ((nextnode = new_node(code)) < 0) {
2777         archive_set_error(&a->archive, ENOMEM,
2778                           "Unable to allocate memory for node data");
2779         return (ARCHIVE_FATAL);
2780       }
2781 
2782       * Set branches *
2783       code->tree[lastnode].branches[bit] = repeatnode;
2784       code->tree[repeatnode].branches[bit] = repeatnode;
2785       code->tree[repeatnode].branches[bit^1] = nextnode;
2786       lastnode = nextnode;
2787 
2788       bitpos++; * terminating bit already handled, skip it *
2789     }
2790     else
2791     {
2792     */
2793       /* Open branch check */
2794       if (code->tree[lastnode].branches[bit] < 0)
2795       {
2796         if (new_node(code) < 0) {
2797           archive_set_error(&a->archive, ENOMEM,
2798                             "Unable to allocate memory for node data");
2799           return (ARCHIVE_FATAL);
2800         }
2801         code->tree[lastnode].branches[bit] = code->numentries++;
2802       }
2803 
2804       /* set to branch */
2805       lastnode = code->tree[lastnode].branches[bit];
2806  /* } */
2807   }
2808 
2809   if (!(code->tree[lastnode].branches[0] == -1
2810     && code->tree[lastnode].branches[1] == -2))
2811   {
2812     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2813                       "Prefix found");
2814     return (ARCHIVE_FATAL);
2815   }
2816 
2817   /* Set leaf value */
2818   code->tree[lastnode].branches[0] = value;
2819   code->tree[lastnode].branches[1] = value;
2820 
2821   return (ARCHIVE_OK);
2822 }
2823 
2824 static int
new_node(struct huffman_code * code)2825 new_node(struct huffman_code *code)
2826 {
2827   void *new_tree;
2828   if (code->numallocatedentries == code->numentries) {
2829     int new_num_entries = 256;
2830     if (code->numentries > 0) {
2831         new_num_entries = code->numentries * 2;
2832     }
2833     new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree));
2834     if (new_tree == NULL)
2835         return (-1);
2836     code->tree = (struct huffman_tree_node *)new_tree;
2837     code->numallocatedentries = new_num_entries;
2838   }
2839   code->tree[code->numentries].branches[0] = -1;
2840   code->tree[code->numentries].branches[1] = -2;
2841   return 1;
2842 }
2843 
2844 static int
make_table(struct archive_read * a,struct huffman_code * code)2845 make_table(struct archive_read *a, struct huffman_code *code)
2846 {
2847   if (code->maxlength < code->minlength || code->maxlength > 10)
2848     code->tablesize = 10;
2849   else
2850     code->tablesize = code->maxlength;
2851 
2852   code->table = calloc(((size_t)1U) << code->tablesize, sizeof(*code->table));
2853 
2854   return make_table_recurse(a, code, 0, code->table, 0, code->tablesize);
2855 }
2856 
2857 static int
make_table_recurse(struct archive_read * a,struct huffman_code * code,int node,struct huffman_table_entry * table,int depth,int maxdepth)2858 make_table_recurse(struct archive_read *a, struct huffman_code *code, int node,
2859                    struct huffman_table_entry *table, int depth,
2860                    int maxdepth)
2861 {
2862   int currtablesize, i, ret = (ARCHIVE_OK);
2863 
2864   if (!code->tree)
2865   {
2866     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2867                       "Huffman tree was not created");
2868     return (ARCHIVE_FATAL);
2869   }
2870   if (node < 0 || node >= code->numentries)
2871   {
2872     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2873                       "Invalid location to Huffman tree specified");
2874     return (ARCHIVE_FATAL);
2875   }
2876 
2877   currtablesize = 1 << (maxdepth - depth);
2878 
2879   if (code->tree[node].branches[0] ==
2880     code->tree[node].branches[1])
2881   {
2882     for(i = 0; i < currtablesize; i++)
2883     {
2884       table[i].length = depth;
2885       table[i].value = code->tree[node].branches[0];
2886     }
2887   }
2888   /*
2889    * Dead code, node >= 0
2890    *
2891   else if (node < 0)
2892   {
2893     for(i = 0; i < currtablesize; i++)
2894       table[i].length = -1;
2895   }
2896    */
2897   else
2898   {
2899     if(depth == maxdepth)
2900     {
2901       table[0].length = maxdepth + 1;
2902       table[0].value = node;
2903     }
2904     else
2905     {
2906       ret |= make_table_recurse(a, code, code->tree[node].branches[0], table,
2907                                 depth + 1, maxdepth);
2908       ret |= make_table_recurse(a, code, code->tree[node].branches[1],
2909                          table + currtablesize / 2, depth + 1, maxdepth);
2910     }
2911   }
2912   return ret;
2913 }
2914 
2915 static int
expand(struct archive_read * a,int64_t * end)2916 expand(struct archive_read *a, int64_t *end)
2917 {
2918   static const unsigned char lengthbases[] =
2919     {   0,   1,   2,   3,   4,   5,   6,
2920         7,   8,  10,  12,  14,  16,  20,
2921        24,  28,  32,  40,  48,  56,  64,
2922        80,  96, 112, 128, 160, 192, 224 };
2923   static const unsigned char lengthbits[] =
2924     { 0, 0, 0, 0, 0, 0, 0,
2925       0, 1, 1, 1, 1, 2, 2,
2926       2, 2, 3, 3, 3, 3, 4,
2927       4, 4, 4, 5, 5, 5, 5 };
2928   static const int lengthb_min = minimum(
2929     (int)(sizeof(lengthbases)/sizeof(lengthbases[0])),
2930     (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))
2931   );
2932   static const unsigned int offsetbases[] =
2933     {       0,       1,       2,       3,       4,       6,
2934             8,      12,      16,      24,      32,      48,
2935            64,      96,     128,     192,     256,     384,
2936           512,     768,    1024,    1536,    2048,    3072,
2937          4096,    6144,    8192,   12288,   16384,   24576,
2938         32768,   49152,   65536,   98304,  131072,  196608,
2939        262144,  327680,  393216,  458752,  524288,  589824,
2940        655360,  720896,  786432,  851968,  917504,  983040,
2941       1048576, 1310720, 1572864, 1835008, 2097152, 2359296,
2942       2621440, 2883584, 3145728, 3407872, 3670016, 3932160 };
2943   static const unsigned char offsetbits[] =
2944     {  0,  0,  0,  0,  1,  1,  2,  2,  3,  3,  4,  4,
2945        5,  5,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10,
2946       11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16,
2947       16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2948       18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 };
2949   static const int offsetb_min = minimum(
2950     (int)(sizeof(offsetbases)/sizeof(offsetbases[0])),
2951     (int)(sizeof(offsetbits)/sizeof(offsetbits[0]))
2952   );
2953   static const unsigned char shortbases[] =
2954     { 0, 4, 8, 16, 32, 64, 128, 192 };
2955   static const unsigned char shortbits[] =
2956     { 2, 2, 3, 4, 5, 6, 6, 6 };
2957 
2958   int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol;
2959   unsigned char newfile;
2960   struct rar *rar = (struct rar *)(a->format->data);
2961   struct rar_br *br = &(rar->br);
2962 
2963   if (rar->filters.filterstart < *end)
2964     *end = rar->filters.filterstart;
2965 
2966   while (1)
2967   {
2968     if(lzss_position(&rar->lzss) >= *end) {
2969       return (ARCHIVE_OK);
2970     }
2971 
2972     if(rar->is_ppmd_block) {
2973       *end = lzss_position(&rar->lzss);
2974       return (ARCHIVE_OK);
2975     }
2976 
2977     if ((symbol = read_next_symbol(a, &rar->maincode)) < 0)
2978       goto bad_data;
2979 
2980     if (symbol < 256)
2981     {
2982       lzss_emit_literal(rar, (uint8_t)symbol);
2983       continue;
2984     }
2985     else if (symbol == 256)
2986     {
2987       if (!rar_br_read_ahead(a, br, 1))
2988         goto truncated_data;
2989       newfile = !rar_br_bits(br, 1);
2990       rar_br_consume(br, 1);
2991 
2992       if(newfile)
2993       {
2994         rar->start_new_block = 1;
2995         if (!rar_br_read_ahead(a, br, 1))
2996           goto truncated_data;
2997         rar->start_new_table = rar_br_bits(br, 1);
2998         rar_br_consume(br, 1);
2999         *end = lzss_position(&rar->lzss);
3000         return (ARCHIVE_OK);
3001       }
3002       else
3003       {
3004         if (parse_codes(a) != ARCHIVE_OK)
3005           goto bad_data;
3006         continue;
3007       }
3008     }
3009     else if(symbol==257)
3010     {
3011       if (!read_filter(a, end))
3012           goto bad_data;
3013       continue;
3014     }
3015     else if(symbol==258)
3016     {
3017       if(rar->lastlength == 0)
3018         continue;
3019 
3020       offs = rar->lastoffset;
3021       len = rar->lastlength;
3022     }
3023     else if (symbol <= 262)
3024     {
3025       offsindex = symbol - 259;
3026       offs = rar->oldoffset[offsindex];
3027 
3028       if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0)
3029         goto bad_data;
3030       if (lensymbol >= lengthb_min)
3031         goto bad_data;
3032       len = lengthbases[lensymbol] + 2;
3033       if (lengthbits[lensymbol] > 0) {
3034         if (!rar_br_read_ahead(a, br, lengthbits[lensymbol]))
3035           goto truncated_data;
3036         len += rar_br_bits(br, lengthbits[lensymbol]);
3037         rar_br_consume(br, lengthbits[lensymbol]);
3038       }
3039 
3040       for (i = offsindex; i > 0; i--)
3041         rar->oldoffset[i] = rar->oldoffset[i-1];
3042       rar->oldoffset[0] = offs;
3043     }
3044     else if(symbol<=270)
3045     {
3046       offs = shortbases[symbol-263] + 1;
3047       if(shortbits[symbol-263] > 0) {
3048         if (!rar_br_read_ahead(a, br, shortbits[symbol-263]))
3049           goto truncated_data;
3050         offs += rar_br_bits(br, shortbits[symbol-263]);
3051         rar_br_consume(br, shortbits[symbol-263]);
3052       }
3053 
3054       len = 2;
3055 
3056       for(i = 3; i > 0; i--)
3057         rar->oldoffset[i] = rar->oldoffset[i-1];
3058       rar->oldoffset[0] = offs;
3059     }
3060     else
3061     {
3062       if (symbol-271 >= lengthb_min)
3063         goto bad_data;
3064       len = lengthbases[symbol-271]+3;
3065       if(lengthbits[symbol-271] > 0) {
3066         if (!rar_br_read_ahead(a, br, lengthbits[symbol-271]))
3067           goto truncated_data;
3068         len += rar_br_bits(br, lengthbits[symbol-271]);
3069         rar_br_consume(br, lengthbits[symbol-271]);
3070       }
3071 
3072       if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0)
3073         goto bad_data;
3074       if (offssymbol >= offsetb_min)
3075         goto bad_data;
3076       offs = offsetbases[offssymbol]+1;
3077       if(offsetbits[offssymbol] > 0)
3078       {
3079         if(offssymbol > 9)
3080         {
3081           if(offsetbits[offssymbol] > 4) {
3082             if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4))
3083               goto truncated_data;
3084             offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4;
3085             rar_br_consume(br, offsetbits[offssymbol] - 4);
3086           }
3087 
3088           if(rar->numlowoffsetrepeats > 0)
3089           {
3090             rar->numlowoffsetrepeats--;
3091             offs += rar->lastlowoffset;
3092           }
3093           else
3094           {
3095             if ((lowoffsetsymbol =
3096               read_next_symbol(a, &rar->lowoffsetcode)) < 0)
3097               goto bad_data;
3098             if(lowoffsetsymbol == 16)
3099             {
3100               rar->numlowoffsetrepeats = 15;
3101               offs += rar->lastlowoffset;
3102             }
3103             else
3104             {
3105               offs += lowoffsetsymbol;
3106               rar->lastlowoffset = lowoffsetsymbol;
3107             }
3108           }
3109         }
3110         else {
3111           if (!rar_br_read_ahead(a, br, offsetbits[offssymbol]))
3112             goto truncated_data;
3113           offs += rar_br_bits(br, offsetbits[offssymbol]);
3114           rar_br_consume(br, offsetbits[offssymbol]);
3115         }
3116       }
3117 
3118       if (offs >= 0x40000)
3119         len++;
3120       if (offs >= 0x2000)
3121         len++;
3122 
3123       for(i = 3; i > 0; i--)
3124         rar->oldoffset[i] = rar->oldoffset[i-1];
3125       rar->oldoffset[0] = offs;
3126     }
3127 
3128     rar->lastoffset = offs;
3129     rar->lastlength = len;
3130 
3131     lzss_emit_match(rar, rar->lastoffset, rar->lastlength);
3132   }
3133 truncated_data:
3134   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3135                     "Truncated RAR file data");
3136   rar->valid = 0;
3137   return (ARCHIVE_FATAL);
3138 bad_data:
3139   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3140                     "Bad RAR file data");
3141   return (ARCHIVE_FATAL);
3142 }
3143 
3144 static int
copy_from_lzss_window(struct archive_read * a,uint8_t * buffer,int64_t startpos,int length)3145 copy_from_lzss_window(struct archive_read *a, uint8_t *buffer,
3146                       int64_t startpos, int length)
3147 {
3148   int windowoffs, firstpart;
3149   struct rar *rar = (struct rar *)(a->format->data);
3150 
3151   windowoffs = lzss_offset_for_position(&rar->lzss, startpos);
3152   firstpart = lzss_size(&rar->lzss) - windowoffs;
3153   if (length > lzss_size(&rar->lzss)) {
3154     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3155                       "Bad RAR file data");
3156     return (ARCHIVE_FATAL);
3157   }
3158   if (firstpart < 0) {
3159     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3160                       "Bad RAR file data");
3161     return (ARCHIVE_FATAL);
3162   }
3163   if (firstpart < length) {
3164     memcpy(buffer, &rar->lzss.window[windowoffs], firstpart);
3165     memcpy(buffer + firstpart, &rar->lzss.window[0], length - firstpart);
3166   } else {
3167     memcpy(buffer, &rar->lzss.window[windowoffs], length);
3168   }
3169   return (ARCHIVE_OK);
3170 }
3171 
3172 static int
copy_from_lzss_window_to_unp(struct archive_read * a,const void ** buffer,int64_t startpos,size_t length)3173 copy_from_lzss_window_to_unp(struct archive_read *a, const void **buffer,
3174                              int64_t startpos, size_t length)
3175 {
3176   int windowoffs, firstpart;
3177   struct rar *rar = (struct rar *)(a->format->data);
3178 
3179   if (length > rar->unp_buffer_size)
3180   {
3181     goto fatal;
3182   }
3183 
3184   if (!rar->unp_buffer)
3185   {
3186     if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL)
3187     {
3188       archive_set_error(&a->archive, ENOMEM,
3189                         "Unable to allocate memory for uncompressed data");
3190       return (ARCHIVE_FATAL);
3191     }
3192   }
3193 
3194   windowoffs = lzss_offset_for_position(&rar->lzss, startpos);
3195   if(windowoffs + length <= (size_t)lzss_size(&rar->lzss)) {
3196     memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs],
3197            length);
3198   } else if (length <= (size_t)lzss_size(&rar->lzss)) {
3199     firstpart = lzss_size(&rar->lzss) - windowoffs;
3200     if (firstpart < 0) {
3201       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3202                         "Bad RAR file data");
3203       return (ARCHIVE_FATAL);
3204     }
3205     if ((size_t)firstpart < length) {
3206       memcpy(&rar->unp_buffer[rar->unp_offset],
3207              &rar->lzss.window[windowoffs], firstpart);
3208       memcpy(&rar->unp_buffer[rar->unp_offset + firstpart],
3209              &rar->lzss.window[0], length - firstpart);
3210     } else {
3211       memcpy(&rar->unp_buffer[rar->unp_offset],
3212              &rar->lzss.window[windowoffs], length);
3213     }
3214   } else {
3215       goto fatal;
3216   }
3217   rar->unp_offset += (unsigned int) length;
3218   if (rar->unp_offset >= rar->unp_buffer_size)
3219     *buffer = rar->unp_buffer;
3220   else
3221     *buffer = NULL;
3222   return (ARCHIVE_OK);
3223 
3224 fatal:
3225   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3226                     "Bad RAR file data");
3227   return (ARCHIVE_FATAL);
3228 }
3229 
3230 static const void *
rar_read_ahead(struct archive_read * a,size_t min,ssize_t * avail)3231 rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
3232 {
3233   struct rar *rar = (struct rar *)(a->format->data);
3234   const void *h;
3235   int ret;
3236 
3237 again:
3238   h = __archive_read_ahead(a, min, avail);
3239 
3240   if (avail)
3241   {
3242     if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested)
3243       *avail = a->archive.read_data_requested;
3244     if (*avail > rar->bytes_remaining)
3245       *avail = (ssize_t)rar->bytes_remaining;
3246     if (*avail < 0)
3247       return NULL;
3248     else if (*avail == 0 && rar->main_flags & MHD_VOLUME &&
3249       rar->file_flags & FHD_SPLIT_AFTER)
3250     {
3251       rar->filename_must_match = 1;
3252       ret = archive_read_format_rar_read_header(a, a->entry);
3253       if (ret == (ARCHIVE_EOF))
3254       {
3255         rar->has_endarc_header = 1;
3256         ret = archive_read_format_rar_read_header(a, a->entry);
3257       }
3258       rar->filename_must_match = 0;
3259       if (ret != (ARCHIVE_OK))
3260         return NULL;
3261       goto again;
3262     }
3263   }
3264   return h;
3265 }
3266 
3267 static int
parse_filter(struct archive_read * a,const uint8_t * bytes,uint16_t length,uint8_t flags)3268 parse_filter(struct archive_read *a, const uint8_t *bytes, uint16_t length, uint8_t flags)
3269 {
3270   struct rar *rar = (struct rar *)(a->format->data);
3271   struct rar_filters *filters = &rar->filters;
3272 
3273   struct memory_bit_reader br = { 0 };
3274   struct rar_program_code *prog;
3275   struct rar_filter *filter, **nextfilter;
3276 
3277   uint32_t numprogs, num, blocklength, globaldatalen;
3278   uint8_t *globaldata;
3279   size_t blockstartpos;
3280   uint32_t registers[8] = { 0 };
3281   uint32_t i;
3282 
3283   br.bytes = bytes;
3284   br.length = length;
3285 
3286   numprogs = 0;
3287   for (prog = filters->progs; prog; prog = prog->next)
3288     numprogs++;
3289 
3290   if ((flags & 0x80))
3291   {
3292     num = membr_next_rarvm_number(&br);
3293     if (num == 0)
3294     {
3295       delete_filter(filters->stack);
3296       filters->stack = NULL;
3297       delete_program_code(filters->progs);
3298       filters->progs = NULL;
3299     }
3300     else
3301       num--;
3302     if (num > numprogs) {
3303       return 0;
3304     }
3305     filters->lastfilternum = num;
3306   }
3307   else
3308     num = filters->lastfilternum;
3309 
3310   prog = filters->progs;
3311   for (i = 0; i < num; i++)
3312     prog = prog->next;
3313   if (prog)
3314     prog->usagecount++;
3315 
3316   blockstartpos = membr_next_rarvm_number(&br) + (size_t)lzss_position(&rar->lzss);
3317   if ((flags & 0x40))
3318     blockstartpos += 258;
3319   if ((flags & 0x20))
3320     blocklength = membr_next_rarvm_number(&br);
3321   else
3322     blocklength = prog ? prog->oldfilterlength : 0;
3323 
3324   if (blocklength > rar->dictionary_size ||
3325       blocklength > (uint32_t)(rar->lzss.mask + 1))
3326     return 0;
3327 
3328   registers[3] = PROGRAM_SYSTEM_GLOBAL_ADDRESS;
3329   registers[4] = blocklength;
3330   registers[5] = prog ? prog->usagecount : 0;
3331   registers[7] = VM_MEMORY_SIZE;
3332 
3333   if ((flags & 0x10))
3334   {
3335     uint8_t mask = (uint8_t)membr_bits(&br, 7);
3336     for (i = 0; i < 7; i++)
3337       if ((mask & (1 << i)))
3338         registers[i] = membr_next_rarvm_number(&br);
3339   }
3340 
3341   if (!prog)
3342   {
3343     uint32_t len = membr_next_rarvm_number(&br);
3344     uint8_t *bytecode;
3345     struct rar_program_code **next;
3346 
3347     if (len == 0 || len > 0x10000)
3348       return 0;
3349     bytecode = malloc(len);
3350     if (!bytecode)
3351       return 0;
3352     for (i = 0; i < len; i++)
3353       bytecode[i] = (uint8_t)membr_bits(&br, 8);
3354     prog = compile_program(bytecode, len);
3355     if (!prog) {
3356       free(bytecode);
3357       return 0;
3358     }
3359     free(bytecode);
3360     next = &filters->progs;
3361     while (*next)
3362       next = &(*next)->next;
3363     *next = prog;
3364   }
3365   prog->oldfilterlength = blocklength;
3366 
3367   globaldata = NULL;
3368   globaldatalen = 0;
3369   if ((flags & 0x08))
3370   {
3371     globaldatalen = membr_next_rarvm_number(&br);
3372     if (globaldatalen > PROGRAM_USER_GLOBAL_SIZE)
3373       return 0;
3374     globaldata = malloc(globaldatalen + PROGRAM_SYSTEM_GLOBAL_SIZE);
3375     if (!globaldata)
3376       return 0;
3377     for (i = 0; i < globaldatalen; i++)
3378       globaldata[i + PROGRAM_SYSTEM_GLOBAL_SIZE] = (uint8_t)membr_bits(&br, 8);
3379   }
3380 
3381   if (br.at_eof)
3382   {
3383       free(globaldata);
3384       return 0;
3385   }
3386 
3387   filter = create_filter(prog, globaldata, globaldatalen, registers, blockstartpos, blocklength);
3388   free(globaldata);
3389   if (!filter)
3390     return 0;
3391 
3392   for (i = 0; i < 7; i++)
3393     archive_le32enc(&filter->globaldata[i * 4], registers[i]);
3394   archive_le32enc(&filter->globaldata[0x1C], blocklength);
3395   archive_le32enc(&filter->globaldata[0x20], 0);
3396   archive_le32enc(&filter->globaldata[0x2C], prog->usagecount);
3397 
3398   nextfilter = &filters->stack;
3399   while (*nextfilter)
3400     nextfilter = &(*nextfilter)->next;
3401   *nextfilter = filter;
3402 
3403   if (!filters->stack->next)
3404     filters->filterstart = blockstartpos;
3405 
3406   return 1;
3407 }
3408 
3409 static struct rar_filter *
create_filter(struct rar_program_code * prog,const uint8_t * globaldata,uint32_t globaldatalen,uint32_t registers[8],size_t startpos,uint32_t length)3410 create_filter(struct rar_program_code *prog, const uint8_t *globaldata, uint32_t globaldatalen, uint32_t registers[8], size_t startpos, uint32_t length)
3411 {
3412   struct rar_filter *filter;
3413 
3414   filter = calloc(1, sizeof(*filter));
3415   if (!filter)
3416     return NULL;
3417   filter->prog = prog;
3418   filter->globaldatalen = globaldatalen > PROGRAM_SYSTEM_GLOBAL_SIZE ? globaldatalen : PROGRAM_SYSTEM_GLOBAL_SIZE;
3419   filter->globaldata = calloc(1, filter->globaldatalen);
3420   if (!filter->globaldata)
3421   {
3422     free(filter);
3423     return NULL;
3424   }
3425   if (globaldata)
3426     memcpy(filter->globaldata, globaldata, globaldatalen);
3427   if (registers)
3428     memcpy(filter->initialregisters, registers, sizeof(filter->initialregisters));
3429   filter->blockstartpos = startpos;
3430   filter->blocklength = length;
3431 
3432   return filter;
3433 }
3434 
3435 static int
run_filters(struct archive_read * a)3436 run_filters(struct archive_read *a)
3437 {
3438   struct rar *rar = (struct rar *)(a->format->data);
3439   struct rar_filters *filters = &rar->filters;
3440   struct rar_filter *filter = filters->stack;
3441   struct rar_filter *f;
3442   size_t start, end;
3443   int64_t tend;
3444   uint32_t lastfilteraddress;
3445   uint32_t lastfilterlength;
3446   int ret;
3447 
3448   if (filters == NULL || filter == NULL)
3449     return (0);
3450 
3451   start = (size_t)filters->filterstart;
3452   end = start + filter->blocklength;
3453 
3454   filters->filterstart = INT64_MAX;
3455   tend = (int64_t)end;
3456   ret = expand(a, &tend);
3457   if (ret != ARCHIVE_OK)
3458     return 0;
3459 
3460   /* Check if filter stack was modified in expand() */
3461   ret = ARCHIVE_FATAL;
3462   f = filters->stack;
3463   while (f)
3464   {
3465     if (f == filter)
3466     {
3467       ret = ARCHIVE_OK;
3468       break;
3469     }
3470     f = f->next;
3471   }
3472   if (ret != ARCHIVE_OK)
3473     return 0;
3474 
3475   if (tend < 0)
3476     return 0;
3477   end = (size_t)tend;
3478   if (end != start + filter->blocklength)
3479     return 0;
3480 
3481   if (!filters->vm)
3482   {
3483     filters->vm = calloc(1, sizeof(*filters->vm));
3484     if (!filters->vm)
3485       return 0;
3486   }
3487 
3488   if (filter->blocklength > VM_MEMORY_SIZE)
3489   {
3490     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data");
3491     return 0;
3492   }
3493 
3494   ret = copy_from_lzss_window(a, filters->vm->memory, start, filter->blocklength);
3495   if (ret != ARCHIVE_OK)
3496     return 0;
3497   if (!execute_filter(a, filter, filters->vm, (size_t)rar->offset))
3498     return 0;
3499 
3500   lastfilteraddress = filter->filteredblockaddress;
3501   lastfilterlength = filter->filteredblocklength;
3502   filters->stack = filter->next;
3503   filter->next = NULL;
3504   delete_filter(filter);
3505 
3506   while ((filter = filters->stack) != NULL && (int64_t)filter->blockstartpos == filters->filterstart && filter->blocklength == lastfilterlength)
3507   {
3508     memmove(&filters->vm->memory[0], &filters->vm->memory[lastfilteraddress], lastfilterlength);
3509     if (!execute_filter(a, filter, filters->vm, (size_t)rar->offset))
3510       return 0;
3511 
3512     lastfilteraddress = filter->filteredblockaddress;
3513     lastfilterlength = filter->filteredblocklength;
3514     filters->stack = filter->next;
3515     filter->next = NULL;
3516     delete_filter(filter);
3517   }
3518 
3519   if (filters->stack)
3520   {
3521     if (filters->stack->blockstartpos < end)
3522       return 0;
3523     filters->filterstart = filters->stack->blockstartpos;
3524   }
3525 
3526   filters->lastend = end;
3527   filters->bytes = &filters->vm->memory[lastfilteraddress];
3528   filters->bytes_ready = lastfilterlength;
3529 
3530   return 1;
3531 }
3532 
3533 static struct rar_program_code *
compile_program(const uint8_t * bytes,size_t length)3534 compile_program(const uint8_t *bytes, size_t length)
3535 {
3536   struct memory_bit_reader br = { 0 };
3537   struct rar_program_code *prog;
3538   // uint32_t instrcount = 0;
3539   uint8_t xor;
3540   size_t i;
3541 
3542   xor = 0;
3543   for (i = 1; i < length; i++)
3544     xor ^= bytes[i];
3545   if (!length || xor != bytes[0])
3546     return NULL;
3547 
3548   br.bytes = bytes;
3549   br.length = length;
3550   br.offset = 1;
3551 
3552   prog = calloc(1, sizeof(*prog));
3553   if (!prog)
3554     return NULL;
3555   prog->fingerprint = crc32(0, bytes, (unsigned int)length) | ((uint64_t)length << 32);
3556 
3557   if (membr_bits(&br, 1))
3558   {
3559     prog->staticdatalen = membr_next_rarvm_number(&br) + 1;
3560     prog->staticdata = malloc(prog->staticdatalen);
3561     if (!prog->staticdata)
3562     {
3563       delete_program_code(prog);
3564       return NULL;
3565     }
3566     for (i = 0; i < prog->staticdatalen; i++)
3567       prog->staticdata[i] = (uint8_t)membr_bits(&br, 8);
3568   }
3569 
3570   return prog;
3571 }
3572 
3573 static void
delete_filter(struct rar_filter * filter)3574 delete_filter(struct rar_filter *filter)
3575 {
3576   while (filter)
3577   {
3578     struct rar_filter *next = filter->next;
3579     free(filter->globaldata);
3580     free(filter);
3581     filter = next;
3582   }
3583 }
3584 
3585 static void
clear_filters(struct rar_filters * filters)3586 clear_filters(struct rar_filters *filters)
3587 {
3588   delete_filter(filters->stack);
3589   delete_program_code(filters->progs);
3590   free(filters->vm);
3591 }
3592 
3593 static void
delete_program_code(struct rar_program_code * prog)3594 delete_program_code(struct rar_program_code *prog)
3595 {
3596   while (prog)
3597   {
3598     struct rar_program_code *next = prog->next;
3599     free(prog->staticdata);
3600     free(prog->globalbackup);
3601     free(prog);
3602     prog = next;
3603   }
3604 }
3605 
3606 static uint32_t
membr_next_rarvm_number(struct memory_bit_reader * br)3607 membr_next_rarvm_number(struct memory_bit_reader *br)
3608 {
3609   uint32_t val;
3610   switch (membr_bits(br, 2))
3611   {
3612     case 0:
3613       return membr_bits(br, 4);
3614     case 1:
3615       val = membr_bits(br, 8);
3616       if (val >= 16)
3617         return val;
3618       return 0xFFFFFF00 | (val << 4) | membr_bits(br, 4);
3619     case 2:
3620       return membr_bits(br, 16);
3621     default:
3622       return membr_bits(br, 32);
3623   }
3624 }
3625 
3626 static inline uint32_t
membr_bits(struct memory_bit_reader * br,int bits)3627 membr_bits(struct memory_bit_reader *br, int bits)
3628 {
3629   if (bits > br->available && (br->at_eof || !membr_fill(br, bits)))
3630     return 0;
3631   return (uint32_t)((br->bits >> (br->available -= bits)) & (((uint64_t)1 << bits) - 1));
3632 }
3633 
3634 static int
membr_fill(struct memory_bit_reader * br,int bits)3635 membr_fill(struct memory_bit_reader *br, int bits)
3636 {
3637   while (br->available < bits && br->offset < br->length)
3638   {
3639     br->bits = (br->bits << 8) | br->bytes[br->offset++];
3640     br->available += 8;
3641   }
3642   if (bits > br->available)
3643   {
3644     br->at_eof = 1;
3645     return 0;
3646   }
3647   return 1;
3648 }
3649 
3650 static int
read_filter(struct archive_read * a,int64_t * end)3651 read_filter(struct archive_read *a, int64_t *end)
3652 {
3653   struct rar *rar = (struct rar *)(a->format->data);
3654   uint8_t flags, val, *code;
3655   uint16_t length, i;
3656 
3657   if (!rar_decode_byte(a, &flags))
3658     return 0;
3659   length = (flags & 0x07) + 1;
3660   if (length == 7)
3661   {
3662     if (!rar_decode_byte(a, &val))
3663       return 0;
3664     length = val + 7;
3665   }
3666   else if (length == 8)
3667   {
3668     if (!rar_decode_byte(a, &val))
3669       return 0;
3670     length = val << 8;
3671     if (!rar_decode_byte(a, &val))
3672       return 0;
3673     length |= val;
3674   }
3675 
3676   code = malloc(length);
3677   if (!code)
3678     return 0;
3679   for (i = 0; i < length; i++)
3680   {
3681     if (!rar_decode_byte(a, &code[i]))
3682     {
3683       free(code);
3684       return 0;
3685     }
3686   }
3687   if (!parse_filter(a, code, length, flags))
3688   {
3689     free(code);
3690     return 0;
3691   }
3692   free(code);
3693 
3694   if (rar->filters.filterstart < *end)
3695     *end = rar->filters.filterstart;
3696 
3697   return 1;
3698 }
3699 
3700 static int
execute_filter_delta(struct rar_filter * filter,struct rar_virtual_machine * vm)3701 execute_filter_delta(struct rar_filter *filter, struct rar_virtual_machine *vm)
3702 {
3703   uint32_t length = filter->initialregisters[4];
3704   uint32_t numchannels = filter->initialregisters[0];
3705   uint8_t *src, *dst;
3706   uint32_t i, idx;
3707 
3708   if (length > PROGRAM_WORK_SIZE / 2)
3709     return 0;
3710 
3711   src = &vm->memory[0];
3712   dst = &vm->memory[length];
3713   for (i = 0; i < numchannels; i++)
3714   {
3715     uint8_t lastbyte = 0;
3716     for (idx = i; idx < length; idx += numchannels)
3717     {
3718       /*
3719        * The src block should not overlap with the dst block.
3720        * If so it would be better to consider this archive is broken.
3721        */
3722       if (src >= dst)
3723         return 0;
3724       lastbyte = dst[idx] = lastbyte - *src++;
3725     }
3726   }
3727 
3728   filter->filteredblockaddress = length;
3729   filter->filteredblocklength = length;
3730 
3731   return 1;
3732 }
3733 
3734 static int
execute_filter_e8(struct rar_filter * filter,struct rar_virtual_machine * vm,size_t pos,int e9also)3735 execute_filter_e8(struct rar_filter *filter, struct rar_virtual_machine *vm, size_t pos, int e9also)
3736 {
3737   uint32_t length = filter->initialregisters[4];
3738   uint32_t filesize = 0x1000000;
3739   uint32_t i;
3740 
3741   if (length > PROGRAM_WORK_SIZE || length <= 4)
3742     return 0;
3743 
3744   for (i = 0; i <= length - 5; i++)
3745   {
3746     if (vm->memory[i] == 0xE8 || (e9also && vm->memory[i] == 0xE9))
3747     {
3748       uint32_t currpos = (uint32_t)pos + i + 1;
3749       int32_t address = (int32_t)vm_read_32(vm, i + 1);
3750       if (address < 0 && currpos >= (~(uint32_t)address + 1))
3751         vm_write_32(vm, i + 1, address + filesize);
3752       else if (address >= 0 && (uint32_t)address < filesize)
3753         vm_write_32(vm, i + 1, address - currpos);
3754       i += 4;
3755     }
3756   }
3757 
3758   filter->filteredblockaddress = 0;
3759   filter->filteredblocklength = length;
3760 
3761   return 1;
3762 }
3763 
3764 static int
execute_filter_rgb(struct rar_filter * filter,struct rar_virtual_machine * vm)3765 execute_filter_rgb(struct rar_filter *filter, struct rar_virtual_machine *vm)
3766 {
3767   uint32_t stride = filter->initialregisters[0];
3768   uint32_t byteoffset = filter->initialregisters[1];
3769   uint32_t blocklength = filter->initialregisters[4];
3770   uint8_t *src, *dst;
3771   uint32_t i, j;
3772 
3773   if (blocklength > PROGRAM_WORK_SIZE / 2 || stride > blocklength || blocklength < 3 || byteoffset > 2)
3774     return 0;
3775 
3776   src = &vm->memory[0];
3777   dst = &vm->memory[blocklength];
3778   for (i = 0; i < 3; i++) {
3779     uint8_t byte = 0;
3780     uint8_t *prev = dst + i - stride;
3781     for (j = i; j < blocklength; j += 3)
3782     {
3783       /*
3784        * The src block should not overlap with the dst block.
3785        * If so it would be better to consider this archive is broken.
3786        */
3787       if (src >= dst)
3788         return 0;
3789 
3790       if (prev >= dst)
3791       {
3792         uint32_t delta1 = abs(prev[3] - prev[0]);
3793         uint32_t delta2 = abs(byte - prev[0]);
3794         uint32_t delta3 = abs(prev[3] - prev[0] + byte - prev[0]);
3795         if (delta1 > delta2 || delta1 > delta3)
3796           byte = delta2 <= delta3 ? prev[3] : prev[0];
3797       }
3798       byte -= *src++;
3799       dst[j] = byte;
3800       prev += 3;
3801     }
3802   }
3803   for (i = byteoffset; i < blocklength - 2; i += 3)
3804   {
3805     dst[i] += dst[i + 1];
3806     dst[i + 2] += dst[i + 1];
3807   }
3808 
3809   filter->filteredblockaddress = blocklength;
3810   filter->filteredblocklength = blocklength;
3811 
3812   return 1;
3813 }
3814 
3815 static int
execute_filter_audio(struct rar_filter * filter,struct rar_virtual_machine * vm)3816 execute_filter_audio(struct rar_filter *filter, struct rar_virtual_machine *vm)
3817 {
3818   uint32_t length = filter->initialregisters[4];
3819   uint32_t numchannels = filter->initialregisters[0];
3820   uint8_t *src, *dst;
3821   uint32_t i, j;
3822 
3823   if (length > PROGRAM_WORK_SIZE / 2)
3824     return 0;
3825 
3826   src = &vm->memory[0];
3827   dst = &vm->memory[length];
3828   for (i = 0; i < numchannels; i++)
3829   {
3830     struct audio_state state;
3831     memset(&state, 0, sizeof(state));
3832     for (j = i; j < length; j += numchannels)
3833     {
3834       /*
3835        * The src block should not overlap with the dst block.
3836        * If so it would be better to consider this archive is broken.
3837        */
3838       if (src >= dst)
3839         return 0;
3840 
3841       int8_t delta = (int8_t)*src++;
3842       uint8_t predbyte, byte;
3843       int prederror;
3844       state.delta[2] = state.delta[1];
3845       state.delta[1] = state.lastdelta - state.delta[0];
3846       state.delta[0] = state.lastdelta;
3847       predbyte = ((8 * state.lastbyte + state.weight[0] * state.delta[0] + state.weight[1] * state.delta[1] + state.weight[2] * state.delta[2]) >> 3) & 0xFF;
3848       byte = (predbyte - delta) & 0xFF;
3849       prederror = delta << 3;
3850       state.error[0] += abs(prederror);
3851       state.error[1] += abs(prederror - state.delta[0]); state.error[2] += abs(prederror + state.delta[0]);
3852       state.error[3] += abs(prederror - state.delta[1]); state.error[4] += abs(prederror + state.delta[1]);
3853       state.error[5] += abs(prederror - state.delta[2]); state.error[6] += abs(prederror + state.delta[2]);
3854       state.lastdelta = (int8_t)(byte - state.lastbyte);
3855       dst[j] = state.lastbyte = byte;
3856       if (!(state.count++ & 0x1F))
3857       {
3858         uint8_t k, idx = 0;
3859         for (k = 1; k < 7; k++)
3860         {
3861           if (state.error[k] < state.error[idx])
3862             idx = k;
3863         }
3864         memset(state.error, 0, sizeof(state.error));
3865         switch (idx)
3866         {
3867           case 1: if (state.weight[0] >= -16) state.weight[0]--; break;
3868           case 2: if (state.weight[0] < 16) state.weight[0]++; break;
3869           case 3: if (state.weight[1] >= -16) state.weight[1]--; break;
3870           case 4: if (state.weight[1] < 16) state.weight[1]++; break;
3871           case 5: if (state.weight[2] >= -16) state.weight[2]--; break;
3872           case 6: if (state.weight[2] < 16) state.weight[2]++; break;
3873         }
3874       }
3875     }
3876   }
3877 
3878   filter->filteredblockaddress = length;
3879   filter->filteredblocklength = length;
3880 
3881   return 1;
3882 }
3883 
3884 
3885 static int
execute_filter(struct archive_read * a,struct rar_filter * filter,struct rar_virtual_machine * vm,size_t pos)3886 execute_filter(struct archive_read *a, struct rar_filter *filter, struct rar_virtual_machine *vm, size_t pos)
3887 {
3888   if (filter->prog->fingerprint == 0x1D0E06077D)
3889     return execute_filter_delta(filter, vm);
3890   if (filter->prog->fingerprint == 0x35AD576887)
3891     return execute_filter_e8(filter, vm, pos, 0);
3892   if (filter->prog->fingerprint == 0x393CD7E57E)
3893     return execute_filter_e8(filter, vm, pos, 1);
3894   if (filter->prog->fingerprint == 0x951C2C5DC8)
3895     return execute_filter_rgb(filter, vm);
3896   if (filter->prog->fingerprint == 0xD8BC85E701)
3897     return execute_filter_audio(filter, vm);
3898 
3899   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "No support for RAR VM program filter");
3900   return 0;
3901 }
3902 
3903 static int
rar_decode_byte(struct archive_read * a,uint8_t * byte)3904 rar_decode_byte(struct archive_read *a, uint8_t *byte)
3905 {
3906   struct rar *rar = (struct rar *)(a->format->data);
3907   struct rar_br *br = &(rar->br);
3908   if (!rar_br_read_ahead(a, br, 8))
3909     return 0;
3910   *byte = (uint8_t)rar_br_bits(br, 8);
3911   rar_br_consume(br, 8);
3912   return 1;
3913 }
3914 
3915 static inline void
vm_write_32(struct rar_virtual_machine * vm,size_t offset,uint32_t u32)3916 vm_write_32(struct rar_virtual_machine* vm, size_t offset, uint32_t u32)
3917 {
3918   archive_le32enc(vm->memory + offset, u32);
3919 }
3920 
3921 static inline uint32_t
vm_read_32(struct rar_virtual_machine * vm,size_t offset)3922 vm_read_32(struct rar_virtual_machine* vm, size_t offset)
3923 {
3924   return archive_le32dec(vm->memory + offset);
3925 }
3926