xref: /freebsd/contrib/libarchive/libarchive/archive_read_support_format_rar.c (revision 2e113ef82465598b8c26e0ca415fbe90677fbd47)
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     if (*offset < rar->unp_size)
1121       *offset = rar->unp_size;
1122     return (ARCHIVE_EOF);
1123   }
1124 
1125   switch (rar->compression_method)
1126   {
1127   case COMPRESS_METHOD_STORE:
1128     ret = read_data_stored(a, buff, size, offset);
1129     break;
1130 
1131   case COMPRESS_METHOD_FASTEST:
1132   case COMPRESS_METHOD_FAST:
1133   case COMPRESS_METHOD_NORMAL:
1134   case COMPRESS_METHOD_GOOD:
1135   case COMPRESS_METHOD_BEST:
1136     ret = read_data_compressed(a, buff, size, offset, 0);
1137     if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN) {
1138       __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
1139       rar->start_new_table = 1;
1140       rar->ppmd_valid = 0;
1141     }
1142     break;
1143 
1144   default:
1145     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1146                       "Unsupported compression method for RAR file.");
1147     ret = ARCHIVE_FATAL;
1148     break;
1149   }
1150   return (ret);
1151 }
1152 
1153 static int
archive_read_format_rar_read_data_skip(struct archive_read * a)1154 archive_read_format_rar_read_data_skip(struct archive_read *a)
1155 {
1156   struct rar *rar;
1157   int64_t bytes_skipped;
1158   int ret;
1159 
1160   rar = (struct rar *)(a->format->data);
1161 
1162   if (rar->bytes_unconsumed > 0) {
1163       /* Consume as much as the decompressor actually used. */
1164       __archive_read_consume(a, rar->bytes_unconsumed);
1165       rar->bytes_unconsumed = 0;
1166   }
1167 
1168   if (rar->bytes_remaining > 0) {
1169     bytes_skipped = __archive_read_consume(a, rar->bytes_remaining);
1170     if (bytes_skipped < 0)
1171       return (ARCHIVE_FATAL);
1172   }
1173 
1174   /* Compressed data to skip must be read from each header in a multivolume
1175    * archive.
1176    */
1177   if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)
1178   {
1179     ret = archive_read_format_rar_read_header(a, a->entry);
1180     if (ret == (ARCHIVE_EOF))
1181       ret = archive_read_format_rar_read_header(a, a->entry);
1182     if (ret != (ARCHIVE_OK))
1183       return ret;
1184     return archive_read_format_rar_read_data_skip(a);
1185   }
1186 
1187   return (ARCHIVE_OK);
1188 }
1189 
1190 static int64_t
archive_read_format_rar_seek_data(struct archive_read * a,int64_t offset,int whence)1191 archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset,
1192     int whence)
1193 {
1194   int64_t client_offset, ret;
1195   size_t i;
1196   struct rar *rar = (struct rar *)(a->format->data);
1197 
1198   if (rar->compression_method == COMPRESS_METHOD_STORE)
1199   {
1200     /* Modify the offset for use with SEEK_SET */
1201     switch (whence)
1202     {
1203       case SEEK_CUR:
1204         client_offset = rar->offset_seek;
1205         break;
1206       case SEEK_END:
1207         client_offset = rar->unp_size;
1208         break;
1209       case SEEK_SET:
1210       default:
1211         client_offset = 0;
1212     }
1213     client_offset += offset;
1214     if (client_offset < 0)
1215     {
1216       /* Can't seek past beginning of data block */
1217       return -1;
1218     }
1219     else if (client_offset > rar->unp_size)
1220     {
1221       /*
1222        * Set the returned offset but only seek to the end of
1223        * the data block.
1224        */
1225       rar->offset_seek = client_offset;
1226       client_offset = rar->unp_size;
1227     }
1228 
1229     client_offset += rar->dbo[0].start_offset;
1230     i = 0;
1231     while (i < rar->cursor)
1232     {
1233       i++;
1234       client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset;
1235     }
1236     if (rar->main_flags & MHD_VOLUME)
1237     {
1238       /* Find the appropriate offset among the multivolume archive */
1239       while (1)
1240       {
1241         if (client_offset < rar->dbo[rar->cursor].start_offset &&
1242           rar->file_flags & FHD_SPLIT_BEFORE)
1243         {
1244           /* Search backwards for the correct data block */
1245           if (rar->cursor == 0)
1246           {
1247             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1248               "Attempt to seek past beginning of RAR data block");
1249             return (ARCHIVE_FAILED);
1250           }
1251           rar->cursor--;
1252           client_offset -= rar->dbo[rar->cursor+1].start_offset -
1253             rar->dbo[rar->cursor].end_offset;
1254           if (client_offset < rar->dbo[rar->cursor].start_offset)
1255             continue;
1256           ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset -
1257             rar->dbo[rar->cursor].header_size, SEEK_SET);
1258           if (ret < (ARCHIVE_OK))
1259             return ret;
1260           ret = archive_read_format_rar_read_header(a, a->entry);
1261           if (ret != (ARCHIVE_OK))
1262           {
1263             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1264               "Error during seek of RAR file");
1265             return (ARCHIVE_FAILED);
1266           }
1267           rar->cursor--;
1268           break;
1269         }
1270         else if (client_offset > rar->dbo[rar->cursor].end_offset &&
1271           rar->file_flags & FHD_SPLIT_AFTER)
1272         {
1273           /* Search forward for the correct data block */
1274           rar->cursor++;
1275           if (rar->cursor < rar->nodes &&
1276             client_offset > rar->dbo[rar->cursor].end_offset)
1277           {
1278             client_offset += rar->dbo[rar->cursor].start_offset -
1279               rar->dbo[rar->cursor-1].end_offset;
1280             continue;
1281           }
1282           rar->cursor--;
1283           ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset,
1284                                     SEEK_SET);
1285           if (ret < (ARCHIVE_OK))
1286             return ret;
1287           ret = archive_read_format_rar_read_header(a, a->entry);
1288           if (ret == (ARCHIVE_EOF))
1289           {
1290             rar->has_endarc_header = 1;
1291             ret = archive_read_format_rar_read_header(a, a->entry);
1292           }
1293           if (ret != (ARCHIVE_OK))
1294           {
1295             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1296               "Error during seek of RAR file");
1297             return (ARCHIVE_FAILED);
1298           }
1299           client_offset += rar->dbo[rar->cursor].start_offset -
1300             rar->dbo[rar->cursor-1].end_offset;
1301           continue;
1302         }
1303         break;
1304       }
1305     }
1306 
1307     ret = __archive_read_seek(a, client_offset, SEEK_SET);
1308     if (ret < (ARCHIVE_OK))
1309       return ret;
1310     rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret;
1311     i = rar->cursor;
1312     while (i > 0)
1313     {
1314       i--;
1315       ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset;
1316     }
1317     ret -= rar->dbo[0].start_offset;
1318 
1319     /* Always restart reading the file after a seek */
1320     __archive_reset_read_data(&a->archive);
1321 
1322     rar->bytes_unconsumed = 0;
1323     rar->offset = 0;
1324 
1325     /*
1326      * If a seek past the end of file was requested, return the requested
1327      * offset.
1328      */
1329     if (ret == rar->unp_size && rar->offset_seek > rar->unp_size)
1330       return rar->offset_seek;
1331 
1332     /* Return the new offset */
1333     rar->offset_seek = ret;
1334     return rar->offset_seek;
1335   }
1336   else
1337   {
1338     archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1339       "Seeking of compressed RAR files is unsupported");
1340   }
1341   return (ARCHIVE_FAILED);
1342 }
1343 
1344 static int
archive_read_format_rar_cleanup(struct archive_read * a)1345 archive_read_format_rar_cleanup(struct archive_read *a)
1346 {
1347   struct rar *rar;
1348 
1349   rar = (struct rar *)(a->format->data);
1350   free_codes(a);
1351   clear_filters(&rar->filters);
1352   free(rar->filename);
1353   free(rar->filename_save);
1354   free(rar->dbo);
1355   free(rar->unp_buffer);
1356   free(rar->lzss.window);
1357   __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
1358   free(rar);
1359   (a->format->data) = NULL;
1360   return (ARCHIVE_OK);
1361 }
1362 
1363 static int
read_header(struct archive_read * a,struct archive_entry * entry,char head_type)1364 read_header(struct archive_read *a, struct archive_entry *entry,
1365             char head_type)
1366 {
1367   const void *h;
1368   const char *p, *endp;
1369   struct rar *rar;
1370   struct rar_header rar_header;
1371   struct rar_file_header file_header;
1372   int64_t header_size;
1373   unsigned filename_size, end;
1374   char *filename;
1375   char *strp;
1376   char packed_size[8];
1377   char unp_size[8];
1378   int ttime;
1379   struct archive_string_conv *sconv, *fn_sconv;
1380   uint32_t crc32_computed, crc32_read;
1381   int ret = (ARCHIVE_OK), ret2;
1382   char *newptr;
1383   size_t newsize;
1384 
1385   rar = (struct rar *)(a->format->data);
1386 
1387   /* Setup a string conversion object for non-rar-unicode filenames. */
1388   sconv = rar->opt_sconv;
1389   if (sconv == NULL) {
1390     if (!rar->init_default_conversion) {
1391       rar->sconv_default =
1392           archive_string_default_conversion_for_read(
1393             &(a->archive));
1394       rar->init_default_conversion = 1;
1395     }
1396     sconv = rar->sconv_default;
1397   }
1398 
1399 
1400   if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
1401     return (ARCHIVE_FATAL);
1402   p = h;
1403   memcpy(&rar_header, p, sizeof(rar_header));
1404   rar->file_flags = archive_le16dec(rar_header.flags);
1405   header_size = archive_le16dec(rar_header.size);
1406   if (header_size < (int64_t)sizeof(file_header) + 7) {
1407     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1408       "Invalid header size");
1409     return (ARCHIVE_FATAL);
1410   }
1411   crc32_computed = crc32(0, (const unsigned char *)p + 2, 7 - 2);
1412   __archive_read_consume(a, 7);
1413 
1414   if (!(rar->file_flags & FHD_SOLID))
1415   {
1416     rar->compression_method = 0;
1417     rar->packed_size = 0;
1418     rar->unp_size = 0;
1419     rar->mtime = 0;
1420     rar->ctime = 0;
1421     rar->atime = 0;
1422     rar->arctime = 0;
1423     rar->mode = 0;
1424     memset(&rar->salt, 0, sizeof(rar->salt));
1425     rar->atime = 0;
1426     rar->ansec = 0;
1427     rar->ctime = 0;
1428     rar->cnsec = 0;
1429     rar->mtime = 0;
1430     rar->mnsec = 0;
1431     rar->arctime = 0;
1432     rar->arcnsec = 0;
1433   }
1434   else
1435   {
1436     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1437                       "RAR solid archive support unavailable.");
1438     return (ARCHIVE_FATAL);
1439   }
1440 
1441   if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
1442   {
1443     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1444                       "Failed to read full header content.");
1445     return (ARCHIVE_FATAL);
1446   }
1447 
1448   /* File Header CRC check. */
1449   crc32_computed = crc32(crc32_computed, h, (unsigned)(header_size - 7));
1450   crc32_read = archive_le16dec(rar_header.crc);
1451   if ((crc32_computed & 0xffff) != crc32_read) {
1452 #ifndef DONT_FAIL_ON_CRC_ERROR
1453     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1454       "Header CRC error");
1455     return (ARCHIVE_FATAL);
1456 #endif
1457   }
1458   /* If no CRC error, Go on parsing File Header. */
1459   p = h;
1460   endp = p + header_size - 7;
1461   memcpy(&file_header, p, sizeof(file_header));
1462   p += sizeof(file_header);
1463 
1464   rar->compression_method = file_header.method;
1465 
1466   ttime = archive_le32dec(file_header.file_time);
1467   rar->mtime = get_time(ttime);
1468 
1469   rar->file_crc = archive_le32dec(file_header.file_crc);
1470 
1471   if (rar->file_flags & FHD_PASSWORD)
1472   {
1473     archive_entry_set_is_data_encrypted(entry, 1);
1474     rar->has_encrypted_entries = 1;
1475     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1476                       "RAR encryption support unavailable.");
1477     /* Since it is only the data part itself that is encrypted we can at least
1478        extract information about the currently processed entry and don't need
1479        to return ARCHIVE_FATAL here. */
1480     /*return (ARCHIVE_FATAL);*/
1481   }
1482 
1483   if (rar->file_flags & FHD_LARGE)
1484   {
1485     if (p + 8 > endp) {
1486       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1487                         "Invalid header size");
1488       return (ARCHIVE_FATAL);
1489     }
1490     memcpy(packed_size, file_header.pack_size, 4);
1491     memcpy(packed_size + 4, p, 4); /* High pack size */
1492     p += 4;
1493     memcpy(unp_size, file_header.unp_size, 4);
1494     memcpy(unp_size + 4, p, 4); /* High unpack size */
1495     p += 4;
1496     rar->packed_size = archive_le64dec(&packed_size);
1497     rar->unp_size = archive_le64dec(&unp_size);
1498   }
1499   else
1500   {
1501     rar->packed_size = archive_le32dec(file_header.pack_size);
1502     rar->unp_size = archive_le32dec(file_header.unp_size);
1503   }
1504 
1505   if (rar->packed_size < 0 || rar->unp_size < 0)
1506   {
1507     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1508                       "Invalid sizes specified.");
1509     return (ARCHIVE_FATAL);
1510   }
1511 
1512   rar->bytes_remaining = rar->packed_size;
1513 
1514   /* TODO: RARv3 subblocks contain comments. For now the complete block is
1515    * consumed at the end.
1516    */
1517   if (head_type == NEWSUB_HEAD) {
1518     size_t distance = p - (const char *)h;
1519     if (rar->packed_size > INT64_MAX - header_size) {
1520       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1521                         "Extended header size too large.");
1522       return (ARCHIVE_FATAL);
1523     }
1524     header_size += rar->packed_size;
1525     if ((uintmax_t)header_size > SIZE_MAX) {
1526       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1527                         "Unable to read extended header data.");
1528       return (ARCHIVE_FATAL);
1529     }
1530     /* Make sure we have the extended data. */
1531     if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL) {
1532       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1533                         "Failed to read extended header data.");
1534       return (ARCHIVE_FATAL);
1535     }
1536     p = h;
1537     endp = p + header_size - 7;
1538     p += distance;
1539   }
1540 
1541   filename_size = archive_le16dec(file_header.name_size);
1542   if (p + filename_size > endp) {
1543     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1544       "Invalid filename size");
1545     return (ARCHIVE_FATAL);
1546   }
1547   if (rar->filename_allocated < filename_size * 2 + 2) {
1548     newsize = filename_size * 2 + 2;
1549     newptr = realloc(rar->filename, newsize);
1550     if (newptr == NULL) {
1551       archive_set_error(&a->archive, ENOMEM,
1552                         "Couldn't allocate memory.");
1553       return (ARCHIVE_FATAL);
1554     }
1555     rar->filename = newptr;
1556     rar->filename_allocated = newsize;
1557   }
1558   filename = rar->filename;
1559   memcpy(filename, p, filename_size);
1560   filename[filename_size] = '\0';
1561   if (rar->file_flags & FHD_UNICODE)
1562   {
1563     if (filename_size != strlen(filename))
1564     {
1565       unsigned char highbyte, flagbits, flagbyte;
1566       unsigned fn_end, offset;
1567 
1568       end = filename_size;
1569       fn_end = filename_size * 2;
1570       filename_size = 0;
1571       offset = (unsigned)strlen(filename) + 1;
1572       highbyte = offset >= end ? 0 : *(p + offset++);
1573       flagbits = 0;
1574       flagbyte = 0;
1575       while (offset < end && filename_size < fn_end)
1576       {
1577         if (!flagbits)
1578         {
1579           flagbyte = *(p + offset++);
1580           flagbits = 8;
1581         }
1582 
1583         flagbits -= 2;
1584         switch((flagbyte >> flagbits) & 3)
1585         {
1586           case 0:
1587             if (offset >= end)
1588               continue;
1589             filename[filename_size++] = '\0';
1590             filename[filename_size++] = *(p + offset++);
1591             break;
1592           case 1:
1593             if (offset >= end)
1594               continue;
1595             filename[filename_size++] = highbyte;
1596             filename[filename_size++] = *(p + offset++);
1597             break;
1598           case 2:
1599             if (offset >= end - 1) {
1600               offset = end;
1601               continue;
1602             }
1603             filename[filename_size++] = *(p + offset + 1);
1604             filename[filename_size++] = *(p + offset);
1605             offset += 2;
1606             break;
1607           case 3:
1608           {
1609             char extra, high;
1610             uint8_t length;
1611 
1612             if (offset >= end)
1613               continue;
1614 
1615             length = *(p + offset++);
1616             if (length & 0x80) {
1617               if (offset >= end)
1618                 continue;
1619               extra = *(p + offset++);
1620               high = (char)highbyte;
1621             } else
1622               extra = high = 0;
1623             length = (length & 0x7f) + 2;
1624             while (length && filename_size < fn_end) {
1625               unsigned cp = filename_size >> 1;
1626               filename[filename_size++] = high;
1627               filename[filename_size++] = p[cp] + extra;
1628               length--;
1629             }
1630           }
1631           break;
1632         }
1633       }
1634       if (filename_size > fn_end) {
1635         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1636           "Invalid filename");
1637         return (ARCHIVE_FATAL);
1638       }
1639       filename[filename_size++] = '\0';
1640       /*
1641        * Do not increment filename_size here as the computations below
1642        * add the space for the terminating NUL explicitly.
1643        */
1644       filename[filename_size] = '\0';
1645 
1646       /* Decoded unicode form is UTF-16BE, so we have to update a string
1647        * conversion object for it. */
1648       if (rar->sconv_utf16be == NULL) {
1649         rar->sconv_utf16be = archive_string_conversion_from_charset(
1650            &a->archive, "UTF-16BE", 1);
1651         if (rar->sconv_utf16be == NULL)
1652           return (ARCHIVE_FATAL);
1653       }
1654       fn_sconv = rar->sconv_utf16be;
1655 
1656       strp = filename;
1657       while (memcmp(strp, "\x00\x00", 2))
1658       {
1659         if (!memcmp(strp, "\x00\\", 2))
1660           *(strp + 1) = '/';
1661         strp += 2;
1662       }
1663       p += offset;
1664     } else {
1665       /*
1666        * If FHD_UNICODE is set but no unicode data, this file name form
1667        * is UTF-8, so we have to update a string conversion object for
1668        * it accordingly.
1669        */
1670       if (rar->sconv_utf8 == NULL) {
1671         rar->sconv_utf8 = archive_string_conversion_from_charset(
1672            &a->archive, "UTF-8", 1);
1673         if (rar->sconv_utf8 == NULL)
1674           return (ARCHIVE_FATAL);
1675       }
1676       fn_sconv = rar->sconv_utf8;
1677       while ((strp = strchr(filename, '\\')) != NULL)
1678         *strp = '/';
1679       p += filename_size;
1680     }
1681   }
1682   else
1683   {
1684     fn_sconv = sconv;
1685     while ((strp = strchr(filename, '\\')) != NULL)
1686       *strp = '/';
1687     p += filename_size;
1688   }
1689 
1690   /* Split file in multivolume RAR. No more need to process header. */
1691   if (rar->filename_save &&
1692     filename_size == rar->filename_save_size &&
1693     !memcmp(rar->filename, rar->filename_save, filename_size + 1))
1694   {
1695     __archive_read_consume(a, header_size - 7);
1696     rar->br.avail_in = 0;
1697     rar->br.next_in = NULL;
1698     rar->cursor++;
1699     if (rar->cursor >= rar->nodes)
1700     {
1701       struct data_block_offsets *newdbo;
1702 
1703       newsize = sizeof(*rar->dbo) * (rar->nodes + 1);
1704       if ((newdbo = realloc(rar->dbo, newsize)) == NULL)
1705       {
1706         archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
1707         return (ARCHIVE_FATAL);
1708       }
1709       rar->dbo = newdbo;
1710       rar->nodes++;
1711       rar->dbo[rar->cursor].header_size = header_size;
1712       rar->dbo[rar->cursor].start_offset = -1;
1713       rar->dbo[rar->cursor].end_offset = -1;
1714     }
1715     if (rar->dbo[rar->cursor].start_offset < 0)
1716     {
1717       if (rar->packed_size > INT64_MAX - a->filter->position)
1718       {
1719         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1720                           "Unable to store offsets.");
1721         return (ARCHIVE_FATAL);
1722       }
1723       rar->dbo[rar->cursor].start_offset = a->filter->position;
1724       rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset +
1725         rar->packed_size;
1726     }
1727     return ret;
1728   }
1729   else if (rar->filename_must_match)
1730   {
1731     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1732       "Mismatch of file parts split across multi-volume archive");
1733     return (ARCHIVE_FATAL);
1734   }
1735 
1736   newsize = filename_size + 1;
1737   if ((newptr = realloc(rar->filename_save, newsize)) == NULL)
1738   {
1739     archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
1740     return (ARCHIVE_FATAL);
1741   }
1742   rar->filename_save = newptr;
1743   memcpy(rar->filename_save, rar->filename, newsize);
1744   rar->filename_save_size = filename_size;
1745 
1746   /* Set info for seeking */
1747   free(rar->dbo);
1748   if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL)
1749   {
1750     archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
1751     return (ARCHIVE_FATAL);
1752   }
1753   rar->dbo[0].header_size = header_size;
1754   rar->dbo[0].start_offset = -1;
1755   rar->dbo[0].end_offset = -1;
1756   rar->cursor = 0;
1757   rar->nodes = 1;
1758 
1759   if (rar->file_flags & FHD_SALT)
1760   {
1761     if (p + 8 > endp) {
1762       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1763         "Invalid header size");
1764       return (ARCHIVE_FATAL);
1765     }
1766     memcpy(rar->salt, p, 8);
1767     p += 8;
1768   }
1769 
1770   if (rar->file_flags & FHD_EXTTIME) {
1771     if (read_exttime(p, rar, endp) < 0) {
1772       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1773         "Invalid header size");
1774       return (ARCHIVE_FATAL);
1775     }
1776   }
1777 
1778   __archive_read_consume(a, header_size - 7);
1779   if (rar->packed_size > INT64_MAX - a->filter->position) {
1780     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1781                       "Unable to store offsets.");
1782     return (ARCHIVE_FATAL);
1783   }
1784   rar->dbo[0].start_offset = a->filter->position;
1785   rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size;
1786 
1787   switch(file_header.host_os)
1788   {
1789   case OS_MSDOS:
1790   case OS_OS2:
1791   case OS_WIN32:
1792     rar->mode = (__LA_MODE_T)archive_le32dec(file_header.file_attr);
1793     if (rar->mode & FILE_ATTRIBUTE_DIRECTORY)
1794       rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
1795     else
1796       rar->mode = AE_IFREG;
1797     rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
1798     break;
1799 
1800   case OS_UNIX:
1801   case OS_MAC_OS:
1802   case OS_BEOS:
1803     rar->mode = (__LA_MODE_T)archive_le32dec(file_header.file_attr);
1804     break;
1805 
1806   default:
1807     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1808                       "Unknown file attributes from RAR file's host OS");
1809     return (ARCHIVE_FATAL);
1810   }
1811 
1812   rar->bytes_uncopied = rar->bytes_unconsumed = 0;
1813   rar->lzss.position = rar->offset = 0;
1814   rar->offset_seek = 0;
1815   rar->dictionary_size = 0;
1816   rar->offset_outgoing = 0;
1817   rar->br.cache_avail = 0;
1818   rar->br.avail_in = 0;
1819   rar->br.next_in = NULL;
1820   rar->crc_calculated = 0;
1821   rar->entry_eof = 0;
1822   rar->valid = 1;
1823   rar->is_ppmd_block = 0;
1824   rar->start_new_table = 1;
1825   free(rar->unp_buffer);
1826   rar->unp_buffer = NULL;
1827   rar->unp_offset = 0;
1828   rar->unp_buffer_size = UNP_BUFFER_SIZE;
1829   memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
1830   __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
1831   rar->ppmd_valid = rar->ppmd_eod = 0;
1832   rar->filters.filterstart = INT64_MAX;
1833 
1834   /* Don't set any archive entries for non-file header types */
1835   if (head_type == NEWSUB_HEAD)
1836     return ret;
1837 
1838   archive_entry_set_mtime(entry, rar->mtime, rar->mnsec);
1839   archive_entry_set_ctime(entry, rar->ctime, rar->cnsec);
1840   archive_entry_set_atime(entry, rar->atime, rar->ansec);
1841   archive_entry_set_size(entry, rar->unp_size);
1842   archive_entry_set_mode(entry, rar->mode);
1843 
1844   if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv))
1845   {
1846     if (errno == ENOMEM)
1847     {
1848       archive_set_error(&a->archive, ENOMEM,
1849                         "Can't allocate memory for Pathname");
1850       return (ARCHIVE_FATAL);
1851     }
1852     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1853                       "Pathname cannot be converted from %s to current locale.",
1854                       archive_string_conversion_charset_name(fn_sconv));
1855     ret = (ARCHIVE_WARN);
1856   }
1857 
1858   if (((rar->mode) & AE_IFMT) == AE_IFLNK)
1859   {
1860     /* Make sure a symbolic-link file does not have its body. */
1861     rar->bytes_remaining = 0;
1862     archive_entry_set_size(entry, 0);
1863 
1864     /* Read a symbolic-link name. */
1865     if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN))
1866       return ret2;
1867     if (ret > ret2)
1868       ret = ret2;
1869   }
1870 
1871   if (rar->bytes_remaining == 0)
1872     rar->entry_eof = 1;
1873 
1874   return ret;
1875 }
1876 
1877 static time_t
get_time(int ttime)1878 get_time(int ttime)
1879 {
1880   struct tm tm;
1881   tm.tm_sec = 2 * (ttime & 0x1f);
1882   tm.tm_min = (ttime >> 5) & 0x3f;
1883   tm.tm_hour = (ttime >> 11) & 0x1f;
1884   tm.tm_mday = (ttime >> 16) & 0x1f;
1885   tm.tm_mon = ((ttime >> 21) & 0x0f) - 1;
1886   tm.tm_year = ((ttime >> 25) & 0x7f) + 80;
1887   tm.tm_isdst = -1;
1888   return mktime(&tm);
1889 }
1890 
1891 static int
read_exttime(const char * p,struct rar * rar,const char * endp)1892 read_exttime(const char *p, struct rar *rar, const char *endp)
1893 {
1894   unsigned rmode, flags, rem, j, count;
1895   int ttime, i;
1896   struct tm *tm;
1897   time_t t;
1898   long nsec;
1899 #if defined(HAVE_LOCALTIME_R) || defined(HAVE_LOCALTIME_S)
1900   struct tm tmbuf;
1901 #endif
1902 
1903   if (p + 2 > endp)
1904     return (-1);
1905   flags = archive_le16dec(p);
1906   p += 2;
1907 
1908   for (i = 3; i >= 0; i--)
1909   {
1910     t = 0;
1911     if (i == 3)
1912       t = rar->mtime;
1913     rmode = flags >> i * 4;
1914     if (rmode & 8)
1915     {
1916       if (!t)
1917       {
1918         if (p + 4 > endp)
1919           return (-1);
1920         ttime = archive_le32dec(p);
1921         t = get_time(ttime);
1922         p += 4;
1923       }
1924       rem = 0;
1925       count = rmode & 3;
1926       if (p + count > endp)
1927         return (-1);
1928       for (j = 0; j < count; j++)
1929       {
1930         rem = (((unsigned)(unsigned char)*p) << 16) | (rem >> 8);
1931         p++;
1932       }
1933 #if defined(HAVE_LOCALTIME_S)
1934       tm = localtime_s(&tmbuf, &t) ? NULL : &tmbuf;
1935 #elif defined(HAVE_LOCALTIME_R)
1936       tm = localtime_r(&t, &tmbuf);
1937 #else
1938       tm = localtime(&t);
1939 #endif
1940       nsec = tm->tm_sec + rem / NS_UNIT;
1941       if (rmode & 4)
1942       {
1943         tm->tm_sec++;
1944         t = mktime(tm);
1945       }
1946       if (i == 3)
1947       {
1948         rar->mtime = t;
1949         rar->mnsec = nsec;
1950       }
1951       else if (i == 2)
1952       {
1953         rar->ctime = t;
1954         rar->cnsec = nsec;
1955       }
1956       else if (i == 1)
1957       {
1958         rar->atime = t;
1959         rar->ansec = nsec;
1960       }
1961       else
1962       {
1963         rar->arctime = t;
1964         rar->arcnsec = nsec;
1965       }
1966     }
1967   }
1968   return (0);
1969 }
1970 
1971 static int
read_symlink_stored(struct archive_read * a,struct archive_entry * entry,struct archive_string_conv * sconv)1972 read_symlink_stored(struct archive_read *a, struct archive_entry *entry,
1973                     struct archive_string_conv *sconv)
1974 {
1975   const void *h;
1976   const char *p;
1977   struct rar *rar;
1978   int ret = (ARCHIVE_OK);
1979 
1980   rar = (struct rar *)(a->format->data);
1981   if ((uintmax_t)rar->packed_size > SIZE_MAX)
1982   {
1983     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1984                       "Unable to read link.");
1985     return (ARCHIVE_FATAL);
1986   }
1987   if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL)
1988   {
1989     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1990                       "Failed to read link.");
1991     return (ARCHIVE_FATAL);
1992   }
1993   p = h;
1994 
1995   if (archive_entry_copy_symlink_l(entry,
1996       p, (size_t)rar->packed_size, sconv))
1997   {
1998     if (errno == ENOMEM)
1999     {
2000       archive_set_error(&a->archive, ENOMEM,
2001                         "Can't allocate memory for link");
2002       return (ARCHIVE_FATAL);
2003     }
2004     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2005                       "link cannot be converted from %s to current locale.",
2006                       archive_string_conversion_charset_name(sconv));
2007     ret = (ARCHIVE_WARN);
2008   }
2009   __archive_read_consume(a, rar->packed_size);
2010   return ret;
2011 }
2012 
2013 static int
read_data_stored(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset)2014 read_data_stored(struct archive_read *a, const void **buff, size_t *size,
2015                  int64_t *offset)
2016 {
2017   struct rar *rar;
2018   ssize_t bytes_avail;
2019 
2020   rar = (struct rar *)(a->format->data);
2021   if (rar->bytes_remaining == 0 &&
2022     !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER))
2023   {
2024     *buff = NULL;
2025     *size = 0;
2026     *offset = rar->offset;
2027     if (rar->file_crc != rar->crc_calculated) {
2028 #ifndef DONT_FAIL_ON_CRC_ERROR
2029       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2030                         "File CRC error");
2031       return (ARCHIVE_FATAL);
2032 #endif
2033     }
2034     rar->entry_eof = 1;
2035     return (ARCHIVE_EOF);
2036   }
2037 
2038   *buff = rar_read_ahead(a, 1, &bytes_avail);
2039   if (bytes_avail <= 0)
2040   {
2041     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2042                       "Truncated RAR file data");
2043     return (ARCHIVE_FATAL);
2044   }
2045 
2046   *size = bytes_avail;
2047   *offset = rar->offset;
2048   rar->offset += bytes_avail;
2049   rar->offset_seek += bytes_avail;
2050   rar->bytes_remaining -= bytes_avail;
2051   rar->bytes_unconsumed = bytes_avail;
2052   /* Calculate File CRC. */
2053   rar->crc_calculated = crc32(rar->crc_calculated, *buff,
2054     (unsigned)bytes_avail);
2055   return (ARCHIVE_OK);
2056 }
2057 
2058 static int
read_data_compressed(struct archive_read * a,const void ** buff,size_t * size,int64_t * offset,size_t looper)2059 read_data_compressed(struct archive_read *a, const void **buff, size_t *size,
2060                      int64_t *offset, size_t looper)
2061 {
2062   if (looper++ > MAX_COMPRESS_DEPTH)
2063     return (ARCHIVE_FATAL);
2064 
2065   struct rar *rar;
2066   int64_t start, end;
2067   size_t bs;
2068   int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i;
2069 
2070   rar = (struct rar *)(a->format->data);
2071 
2072   do {
2073     if (!rar->valid)
2074       return (ARCHIVE_FATAL);
2075 
2076     if (rar->filters.bytes_ready > 0)
2077     {
2078       /* Flush unp_buffer first */
2079       if (rar->unp_offset > 0)
2080       {
2081         *buff = rar->unp_buffer;
2082         *size = rar->unp_offset;
2083         rar->unp_offset = 0;
2084         *offset = rar->offset_outgoing;
2085         rar->offset_outgoing += *size;
2086       }
2087       else
2088       {
2089         *buff = rar->filters.bytes;
2090         *size = rar->filters.bytes_ready;
2091 
2092         rar->offset += *size;
2093         *offset = rar->offset_outgoing;
2094         rar->offset_outgoing += *size;
2095 
2096         rar->filters.bytes_ready -= *size;
2097         rar->filters.bytes += *size;
2098       }
2099       goto ending_block;
2100     }
2101 
2102     if (rar->ppmd_eod ||
2103        (rar->dictionary_size && rar->offset >= rar->unp_size))
2104     {
2105       if (rar->unp_offset > 0) {
2106         /*
2107          * We have unprocessed extracted data. write it out.
2108          */
2109         *buff = rar->unp_buffer;
2110         *size = rar->unp_offset;
2111         *offset = rar->offset_outgoing;
2112         rar->offset_outgoing += *size;
2113         /* Calculate File CRC. */
2114         rar->crc_calculated = crc32(rar->crc_calculated, *buff,
2115           (unsigned)*size);
2116         rar->unp_offset = 0;
2117         return (ARCHIVE_OK);
2118       }
2119       *buff = NULL;
2120       *size = 0;
2121       *offset = rar->offset;
2122       if (rar->file_crc != rar->crc_calculated) {
2123 #ifndef DONT_FAIL_ON_CRC_ERROR
2124         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2125                           "File CRC error");
2126         return (ARCHIVE_FATAL);
2127 #endif
2128       }
2129       rar->entry_eof = 1;
2130       return (ARCHIVE_EOF);
2131     }
2132 
2133     if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0)
2134     {
2135       if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
2136         bs = rar->unp_buffer_size - rar->unp_offset;
2137       else
2138         bs = (size_t)rar->bytes_uncopied;
2139       ret = copy_from_lzss_window_to_unp(a, buff, rar->offset, bs);
2140       if (ret != ARCHIVE_OK)
2141         return (ret);
2142       rar->offset += bs;
2143       rar->bytes_uncopied -= bs;
2144       if (*buff != NULL) {
2145         rar->unp_offset = 0;
2146         *size = rar->unp_buffer_size;
2147         *offset = rar->offset_outgoing;
2148         rar->offset_outgoing += *size;
2149         /* Calculate File CRC. */
2150         rar->crc_calculated = crc32(rar->crc_calculated, *buff,
2151           (unsigned)*size);
2152         return (ret);
2153       }
2154       continue;
2155     }
2156 
2157     if (rar->filters.lastend == rar->filters.filterstart)
2158     {
2159       if (!run_filters(a))
2160         return (ARCHIVE_FATAL);
2161       continue;
2162     }
2163 
2164     if (!rar->br.next_in &&
2165       (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN)
2166       return (ret);
2167     if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN)))
2168       return (ret);
2169 
2170     if (rar->is_ppmd_block)
2171     {
2172       if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2173         &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2174       {
2175         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2176                           "Invalid symbol");
2177         return (ARCHIVE_FATAL);
2178       }
2179       if(sym != rar->ppmd_escape)
2180       {
2181         lzss_emit_literal(rar, sym);
2182         rar->bytes_uncopied++;
2183       }
2184       else
2185       {
2186         if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2187           &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2188         {
2189           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2190                             "Invalid symbol");
2191           return (ARCHIVE_FATAL);
2192         }
2193 
2194         switch(code)
2195         {
2196           case 0:
2197             rar->start_new_table = 1;
2198             return read_data_compressed(a, buff, size, offset, looper);
2199 
2200           case 2:
2201             rar->ppmd_eod = 1;/* End Of ppmd Data. */
2202             continue;
2203 
2204           case 3:
2205             archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2206                               "Parsing filters is unsupported.");
2207             return (ARCHIVE_FAILED);
2208 
2209           case 4:
2210             lzss_offset = 0;
2211             for (i = 2; i >= 0; i--)
2212             {
2213               if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2214                 &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2215               {
2216                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2217                                   "Invalid symbol");
2218                 return (ARCHIVE_FATAL);
2219               }
2220               lzss_offset |= code << (i * 8);
2221             }
2222             if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2223               &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2224             {
2225               archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2226                                 "Invalid symbol");
2227               return (ARCHIVE_FATAL);
2228             }
2229             lzss_emit_match(rar, lzss_offset + 2, length + 32);
2230             rar->bytes_uncopied += length + 32;
2231             break;
2232 
2233           case 5:
2234             if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
2235               &rar->ppmd7_context, &rar->range_dec.p)) < 0)
2236             {
2237               archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2238                                 "Invalid symbol");
2239               return (ARCHIVE_FATAL);
2240             }
2241             lzss_emit_match(rar, 1, length + 4);
2242             rar->bytes_uncopied += length + 4;
2243             break;
2244 
2245          default:
2246            lzss_emit_literal(rar, sym);
2247            rar->bytes_uncopied++;
2248         }
2249       }
2250     }
2251     else
2252     {
2253       start = rar->offset;
2254       end = start + rar->dictionary_size;
2255 
2256       /* We don't want to overflow the window and overwrite data that we write
2257        * at 'start'. Therefore, reduce the end length by the maximum match size,
2258        * which is 260 bytes. You can compute this maximum by looking at the
2259        * definition of 'expand', in particular when 'symbol >= 271'. */
2260       /* NOTE: It's possible for 'dictionary_size' to be less than this 260
2261        * value, however that will only be the case when 'unp_size' is small,
2262        * which should only happen when the entry size is small and there's no
2263        * risk of overflowing the buffer */
2264       if (rar->dictionary_size > 260) {
2265         end -= 260;
2266       }
2267 
2268       if (rar->filters.filterstart < end) {
2269         end = rar->filters.filterstart;
2270       }
2271 
2272       ret = expand(a, &end);
2273       if (ret != ARCHIVE_OK)
2274         return (ret);
2275 
2276       rar->bytes_uncopied = end - start;
2277       rar->filters.lastend = end;
2278       if (rar->filters.lastend != rar->filters.filterstart && rar->bytes_uncopied == 0) {
2279           /* Broken RAR files cause this case.
2280           * NOTE: If this case were possible on a normal RAR file
2281           * we would find out where it was actually bad and
2282           * what we would do to solve it. */
2283           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2284                             "Internal error extracting RAR file");
2285           return (ARCHIVE_FATAL);
2286       }
2287     }
2288     if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
2289       bs = rar->unp_buffer_size - rar->unp_offset;
2290     else
2291       bs = (size_t)rar->bytes_uncopied;
2292     ret = copy_from_lzss_window_to_unp(a, buff, rar->offset, bs);
2293     if (ret != ARCHIVE_OK)
2294       return (ret);
2295     rar->offset += bs;
2296     rar->bytes_uncopied -= bs;
2297     /*
2298      * If *buff is NULL, it means unp_buffer is not full.
2299      * So we have to continue extracting a RAR file.
2300      */
2301   } while (*buff == NULL);
2302 
2303   rar->unp_offset = 0;
2304   *size = rar->unp_buffer_size;
2305   *offset = rar->offset_outgoing;
2306   rar->offset_outgoing += *size;
2307 ending_block:
2308   /* Calculate File CRC. */
2309   rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size);
2310   return ret;
2311 }
2312 
2313 static int
parse_codes(struct archive_read * a)2314 parse_codes(struct archive_read *a)
2315 {
2316   int i, j, val, n, r;
2317   unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags;
2318   unsigned int maxorder;
2319   struct huffman_code precode;
2320   struct rar *rar = (struct rar *)(a->format->data);
2321   struct rar_br *br = &(rar->br);
2322 
2323   free_codes(a);
2324 
2325   /* Skip to the next byte */
2326   rar_br_consume_unaligned_bits(br);
2327 
2328   /* PPMd block flag */
2329   if (!rar_br_read_ahead(a, br, 1))
2330     goto truncated_data;
2331   if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0)
2332   {
2333     rar_br_consume(br, 1);
2334     if (!rar_br_read_ahead(a, br, 7))
2335       goto truncated_data;
2336     ppmd_flags = rar_br_bits(br, 7);
2337     rar_br_consume(br, 7);
2338 
2339     /* Memory is allocated in MB */
2340     if (ppmd_flags & 0x20)
2341     {
2342       if (!rar_br_read_ahead(a, br, 8))
2343         goto truncated_data;
2344       rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20;
2345       rar_br_consume(br, 8);
2346     }
2347 
2348     if (ppmd_flags & 0x40)
2349     {
2350       if (!rar_br_read_ahead(a, br, 8))
2351         goto truncated_data;
2352       rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8);
2353       rar_br_consume(br, 8);
2354     }
2355     else
2356       rar->ppmd_escape = 2;
2357 
2358     if (ppmd_flags & 0x20)
2359     {
2360       maxorder = (ppmd_flags & 0x1F) + 1;
2361       if(maxorder > 16)
2362         maxorder = 16 + (maxorder - 16) * 3;
2363 
2364       if (maxorder == 1)
2365       {
2366         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2367                           "Truncated RAR file data");
2368         return (ARCHIVE_FATAL);
2369       }
2370 
2371       /* Make sure ppmd7_contest is freed before Ppmd7_Construct
2372        * because reading a broken file cause this abnormal sequence. */
2373       __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context);
2374 
2375       rar->bytein.a = a;
2376       rar->bytein.Read = &ppmd_read;
2377       __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec);
2378       rar->range_dec.Stream = &rar->bytein;
2379       __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context);
2380 
2381       if (rar->dictionary_size == 0) {
2382         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2383                           "Invalid zero dictionary size");
2384         return (ARCHIVE_FATAL);
2385       }
2386 
2387       if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context,
2388         rar->dictionary_size))
2389       {
2390         archive_set_error(&a->archive, ENOMEM,
2391                           "Out of memory");
2392         return (ARCHIVE_FATAL);
2393       }
2394       if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
2395       {
2396         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2397                           "Unable to initialize PPMd range decoder");
2398         return (ARCHIVE_FATAL);
2399       }
2400       __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder);
2401       rar->ppmd_valid = 1;
2402     }
2403     else
2404     {
2405       if (!rar->ppmd_valid) {
2406         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2407                           "Invalid PPMd sequence");
2408         return (ARCHIVE_FATAL);
2409       }
2410       if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
2411       {
2412         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2413                           "Unable to initialize PPMd range decoder");
2414         return (ARCHIVE_FATAL);
2415       }
2416     }
2417   }
2418   else
2419   {
2420     rar_br_consume(br, 1);
2421 
2422     /* Keep existing table flag */
2423     if (!rar_br_read_ahead(a, br, 1))
2424       goto truncated_data;
2425     if (!rar_br_bits(br, 1))
2426       memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
2427     rar_br_consume(br, 1);
2428 
2429     memset(&bitlengths, 0, sizeof(bitlengths));
2430     for (i = 0; i < MAX_SYMBOLS;)
2431     {
2432       if (!rar_br_read_ahead(a, br, 4))
2433         goto truncated_data;
2434       bitlengths[i++] = rar_br_bits(br, 4);
2435       rar_br_consume(br, 4);
2436       if (bitlengths[i-1] == 0xF)
2437       {
2438         if (!rar_br_read_ahead(a, br, 4))
2439           goto truncated_data;
2440         zerocount = rar_br_bits(br, 4);
2441         rar_br_consume(br, 4);
2442         if (zerocount)
2443         {
2444           i--;
2445           for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++)
2446             bitlengths[i++] = 0;
2447         }
2448       }
2449     }
2450 
2451     memset(&precode, 0, sizeof(precode));
2452     r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH);
2453     if (r != ARCHIVE_OK) {
2454       free(precode.tree);
2455       free(precode.table);
2456       return (r);
2457     }
2458 
2459     for (i = 0; i < HUFFMAN_TABLE_SIZE;)
2460     {
2461       if ((val = read_next_symbol(a, &precode)) < 0) {
2462         free(precode.tree);
2463         free(precode.table);
2464         return (ARCHIVE_FATAL);
2465       }
2466       if (val < 16)
2467       {
2468         rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF;
2469         i++;
2470       }
2471       else if (val < 18)
2472       {
2473         if (i == 0)
2474         {
2475           free(precode.tree);
2476           free(precode.table);
2477           archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2478                             "Internal error extracting RAR file.");
2479           return (ARCHIVE_FATAL);
2480         }
2481 
2482         if(val == 16) {
2483           if (!rar_br_read_ahead(a, br, 3)) {
2484             free(precode.tree);
2485             free(precode.table);
2486             goto truncated_data;
2487           }
2488           n = rar_br_bits(br, 3) + 3;
2489           rar_br_consume(br, 3);
2490         } else {
2491           if (!rar_br_read_ahead(a, br, 7)) {
2492             free(precode.tree);
2493             free(precode.table);
2494             goto truncated_data;
2495           }
2496           n = rar_br_bits(br, 7) + 11;
2497           rar_br_consume(br, 7);
2498         }
2499 
2500         for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
2501         {
2502           rar->lengthtable[i] = rar->lengthtable[i-1];
2503           i++;
2504         }
2505       }
2506       else
2507       {
2508         if(val == 18) {
2509           if (!rar_br_read_ahead(a, br, 3)) {
2510             free(precode.tree);
2511             free(precode.table);
2512             goto truncated_data;
2513           }
2514           n = rar_br_bits(br, 3) + 3;
2515           rar_br_consume(br, 3);
2516         } else {
2517           if (!rar_br_read_ahead(a, br, 7)) {
2518             free(precode.tree);
2519             free(precode.table);
2520             goto truncated_data;
2521           }
2522           n = rar_br_bits(br, 7) + 11;
2523           rar_br_consume(br, 7);
2524         }
2525 
2526         for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
2527           rar->lengthtable[i++] = 0;
2528       }
2529     }
2530     free(precode.tree);
2531     free(precode.table);
2532 
2533     r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE,
2534                 MAX_SYMBOL_LENGTH);
2535     if (r != ARCHIVE_OK)
2536       return (r);
2537     r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE],
2538                 OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
2539     if (r != ARCHIVE_OK)
2540       return (r);
2541     r = create_code(a, &rar->lowoffsetcode,
2542                 &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE],
2543                 LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
2544     if (r != ARCHIVE_OK)
2545       return (r);
2546     r = create_code(a, &rar->lengthcode,
2547                 &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE +
2548                 LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH);
2549     if (r != ARCHIVE_OK)
2550       return (r);
2551   }
2552 
2553   if (!rar->dictionary_size || !rar->lzss.window)
2554   {
2555     /* Seems as though dictionary sizes are not used. Even so, minimize
2556      * memory usage as much as possible.
2557      */
2558     void *new_window;
2559     unsigned int new_size;
2560 
2561     if (rar->unp_size >= DICTIONARY_MAX_SIZE)
2562       new_size = DICTIONARY_MAX_SIZE;
2563     else
2564       new_size = rar_fls((unsigned int)rar->unp_size) << 1;
2565     if (new_size == 0) {
2566       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2567                         "Zero window size is invalid.");
2568       return (ARCHIVE_FATAL);
2569     }
2570     new_window = realloc(rar->lzss.window, new_size);
2571     if (new_window == NULL) {
2572       archive_set_error(&a->archive, ENOMEM,
2573                         "Unable to allocate memory for uncompressed data.");
2574       return (ARCHIVE_FATAL);
2575     }
2576     rar->lzss.window = (unsigned char *)new_window;
2577     rar->dictionary_size = new_size;
2578     memset(rar->lzss.window, 0, rar->dictionary_size);
2579     rar->lzss.mask = rar->dictionary_size - 1;
2580   }
2581 
2582   rar->start_new_table = 0;
2583   return (ARCHIVE_OK);
2584 truncated_data:
2585   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2586                     "Truncated RAR file data");
2587   rar->valid = 0;
2588   return (ARCHIVE_FATAL);
2589 }
2590 
2591 static void
free_codes(struct archive_read * a)2592 free_codes(struct archive_read *a)
2593 {
2594   struct rar *rar = (struct rar *)(a->format->data);
2595   free(rar->maincode.tree);
2596   free(rar->offsetcode.tree);
2597   free(rar->lowoffsetcode.tree);
2598   free(rar->lengthcode.tree);
2599   free(rar->maincode.table);
2600   free(rar->offsetcode.table);
2601   free(rar->lowoffsetcode.table);
2602   free(rar->lengthcode.table);
2603   memset(&rar->maincode, 0, sizeof(rar->maincode));
2604   memset(&rar->offsetcode, 0, sizeof(rar->offsetcode));
2605   memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode));
2606   memset(&rar->lengthcode, 0, sizeof(rar->lengthcode));
2607 }
2608 
2609 
2610 static int
read_next_symbol(struct archive_read * a,struct huffman_code * code)2611 read_next_symbol(struct archive_read *a, struct huffman_code *code)
2612 {
2613   unsigned char bit;
2614   unsigned int bits;
2615   int length, value, node;
2616   struct rar *rar;
2617   struct rar_br *br;
2618 
2619   if (!code->table)
2620   {
2621     if (make_table(a, code) != (ARCHIVE_OK))
2622       return -1;
2623   }
2624 
2625   rar = (struct rar *)(a->format->data);
2626   br = &(rar->br);
2627 
2628   /* Look ahead (peek) at bits */
2629   if (!rar_br_read_ahead(a, br, code->tablesize)) {
2630     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2631                       "Truncated RAR file data");
2632     rar->valid = 0;
2633     return -1;
2634   }
2635   bits = rar_br_bits(br, code->tablesize);
2636 
2637   length = code->table[bits].length;
2638   value = code->table[bits].value;
2639 
2640   if (length < 0)
2641   {
2642     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2643                       "Invalid prefix code in bitstream");
2644     return -1;
2645   }
2646 
2647   if (length <= code->tablesize)
2648   {
2649     /* Skip length bits */
2650     rar_br_consume(br, length);
2651     return value;
2652   }
2653 
2654   /* Skip tablesize bits */
2655   rar_br_consume(br, code->tablesize);
2656 
2657   node = value;
2658   while (code->tree[node].branches[0] != code->tree[node].branches[1])
2659   {
2660     if (!rar_br_read_ahead(a, br, 1)) {
2661       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2662                         "Truncated RAR file data");
2663       rar->valid = 0;
2664       return -1;
2665     }
2666     bit = rar_br_bits(br, 1);
2667     rar_br_consume(br, 1);
2668 
2669     if (code->tree[node].branches[bit] < 0)
2670     {
2671       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2672                         "Invalid prefix code in bitstream");
2673       return -1;
2674     }
2675     node = code->tree[node].branches[bit];
2676   }
2677 
2678   return code->tree[node].branches[0];
2679 }
2680 
2681 static int
create_code(struct archive_read * a,struct huffman_code * code,unsigned char * lengths,int numsymbols,char maxlength)2682 create_code(struct archive_read *a, struct huffman_code *code,
2683             unsigned char *lengths, int numsymbols, char maxlength)
2684 {
2685   int i, j, codebits = 0, symbolsleft = numsymbols;
2686 
2687   code->numentries = 0;
2688   code->numallocatedentries = 0;
2689   if (new_node(code) < 0) {
2690     archive_set_error(&a->archive, ENOMEM,
2691                       "Unable to allocate memory for node data.");
2692     return (ARCHIVE_FATAL);
2693   }
2694   code->numentries = 1;
2695   code->minlength = INT_MAX;
2696   code->maxlength = INT_MIN;
2697   codebits = 0;
2698   for(i = 1; i <= maxlength; i++)
2699   {
2700     for(j = 0; j < numsymbols; j++)
2701     {
2702       if (lengths[j] != i) continue;
2703       if (add_value(a, code, j, codebits, i) != ARCHIVE_OK)
2704         return (ARCHIVE_FATAL);
2705       codebits++;
2706       if (--symbolsleft <= 0)
2707         break;
2708     }
2709     if (symbolsleft <= 0)
2710       break;
2711     codebits <<= 1;
2712   }
2713   return (ARCHIVE_OK);
2714 }
2715 
2716 static int
add_value(struct archive_read * a,struct huffman_code * code,int value,int codebits,int length)2717 add_value(struct archive_read *a, struct huffman_code *code, int value,
2718           int codebits, int length)
2719 {
2720   int lastnode, bitpos, bit;
2721   /* int repeatpos, repeatnode, nextnode; */
2722 
2723   free(code->table);
2724   code->table = NULL;
2725 
2726   if(length > code->maxlength)
2727     code->maxlength = length;
2728   if(length < code->minlength)
2729     code->minlength = length;
2730 
2731   /*
2732    * Dead code, repeatpos was is -1
2733    *
2734   repeatpos = -1;
2735   if (repeatpos == 0 || (repeatpos >= 0
2736     && (((codebits >> (repeatpos - 1)) & 3) == 0
2737     || ((codebits >> (repeatpos - 1)) & 3) == 3)))
2738   {
2739     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2740                       "Invalid repeat position");
2741     return (ARCHIVE_FATAL);
2742   }
2743   */
2744 
2745   lastnode = 0;
2746   for (bitpos = length - 1; bitpos >= 0; bitpos--)
2747   {
2748     bit = (codebits >> bitpos) & 1;
2749 
2750     /* Leaf node check */
2751     if (code->tree[lastnode].branches[0] ==
2752       code->tree[lastnode].branches[1])
2753     {
2754       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2755                         "Prefix found");
2756       return (ARCHIVE_FATAL);
2757     }
2758 
2759     /*
2760      * Dead code, repeatpos was -1, bitpos >=0
2761      *
2762     if (bitpos == repeatpos)
2763     {
2764       * Open branch check *
2765       if (!(code->tree[lastnode].branches[bit] < 0))
2766       {
2767         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2768                           "Invalid repeating code");
2769         return (ARCHIVE_FATAL);
2770       }
2771 
2772       if ((repeatnode = new_node(code)) < 0) {
2773         archive_set_error(&a->archive, ENOMEM,
2774                           "Unable to allocate memory for node data.");
2775         return (ARCHIVE_FATAL);
2776       }
2777       if ((nextnode = new_node(code)) < 0) {
2778         archive_set_error(&a->archive, ENOMEM,
2779                           "Unable to allocate memory for node data.");
2780         return (ARCHIVE_FATAL);
2781       }
2782 
2783       * Set branches *
2784       code->tree[lastnode].branches[bit] = repeatnode;
2785       code->tree[repeatnode].branches[bit] = repeatnode;
2786       code->tree[repeatnode].branches[bit^1] = nextnode;
2787       lastnode = nextnode;
2788 
2789       bitpos++; * terminating bit already handled, skip it *
2790     }
2791     else
2792     {
2793     */
2794       /* Open branch check */
2795       if (code->tree[lastnode].branches[bit] < 0)
2796       {
2797         if (new_node(code) < 0) {
2798           archive_set_error(&a->archive, ENOMEM,
2799                             "Unable to allocate memory for node data.");
2800           return (ARCHIVE_FATAL);
2801         }
2802         code->tree[lastnode].branches[bit] = code->numentries++;
2803       }
2804 
2805       /* set to branch */
2806       lastnode = code->tree[lastnode].branches[bit];
2807  /* } */
2808   }
2809 
2810   if (!(code->tree[lastnode].branches[0] == -1
2811     && code->tree[lastnode].branches[1] == -2))
2812   {
2813     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2814                       "Prefix found");
2815     return (ARCHIVE_FATAL);
2816   }
2817 
2818   /* Set leaf value */
2819   code->tree[lastnode].branches[0] = value;
2820   code->tree[lastnode].branches[1] = value;
2821 
2822   return (ARCHIVE_OK);
2823 }
2824 
2825 static int
new_node(struct huffman_code * code)2826 new_node(struct huffman_code *code)
2827 {
2828   void *new_tree;
2829   if (code->numallocatedentries == code->numentries) {
2830     int new_num_entries = 256;
2831     if (code->numentries > 0) {
2832         new_num_entries = code->numentries * 2;
2833     }
2834     new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree));
2835     if (new_tree == NULL)
2836         return (-1);
2837     code->tree = (struct huffman_tree_node *)new_tree;
2838     code->numallocatedentries = new_num_entries;
2839   }
2840   code->tree[code->numentries].branches[0] = -1;
2841   code->tree[code->numentries].branches[1] = -2;
2842   return 1;
2843 }
2844 
2845 static int
make_table(struct archive_read * a,struct huffman_code * code)2846 make_table(struct archive_read *a, struct huffman_code *code)
2847 {
2848   if (code->maxlength < code->minlength || code->maxlength > 10)
2849     code->tablesize = 10;
2850   else
2851     code->tablesize = code->maxlength;
2852 
2853   code->table = calloc(((size_t)1U) << code->tablesize, sizeof(*code->table));
2854 
2855   return make_table_recurse(a, code, 0, code->table, 0, code->tablesize);
2856 }
2857 
2858 static int
make_table_recurse(struct archive_read * a,struct huffman_code * code,int node,struct huffman_table_entry * table,int depth,int maxdepth)2859 make_table_recurse(struct archive_read *a, struct huffman_code *code, int node,
2860                    struct huffman_table_entry *table, int depth,
2861                    int maxdepth)
2862 {
2863   int currtablesize, i, ret = (ARCHIVE_OK);
2864 
2865   if (!code->tree)
2866   {
2867     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2868                       "Huffman tree was not created.");
2869     return (ARCHIVE_FATAL);
2870   }
2871   if (node < 0 || node >= code->numentries)
2872   {
2873     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2874                       "Invalid location to Huffman tree specified.");
2875     return (ARCHIVE_FATAL);
2876   }
2877 
2878   currtablesize = 1 << (maxdepth - depth);
2879 
2880   if (code->tree[node].branches[0] ==
2881     code->tree[node].branches[1])
2882   {
2883     for(i = 0; i < currtablesize; i++)
2884     {
2885       table[i].length = depth;
2886       table[i].value = code->tree[node].branches[0];
2887     }
2888   }
2889   /*
2890    * Dead code, node >= 0
2891    *
2892   else if (node < 0)
2893   {
2894     for(i = 0; i < currtablesize; i++)
2895       table[i].length = -1;
2896   }
2897    */
2898   else
2899   {
2900     if(depth == maxdepth)
2901     {
2902       table[0].length = maxdepth + 1;
2903       table[0].value = node;
2904     }
2905     else
2906     {
2907       ret |= make_table_recurse(a, code, code->tree[node].branches[0], table,
2908                                 depth + 1, maxdepth);
2909       ret |= make_table_recurse(a, code, code->tree[node].branches[1],
2910                          table + currtablesize / 2, depth + 1, maxdepth);
2911     }
2912   }
2913   return ret;
2914 }
2915 
2916 static int
expand(struct archive_read * a,int64_t * end)2917 expand(struct archive_read *a, int64_t *end)
2918 {
2919   static const unsigned char lengthbases[] =
2920     {   0,   1,   2,   3,   4,   5,   6,
2921         7,   8,  10,  12,  14,  16,  20,
2922        24,  28,  32,  40,  48,  56,  64,
2923        80,  96, 112, 128, 160, 192, 224 };
2924   static const unsigned char lengthbits[] =
2925     { 0, 0, 0, 0, 0, 0, 0,
2926       0, 1, 1, 1, 1, 2, 2,
2927       2, 2, 3, 3, 3, 3, 4,
2928       4, 4, 4, 5, 5, 5, 5 };
2929   static const int lengthb_min = minimum(
2930     (int)(sizeof(lengthbases)/sizeof(lengthbases[0])),
2931     (int)(sizeof(lengthbits)/sizeof(lengthbits[0]))
2932   );
2933   static const unsigned int offsetbases[] =
2934     {       0,       1,       2,       3,       4,       6,
2935             8,      12,      16,      24,      32,      48,
2936            64,      96,     128,     192,     256,     384,
2937           512,     768,    1024,    1536,    2048,    3072,
2938          4096,    6144,    8192,   12288,   16384,   24576,
2939         32768,   49152,   65536,   98304,  131072,  196608,
2940        262144,  327680,  393216,  458752,  524288,  589824,
2941        655360,  720896,  786432,  851968,  917504,  983040,
2942       1048576, 1310720, 1572864, 1835008, 2097152, 2359296,
2943       2621440, 2883584, 3145728, 3407872, 3670016, 3932160 };
2944   static const unsigned char offsetbits[] =
2945     {  0,  0,  0,  0,  1,  1,  2,  2,  3,  3,  4,  4,
2946        5,  5,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10,
2947       11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16,
2948       16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
2949       18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 };
2950   static const int offsetb_min = minimum(
2951     (int)(sizeof(offsetbases)/sizeof(offsetbases[0])),
2952     (int)(sizeof(offsetbits)/sizeof(offsetbits[0]))
2953   );
2954   static const unsigned char shortbases[] =
2955     { 0, 4, 8, 16, 32, 64, 128, 192 };
2956   static const unsigned char shortbits[] =
2957     { 2, 2, 3, 4, 5, 6, 6, 6 };
2958 
2959   int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol;
2960   unsigned char newfile;
2961   struct rar *rar = (struct rar *)(a->format->data);
2962   struct rar_br *br = &(rar->br);
2963 
2964   if (rar->filters.filterstart < *end)
2965     *end = rar->filters.filterstart;
2966 
2967   while (1)
2968   {
2969     if(lzss_position(&rar->lzss) >= *end) {
2970       return (ARCHIVE_OK);
2971     }
2972 
2973     if(rar->is_ppmd_block) {
2974       *end = lzss_position(&rar->lzss);
2975       return (ARCHIVE_OK);
2976     }
2977 
2978     if ((symbol = read_next_symbol(a, &rar->maincode)) < 0)
2979       goto bad_data;
2980 
2981     if (symbol < 256)
2982     {
2983       lzss_emit_literal(rar, (uint8_t)symbol);
2984       continue;
2985     }
2986     else if (symbol == 256)
2987     {
2988       if (!rar_br_read_ahead(a, br, 1))
2989         goto truncated_data;
2990       newfile = !rar_br_bits(br, 1);
2991       rar_br_consume(br, 1);
2992 
2993       if(newfile)
2994       {
2995         rar->start_new_block = 1;
2996         if (!rar_br_read_ahead(a, br, 1))
2997           goto truncated_data;
2998         rar->start_new_table = rar_br_bits(br, 1);
2999         rar_br_consume(br, 1);
3000         *end = lzss_position(&rar->lzss);
3001         return (ARCHIVE_OK);
3002       }
3003       else
3004       {
3005         if (parse_codes(a) != ARCHIVE_OK)
3006           goto bad_data;
3007         continue;
3008       }
3009     }
3010     else if(symbol==257)
3011     {
3012       if (!read_filter(a, end))
3013           goto bad_data;
3014       continue;
3015     }
3016     else if(symbol==258)
3017     {
3018       if(rar->lastlength == 0)
3019         continue;
3020 
3021       offs = rar->lastoffset;
3022       len = rar->lastlength;
3023     }
3024     else if (symbol <= 262)
3025     {
3026       offsindex = symbol - 259;
3027       offs = rar->oldoffset[offsindex];
3028 
3029       if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0)
3030         goto bad_data;
3031       if (lensymbol >= lengthb_min)
3032         goto bad_data;
3033       len = lengthbases[lensymbol] + 2;
3034       if (lengthbits[lensymbol] > 0) {
3035         if (!rar_br_read_ahead(a, br, lengthbits[lensymbol]))
3036           goto truncated_data;
3037         len += rar_br_bits(br, lengthbits[lensymbol]);
3038         rar_br_consume(br, lengthbits[lensymbol]);
3039       }
3040 
3041       for (i = offsindex; i > 0; i--)
3042         rar->oldoffset[i] = rar->oldoffset[i-1];
3043       rar->oldoffset[0] = offs;
3044     }
3045     else if(symbol<=270)
3046     {
3047       offs = shortbases[symbol-263] + 1;
3048       if(shortbits[symbol-263] > 0) {
3049         if (!rar_br_read_ahead(a, br, shortbits[symbol-263]))
3050           goto truncated_data;
3051         offs += rar_br_bits(br, shortbits[symbol-263]);
3052         rar_br_consume(br, shortbits[symbol-263]);
3053       }
3054 
3055       len = 2;
3056 
3057       for(i = 3; i > 0; i--)
3058         rar->oldoffset[i] = rar->oldoffset[i-1];
3059       rar->oldoffset[0] = offs;
3060     }
3061     else
3062     {
3063       if (symbol-271 >= lengthb_min)
3064         goto bad_data;
3065       len = lengthbases[symbol-271]+3;
3066       if(lengthbits[symbol-271] > 0) {
3067         if (!rar_br_read_ahead(a, br, lengthbits[symbol-271]))
3068           goto truncated_data;
3069         len += rar_br_bits(br, lengthbits[symbol-271]);
3070         rar_br_consume(br, lengthbits[symbol-271]);
3071       }
3072 
3073       if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0)
3074         goto bad_data;
3075       if (offssymbol >= offsetb_min)
3076         goto bad_data;
3077       offs = offsetbases[offssymbol]+1;
3078       if(offsetbits[offssymbol] > 0)
3079       {
3080         if(offssymbol > 9)
3081         {
3082           if(offsetbits[offssymbol] > 4) {
3083             if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4))
3084               goto truncated_data;
3085             offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4;
3086             rar_br_consume(br, offsetbits[offssymbol] - 4);
3087           }
3088 
3089           if(rar->numlowoffsetrepeats > 0)
3090           {
3091             rar->numlowoffsetrepeats--;
3092             offs += rar->lastlowoffset;
3093           }
3094           else
3095           {
3096             if ((lowoffsetsymbol =
3097               read_next_symbol(a, &rar->lowoffsetcode)) < 0)
3098               goto bad_data;
3099             if(lowoffsetsymbol == 16)
3100             {
3101               rar->numlowoffsetrepeats = 15;
3102               offs += rar->lastlowoffset;
3103             }
3104             else
3105             {
3106               offs += lowoffsetsymbol;
3107               rar->lastlowoffset = lowoffsetsymbol;
3108             }
3109           }
3110         }
3111         else {
3112           if (!rar_br_read_ahead(a, br, offsetbits[offssymbol]))
3113             goto truncated_data;
3114           offs += rar_br_bits(br, offsetbits[offssymbol]);
3115           rar_br_consume(br, offsetbits[offssymbol]);
3116         }
3117       }
3118 
3119       if (offs >= 0x40000)
3120         len++;
3121       if (offs >= 0x2000)
3122         len++;
3123 
3124       for(i = 3; i > 0; i--)
3125         rar->oldoffset[i] = rar->oldoffset[i-1];
3126       rar->oldoffset[0] = offs;
3127     }
3128 
3129     rar->lastoffset = offs;
3130     rar->lastlength = len;
3131 
3132     lzss_emit_match(rar, rar->lastoffset, rar->lastlength);
3133   }
3134 truncated_data:
3135   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3136                     "Truncated RAR file data");
3137   rar->valid = 0;
3138   return (ARCHIVE_FATAL);
3139 bad_data:
3140   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3141                     "Bad RAR file data");
3142   return (ARCHIVE_FATAL);
3143 }
3144 
3145 static int
copy_from_lzss_window(struct archive_read * a,uint8_t * buffer,int64_t startpos,int length)3146 copy_from_lzss_window(struct archive_read *a, uint8_t *buffer,
3147                       int64_t startpos, int length)
3148 {
3149   int windowoffs, firstpart;
3150   struct rar *rar = (struct rar *)(a->format->data);
3151 
3152   windowoffs = lzss_offset_for_position(&rar->lzss, startpos);
3153   firstpart = lzss_size(&rar->lzss) - windowoffs;
3154   if (firstpart < 0) {
3155     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3156                       "Bad RAR file data");
3157     return (ARCHIVE_FATAL);
3158   }
3159   if (firstpart < length) {
3160     memcpy(buffer, &rar->lzss.window[windowoffs], firstpart);
3161     memcpy(buffer + firstpart, &rar->lzss.window[0], length - firstpart);
3162   } else {
3163     memcpy(buffer, &rar->lzss.window[windowoffs], length);
3164   }
3165   return (ARCHIVE_OK);
3166 }
3167 
3168 static int
copy_from_lzss_window_to_unp(struct archive_read * a,const void ** buffer,int64_t startpos,size_t length)3169 copy_from_lzss_window_to_unp(struct archive_read *a, const void **buffer,
3170                              int64_t startpos, size_t length)
3171 {
3172   int windowoffs, firstpart;
3173   struct rar *rar = (struct rar *)(a->format->data);
3174 
3175   if (length > rar->unp_buffer_size)
3176   {
3177     goto fatal;
3178   }
3179 
3180   if (!rar->unp_buffer)
3181   {
3182     if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL)
3183     {
3184       archive_set_error(&a->archive, ENOMEM,
3185                         "Unable to allocate memory for uncompressed data.");
3186       return (ARCHIVE_FATAL);
3187     }
3188   }
3189 
3190   windowoffs = lzss_offset_for_position(&rar->lzss, startpos);
3191   if(windowoffs + length <= (size_t)lzss_size(&rar->lzss)) {
3192     memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs],
3193            length);
3194   } else if (length <= (size_t)lzss_size(&rar->lzss)) {
3195     firstpart = lzss_size(&rar->lzss) - windowoffs;
3196     if (firstpart < 0) {
3197       archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3198                         "Bad RAR file data");
3199       return (ARCHIVE_FATAL);
3200     }
3201     if ((size_t)firstpart < length) {
3202       memcpy(&rar->unp_buffer[rar->unp_offset],
3203              &rar->lzss.window[windowoffs], firstpart);
3204       memcpy(&rar->unp_buffer[rar->unp_offset + firstpart],
3205              &rar->lzss.window[0], length - firstpart);
3206     } else {
3207       memcpy(&rar->unp_buffer[rar->unp_offset],
3208              &rar->lzss.window[windowoffs], length);
3209     }
3210   } else {
3211       goto fatal;
3212   }
3213   rar->unp_offset += (unsigned int) length;
3214   if (rar->unp_offset >= rar->unp_buffer_size)
3215     *buffer = rar->unp_buffer;
3216   else
3217     *buffer = NULL;
3218   return (ARCHIVE_OK);
3219 
3220 fatal:
3221   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3222                     "Bad RAR file data");
3223   return (ARCHIVE_FATAL);
3224 }
3225 
3226 static const void *
rar_read_ahead(struct archive_read * a,size_t min,ssize_t * avail)3227 rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
3228 {
3229   struct rar *rar = (struct rar *)(a->format->data);
3230   const void *h;
3231   int ret;
3232 
3233 again:
3234   h = __archive_read_ahead(a, min, avail);
3235 
3236   if (avail)
3237   {
3238     if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested)
3239       *avail = a->archive.read_data_requested;
3240     if (*avail > rar->bytes_remaining)
3241       *avail = (ssize_t)rar->bytes_remaining;
3242     if (*avail < 0)
3243       return NULL;
3244     else if (*avail == 0 && rar->main_flags & MHD_VOLUME &&
3245       rar->file_flags & FHD_SPLIT_AFTER)
3246     {
3247       rar->filename_must_match = 1;
3248       ret = archive_read_format_rar_read_header(a, a->entry);
3249       if (ret == (ARCHIVE_EOF))
3250       {
3251         rar->has_endarc_header = 1;
3252         ret = archive_read_format_rar_read_header(a, a->entry);
3253       }
3254       rar->filename_must_match = 0;
3255       if (ret != (ARCHIVE_OK))
3256         return NULL;
3257       goto again;
3258     }
3259   }
3260   return h;
3261 }
3262 
3263 static int
parse_filter(struct archive_read * a,const uint8_t * bytes,uint16_t length,uint8_t flags)3264 parse_filter(struct archive_read *a, const uint8_t *bytes, uint16_t length, uint8_t flags)
3265 {
3266   struct rar *rar = (struct rar *)(a->format->data);
3267   struct rar_filters *filters = &rar->filters;
3268 
3269   struct memory_bit_reader br = { 0 };
3270   struct rar_program_code *prog;
3271   struct rar_filter *filter, **nextfilter;
3272 
3273   uint32_t numprogs, num, blocklength, globaldatalen;
3274   uint8_t *globaldata;
3275   size_t blockstartpos;
3276   uint32_t registers[8] = { 0 };
3277   uint32_t i;
3278 
3279   br.bytes = bytes;
3280   br.length = length;
3281 
3282   numprogs = 0;
3283   for (prog = filters->progs; prog; prog = prog->next)
3284     numprogs++;
3285 
3286   if ((flags & 0x80))
3287   {
3288     num = membr_next_rarvm_number(&br);
3289     if (num == 0)
3290     {
3291       delete_filter(filters->stack);
3292       filters->stack = NULL;
3293       delete_program_code(filters->progs);
3294       filters->progs = NULL;
3295     }
3296     else
3297       num--;
3298     if (num > numprogs) {
3299       return 0;
3300     }
3301     filters->lastfilternum = num;
3302   }
3303   else
3304     num = filters->lastfilternum;
3305 
3306   prog = filters->progs;
3307   for (i = 0; i < num; i++)
3308     prog = prog->next;
3309   if (prog)
3310     prog->usagecount++;
3311 
3312   blockstartpos = membr_next_rarvm_number(&br) + (size_t)lzss_position(&rar->lzss);
3313   if ((flags & 0x40))
3314     blockstartpos += 258;
3315   if ((flags & 0x20))
3316     blocklength = membr_next_rarvm_number(&br);
3317   else
3318     blocklength = prog ? prog->oldfilterlength : 0;
3319 
3320   if (blocklength > rar->dictionary_size)
3321     return 0;
3322 
3323   registers[3] = PROGRAM_SYSTEM_GLOBAL_ADDRESS;
3324   registers[4] = blocklength;
3325   registers[5] = prog ? prog->usagecount : 0;
3326   registers[7] = VM_MEMORY_SIZE;
3327 
3328   if ((flags & 0x10))
3329   {
3330     uint8_t mask = (uint8_t)membr_bits(&br, 7);
3331     for (i = 0; i < 7; i++)
3332       if ((mask & (1 << i)))
3333         registers[i] = membr_next_rarvm_number(&br);
3334   }
3335 
3336   if (!prog)
3337   {
3338     uint32_t len = membr_next_rarvm_number(&br);
3339     uint8_t *bytecode;
3340     struct rar_program_code **next;
3341 
3342     if (len == 0 || len > 0x10000)
3343       return 0;
3344     bytecode = malloc(len);
3345     if (!bytecode)
3346       return 0;
3347     for (i = 0; i < len; i++)
3348       bytecode[i] = (uint8_t)membr_bits(&br, 8);
3349     prog = compile_program(bytecode, len);
3350     if (!prog) {
3351       free(bytecode);
3352       return 0;
3353     }
3354     free(bytecode);
3355     next = &filters->progs;
3356     while (*next)
3357       next = &(*next)->next;
3358     *next = prog;
3359   }
3360   prog->oldfilterlength = blocklength;
3361 
3362   globaldata = NULL;
3363   globaldatalen = 0;
3364   if ((flags & 0x08))
3365   {
3366     globaldatalen = membr_next_rarvm_number(&br);
3367     if (globaldatalen > PROGRAM_USER_GLOBAL_SIZE)
3368       return 0;
3369     globaldata = malloc(globaldatalen + PROGRAM_SYSTEM_GLOBAL_SIZE);
3370     if (!globaldata)
3371       return 0;
3372     for (i = 0; i < globaldatalen; i++)
3373       globaldata[i + PROGRAM_SYSTEM_GLOBAL_SIZE] = (uint8_t)membr_bits(&br, 8);
3374   }
3375 
3376   if (br.at_eof)
3377   {
3378       free(globaldata);
3379       return 0;
3380   }
3381 
3382   filter = create_filter(prog, globaldata, globaldatalen, registers, blockstartpos, blocklength);
3383   free(globaldata);
3384   if (!filter)
3385     return 0;
3386 
3387   for (i = 0; i < 7; i++)
3388     archive_le32enc(&filter->globaldata[i * 4], registers[i]);
3389   archive_le32enc(&filter->globaldata[0x1C], blocklength);
3390   archive_le32enc(&filter->globaldata[0x20], 0);
3391   archive_le32enc(&filter->globaldata[0x2C], prog->usagecount);
3392 
3393   nextfilter = &filters->stack;
3394   while (*nextfilter)
3395     nextfilter = &(*nextfilter)->next;
3396   *nextfilter = filter;
3397 
3398   if (!filters->stack->next)
3399     filters->filterstart = blockstartpos;
3400 
3401   return 1;
3402 }
3403 
3404 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)3405 create_filter(struct rar_program_code *prog, const uint8_t *globaldata, uint32_t globaldatalen, uint32_t registers[8], size_t startpos, uint32_t length)
3406 {
3407   struct rar_filter *filter;
3408 
3409   filter = calloc(1, sizeof(*filter));
3410   if (!filter)
3411     return NULL;
3412   filter->prog = prog;
3413   filter->globaldatalen = globaldatalen > PROGRAM_SYSTEM_GLOBAL_SIZE ? globaldatalen : PROGRAM_SYSTEM_GLOBAL_SIZE;
3414   filter->globaldata = calloc(1, filter->globaldatalen);
3415   if (!filter->globaldata)
3416   {
3417     free(filter);
3418     return NULL;
3419   }
3420   if (globaldata)
3421     memcpy(filter->globaldata, globaldata, globaldatalen);
3422   if (registers)
3423     memcpy(filter->initialregisters, registers, sizeof(filter->initialregisters));
3424   filter->blockstartpos = startpos;
3425   filter->blocklength = length;
3426 
3427   return filter;
3428 }
3429 
3430 static int
run_filters(struct archive_read * a)3431 run_filters(struct archive_read *a)
3432 {
3433   struct rar *rar = (struct rar *)(a->format->data);
3434   struct rar_filters *filters = &rar->filters;
3435   struct rar_filter *filter = filters->stack;
3436   struct rar_filter *f;
3437   size_t start, end;
3438   int64_t tend;
3439   uint32_t lastfilteraddress;
3440   uint32_t lastfilterlength;
3441   int ret;
3442 
3443   if (filters == NULL || filter == NULL)
3444     return (0);
3445 
3446   start = (size_t)filters->filterstart;
3447   end = start + filter->blocklength;
3448 
3449   filters->filterstart = INT64_MAX;
3450   tend = (int64_t)end;
3451   ret = expand(a, &tend);
3452   if (ret != ARCHIVE_OK)
3453     return 0;
3454 
3455   /* Check if filter stack was modified in expand() */
3456   ret = ARCHIVE_FATAL;
3457   f = filters->stack;
3458   while (f)
3459   {
3460     if (f == filter)
3461     {
3462       ret = ARCHIVE_OK;
3463       break;
3464     }
3465     f = f->next;
3466   }
3467   if (ret != ARCHIVE_OK)
3468     return 0;
3469 
3470   if (tend < 0)
3471     return 0;
3472   end = (size_t)tend;
3473   if (end != start + filter->blocklength)
3474     return 0;
3475 
3476   if (!filters->vm)
3477   {
3478     filters->vm = calloc(1, sizeof(*filters->vm));
3479     if (!filters->vm)
3480       return 0;
3481   }
3482 
3483   if (filter->blocklength > VM_MEMORY_SIZE)
3484   {
3485     archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "Bad RAR file data");
3486     return 0;
3487   }
3488 
3489   ret = copy_from_lzss_window(a, filters->vm->memory, start, filter->blocklength);
3490   if (ret != ARCHIVE_OK)
3491     return 0;
3492   if (!execute_filter(a, filter, filters->vm, (size_t)rar->offset))
3493     return 0;
3494 
3495   lastfilteraddress = filter->filteredblockaddress;
3496   lastfilterlength = filter->filteredblocklength;
3497   filters->stack = filter->next;
3498   filter->next = NULL;
3499   delete_filter(filter);
3500 
3501   while ((filter = filters->stack) != NULL && (int64_t)filter->blockstartpos == filters->filterstart && filter->blocklength == lastfilterlength)
3502   {
3503     memmove(&filters->vm->memory[0], &filters->vm->memory[lastfilteraddress], lastfilterlength);
3504     if (!execute_filter(a, filter, filters->vm, (size_t)rar->offset))
3505       return 0;
3506 
3507     lastfilteraddress = filter->filteredblockaddress;
3508     lastfilterlength = filter->filteredblocklength;
3509     filters->stack = filter->next;
3510     filter->next = NULL;
3511     delete_filter(filter);
3512   }
3513 
3514   if (filters->stack)
3515   {
3516     if (filters->stack->blockstartpos < end)
3517       return 0;
3518     filters->filterstart = filters->stack->blockstartpos;
3519   }
3520 
3521   filters->lastend = end;
3522   filters->bytes = &filters->vm->memory[lastfilteraddress];
3523   filters->bytes_ready = lastfilterlength;
3524 
3525   return 1;
3526 }
3527 
3528 static struct rar_program_code *
compile_program(const uint8_t * bytes,size_t length)3529 compile_program(const uint8_t *bytes, size_t length)
3530 {
3531   struct memory_bit_reader br = { 0 };
3532   struct rar_program_code *prog;
3533   // uint32_t instrcount = 0;
3534   uint8_t xor;
3535   size_t i;
3536 
3537   xor = 0;
3538   for (i = 1; i < length; i++)
3539     xor ^= bytes[i];
3540   if (!length || xor != bytes[0])
3541     return NULL;
3542 
3543   br.bytes = bytes;
3544   br.length = length;
3545   br.offset = 1;
3546 
3547   prog = calloc(1, sizeof(*prog));
3548   if (!prog)
3549     return NULL;
3550   prog->fingerprint = crc32(0, bytes, (unsigned int)length) | ((uint64_t)length << 32);
3551 
3552   if (membr_bits(&br, 1))
3553   {
3554     prog->staticdatalen = membr_next_rarvm_number(&br) + 1;
3555     prog->staticdata = malloc(prog->staticdatalen);
3556     if (!prog->staticdata)
3557     {
3558       delete_program_code(prog);
3559       return NULL;
3560     }
3561     for (i = 0; i < prog->staticdatalen; i++)
3562       prog->staticdata[i] = (uint8_t)membr_bits(&br, 8);
3563   }
3564 
3565   return prog;
3566 }
3567 
3568 static void
delete_filter(struct rar_filter * filter)3569 delete_filter(struct rar_filter *filter)
3570 {
3571   while (filter)
3572   {
3573     struct rar_filter *next = filter->next;
3574     free(filter->globaldata);
3575     free(filter);
3576     filter = next;
3577   }
3578 }
3579 
3580 static void
clear_filters(struct rar_filters * filters)3581 clear_filters(struct rar_filters *filters)
3582 {
3583   delete_filter(filters->stack);
3584   delete_program_code(filters->progs);
3585   free(filters->vm);
3586 }
3587 
3588 static void
delete_program_code(struct rar_program_code * prog)3589 delete_program_code(struct rar_program_code *prog)
3590 {
3591   while (prog)
3592   {
3593     struct rar_program_code *next = prog->next;
3594     free(prog->staticdata);
3595     free(prog->globalbackup);
3596     free(prog);
3597     prog = next;
3598   }
3599 }
3600 
3601 static uint32_t
membr_next_rarvm_number(struct memory_bit_reader * br)3602 membr_next_rarvm_number(struct memory_bit_reader *br)
3603 {
3604   uint32_t val;
3605   switch (membr_bits(br, 2))
3606   {
3607     case 0:
3608       return membr_bits(br, 4);
3609     case 1:
3610       val = membr_bits(br, 8);
3611       if (val >= 16)
3612         return val;
3613       return 0xFFFFFF00 | (val << 4) | membr_bits(br, 4);
3614     case 2:
3615       return membr_bits(br, 16);
3616     default:
3617       return membr_bits(br, 32);
3618   }
3619 }
3620 
3621 static inline uint32_t
membr_bits(struct memory_bit_reader * br,int bits)3622 membr_bits(struct memory_bit_reader *br, int bits)
3623 {
3624   if (bits > br->available && (br->at_eof || !membr_fill(br, bits)))
3625     return 0;
3626   return (uint32_t)((br->bits >> (br->available -= bits)) & (((uint64_t)1 << bits) - 1));
3627 }
3628 
3629 static int
membr_fill(struct memory_bit_reader * br,int bits)3630 membr_fill(struct memory_bit_reader *br, int bits)
3631 {
3632   while (br->available < bits && br->offset < br->length)
3633   {
3634     br->bits = (br->bits << 8) | br->bytes[br->offset++];
3635     br->available += 8;
3636   }
3637   if (bits > br->available)
3638   {
3639     br->at_eof = 1;
3640     return 0;
3641   }
3642   return 1;
3643 }
3644 
3645 static int
read_filter(struct archive_read * a,int64_t * end)3646 read_filter(struct archive_read *a, int64_t *end)
3647 {
3648   struct rar *rar = (struct rar *)(a->format->data);
3649   uint8_t flags, val, *code;
3650   uint16_t length, i;
3651 
3652   if (!rar_decode_byte(a, &flags))
3653     return 0;
3654   length = (flags & 0x07) + 1;
3655   if (length == 7)
3656   {
3657     if (!rar_decode_byte(a, &val))
3658       return 0;
3659     length = val + 7;
3660   }
3661   else if (length == 8)
3662   {
3663     if (!rar_decode_byte(a, &val))
3664       return 0;
3665     length = val << 8;
3666     if (!rar_decode_byte(a, &val))
3667       return 0;
3668     length |= val;
3669   }
3670 
3671   code = malloc(length);
3672   if (!code)
3673     return 0;
3674   for (i = 0; i < length; i++)
3675   {
3676     if (!rar_decode_byte(a, &code[i]))
3677     {
3678       free(code);
3679       return 0;
3680     }
3681   }
3682   if (!parse_filter(a, code, length, flags))
3683   {
3684     free(code);
3685     return 0;
3686   }
3687   free(code);
3688 
3689   if (rar->filters.filterstart < *end)
3690     *end = rar->filters.filterstart;
3691 
3692   return 1;
3693 }
3694 
3695 static int
execute_filter_delta(struct rar_filter * filter,struct rar_virtual_machine * vm)3696 execute_filter_delta(struct rar_filter *filter, struct rar_virtual_machine *vm)
3697 {
3698   uint32_t length = filter->initialregisters[4];
3699   uint32_t numchannels = filter->initialregisters[0];
3700   uint8_t *src, *dst;
3701   uint32_t i, idx;
3702 
3703   if (length > PROGRAM_WORK_SIZE / 2)
3704     return 0;
3705 
3706   src = &vm->memory[0];
3707   dst = &vm->memory[length];
3708   for (i = 0; i < numchannels; i++)
3709   {
3710     uint8_t lastbyte = 0;
3711     for (idx = i; idx < length; idx += numchannels)
3712     {
3713       /*
3714        * The src block should not overlap with the dst block.
3715        * If so it would be better to consider this archive is broken.
3716        */
3717       if (src >= dst)
3718         return 0;
3719       lastbyte = dst[idx] = lastbyte - *src++;
3720     }
3721   }
3722 
3723   filter->filteredblockaddress = length;
3724   filter->filteredblocklength = length;
3725 
3726   return 1;
3727 }
3728 
3729 static int
execute_filter_e8(struct rar_filter * filter,struct rar_virtual_machine * vm,size_t pos,int e9also)3730 execute_filter_e8(struct rar_filter *filter, struct rar_virtual_machine *vm, size_t pos, int e9also)
3731 {
3732   uint32_t length = filter->initialregisters[4];
3733   uint32_t filesize = 0x1000000;
3734   uint32_t i;
3735 
3736   if (length > PROGRAM_WORK_SIZE || length <= 4)
3737     return 0;
3738 
3739   for (i = 0; i <= length - 5; i++)
3740   {
3741     if (vm->memory[i] == 0xE8 || (e9also && vm->memory[i] == 0xE9))
3742     {
3743       uint32_t currpos = (uint32_t)pos + i + 1;
3744       int32_t address = (int32_t)vm_read_32(vm, i + 1);
3745       if (address < 0 && currpos >= (~(uint32_t)address + 1))
3746         vm_write_32(vm, i + 1, address + filesize);
3747       else if (address >= 0 && (uint32_t)address < filesize)
3748         vm_write_32(vm, i + 1, address - currpos);
3749       i += 4;
3750     }
3751   }
3752 
3753   filter->filteredblockaddress = 0;
3754   filter->filteredblocklength = length;
3755 
3756   return 1;
3757 }
3758 
3759 static int
execute_filter_rgb(struct rar_filter * filter,struct rar_virtual_machine * vm)3760 execute_filter_rgb(struct rar_filter *filter, struct rar_virtual_machine *vm)
3761 {
3762   uint32_t stride = filter->initialregisters[0];
3763   uint32_t byteoffset = filter->initialregisters[1];
3764   uint32_t blocklength = filter->initialregisters[4];
3765   uint8_t *src, *dst;
3766   uint32_t i, j;
3767 
3768   if (blocklength > PROGRAM_WORK_SIZE / 2 || stride > blocklength || blocklength < 3 || byteoffset > 2)
3769     return 0;
3770 
3771   src = &vm->memory[0];
3772   dst = &vm->memory[blocklength];
3773   for (i = 0; i < 3; i++) {
3774     uint8_t byte = 0;
3775     uint8_t *prev = dst + i - stride;
3776     for (j = i; j < blocklength; j += 3)
3777     {
3778       /*
3779        * The src block should not overlap with the dst block.
3780        * If so it would be better to consider this archive is broken.
3781        */
3782       if (src >= dst)
3783         return 0;
3784 
3785       if (prev >= dst)
3786       {
3787         uint32_t delta1 = abs(prev[3] - prev[0]);
3788         uint32_t delta2 = abs(byte - prev[0]);
3789         uint32_t delta3 = abs(prev[3] - prev[0] + byte - prev[0]);
3790         if (delta1 > delta2 || delta1 > delta3)
3791           byte = delta2 <= delta3 ? prev[3] : prev[0];
3792       }
3793       byte -= *src++;
3794       dst[j] = byte;
3795       prev += 3;
3796     }
3797   }
3798   for (i = byteoffset; i < blocklength - 2; i += 3)
3799   {
3800     dst[i] += dst[i + 1];
3801     dst[i + 2] += dst[i + 1];
3802   }
3803 
3804   filter->filteredblockaddress = blocklength;
3805   filter->filteredblocklength = blocklength;
3806 
3807   return 1;
3808 }
3809 
3810 static int
execute_filter_audio(struct rar_filter * filter,struct rar_virtual_machine * vm)3811 execute_filter_audio(struct rar_filter *filter, struct rar_virtual_machine *vm)
3812 {
3813   uint32_t length = filter->initialregisters[4];
3814   uint32_t numchannels = filter->initialregisters[0];
3815   uint8_t *src, *dst;
3816   uint32_t i, j;
3817 
3818   if (length > PROGRAM_WORK_SIZE / 2)
3819     return 0;
3820 
3821   src = &vm->memory[0];
3822   dst = &vm->memory[length];
3823   for (i = 0; i < numchannels; i++)
3824   {
3825     struct audio_state state;
3826     memset(&state, 0, sizeof(state));
3827     for (j = i; j < length; j += numchannels)
3828     {
3829       /*
3830        * The src block should not overlap with the dst block.
3831        * If so it would be better to consider this archive is broken.
3832        */
3833       if (src >= dst)
3834         return 0;
3835 
3836       int8_t delta = (int8_t)*src++;
3837       uint8_t predbyte, byte;
3838       int prederror;
3839       state.delta[2] = state.delta[1];
3840       state.delta[1] = state.lastdelta - state.delta[0];
3841       state.delta[0] = state.lastdelta;
3842       predbyte = ((8 * state.lastbyte + state.weight[0] * state.delta[0] + state.weight[1] * state.delta[1] + state.weight[2] * state.delta[2]) >> 3) & 0xFF;
3843       byte = (predbyte - delta) & 0xFF;
3844       prederror = delta << 3;
3845       state.error[0] += abs(prederror);
3846       state.error[1] += abs(prederror - state.delta[0]); state.error[2] += abs(prederror + state.delta[0]);
3847       state.error[3] += abs(prederror - state.delta[1]); state.error[4] += abs(prederror + state.delta[1]);
3848       state.error[5] += abs(prederror - state.delta[2]); state.error[6] += abs(prederror + state.delta[2]);
3849       state.lastdelta = (int8_t)(byte - state.lastbyte);
3850       dst[j] = state.lastbyte = byte;
3851       if (!(state.count++ & 0x1F))
3852       {
3853         uint8_t k, idx = 0;
3854         for (k = 1; k < 7; k++)
3855         {
3856           if (state.error[k] < state.error[idx])
3857             idx = k;
3858         }
3859         memset(state.error, 0, sizeof(state.error));
3860         switch (idx)
3861         {
3862           case 1: if (state.weight[0] >= -16) state.weight[0]--; break;
3863           case 2: if (state.weight[0] < 16) state.weight[0]++; break;
3864           case 3: if (state.weight[1] >= -16) state.weight[1]--; break;
3865           case 4: if (state.weight[1] < 16) state.weight[1]++; break;
3866           case 5: if (state.weight[2] >= -16) state.weight[2]--; break;
3867           case 6: if (state.weight[2] < 16) state.weight[2]++; break;
3868         }
3869       }
3870     }
3871   }
3872 
3873   filter->filteredblockaddress = length;
3874   filter->filteredblocklength = length;
3875 
3876   return 1;
3877 }
3878 
3879 
3880 static int
execute_filter(struct archive_read * a,struct rar_filter * filter,struct rar_virtual_machine * vm,size_t pos)3881 execute_filter(struct archive_read *a, struct rar_filter *filter, struct rar_virtual_machine *vm, size_t pos)
3882 {
3883   if (filter->prog->fingerprint == 0x1D0E06077D)
3884     return execute_filter_delta(filter, vm);
3885   if (filter->prog->fingerprint == 0x35AD576887)
3886     return execute_filter_e8(filter, vm, pos, 0);
3887   if (filter->prog->fingerprint == 0x393CD7E57E)
3888     return execute_filter_e8(filter, vm, pos, 1);
3889   if (filter->prog->fingerprint == 0x951C2C5DC8)
3890     return execute_filter_rgb(filter, vm);
3891   if (filter->prog->fingerprint == 0xD8BC85E701)
3892     return execute_filter_audio(filter, vm);
3893 
3894   archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT, "No support for RAR VM program filter");
3895   return 0;
3896 }
3897 
3898 static int
rar_decode_byte(struct archive_read * a,uint8_t * byte)3899 rar_decode_byte(struct archive_read *a, uint8_t *byte)
3900 {
3901   struct rar *rar = (struct rar *)(a->format->data);
3902   struct rar_br *br = &(rar->br);
3903   if (!rar_br_read_ahead(a, br, 8))
3904     return 0;
3905   *byte = (uint8_t)rar_br_bits(br, 8);
3906   rar_br_consume(br, 8);
3907   return 1;
3908 }
3909 
3910 static inline void
vm_write_32(struct rar_virtual_machine * vm,size_t offset,uint32_t u32)3911 vm_write_32(struct rar_virtual_machine* vm, size_t offset, uint32_t u32)
3912 {
3913   archive_le32enc(vm->memory + offset, u32);
3914 }
3915 
3916 static inline uint32_t
vm_read_32(struct rar_virtual_machine * vm,size_t offset)3917 vm_read_32(struct rar_virtual_machine* vm, size_t offset)
3918 {
3919   return archive_le32dec(vm->memory + offset);
3920 }
3921