~ubuntu-branches/ubuntu/trusty/cmake3/trusty-updates

« back to all changes in this revision

Viewing changes to Utilities/cmlibarchive/libarchive/archive_read_support_format_rar.c

  • Committer: Package Import Robot
  • Author(s): Matthias Klose
  • Date: 2017-02-23 17:55:24 UTC
  • Revision ID: package-import@ubuntu.com-20170223175524-5nh7s4pu97fsa0t7
Tags: upstream-3.5.1
ImportĀ upstreamĀ versionĀ 3.5.1

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
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 <cm_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
/*
 
139
 * Considering L1,L2 cache miss and a calling of write system-call,
 
140
 * the best size of the output buffer(uncompressed buffer) is 128K.
 
141
 * If the structure of extracting process is changed, this value
 
142
 * might be researched again.
 
143
 */
 
144
#define UNP_BUFFER_SIZE   (128 * 1024)
 
145
 
 
146
/* Define this here for non-Windows platforms */
 
147
#if !((defined(__WIN32__) || defined(_WIN32) || defined(__WIN32)) && !defined(__CYGWIN__))
 
148
#define FILE_ATTRIBUTE_DIRECTORY 0x10
 
149
#endif
 
150
 
 
151
/* Fields common to all headers */
 
152
struct rar_header
 
153
{
 
154
  char crc[2];
 
155
  char type;
 
156
  char flags[2];
 
157
  char size[2];
 
158
};
 
159
 
 
160
/* Fields common to all file headers */
 
161
struct rar_file_header
 
162
{
 
163
  char pack_size[4];
 
164
  char unp_size[4];
 
165
  char host_os;
 
166
  char file_crc[4];
 
167
  char file_time[4];
 
168
  char unp_ver;
 
169
  char method;
 
170
  char name_size[2];
 
171
  char file_attr[4];
 
172
};
 
173
 
 
174
struct huffman_tree_node
 
175
{
 
176
  int branches[2];
 
177
};
 
178
 
 
179
struct huffman_table_entry
 
180
{
 
181
  unsigned int length;
 
182
  int value;
 
183
};
 
184
 
 
185
struct huffman_code
 
186
{
 
187
  struct huffman_tree_node *tree;
 
188
  int numentries;
 
189
  int numallocatedentries;
 
190
  int minlength;
 
191
  int maxlength;
 
192
  int tablesize;
 
193
  struct huffman_table_entry *table;
 
194
};
 
195
 
 
196
struct lzss
 
197
{
 
198
  unsigned char *window;
 
199
  int mask;
 
200
  int64_t position;
 
201
};
 
202
 
 
203
struct data_block_offsets
 
204
{
 
205
  int64_t header_size;
 
206
  int64_t start_offset;
 
207
  int64_t end_offset;
 
208
};
 
209
 
 
210
struct rar
 
211
{
 
212
  /* Entries from main RAR header */
 
213
  unsigned main_flags;
 
214
  unsigned long file_crc;
 
215
  char reserved1[2];
 
216
  char reserved2[4];
 
217
  char encryptver;
 
218
 
 
219
  /* File header entries */
 
220
  char compression_method;
 
221
  unsigned file_flags;
 
222
  int64_t packed_size;
 
223
  int64_t unp_size;
 
224
  time_t mtime;
 
225
  long mnsec;
 
226
  mode_t mode;
 
227
  char *filename;
 
228
  char *filename_save;
 
229
  size_t filename_save_size;
 
230
  size_t filename_allocated;
 
231
 
 
232
  /* File header optional entries */
 
233
  char salt[8];
 
234
  time_t atime;
 
235
  long ansec;
 
236
  time_t ctime;
 
237
  long cnsec;
 
238
  time_t arctime;
 
239
  long arcnsec;
 
240
 
 
241
  /* Fields to help with tracking decompression of files. */
 
242
  int64_t bytes_unconsumed;
 
243
  int64_t bytes_remaining;
 
244
  int64_t bytes_uncopied;
 
245
  int64_t offset;
 
246
  int64_t offset_outgoing;
 
247
  int64_t offset_seek;
 
248
  char valid;
 
249
  unsigned int unp_offset;
 
250
  unsigned int unp_buffer_size;
 
251
  unsigned char *unp_buffer;
 
252
  unsigned int dictionary_size;
 
253
  char start_new_block;
 
254
  char entry_eof;
 
255
  unsigned long crc_calculated;
 
256
  int found_first_header;
 
257
  char has_endarc_header;
 
258
  struct data_block_offsets *dbo;
 
259
  unsigned int cursor;
 
260
  unsigned int nodes;
 
261
 
 
262
  /* LZSS members */
 
263
  struct huffman_code maincode;
 
264
  struct huffman_code offsetcode;
 
265
  struct huffman_code lowoffsetcode;
 
266
  struct huffman_code lengthcode;
 
267
  unsigned char lengthtable[HUFFMAN_TABLE_SIZE];
 
268
  struct lzss lzss;
 
269
  char output_last_match;
 
270
  unsigned int lastlength;
 
271
  unsigned int lastoffset;
 
272
  unsigned int oldoffset[4];
 
273
  unsigned int lastlowoffset;
 
274
  unsigned int numlowoffsetrepeats;
 
275
  int64_t filterstart;
 
276
  char start_new_table;
 
277
 
 
278
  /* PPMd Variant H members */
 
279
  char ppmd_valid;
 
280
  char ppmd_eod;
 
281
  char is_ppmd_block;
 
282
  int ppmd_escape;
 
283
  CPpmd7 ppmd7_context;
 
284
  CPpmd7z_RangeDec range_dec;
 
285
  IByteIn bytein;
 
286
 
 
287
  /*
 
288
   * String conversion object.
 
289
   */
 
290
  int init_default_conversion;
 
291
  struct archive_string_conv *sconv_default;
 
292
  struct archive_string_conv *opt_sconv;
 
293
  struct archive_string_conv *sconv_utf8;
 
294
  struct archive_string_conv *sconv_utf16be;
 
295
 
 
296
  /*
 
297
   * Bit stream reader.
 
298
   */
 
299
  struct rar_br {
 
300
#define CACHE_TYPE      uint64_t
 
301
#define CACHE_BITS      (8 * sizeof(CACHE_TYPE))
 
302
    /* Cache buffer. */
 
303
    CACHE_TYPE           cache_buffer;
 
304
    /* Indicates how many bits avail in cache_buffer. */
 
305
    int                  cache_avail;
 
306
    ssize_t              avail_in;
 
307
    const unsigned char *next_in;
 
308
  } br;
 
309
 
 
310
  /*
 
311
   * Custom field to denote that this archive contains encrypted entries
 
312
   */
 
313
  int has_encrypted_entries;
 
314
};
 
315
 
 
316
static int archive_read_support_format_rar_capabilities(struct archive_read *);
 
317
static int archive_read_format_rar_has_encrypted_entries(struct archive_read *);
 
318
static int archive_read_format_rar_bid(struct archive_read *, int);
 
319
static int archive_read_format_rar_options(struct archive_read *,
 
320
    const char *, const char *);
 
321
static int archive_read_format_rar_read_header(struct archive_read *,
 
322
    struct archive_entry *);
 
323
static int archive_read_format_rar_read_data(struct archive_read *,
 
324
    const void **, size_t *, int64_t *);
 
325
static int archive_read_format_rar_read_data_skip(struct archive_read *a);
 
326
static int64_t archive_read_format_rar_seek_data(struct archive_read *, int64_t,
 
327
    int);
 
328
static int archive_read_format_rar_cleanup(struct archive_read *);
 
329
 
 
330
/* Support functions */
 
331
static int read_header(struct archive_read *, struct archive_entry *, char);
 
332
static time_t get_time(int);
 
333
static int read_exttime(const char *, struct rar *, const char *);
 
334
static int read_symlink_stored(struct archive_read *, struct archive_entry *,
 
335
                               struct archive_string_conv *);
 
336
static int read_data_stored(struct archive_read *, const void **, size_t *,
 
337
                            int64_t *);
 
338
static int read_data_compressed(struct archive_read *, const void **, size_t *,
 
339
                          int64_t *);
 
340
static int rar_br_preparation(struct archive_read *, struct rar_br *);
 
341
static int parse_codes(struct archive_read *);
 
342
static void free_codes(struct archive_read *);
 
343
static int read_next_symbol(struct archive_read *, struct huffman_code *);
 
344
static int create_code(struct archive_read *, struct huffman_code *,
 
345
                        unsigned char *, int, char);
 
346
static int add_value(struct archive_read *, struct huffman_code *, int, int,
 
347
                     int);
 
348
static int new_node(struct huffman_code *);
 
349
static int make_table(struct archive_read *, struct huffman_code *);
 
350
static int make_table_recurse(struct archive_read *, struct huffman_code *, int,
 
351
                              struct huffman_table_entry *, int, int);
 
352
static int64_t expand(struct archive_read *, int64_t);
 
353
static int copy_from_lzss_window(struct archive_read *, const void **,
 
354
                                   int64_t, int);
 
355
static const void *rar_read_ahead(struct archive_read *, size_t, ssize_t *);
 
356
 
 
357
/*
 
358
 * Bit stream reader.
 
359
 */
 
360
/* Check that the cache buffer has enough bits. */
 
361
#define rar_br_has(br, n) ((br)->cache_avail >= n)
 
362
/* Get compressed data by bit. */
 
363
#define rar_br_bits(br, n)        \
 
364
  (((uint32_t)((br)->cache_buffer >>    \
 
365
    ((br)->cache_avail - (n)))) & cache_masks[n])
 
366
#define rar_br_bits_forced(br, n)     \
 
367
  (((uint32_t)((br)->cache_buffer <<    \
 
368
    ((n) - (br)->cache_avail))) & cache_masks[n])
 
369
/* Read ahead to make sure the cache buffer has enough compressed data we
 
370
 * will use.
 
371
 *  True  : completed, there is enough data in the cache buffer.
 
372
 *  False : there is no data in the stream. */
 
373
#define rar_br_read_ahead(a, br, n) \
 
374
  ((rar_br_has(br, (n)) || rar_br_fillup(a, br)) || rar_br_has(br, (n)))
 
375
/* Notify how many bits we consumed. */
 
376
#define rar_br_consume(br, n) ((br)->cache_avail -= (n))
 
377
#define rar_br_consume_unalined_bits(br) ((br)->cache_avail &= ~7)
 
378
 
 
379
static const uint32_t cache_masks[] = {
 
380
  0x00000000, 0x00000001, 0x00000003, 0x00000007,
 
381
  0x0000000F, 0x0000001F, 0x0000003F, 0x0000007F,
 
382
  0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF,
 
383
  0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF,
 
384
  0x0000FFFF, 0x0001FFFF, 0x0003FFFF, 0x0007FFFF,
 
385
  0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,
 
386
  0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF,
 
387
  0x0FFFFFFF, 0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF,
 
388
  0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF
 
389
};
 
390
 
 
391
/*
 
392
 * Shift away used bits in the cache data and fill it up with following bits.
 
393
 * Call this when cache buffer does not have enough bits you need.
 
394
 *
 
395
 * Returns 1 if the cache buffer is full.
 
396
 * Returns 0 if the cache buffer is not full; input buffer is empty.
 
397
 */
 
398
static int
 
399
rar_br_fillup(struct archive_read *a, struct rar_br *br)
 
400
{
 
401
  struct rar *rar = (struct rar *)(a->format->data);
 
402
  int n = CACHE_BITS - br->cache_avail;
 
403
 
 
404
  for (;;) {
 
405
    switch (n >> 3) {
 
406
    case 8:
 
407
      if (br->avail_in >= 8) {
 
408
        br->cache_buffer =
 
409
            ((uint64_t)br->next_in[0]) << 56 |
 
410
            ((uint64_t)br->next_in[1]) << 48 |
 
411
            ((uint64_t)br->next_in[2]) << 40 |
 
412
            ((uint64_t)br->next_in[3]) << 32 |
 
413
            ((uint32_t)br->next_in[4]) << 24 |
 
414
            ((uint32_t)br->next_in[5]) << 16 |
 
415
            ((uint32_t)br->next_in[6]) << 8 |
 
416
             (uint32_t)br->next_in[7];
 
417
        br->next_in += 8;
 
418
        br->avail_in -= 8;
 
419
        br->cache_avail += 8 * 8;
 
420
        rar->bytes_unconsumed += 8;
 
421
        rar->bytes_remaining -= 8;
 
422
        return (1);
 
423
      }
 
424
      break;
 
425
    case 7:
 
426
      if (br->avail_in >= 7) {
 
427
        br->cache_buffer =
 
428
           (br->cache_buffer << 56) |
 
429
            ((uint64_t)br->next_in[0]) << 48 |
 
430
            ((uint64_t)br->next_in[1]) << 40 |
 
431
            ((uint64_t)br->next_in[2]) << 32 |
 
432
            ((uint32_t)br->next_in[3]) << 24 |
 
433
            ((uint32_t)br->next_in[4]) << 16 |
 
434
            ((uint32_t)br->next_in[5]) << 8 |
 
435
             (uint32_t)br->next_in[6];
 
436
        br->next_in += 7;
 
437
        br->avail_in -= 7;
 
438
        br->cache_avail += 7 * 8;
 
439
        rar->bytes_unconsumed += 7;
 
440
        rar->bytes_remaining -= 7;
 
441
        return (1);
 
442
      }
 
443
      break;
 
444
    case 6:
 
445
      if (br->avail_in >= 6) {
 
446
        br->cache_buffer =
 
447
           (br->cache_buffer << 48) |
 
448
            ((uint64_t)br->next_in[0]) << 40 |
 
449
            ((uint64_t)br->next_in[1]) << 32 |
 
450
            ((uint32_t)br->next_in[2]) << 24 |
 
451
            ((uint32_t)br->next_in[3]) << 16 |
 
452
            ((uint32_t)br->next_in[4]) << 8 |
 
453
             (uint32_t)br->next_in[5];
 
454
        br->next_in += 6;
 
455
        br->avail_in -= 6;
 
456
        br->cache_avail += 6 * 8;
 
457
        rar->bytes_unconsumed += 6;
 
458
        rar->bytes_remaining -= 6;
 
459
        return (1);
 
460
      }
 
461
      break;
 
462
    case 0:
 
463
      /* We have enough compressed data in
 
464
       * the cache buffer.*/
 
465
      return (1);
 
466
    default:
 
467
      break;
 
468
    }
 
469
    if (br->avail_in <= 0) {
 
470
 
 
471
      if (rar->bytes_unconsumed > 0) {
 
472
        /* Consume as much as the decompressor
 
473
         * actually used. */
 
474
        __archive_read_consume(a, rar->bytes_unconsumed);
 
475
        rar->bytes_unconsumed = 0;
 
476
      }
 
477
      br->next_in = rar_read_ahead(a, 1, &(br->avail_in));
 
478
      if (br->next_in == NULL)
 
479
        return (0);
 
480
      if (br->avail_in == 0)
 
481
        return (0);
 
482
    }
 
483
    br->cache_buffer =
 
484
       (br->cache_buffer << 8) | *br->next_in++;
 
485
    br->avail_in--;
 
486
    br->cache_avail += 8;
 
487
    n -= 8;
 
488
    rar->bytes_unconsumed++;
 
489
    rar->bytes_remaining--;
 
490
  }
 
491
}
 
492
 
 
493
static int
 
494
rar_br_preparation(struct archive_read *a, struct rar_br *br)
 
495
{
 
496
  struct rar *rar = (struct rar *)(a->format->data);
 
497
 
 
498
  if (rar->bytes_remaining > 0) {
 
499
    br->next_in = rar_read_ahead(a, 1, &(br->avail_in));
 
500
    if (br->next_in == NULL) {
 
501
      archive_set_error(&a->archive,
 
502
          ARCHIVE_ERRNO_FILE_FORMAT,
 
503
          "Truncated RAR file data");
 
504
      return (ARCHIVE_FATAL);
 
505
    }
 
506
    if (br->cache_avail == 0)
 
507
      (void)rar_br_fillup(a, br);
 
508
  }
 
509
  return (ARCHIVE_OK);
 
510
}
 
511
 
 
512
/* Find last bit set */
 
513
static inline int
 
514
rar_fls(unsigned int word)
 
515
{
 
516
  word |= (word >>  1);
 
517
  word |= (word >>  2);
 
518
  word |= (word >>  4);
 
519
  word |= (word >>  8);
 
520
  word |= (word >> 16);
 
521
  return word - (word >> 1);
 
522
}
 
523
 
 
524
/* LZSS functions */
 
525
static inline int64_t
 
526
lzss_position(struct lzss *lzss)
 
527
{
 
528
  return lzss->position;
 
529
}
 
530
 
 
531
static inline int
 
532
lzss_mask(struct lzss *lzss)
 
533
{
 
534
  return lzss->mask;
 
535
}
 
536
 
 
537
static inline int
 
538
lzss_size(struct lzss *lzss)
 
539
{
 
540
  return lzss->mask + 1;
 
541
}
 
542
 
 
543
static inline int
 
544
lzss_offset_for_position(struct lzss *lzss, int64_t pos)
 
545
{
 
546
  return (int)(pos & lzss->mask);
 
547
}
 
548
 
 
549
static inline unsigned char *
 
550
lzss_pointer_for_position(struct lzss *lzss, int64_t pos)
 
551
{
 
552
  return &lzss->window[lzss_offset_for_position(lzss, pos)];
 
553
}
 
554
 
 
555
static inline int
 
556
lzss_current_offset(struct lzss *lzss)
 
557
{
 
558
  return lzss_offset_for_position(lzss, lzss->position);
 
559
}
 
560
 
 
561
static inline uint8_t *
 
562
lzss_current_pointer(struct lzss *lzss)
 
563
{
 
564
  return lzss_pointer_for_position(lzss, lzss->position);
 
565
}
 
566
 
 
567
static inline void
 
568
lzss_emit_literal(struct rar *rar, uint8_t literal)
 
569
{
 
570
  *lzss_current_pointer(&rar->lzss) = literal;
 
571
  rar->lzss.position++;
 
572
}
 
573
 
 
574
static inline void
 
575
lzss_emit_match(struct rar *rar, int offset, int length)
 
576
{
 
577
  int dstoffs = lzss_current_offset(&rar->lzss);
 
578
  int srcoffs = (dstoffs - offset) & lzss_mask(&rar->lzss);
 
579
  int l, li, remaining;
 
580
  unsigned char *d, *s;
 
581
 
 
582
  remaining = length;
 
583
  while (remaining > 0) {
 
584
    l = remaining;
 
585
    if (dstoffs > srcoffs) {
 
586
      if (l > lzss_size(&rar->lzss) - dstoffs)
 
587
        l = lzss_size(&rar->lzss) - dstoffs;
 
588
    } else {
 
589
      if (l > lzss_size(&rar->lzss) - srcoffs)
 
590
        l = lzss_size(&rar->lzss) - srcoffs;
 
591
    }
 
592
    d = &(rar->lzss.window[dstoffs]);
 
593
    s = &(rar->lzss.window[srcoffs]);
 
594
    if ((dstoffs + l < srcoffs) || (srcoffs + l < dstoffs))
 
595
      memcpy(d, s, l);
 
596
    else {
 
597
      for (li = 0; li < l; li++)
 
598
        d[li] = s[li];
 
599
    }
 
600
    remaining -= l;
 
601
    dstoffs = (dstoffs + l) & lzss_mask(&(rar->lzss));
 
602
    srcoffs = (srcoffs + l) & lzss_mask(&(rar->lzss));
 
603
  }
 
604
  rar->lzss.position += length;
 
605
}
 
606
 
 
607
static void *
 
608
ppmd_alloc(void *p, size_t size)
 
609
{
 
610
  (void)p;
 
611
  return malloc(size);
 
612
}
 
613
static void
 
614
ppmd_free(void *p, void *address)
 
615
{
 
616
  (void)p;
 
617
  free(address);
 
618
}
 
619
static ISzAlloc g_szalloc = { ppmd_alloc, ppmd_free };
 
620
 
 
621
static Byte
 
622
ppmd_read(void *p)
 
623
{
 
624
  struct archive_read *a = ((IByteIn*)p)->a;
 
625
  struct rar *rar = (struct rar *)(a->format->data);
 
626
  struct rar_br *br = &(rar->br);
 
627
  Byte b;
 
628
  if (!rar_br_read_ahead(a, br, 8))
 
629
  {
 
630
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
631
                      "Truncated RAR file data");
 
632
    rar->valid = 0;
 
633
    return 0;
 
634
  }
 
635
  b = rar_br_bits(br, 8);
 
636
  rar_br_consume(br, 8);
 
637
  return b;
 
638
}
 
639
 
 
640
int
 
641
archive_read_support_format_rar(struct archive *_a)
 
642
{
 
643
  struct archive_read *a = (struct archive_read *)_a;
 
644
  struct rar *rar;
 
645
  int r;
 
646
 
 
647
  archive_check_magic(_a, ARCHIVE_READ_MAGIC, ARCHIVE_STATE_NEW,
 
648
                      "archive_read_support_format_rar");
 
649
 
 
650
  rar = (struct rar *)malloc(sizeof(*rar));
 
651
  if (rar == NULL)
 
652
  {
 
653
    archive_set_error(&a->archive, ENOMEM, "Can't allocate rar data");
 
654
    return (ARCHIVE_FATAL);
 
655
  }
 
656
  memset(rar, 0, sizeof(*rar));
 
657
 
 
658
        /*
 
659
         * Until enough data has been read, we cannot tell about
 
660
         * any encrypted entries yet.
 
661
         */
 
662
        rar->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
 
663
 
 
664
  r = __archive_read_register_format(a,
 
665
                                     rar,
 
666
                                     "rar",
 
667
                                     archive_read_format_rar_bid,
 
668
                                     archive_read_format_rar_options,
 
669
                                     archive_read_format_rar_read_header,
 
670
                                     archive_read_format_rar_read_data,
 
671
                                     archive_read_format_rar_read_data_skip,
 
672
                                     archive_read_format_rar_seek_data,
 
673
                                     archive_read_format_rar_cleanup,
 
674
                                     archive_read_support_format_rar_capabilities,
 
675
                                     archive_read_format_rar_has_encrypted_entries);
 
676
 
 
677
  if (r != ARCHIVE_OK)
 
678
    free(rar);
 
679
  return (r);
 
680
}
 
681
 
 
682
static int
 
683
archive_read_support_format_rar_capabilities(struct archive_read * a)
 
684
{
 
685
        (void)a; /* UNUSED */
 
686
        return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA
 
687
                        | ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
 
688
}
 
689
 
 
690
static int
 
691
archive_read_format_rar_has_encrypted_entries(struct archive_read *_a)
 
692
{
 
693
        if (_a && _a->format) {
 
694
                struct rar * rar = (struct rar *)_a->format->data;
 
695
                if (rar) {
 
696
                        return rar->has_encrypted_entries;
 
697
                }
 
698
        }
 
699
        return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
 
700
}
 
701
 
 
702
 
 
703
static int
 
704
archive_read_format_rar_bid(struct archive_read *a, int best_bid)
 
705
{
 
706
  const char *p;
 
707
 
 
708
  /* If there's already a bid > 30, we'll never win. */
 
709
  if (best_bid > 30)
 
710
          return (-1);
 
711
 
 
712
  if ((p = __archive_read_ahead(a, 7, NULL)) == NULL)
 
713
    return (-1);
 
714
 
 
715
  if (memcmp(p, RAR_SIGNATURE, 7) == 0)
 
716
    return (30);
 
717
 
 
718
  if ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0) {
 
719
    /* This is a PE file */
 
720
    ssize_t offset = 0x10000;
 
721
    ssize_t window = 4096;
 
722
    ssize_t bytes_avail;
 
723
    while (offset + window <= (1024 * 128)) {
 
724
      const char *buff = __archive_read_ahead(a, offset + window, &bytes_avail);
 
725
      if (buff == NULL) {
 
726
        /* Remaining bytes are less than window. */
 
727
        window >>= 1;
 
728
        if (window < 0x40)
 
729
          return (0);
 
730
        continue;
 
731
      }
 
732
      p = buff + offset;
 
733
      while (p + 7 < buff + bytes_avail) {
 
734
        if (memcmp(p, RAR_SIGNATURE, 7) == 0)
 
735
          return (30);
 
736
        p += 0x10;
 
737
      }
 
738
      offset = p - buff;
 
739
    }
 
740
  }
 
741
  return (0);
 
742
}
 
743
 
 
744
static int
 
745
skip_sfx(struct archive_read *a)
 
746
{
 
747
  const void *h;
 
748
  const char *p, *q;
 
749
  size_t skip, total;
 
750
  ssize_t bytes, window;
 
751
 
 
752
  total = 0;
 
753
  window = 4096;
 
754
  while (total + window <= (1024 * 128)) {
 
755
    h = __archive_read_ahead(a, window, &bytes);
 
756
    if (h == NULL) {
 
757
      /* Remaining bytes are less than window. */
 
758
      window >>= 1;
 
759
      if (window < 0x40)
 
760
        goto fatal;
 
761
      continue;
 
762
    }
 
763
    if (bytes < 0x40)
 
764
      goto fatal;
 
765
    p = h;
 
766
    q = p + bytes;
 
767
 
 
768
    /*
 
769
     * Scan ahead until we find something that looks
 
770
     * like the RAR header.
 
771
     */
 
772
    while (p + 7 < q) {
 
773
      if (memcmp(p, RAR_SIGNATURE, 7) == 0) {
 
774
        skip = p - (const char *)h;
 
775
        __archive_read_consume(a, skip);
 
776
        return (ARCHIVE_OK);
 
777
      }
 
778
      p += 0x10;
 
779
    }
 
780
    skip = p - (const char *)h;
 
781
    __archive_read_consume(a, skip);
 
782
        total += skip;
 
783
  }
 
784
fatal:
 
785
  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
786
      "Couldn't find out RAR header");
 
787
  return (ARCHIVE_FATAL);
 
788
}
 
789
 
 
790
static int
 
791
archive_read_format_rar_options(struct archive_read *a,
 
792
    const char *key, const char *val)
 
793
{
 
794
  struct rar *rar;
 
795
  int ret = ARCHIVE_FAILED;
 
796
 
 
797
  rar = (struct rar *)(a->format->data);
 
798
  if (strcmp(key, "hdrcharset")  == 0) {
 
799
    if (val == NULL || val[0] == 0)
 
800
      archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 
801
          "rar: hdrcharset option needs a character-set name");
 
802
    else {
 
803
      rar->opt_sconv =
 
804
          archive_string_conversion_from_charset(
 
805
              &a->archive, val, 0);
 
806
      if (rar->opt_sconv != NULL)
 
807
        ret = ARCHIVE_OK;
 
808
      else
 
809
        ret = ARCHIVE_FATAL;
 
810
    }
 
811
    return (ret);
 
812
  }
 
813
 
 
814
  /* Note: The "warn" return is just to inform the options
 
815
   * supervisor that we didn't handle it.  It will generate
 
816
   * a suitable error if no one used this option. */
 
817
  return (ARCHIVE_WARN);
 
818
}
 
819
 
 
820
static int
 
821
archive_read_format_rar_read_header(struct archive_read *a,
 
822
                                    struct archive_entry *entry)
 
823
{
 
824
  const void *h;
 
825
  const char *p;
 
826
  struct rar *rar;
 
827
  size_t skip;
 
828
  char head_type;
 
829
  int ret;
 
830
  unsigned flags;
 
831
 
 
832
  a->archive.archive_format = ARCHIVE_FORMAT_RAR;
 
833
  if (a->archive.archive_format_name == NULL)
 
834
    a->archive.archive_format_name = "RAR";
 
835
 
 
836
  rar = (struct rar *)(a->format->data);
 
837
 
 
838
  /*
 
839
   * It should be sufficient to call archive_read_next_header() for
 
840
   * a reader to determine if an entry is encrypted or not. If the
 
841
   * encryption of an entry is only detectable when calling
 
842
   * archive_read_data(), so be it. We'll do the same check there
 
843
   * as well.
 
844
   */
 
845
  if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
 
846
          rar->has_encrypted_entries = 0;
 
847
  }
 
848
 
 
849
  /* RAR files can be generated without EOF headers, so return ARCHIVE_EOF if
 
850
  * this fails.
 
851
  */
 
852
  if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
 
853
    return (ARCHIVE_EOF);
 
854
 
 
855
  p = h;
 
856
  if (rar->found_first_header == 0 &&
 
857
     ((p[0] == 'M' && p[1] == 'Z') || memcmp(p, "\x7F\x45LF", 4) == 0)) {
 
858
    /* This is an executable ? Must be self-extracting... */
 
859
    ret = skip_sfx(a);
 
860
    if (ret < ARCHIVE_WARN)
 
861
      return (ret);
 
862
  }
 
863
  rar->found_first_header = 1;
 
864
 
 
865
  while (1)
 
866
  {
 
867
    unsigned long crc32_val;
 
868
 
 
869
    if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
 
870
      return (ARCHIVE_FATAL);
 
871
    p = h;
 
872
 
 
873
    head_type = p[2];
 
874
    switch(head_type)
 
875
    {
 
876
    case MARK_HEAD:
 
877
      if (memcmp(p, RAR_SIGNATURE, 7) != 0) {
 
878
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
879
          "Invalid marker header");
 
880
        return (ARCHIVE_FATAL);
 
881
      }
 
882
      __archive_read_consume(a, 7);
 
883
      break;
 
884
 
 
885
    case MAIN_HEAD:
 
886
      rar->main_flags = archive_le16dec(p + 3);
 
887
      skip = archive_le16dec(p + 5);
 
888
      if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)) {
 
889
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
890
          "Invalid header size");
 
891
        return (ARCHIVE_FATAL);
 
892
      }
 
893
      if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
 
894
        return (ARCHIVE_FATAL);
 
895
      p = h;
 
896
      memcpy(rar->reserved1, p + 7, sizeof(rar->reserved1));
 
897
      memcpy(rar->reserved2, p + 7 + sizeof(rar->reserved1),
 
898
             sizeof(rar->reserved2));
 
899
      if (rar->main_flags & MHD_ENCRYPTVER) {
 
900
        if (skip < 7 + sizeof(rar->reserved1) + sizeof(rar->reserved2)+1) {
 
901
          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
902
            "Invalid header size");
 
903
          return (ARCHIVE_FATAL);
 
904
        }
 
905
        rar->encryptver = *(p + 7 + sizeof(rar->reserved1) +
 
906
                            sizeof(rar->reserved2));
 
907
      }
 
908
 
 
909
      /* Main header is password encrytped, so we cannot read any
 
910
         file names or any other info about files from the header. */
 
911
      if (rar->main_flags & MHD_PASSWORD)
 
912
      {
 
913
        archive_entry_set_is_metadata_encrypted(entry, 1);
 
914
        archive_entry_set_is_data_encrypted(entry, 1);
 
915
        rar->has_encrypted_entries = 1;
 
916
         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
917
                          "RAR encryption support unavailable.");
 
918
        return (ARCHIVE_FATAL);
 
919
      }
 
920
 
 
921
      crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2);
 
922
      if ((crc32_val & 0xffff) != archive_le16dec(p)) {
 
923
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
924
          "Header CRC error");
 
925
        return (ARCHIVE_FATAL);
 
926
      }
 
927
      __archive_read_consume(a, skip);
 
928
      break;
 
929
 
 
930
    case FILE_HEAD:
 
931
      return read_header(a, entry, head_type);
 
932
 
 
933
    case COMM_HEAD:
 
934
    case AV_HEAD:
 
935
    case SUB_HEAD:
 
936
    case PROTECT_HEAD:
 
937
    case SIGN_HEAD:
 
938
    case ENDARC_HEAD:
 
939
      flags = archive_le16dec(p + 3);
 
940
      skip = archive_le16dec(p + 5);
 
941
      if (skip < 7) {
 
942
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
943
          "Invalid header size");
 
944
        return (ARCHIVE_FATAL);
 
945
      }
 
946
      if (skip > 7) {
 
947
        if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
 
948
          return (ARCHIVE_FATAL);
 
949
        p = h;
 
950
      }
 
951
      if (flags & HD_ADD_SIZE_PRESENT)
 
952
      {
 
953
        if (skip < 7 + 4) {
 
954
          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
955
            "Invalid header size");
 
956
          return (ARCHIVE_FATAL);
 
957
        }
 
958
        skip += archive_le32dec(p + 7);
 
959
        if ((h = __archive_read_ahead(a, skip, NULL)) == NULL)
 
960
          return (ARCHIVE_FATAL);
 
961
        p = h;
 
962
      }
 
963
 
 
964
      crc32_val = crc32(0, (const unsigned char *)p + 2, (unsigned)skip - 2);
 
965
      if ((crc32_val & 0xffff) != archive_le16dec(p)) {
 
966
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
967
          "Header CRC error");
 
968
        return (ARCHIVE_FATAL);
 
969
      }
 
970
      __archive_read_consume(a, skip);
 
971
      if (head_type == ENDARC_HEAD)
 
972
        return (ARCHIVE_EOF);
 
973
      break;
 
974
 
 
975
    case NEWSUB_HEAD:
 
976
      if ((ret = read_header(a, entry, head_type)) < ARCHIVE_WARN)
 
977
        return ret;
 
978
      break;
 
979
 
 
980
    default:
 
981
      archive_set_error(&a->archive,  ARCHIVE_ERRNO_FILE_FORMAT,
 
982
                        "Bad RAR file");
 
983
      return (ARCHIVE_FATAL);
 
984
    }
 
985
  }
 
986
}
 
987
 
 
988
static int
 
989
archive_read_format_rar_read_data(struct archive_read *a, const void **buff,
 
990
                                  size_t *size, int64_t *offset)
 
991
{
 
992
  struct rar *rar = (struct rar *)(a->format->data);
 
993
  int ret;
 
994
 
 
995
  if (rar->has_encrypted_entries == ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
 
996
          rar->has_encrypted_entries = 0;
 
997
  }
 
998
 
 
999
  if (rar->bytes_unconsumed > 0) {
 
1000
      /* Consume as much as the decompressor actually used. */
 
1001
      __archive_read_consume(a, rar->bytes_unconsumed);
 
1002
      rar->bytes_unconsumed = 0;
 
1003
  }
 
1004
 
 
1005
  *buff = NULL;
 
1006
  if (rar->entry_eof || rar->offset_seek >= rar->unp_size) {
 
1007
    *size = 0;
 
1008
    *offset = rar->offset;
 
1009
    if (*offset < rar->unp_size)
 
1010
      *offset = rar->unp_size;
 
1011
    return (ARCHIVE_EOF);
 
1012
  }
 
1013
 
 
1014
  switch (rar->compression_method)
 
1015
  {
 
1016
  case COMPRESS_METHOD_STORE:
 
1017
    ret = read_data_stored(a, buff, size, offset);
 
1018
    break;
 
1019
 
 
1020
  case COMPRESS_METHOD_FASTEST:
 
1021
  case COMPRESS_METHOD_FAST:
 
1022
  case COMPRESS_METHOD_NORMAL:
 
1023
  case COMPRESS_METHOD_GOOD:
 
1024
  case COMPRESS_METHOD_BEST:
 
1025
    ret = read_data_compressed(a, buff, size, offset);
 
1026
    if (ret != ARCHIVE_OK && ret != ARCHIVE_WARN)
 
1027
      __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 
1028
    break;
 
1029
 
 
1030
  default:
 
1031
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1032
                      "Unsupported compression method for RAR file.");
 
1033
    ret = ARCHIVE_FATAL;
 
1034
    break;
 
1035
  }
 
1036
  return (ret);
 
1037
}
 
1038
 
 
1039
static int
 
1040
archive_read_format_rar_read_data_skip(struct archive_read *a)
 
1041
{
 
1042
  struct rar *rar;
 
1043
  int64_t bytes_skipped;
 
1044
  int ret;
 
1045
 
 
1046
  rar = (struct rar *)(a->format->data);
 
1047
 
 
1048
  if (rar->bytes_unconsumed > 0) {
 
1049
      /* Consume as much as the decompressor actually used. */
 
1050
      __archive_read_consume(a, rar->bytes_unconsumed);
 
1051
      rar->bytes_unconsumed = 0;
 
1052
  }
 
1053
 
 
1054
  if (rar->bytes_remaining > 0) {
 
1055
    bytes_skipped = __archive_read_consume(a, rar->bytes_remaining);
 
1056
    if (bytes_skipped < 0)
 
1057
      return (ARCHIVE_FATAL);
 
1058
  }
 
1059
 
 
1060
  /* Compressed data to skip must be read from each header in a multivolume
 
1061
   * archive.
 
1062
   */
 
1063
  if (rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER)
 
1064
  {
 
1065
    ret = archive_read_format_rar_read_header(a, a->entry);
 
1066
    if (ret == (ARCHIVE_EOF))
 
1067
      ret = archive_read_format_rar_read_header(a, a->entry);
 
1068
    if (ret != (ARCHIVE_OK))
 
1069
      return ret;
 
1070
    return archive_read_format_rar_read_data_skip(a);
 
1071
  }
 
1072
 
 
1073
  return (ARCHIVE_OK);
 
1074
}
 
1075
 
 
1076
static int64_t
 
1077
archive_read_format_rar_seek_data(struct archive_read *a, int64_t offset,
 
1078
    int whence)
 
1079
{
 
1080
  int64_t client_offset, ret;
 
1081
  unsigned int i;
 
1082
  struct rar *rar = (struct rar *)(a->format->data);
 
1083
 
 
1084
  if (rar->compression_method == COMPRESS_METHOD_STORE)
 
1085
  {
 
1086
    /* Modify the offset for use with SEEK_SET */
 
1087
    switch (whence)
 
1088
    {
 
1089
      case SEEK_CUR:
 
1090
        client_offset = rar->offset_seek;
 
1091
        break;
 
1092
      case SEEK_END:
 
1093
        client_offset = rar->unp_size;
 
1094
        break;
 
1095
      case SEEK_SET:
 
1096
      default:
 
1097
        client_offset = 0;
 
1098
    }
 
1099
    client_offset += offset;
 
1100
    if (client_offset < 0)
 
1101
    {
 
1102
      /* Can't seek past beginning of data block */
 
1103
      return -1;
 
1104
    }
 
1105
    else if (client_offset > rar->unp_size)
 
1106
    {
 
1107
      /*
 
1108
       * Set the returned offset but only seek to the end of
 
1109
       * the data block.
 
1110
       */
 
1111
      rar->offset_seek = client_offset;
 
1112
      client_offset = rar->unp_size;
 
1113
    }
 
1114
 
 
1115
    client_offset += rar->dbo[0].start_offset;
 
1116
    i = 0;
 
1117
    while (i < rar->cursor)
 
1118
    {
 
1119
      i++;
 
1120
      client_offset += rar->dbo[i].start_offset - rar->dbo[i-1].end_offset;
 
1121
    }
 
1122
    if (rar->main_flags & MHD_VOLUME)
 
1123
    {
 
1124
      /* Find the appropriate offset among the multivolume archive */
 
1125
      while (1)
 
1126
      {
 
1127
        if (client_offset < rar->dbo[rar->cursor].start_offset &&
 
1128
          rar->file_flags & FHD_SPLIT_BEFORE)
 
1129
        {
 
1130
          /* Search backwards for the correct data block */
 
1131
          if (rar->cursor == 0)
 
1132
          {
 
1133
            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 
1134
              "Attempt to seek past beginning of RAR data block");
 
1135
            return (ARCHIVE_FAILED);
 
1136
          }
 
1137
          rar->cursor--;
 
1138
          client_offset -= rar->dbo[rar->cursor+1].start_offset -
 
1139
            rar->dbo[rar->cursor].end_offset;
 
1140
          if (client_offset < rar->dbo[rar->cursor].start_offset)
 
1141
            continue;
 
1142
          ret = __archive_read_seek(a, rar->dbo[rar->cursor].start_offset -
 
1143
            rar->dbo[rar->cursor].header_size, SEEK_SET);
 
1144
          if (ret < (ARCHIVE_OK))
 
1145
            return ret;
 
1146
          ret = archive_read_format_rar_read_header(a, a->entry);
 
1147
          if (ret != (ARCHIVE_OK))
 
1148
          {
 
1149
            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 
1150
              "Error during seek of RAR file");
 
1151
            return (ARCHIVE_FAILED);
 
1152
          }
 
1153
          rar->cursor--;
 
1154
          break;
 
1155
        }
 
1156
        else if (client_offset > rar->dbo[rar->cursor].end_offset &&
 
1157
          rar->file_flags & FHD_SPLIT_AFTER)
 
1158
        {
 
1159
          /* Search forward for the correct data block */
 
1160
          rar->cursor++;
 
1161
          if (rar->cursor < rar->nodes &&
 
1162
            client_offset > rar->dbo[rar->cursor].end_offset)
 
1163
          {
 
1164
            client_offset += rar->dbo[rar->cursor].start_offset -
 
1165
              rar->dbo[rar->cursor-1].end_offset;
 
1166
            continue;
 
1167
          }
 
1168
          rar->cursor--;
 
1169
          ret = __archive_read_seek(a, rar->dbo[rar->cursor].end_offset,
 
1170
                                    SEEK_SET);
 
1171
          if (ret < (ARCHIVE_OK))
 
1172
            return ret;
 
1173
          ret = archive_read_format_rar_read_header(a, a->entry);
 
1174
          if (ret == (ARCHIVE_EOF))
 
1175
          {
 
1176
            rar->has_endarc_header = 1;
 
1177
            ret = archive_read_format_rar_read_header(a, a->entry);
 
1178
          }
 
1179
          if (ret != (ARCHIVE_OK))
 
1180
          {
 
1181
            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 
1182
              "Error during seek of RAR file");
 
1183
            return (ARCHIVE_FAILED);
 
1184
          }
 
1185
          client_offset += rar->dbo[rar->cursor].start_offset -
 
1186
            rar->dbo[rar->cursor-1].end_offset;
 
1187
          continue;
 
1188
        }
 
1189
        break;
 
1190
      }
 
1191
    }
 
1192
 
 
1193
    ret = __archive_read_seek(a, client_offset, SEEK_SET);
 
1194
    if (ret < (ARCHIVE_OK))
 
1195
      return ret;
 
1196
    rar->bytes_remaining = rar->dbo[rar->cursor].end_offset - ret;
 
1197
    i = rar->cursor;
 
1198
    while (i > 0)
 
1199
    {
 
1200
      i--;
 
1201
      ret -= rar->dbo[i+1].start_offset - rar->dbo[i].end_offset;
 
1202
    }
 
1203
    ret -= rar->dbo[0].start_offset;
 
1204
 
 
1205
    /* Always restart reading the file after a seek */
 
1206
    __archive_reset_read_data(&a->archive);
 
1207
 
 
1208
    rar->bytes_unconsumed = 0;
 
1209
    rar->offset = 0;
 
1210
 
 
1211
    /*
 
1212
     * If a seek past the end of file was requested, return the requested
 
1213
     * offset.
 
1214
     */
 
1215
    if (ret == rar->unp_size && rar->offset_seek > rar->unp_size)
 
1216
      return rar->offset_seek;
 
1217
 
 
1218
    /* Return the new offset */
 
1219
    rar->offset_seek = ret;
 
1220
    return rar->offset_seek;
 
1221
  }
 
1222
  else
 
1223
  {
 
1224
    archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 
1225
      "Seeking of compressed RAR files is unsupported");
 
1226
  }
 
1227
  return (ARCHIVE_FAILED);
 
1228
}
 
1229
 
 
1230
static int
 
1231
archive_read_format_rar_cleanup(struct archive_read *a)
 
1232
{
 
1233
  struct rar *rar;
 
1234
 
 
1235
  rar = (struct rar *)(a->format->data);
 
1236
  free_codes(a);
 
1237
  free(rar->filename);
 
1238
  free(rar->filename_save);
 
1239
  free(rar->dbo);
 
1240
  free(rar->unp_buffer);
 
1241
  free(rar->lzss.window);
 
1242
  __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 
1243
  free(rar);
 
1244
  (a->format->data) = NULL;
 
1245
  return (ARCHIVE_OK);
 
1246
}
 
1247
 
 
1248
static int
 
1249
read_header(struct archive_read *a, struct archive_entry *entry,
 
1250
            char head_type)
 
1251
{
 
1252
  const void *h;
 
1253
  const char *p, *endp;
 
1254
  struct rar *rar;
 
1255
  struct rar_header rar_header;
 
1256
  struct rar_file_header file_header;
 
1257
  int64_t header_size;
 
1258
  unsigned filename_size, end;
 
1259
  char *filename;
 
1260
  char *strp;
 
1261
  char packed_size[8];
 
1262
  char unp_size[8];
 
1263
  int ttime;
 
1264
  struct archive_string_conv *sconv, *fn_sconv;
 
1265
  unsigned long crc32_val;
 
1266
  int ret = (ARCHIVE_OK), ret2;
 
1267
 
 
1268
  rar = (struct rar *)(a->format->data);
 
1269
 
 
1270
  /* Setup a string conversion object for non-rar-unicode filenames. */
 
1271
  sconv = rar->opt_sconv;
 
1272
  if (sconv == NULL) {
 
1273
    if (!rar->init_default_conversion) {
 
1274
      rar->sconv_default =
 
1275
          archive_string_default_conversion_for_read(
 
1276
            &(a->archive));
 
1277
      rar->init_default_conversion = 1;
 
1278
    }
 
1279
    sconv = rar->sconv_default;
 
1280
  }
 
1281
 
 
1282
 
 
1283
  if ((h = __archive_read_ahead(a, 7, NULL)) == NULL)
 
1284
    return (ARCHIVE_FATAL);
 
1285
  p = h;
 
1286
  memcpy(&rar_header, p, sizeof(rar_header));
 
1287
  rar->file_flags = archive_le16dec(rar_header.flags);
 
1288
  header_size = archive_le16dec(rar_header.size);
 
1289
  if (header_size < (int64_t)sizeof(file_header) + 7) {
 
1290
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1291
      "Invalid header size");
 
1292
    return (ARCHIVE_FATAL);
 
1293
  }
 
1294
  crc32_val = crc32(0, (const unsigned char *)p + 2, 7 - 2);
 
1295
  __archive_read_consume(a, 7);
 
1296
 
 
1297
  if (!(rar->file_flags & FHD_SOLID))
 
1298
  {
 
1299
    rar->compression_method = 0;
 
1300
    rar->packed_size = 0;
 
1301
    rar->unp_size = 0;
 
1302
    rar->mtime = 0;
 
1303
    rar->ctime = 0;
 
1304
    rar->atime = 0;
 
1305
    rar->arctime = 0;
 
1306
    rar->mode = 0;
 
1307
    memset(&rar->salt, 0, sizeof(rar->salt));
 
1308
    rar->atime = 0;
 
1309
    rar->ansec = 0;
 
1310
    rar->ctime = 0;
 
1311
    rar->cnsec = 0;
 
1312
    rar->mtime = 0;
 
1313
    rar->mnsec = 0;
 
1314
    rar->arctime = 0;
 
1315
    rar->arcnsec = 0;
 
1316
  }
 
1317
  else
 
1318
  {
 
1319
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1320
                      "RAR solid archive support unavailable.");
 
1321
    return (ARCHIVE_FATAL);
 
1322
  }
 
1323
 
 
1324
  if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
 
1325
    return (ARCHIVE_FATAL);
 
1326
 
 
1327
  /* File Header CRC check. */
 
1328
  crc32_val = crc32(crc32_val, h, (unsigned)(header_size - 7));
 
1329
  if ((crc32_val & 0xffff) != archive_le16dec(rar_header.crc)) {
 
1330
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1331
      "Header CRC error");
 
1332
    return (ARCHIVE_FATAL);
 
1333
  }
 
1334
  /* If no CRC error, Go on parsing File Header. */
 
1335
  p = h;
 
1336
  endp = p + header_size - 7;
 
1337
  memcpy(&file_header, p, sizeof(file_header));
 
1338
  p += sizeof(file_header);
 
1339
 
 
1340
  rar->compression_method = file_header.method;
 
1341
 
 
1342
  ttime = archive_le32dec(file_header.file_time);
 
1343
  rar->mtime = get_time(ttime);
 
1344
 
 
1345
  rar->file_crc = archive_le32dec(file_header.file_crc);
 
1346
 
 
1347
  if (rar->file_flags & FHD_PASSWORD)
 
1348
  {
 
1349
        archive_entry_set_is_data_encrypted(entry, 1);
 
1350
        rar->has_encrypted_entries = 1;
 
1351
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1352
                      "RAR encryption support unavailable.");
 
1353
    /* Since it is only the data part itself that is encrypted we can at least
 
1354
       extract information about the currently processed entry and don't need
 
1355
       to return ARCHIVE_FATAL here. */
 
1356
    /*return (ARCHIVE_FATAL);*/
 
1357
  }
 
1358
 
 
1359
  if (rar->file_flags & FHD_LARGE)
 
1360
  {
 
1361
    memcpy(packed_size, file_header.pack_size, 4);
 
1362
    memcpy(packed_size + 4, p, 4); /* High pack size */
 
1363
    p += 4;
 
1364
    memcpy(unp_size, file_header.unp_size, 4);
 
1365
    memcpy(unp_size + 4, p, 4); /* High unpack size */
 
1366
    p += 4;
 
1367
    rar->packed_size = archive_le64dec(&packed_size);
 
1368
    rar->unp_size = archive_le64dec(&unp_size);
 
1369
  }
 
1370
  else
 
1371
  {
 
1372
    rar->packed_size = archive_le32dec(file_header.pack_size);
 
1373
    rar->unp_size = archive_le32dec(file_header.unp_size);
 
1374
  }
 
1375
 
 
1376
  if (rar->packed_size < 0 || rar->unp_size < 0)
 
1377
  {
 
1378
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1379
                      "Invalid sizes specified.");
 
1380
    return (ARCHIVE_FATAL);
 
1381
  }
 
1382
 
 
1383
  rar->bytes_remaining = rar->packed_size;
 
1384
 
 
1385
  /* TODO: RARv3 subblocks contain comments. For now the complete block is
 
1386
   * consumed at the end.
 
1387
   */
 
1388
  if (head_type == NEWSUB_HEAD) {
 
1389
    size_t distance = p - (const char *)h;
 
1390
    header_size += rar->packed_size;
 
1391
    /* Make sure we have the extended data. */
 
1392
    if ((h = __archive_read_ahead(a, (size_t)header_size - 7, NULL)) == NULL)
 
1393
        return (ARCHIVE_FATAL);
 
1394
    p = h;
 
1395
    endp = p + header_size - 7;
 
1396
    p += distance;
 
1397
  }
 
1398
 
 
1399
  filename_size = archive_le16dec(file_header.name_size);
 
1400
  if (p + filename_size > endp) {
 
1401
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1402
      "Invalid filename size");
 
1403
    return (ARCHIVE_FATAL);
 
1404
  }
 
1405
  if (rar->filename_allocated < filename_size * 2 + 2) {
 
1406
    char *newptr;
 
1407
    size_t newsize = filename_size * 2 + 2;
 
1408
    newptr = realloc(rar->filename, newsize);
 
1409
    if (newptr == NULL) {
 
1410
      archive_set_error(&a->archive, ENOMEM,
 
1411
                        "Couldn't allocate memory.");
 
1412
      return (ARCHIVE_FATAL);
 
1413
    }
 
1414
    rar->filename = newptr;
 
1415
    rar->filename_allocated = newsize;
 
1416
  }
 
1417
  filename = rar->filename;
 
1418
  memcpy(filename, p, filename_size);
 
1419
  filename[filename_size] = '\0';
 
1420
  if (rar->file_flags & FHD_UNICODE)
 
1421
  {
 
1422
    if (filename_size != strlen(filename))
 
1423
    {
 
1424
      unsigned char highbyte, flagbits, flagbyte;
 
1425
      unsigned fn_end, offset;
 
1426
 
 
1427
      end = filename_size;
 
1428
      fn_end = filename_size * 2;
 
1429
      filename_size = 0;
 
1430
      offset = (unsigned)strlen(filename) + 1;
 
1431
      highbyte = *(p + offset++);
 
1432
      flagbits = 0;
 
1433
      flagbyte = 0;
 
1434
      while (offset < end && filename_size < fn_end)
 
1435
      {
 
1436
        if (!flagbits)
 
1437
        {
 
1438
          flagbyte = *(p + offset++);
 
1439
          flagbits = 8;
 
1440
        }
 
1441
 
 
1442
        flagbits -= 2;
 
1443
        switch((flagbyte >> flagbits) & 3)
 
1444
        {
 
1445
          case 0:
 
1446
            filename[filename_size++] = '\0';
 
1447
            filename[filename_size++] = *(p + offset++);
 
1448
            break;
 
1449
          case 1:
 
1450
            filename[filename_size++] = highbyte;
 
1451
            filename[filename_size++] = *(p + offset++);
 
1452
            break;
 
1453
          case 2:
 
1454
            filename[filename_size++] = *(p + offset + 1);
 
1455
            filename[filename_size++] = *(p + offset);
 
1456
            offset += 2;
 
1457
            break;
 
1458
          case 3:
 
1459
          {
 
1460
            char extra, high;
 
1461
            uint8_t length = *(p + offset++);
 
1462
 
 
1463
            if (length & 0x80) {
 
1464
              extra = *(p + offset++);
 
1465
              high = (char)highbyte;
 
1466
            } else
 
1467
              extra = high = 0;
 
1468
            length = (length & 0x7f) + 2;
 
1469
            while (length && filename_size < fn_end) {
 
1470
              unsigned cp = filename_size >> 1;
 
1471
              filename[filename_size++] = high;
 
1472
              filename[filename_size++] = p[cp] + extra;
 
1473
              length--;
 
1474
            }
 
1475
          }
 
1476
          break;
 
1477
        }
 
1478
      }
 
1479
      if (filename_size > fn_end) {
 
1480
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1481
          "Invalid filename");
 
1482
        return (ARCHIVE_FATAL);
 
1483
      }
 
1484
      filename[filename_size++] = '\0';
 
1485
      filename[filename_size++] = '\0';
 
1486
 
 
1487
      /* Decoded unicode form is UTF-16BE, so we have to update a string
 
1488
       * conversion object for it. */
 
1489
      if (rar->sconv_utf16be == NULL) {
 
1490
        rar->sconv_utf16be = archive_string_conversion_from_charset(
 
1491
           &a->archive, "UTF-16BE", 1);
 
1492
        if (rar->sconv_utf16be == NULL)
 
1493
          return (ARCHIVE_FATAL);
 
1494
      }
 
1495
      fn_sconv = rar->sconv_utf16be;
 
1496
 
 
1497
      strp = filename;
 
1498
      while (memcmp(strp, "\x00\x00", 2))
 
1499
      {
 
1500
        if (!memcmp(strp, "\x00\\", 2))
 
1501
          *(strp + 1) = '/';
 
1502
        strp += 2;
 
1503
      }
 
1504
      p += offset;
 
1505
    } else {
 
1506
      /*
 
1507
       * If FHD_UNICODE is set but no unicode data, this file name form
 
1508
       * is UTF-8, so we have to update a string conversion object for
 
1509
       * it accordingly.
 
1510
       */
 
1511
      if (rar->sconv_utf8 == NULL) {
 
1512
        rar->sconv_utf8 = archive_string_conversion_from_charset(
 
1513
           &a->archive, "UTF-8", 1);
 
1514
        if (rar->sconv_utf8 == NULL)
 
1515
          return (ARCHIVE_FATAL);
 
1516
      }
 
1517
      fn_sconv = rar->sconv_utf8;
 
1518
      while ((strp = strchr(filename, '\\')) != NULL)
 
1519
        *strp = '/';
 
1520
      p += filename_size;
 
1521
    }
 
1522
  }
 
1523
  else
 
1524
  {
 
1525
    fn_sconv = sconv;
 
1526
    while ((strp = strchr(filename, '\\')) != NULL)
 
1527
      *strp = '/';
 
1528
    p += filename_size;
 
1529
  }
 
1530
 
 
1531
  /* Split file in multivolume RAR. No more need to process header. */
 
1532
  if (rar->filename_save &&
 
1533
    filename_size == rar->filename_save_size &&
 
1534
    !memcmp(rar->filename, rar->filename_save, filename_size + 1))
 
1535
  {
 
1536
    __archive_read_consume(a, header_size - 7);
 
1537
    rar->cursor++;
 
1538
    if (rar->cursor >= rar->nodes)
 
1539
    {
 
1540
      rar->nodes++;
 
1541
      if ((rar->dbo =
 
1542
        realloc(rar->dbo, sizeof(*rar->dbo) * rar->nodes)) == NULL)
 
1543
      {
 
1544
        archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
 
1545
        return (ARCHIVE_FATAL);
 
1546
      }
 
1547
      rar->dbo[rar->cursor].header_size = header_size;
 
1548
      rar->dbo[rar->cursor].start_offset = -1;
 
1549
      rar->dbo[rar->cursor].end_offset = -1;
 
1550
    }
 
1551
    if (rar->dbo[rar->cursor].start_offset < 0)
 
1552
    {
 
1553
      rar->dbo[rar->cursor].start_offset = a->filter->position;
 
1554
      rar->dbo[rar->cursor].end_offset = rar->dbo[rar->cursor].start_offset +
 
1555
        rar->packed_size;
 
1556
    }
 
1557
    return ret;
 
1558
  }
 
1559
 
 
1560
  rar->filename_save = (char*)realloc(rar->filename_save,
 
1561
                                      filename_size + 1);
 
1562
  memcpy(rar->filename_save, rar->filename, filename_size + 1);
 
1563
  rar->filename_save_size = filename_size;
 
1564
 
 
1565
  /* Set info for seeking */
 
1566
  free(rar->dbo);
 
1567
  if ((rar->dbo = calloc(1, sizeof(*rar->dbo))) == NULL)
 
1568
  {
 
1569
    archive_set_error(&a->archive, ENOMEM, "Couldn't allocate memory.");
 
1570
    return (ARCHIVE_FATAL);
 
1571
  }
 
1572
  rar->dbo[0].header_size = header_size;
 
1573
  rar->dbo[0].start_offset = -1;
 
1574
  rar->dbo[0].end_offset = -1;
 
1575
  rar->cursor = 0;
 
1576
  rar->nodes = 1;
 
1577
 
 
1578
  if (rar->file_flags & FHD_SALT)
 
1579
  {
 
1580
    if (p + 8 > endp) {
 
1581
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1582
        "Invalid header size");
 
1583
      return (ARCHIVE_FATAL);
 
1584
    }
 
1585
    memcpy(rar->salt, p, 8);
 
1586
    p += 8;
 
1587
  }
 
1588
 
 
1589
  if (rar->file_flags & FHD_EXTTIME) {
 
1590
    if (read_exttime(p, rar, endp) < 0) {
 
1591
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1592
        "Invalid header size");
 
1593
      return (ARCHIVE_FATAL);
 
1594
    }
 
1595
  }
 
1596
 
 
1597
  __archive_read_consume(a, header_size - 7);
 
1598
  rar->dbo[0].start_offset = a->filter->position;
 
1599
  rar->dbo[0].end_offset = rar->dbo[0].start_offset + rar->packed_size;
 
1600
 
 
1601
  switch(file_header.host_os)
 
1602
  {
 
1603
  case OS_MSDOS:
 
1604
  case OS_OS2:
 
1605
  case OS_WIN32:
 
1606
    rar->mode = archive_le32dec(file_header.file_attr);
 
1607
    if (rar->mode & FILE_ATTRIBUTE_DIRECTORY)
 
1608
      rar->mode = AE_IFDIR | S_IXUSR | S_IXGRP | S_IXOTH;
 
1609
    else
 
1610
      rar->mode = AE_IFREG;
 
1611
    rar->mode |= S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
 
1612
    break;
 
1613
 
 
1614
  case OS_UNIX:
 
1615
  case OS_MAC_OS:
 
1616
  case OS_BEOS:
 
1617
    rar->mode = archive_le32dec(file_header.file_attr);
 
1618
    break;
 
1619
 
 
1620
  default:
 
1621
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1622
                      "Unknown file attributes from RAR file's host OS");
 
1623
    return (ARCHIVE_FATAL);
 
1624
  }
 
1625
 
 
1626
  rar->bytes_uncopied = rar->bytes_unconsumed = 0;
 
1627
  rar->lzss.position = rar->offset = 0;
 
1628
  rar->offset_seek = 0;
 
1629
  rar->dictionary_size = 0;
 
1630
  rar->offset_outgoing = 0;
 
1631
  rar->br.cache_avail = 0;
 
1632
  rar->br.avail_in = 0;
 
1633
  rar->crc_calculated = 0;
 
1634
  rar->entry_eof = 0;
 
1635
  rar->valid = 1;
 
1636
  rar->is_ppmd_block = 0;
 
1637
  rar->start_new_table = 1;
 
1638
  free(rar->unp_buffer);
 
1639
  rar->unp_buffer = NULL;
 
1640
  rar->unp_offset = 0;
 
1641
  rar->unp_buffer_size = UNP_BUFFER_SIZE;
 
1642
  memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
 
1643
  __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 
1644
  rar->ppmd_valid = rar->ppmd_eod = 0;
 
1645
 
 
1646
  /* Don't set any archive entries for non-file header types */
 
1647
  if (head_type == NEWSUB_HEAD)
 
1648
    return ret;
 
1649
 
 
1650
  archive_entry_set_mtime(entry, rar->mtime, rar->mnsec);
 
1651
  archive_entry_set_ctime(entry, rar->ctime, rar->cnsec);
 
1652
  archive_entry_set_atime(entry, rar->atime, rar->ansec);
 
1653
  archive_entry_set_size(entry, rar->unp_size);
 
1654
  archive_entry_set_mode(entry, rar->mode);
 
1655
 
 
1656
  if (archive_entry_copy_pathname_l(entry, filename, filename_size, fn_sconv))
 
1657
  {
 
1658
    if (errno == ENOMEM)
 
1659
    {
 
1660
      archive_set_error(&a->archive, ENOMEM,
 
1661
                        "Can't allocate memory for Pathname");
 
1662
      return (ARCHIVE_FATAL);
 
1663
    }
 
1664
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1665
                      "Pathname cannot be converted from %s to current locale.",
 
1666
                      archive_string_conversion_charset_name(fn_sconv));
 
1667
    ret = (ARCHIVE_WARN);
 
1668
  }
 
1669
 
 
1670
  if (((rar->mode) & AE_IFMT) == AE_IFLNK)
 
1671
  {
 
1672
    /* Make sure a symbolic-link file does not have its body. */
 
1673
    rar->bytes_remaining = 0;
 
1674
    archive_entry_set_size(entry, 0);
 
1675
 
 
1676
    /* Read a symbolic-link name. */
 
1677
    if ((ret2 = read_symlink_stored(a, entry, sconv)) < (ARCHIVE_WARN))
 
1678
      return ret2;
 
1679
    if (ret > ret2)
 
1680
      ret = ret2;
 
1681
  }
 
1682
 
 
1683
  if (rar->bytes_remaining == 0)
 
1684
    rar->entry_eof = 1;
 
1685
 
 
1686
  return ret;
 
1687
}
 
1688
 
 
1689
static time_t
 
1690
get_time(int ttime)
 
1691
{
 
1692
  struct tm tm;
 
1693
  tm.tm_sec = 2 * (ttime & 0x1f);
 
1694
  tm.tm_min = (ttime >> 5) & 0x3f;
 
1695
  tm.tm_hour = (ttime >> 11) & 0x1f;
 
1696
  tm.tm_mday = (ttime >> 16) & 0x1f;
 
1697
  tm.tm_mon = ((ttime >> 21) & 0x0f) - 1;
 
1698
  tm.tm_year = ((ttime >> 25) & 0x7f) + 80;
 
1699
  tm.tm_isdst = -1;
 
1700
  return mktime(&tm);
 
1701
}
 
1702
 
 
1703
static int
 
1704
read_exttime(const char *p, struct rar *rar, const char *endp)
 
1705
{
 
1706
  unsigned rmode, flags, rem, j, count;
 
1707
  int ttime, i;
 
1708
  struct tm *tm;
 
1709
  time_t t;
 
1710
  long nsec;
 
1711
 
 
1712
  if (p + 2 > endp)
 
1713
    return (-1);
 
1714
  flags = archive_le16dec(p);
 
1715
  p += 2;
 
1716
 
 
1717
  for (i = 3; i >= 0; i--)
 
1718
  {
 
1719
    t = 0;
 
1720
    if (i == 3)
 
1721
      t = rar->mtime;
 
1722
    rmode = flags >> i * 4;
 
1723
    if (rmode & 8)
 
1724
    {
 
1725
      if (!t)
 
1726
      {
 
1727
        if (p + 4 > endp)
 
1728
          return (-1);
 
1729
        ttime = archive_le32dec(p);
 
1730
        t = get_time(ttime);
 
1731
        p += 4;
 
1732
      }
 
1733
      rem = 0;
 
1734
      count = rmode & 3;
 
1735
      if (p + count > endp)
 
1736
        return (-1);
 
1737
      for (j = 0; j < count; j++)
 
1738
      {
 
1739
        rem = ((*p) << 16) | (rem >> 8);
 
1740
        p++;
 
1741
      }
 
1742
      tm = localtime(&t);
 
1743
      nsec = tm->tm_sec + rem / NS_UNIT;
 
1744
      if (rmode & 4)
 
1745
      {
 
1746
        tm->tm_sec++;
 
1747
        t = mktime(tm);
 
1748
      }
 
1749
      if (i == 3)
 
1750
      {
 
1751
        rar->mtime = t;
 
1752
        rar->mnsec = nsec;
 
1753
      }
 
1754
      else if (i == 2)
 
1755
      {
 
1756
        rar->ctime = t;
 
1757
        rar->cnsec = nsec;
 
1758
      }
 
1759
      else if (i == 1)
 
1760
      {
 
1761
        rar->atime = t;
 
1762
        rar->ansec = nsec;
 
1763
      }
 
1764
      else
 
1765
      {
 
1766
        rar->arctime = t;
 
1767
        rar->arcnsec = nsec;
 
1768
      }
 
1769
    }
 
1770
  }
 
1771
  return (0);
 
1772
}
 
1773
 
 
1774
static int
 
1775
read_symlink_stored(struct archive_read *a, struct archive_entry *entry,
 
1776
                    struct archive_string_conv *sconv)
 
1777
{
 
1778
  const void *h;
 
1779
  const char *p;
 
1780
  struct rar *rar;
 
1781
  int ret = (ARCHIVE_OK);
 
1782
 
 
1783
  rar = (struct rar *)(a->format->data);
 
1784
  if ((h = rar_read_ahead(a, (size_t)rar->packed_size, NULL)) == NULL)
 
1785
    return (ARCHIVE_FATAL);
 
1786
  p = h;
 
1787
 
 
1788
  if (archive_entry_copy_symlink_l(entry,
 
1789
      p, (size_t)rar->packed_size, sconv))
 
1790
  {
 
1791
    if (errno == ENOMEM)
 
1792
    {
 
1793
      archive_set_error(&a->archive, ENOMEM,
 
1794
                        "Can't allocate memory for link");
 
1795
      return (ARCHIVE_FATAL);
 
1796
    }
 
1797
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1798
                      "link cannot be converted from %s to current locale.",
 
1799
                      archive_string_conversion_charset_name(sconv));
 
1800
    ret = (ARCHIVE_WARN);
 
1801
  }
 
1802
  __archive_read_consume(a, rar->packed_size);
 
1803
  return ret;
 
1804
}
 
1805
 
 
1806
static int
 
1807
read_data_stored(struct archive_read *a, const void **buff, size_t *size,
 
1808
                 int64_t *offset)
 
1809
{
 
1810
  struct rar *rar;
 
1811
  ssize_t bytes_avail;
 
1812
 
 
1813
  rar = (struct rar *)(a->format->data);
 
1814
  if (rar->bytes_remaining == 0 &&
 
1815
    !(rar->main_flags & MHD_VOLUME && rar->file_flags & FHD_SPLIT_AFTER))
 
1816
  {
 
1817
    *buff = NULL;
 
1818
    *size = 0;
 
1819
    *offset = rar->offset;
 
1820
    if (rar->file_crc != rar->crc_calculated) {
 
1821
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1822
                        "File CRC error");
 
1823
      return (ARCHIVE_FATAL);
 
1824
    }
 
1825
    rar->entry_eof = 1;
 
1826
    return (ARCHIVE_EOF);
 
1827
  }
 
1828
 
 
1829
  *buff = rar_read_ahead(a, 1, &bytes_avail);
 
1830
  if (bytes_avail <= 0)
 
1831
  {
 
1832
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1833
                      "Truncated RAR file data");
 
1834
    return (ARCHIVE_FATAL);
 
1835
  }
 
1836
 
 
1837
  *size = bytes_avail;
 
1838
  *offset = rar->offset;
 
1839
  rar->offset += bytes_avail;
 
1840
  rar->offset_seek += bytes_avail;
 
1841
  rar->bytes_remaining -= bytes_avail;
 
1842
  rar->bytes_unconsumed = bytes_avail;
 
1843
  /* Calculate File CRC. */
 
1844
  rar->crc_calculated = crc32(rar->crc_calculated, *buff,
 
1845
    (unsigned)bytes_avail);
 
1846
  return (ARCHIVE_OK);
 
1847
}
 
1848
 
 
1849
static int
 
1850
read_data_compressed(struct archive_read *a, const void **buff, size_t *size,
 
1851
               int64_t *offset)
 
1852
{
 
1853
  struct rar *rar;
 
1854
  int64_t start, end, actualend;
 
1855
  size_t bs;
 
1856
  int ret = (ARCHIVE_OK), sym, code, lzss_offset, length, i;
 
1857
 
 
1858
  rar = (struct rar *)(a->format->data);
 
1859
 
 
1860
  do {
 
1861
    if (!rar->valid)
 
1862
      return (ARCHIVE_FATAL);
 
1863
    if (rar->ppmd_eod ||
 
1864
       (rar->dictionary_size && rar->offset >= rar->unp_size))
 
1865
    {
 
1866
      if (rar->unp_offset > 0) {
 
1867
        /*
 
1868
         * We have unprocessed extracted data. write it out.
 
1869
         */
 
1870
        *buff = rar->unp_buffer;
 
1871
        *size = rar->unp_offset;
 
1872
        *offset = rar->offset_outgoing;
 
1873
        rar->offset_outgoing += *size;
 
1874
        /* Calculate File CRC. */
 
1875
        rar->crc_calculated = crc32(rar->crc_calculated, *buff,
 
1876
          (unsigned)*size);
 
1877
        rar->unp_offset = 0;
 
1878
        return (ARCHIVE_OK);
 
1879
      }
 
1880
      *buff = NULL;
 
1881
      *size = 0;
 
1882
      *offset = rar->offset;
 
1883
      if (rar->file_crc != rar->crc_calculated) {
 
1884
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1885
                          "File CRC error");
 
1886
        return (ARCHIVE_FATAL);
 
1887
      }
 
1888
      rar->entry_eof = 1;
 
1889
      return (ARCHIVE_EOF);
 
1890
    }
 
1891
 
 
1892
    if (!rar->is_ppmd_block && rar->dictionary_size && rar->bytes_uncopied > 0)
 
1893
    {
 
1894
      if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
 
1895
        bs = rar->unp_buffer_size - rar->unp_offset;
 
1896
      else
 
1897
        bs = (size_t)rar->bytes_uncopied;
 
1898
      ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs);
 
1899
      if (ret != ARCHIVE_OK)
 
1900
        return (ret);
 
1901
      rar->offset += bs;
 
1902
      rar->bytes_uncopied -= bs;
 
1903
      if (*buff != NULL) {
 
1904
        rar->unp_offset = 0;
 
1905
        *size = rar->unp_buffer_size;
 
1906
        *offset = rar->offset_outgoing;
 
1907
        rar->offset_outgoing += *size;
 
1908
        /* Calculate File CRC. */
 
1909
        rar->crc_calculated = crc32(rar->crc_calculated, *buff,
 
1910
          (unsigned)*size);
 
1911
        return (ret);
 
1912
      }
 
1913
      continue;
 
1914
    }
 
1915
 
 
1916
    if (!rar->br.next_in &&
 
1917
      (ret = rar_br_preparation(a, &(rar->br))) < ARCHIVE_WARN)
 
1918
      return (ret);
 
1919
    if (rar->start_new_table && ((ret = parse_codes(a)) < (ARCHIVE_WARN)))
 
1920
      return (ret);
 
1921
 
 
1922
    if (rar->is_ppmd_block)
 
1923
    {
 
1924
      if ((sym = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 
1925
        &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 
1926
      {
 
1927
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1928
                          "Invalid symbol");
 
1929
        return (ARCHIVE_FATAL);
 
1930
      }
 
1931
      if(sym != rar->ppmd_escape)
 
1932
      {
 
1933
        lzss_emit_literal(rar, sym);
 
1934
        rar->bytes_uncopied++;
 
1935
      }
 
1936
      else
 
1937
      {
 
1938
        if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 
1939
          &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 
1940
        {
 
1941
          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1942
                            "Invalid symbol");
 
1943
          return (ARCHIVE_FATAL);
 
1944
        }
 
1945
 
 
1946
        switch(code)
 
1947
        {
 
1948
          case 0:
 
1949
            rar->start_new_table = 1;
 
1950
            return read_data_compressed(a, buff, size, offset);
 
1951
 
 
1952
          case 2:
 
1953
            rar->ppmd_eod = 1;/* End Of ppmd Data. */
 
1954
            continue;
 
1955
 
 
1956
          case 3:
 
1957
            archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 
1958
                              "Parsing filters is unsupported.");
 
1959
            return (ARCHIVE_FAILED);
 
1960
 
 
1961
          case 4:
 
1962
            lzss_offset = 0;
 
1963
            for (i = 2; i >= 0; i--)
 
1964
            {
 
1965
              if ((code = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 
1966
                &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 
1967
              {
 
1968
                archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1969
                                  "Invalid symbol");
 
1970
                return (ARCHIVE_FATAL);
 
1971
              }
 
1972
              lzss_offset |= code << (i * 8);
 
1973
            }
 
1974
            if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 
1975
              &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 
1976
            {
 
1977
              archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1978
                                "Invalid symbol");
 
1979
              return (ARCHIVE_FATAL);
 
1980
            }
 
1981
            lzss_emit_match(rar, lzss_offset + 2, length + 32);
 
1982
            rar->bytes_uncopied += length + 32;
 
1983
            break;
 
1984
 
 
1985
          case 5:
 
1986
            if ((length = __archive_ppmd7_functions.Ppmd7_DecodeSymbol(
 
1987
              &rar->ppmd7_context, &rar->range_dec.p)) < 0)
 
1988
            {
 
1989
              archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
1990
                                "Invalid symbol");
 
1991
              return (ARCHIVE_FATAL);
 
1992
            }
 
1993
            lzss_emit_match(rar, 1, length + 4);
 
1994
            rar->bytes_uncopied += length + 4;
 
1995
            break;
 
1996
 
 
1997
         default:
 
1998
           lzss_emit_literal(rar, sym);
 
1999
           rar->bytes_uncopied++;
 
2000
        }
 
2001
      }
 
2002
    }
 
2003
    else
 
2004
    {
 
2005
      start = rar->offset;
 
2006
      end = start + rar->dictionary_size;
 
2007
      rar->filterstart = INT64_MAX;
 
2008
 
 
2009
      if ((actualend = expand(a, end)) < 0)
 
2010
        return ((int)actualend);
 
2011
 
 
2012
      rar->bytes_uncopied = actualend - start;
 
2013
      if (rar->bytes_uncopied == 0) {
 
2014
          /* Broken RAR files cause this case.
 
2015
          * NOTE: If this case were possible on a normal RAR file
 
2016
          * we would find out where it was actually bad and
 
2017
          * what we would do to solve it. */
 
2018
          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2019
                            "Internal error extracting RAR file");
 
2020
          return (ARCHIVE_FATAL);
 
2021
      }
 
2022
    }
 
2023
    if (rar->bytes_uncopied > (rar->unp_buffer_size - rar->unp_offset))
 
2024
      bs = rar->unp_buffer_size - rar->unp_offset;
 
2025
    else
 
2026
      bs = (size_t)rar->bytes_uncopied;
 
2027
    ret = copy_from_lzss_window(a, buff, rar->offset, (int)bs);
 
2028
    if (ret != ARCHIVE_OK)
 
2029
      return (ret);
 
2030
    rar->offset += bs;
 
2031
    rar->bytes_uncopied -= bs;
 
2032
    /*
 
2033
     * If *buff is NULL, it means unp_buffer is not full.
 
2034
     * So we have to continue extracting a RAR file.
 
2035
     */
 
2036
  } while (*buff == NULL);
 
2037
 
 
2038
  rar->unp_offset = 0;
 
2039
  *size = rar->unp_buffer_size;
 
2040
  *offset = rar->offset_outgoing;
 
2041
  rar->offset_outgoing += *size;
 
2042
  /* Calculate File CRC. */
 
2043
  rar->crc_calculated = crc32(rar->crc_calculated, *buff, (unsigned)*size);
 
2044
  return ret;
 
2045
}
 
2046
 
 
2047
static int
 
2048
parse_codes(struct archive_read *a)
 
2049
{
 
2050
  int i, j, val, n, r;
 
2051
  unsigned char bitlengths[MAX_SYMBOLS], zerocount, ppmd_flags;
 
2052
  unsigned int maxorder;
 
2053
  struct huffman_code precode;
 
2054
  struct rar *rar = (struct rar *)(a->format->data);
 
2055
  struct rar_br *br = &(rar->br);
 
2056
 
 
2057
  free_codes(a);
 
2058
 
 
2059
  /* Skip to the next byte */
 
2060
  rar_br_consume_unalined_bits(br);
 
2061
 
 
2062
  /* PPMd block flag */
 
2063
  if (!rar_br_read_ahead(a, br, 1))
 
2064
    goto truncated_data;
 
2065
  if ((rar->is_ppmd_block = rar_br_bits(br, 1)) != 0)
 
2066
  {
 
2067
    rar_br_consume(br, 1);
 
2068
    if (!rar_br_read_ahead(a, br, 7))
 
2069
      goto truncated_data;
 
2070
    ppmd_flags = rar_br_bits(br, 7);
 
2071
    rar_br_consume(br, 7);
 
2072
 
 
2073
    /* Memory is allocated in MB */
 
2074
    if (ppmd_flags & 0x20)
 
2075
    {
 
2076
      if (!rar_br_read_ahead(a, br, 8))
 
2077
        goto truncated_data;
 
2078
      rar->dictionary_size = (rar_br_bits(br, 8) + 1) << 20;
 
2079
      rar_br_consume(br, 8);
 
2080
    }
 
2081
 
 
2082
    if (ppmd_flags & 0x40)
 
2083
    {
 
2084
      if (!rar_br_read_ahead(a, br, 8))
 
2085
        goto truncated_data;
 
2086
      rar->ppmd_escape = rar->ppmd7_context.InitEsc = rar_br_bits(br, 8);
 
2087
      rar_br_consume(br, 8);
 
2088
    }
 
2089
    else
 
2090
      rar->ppmd_escape = 2;
 
2091
 
 
2092
    if (ppmd_flags & 0x20)
 
2093
    {
 
2094
      maxorder = (ppmd_flags & 0x1F) + 1;
 
2095
      if(maxorder > 16)
 
2096
        maxorder = 16 + (maxorder - 16) * 3;
 
2097
 
 
2098
      if (maxorder == 1)
 
2099
      {
 
2100
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2101
                          "Truncated RAR file data");
 
2102
        return (ARCHIVE_FATAL);
 
2103
      }
 
2104
 
 
2105
      /* Make sure ppmd7_contest is freed before Ppmd7_Construct
 
2106
       * because reading a broken file cause this abnormal sequence. */
 
2107
      __archive_ppmd7_functions.Ppmd7_Free(&rar->ppmd7_context, &g_szalloc);
 
2108
 
 
2109
      rar->bytein.a = a;
 
2110
      rar->bytein.Read = &ppmd_read;
 
2111
      __archive_ppmd7_functions.PpmdRAR_RangeDec_CreateVTable(&rar->range_dec);
 
2112
      rar->range_dec.Stream = &rar->bytein;
 
2113
      __archive_ppmd7_functions.Ppmd7_Construct(&rar->ppmd7_context);
 
2114
 
 
2115
      if (!__archive_ppmd7_functions.Ppmd7_Alloc(&rar->ppmd7_context,
 
2116
        rar->dictionary_size, &g_szalloc))
 
2117
      {
 
2118
        archive_set_error(&a->archive, ENOMEM,
 
2119
                          "Out of memory");
 
2120
        return (ARCHIVE_FATAL);
 
2121
      }
 
2122
      if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
 
2123
      {
 
2124
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2125
                          "Unable to initialize PPMd range decoder");
 
2126
        return (ARCHIVE_FATAL);
 
2127
      }
 
2128
      __archive_ppmd7_functions.Ppmd7_Init(&rar->ppmd7_context, maxorder);
 
2129
      rar->ppmd_valid = 1;
 
2130
    }
 
2131
    else
 
2132
    {
 
2133
      if (!rar->ppmd_valid) {
 
2134
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2135
                          "Invalid PPMd sequence");
 
2136
        return (ARCHIVE_FATAL);
 
2137
      }
 
2138
      if (!__archive_ppmd7_functions.PpmdRAR_RangeDec_Init(&rar->range_dec))
 
2139
      {
 
2140
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2141
                          "Unable to initialize PPMd range decoder");
 
2142
        return (ARCHIVE_FATAL);
 
2143
      }
 
2144
    }
 
2145
  }
 
2146
  else
 
2147
  {
 
2148
    rar_br_consume(br, 1);
 
2149
 
 
2150
    /* Keep existing table flag */
 
2151
    if (!rar_br_read_ahead(a, br, 1))
 
2152
      goto truncated_data;
 
2153
    if (!rar_br_bits(br, 1))
 
2154
      memset(rar->lengthtable, 0, sizeof(rar->lengthtable));
 
2155
    rar_br_consume(br, 1);
 
2156
 
 
2157
    memset(&bitlengths, 0, sizeof(bitlengths));
 
2158
    for (i = 0; i < MAX_SYMBOLS;)
 
2159
    {
 
2160
      if (!rar_br_read_ahead(a, br, 4))
 
2161
        goto truncated_data;
 
2162
      bitlengths[i++] = rar_br_bits(br, 4);
 
2163
      rar_br_consume(br, 4);
 
2164
      if (bitlengths[i-1] == 0xF)
 
2165
      {
 
2166
        if (!rar_br_read_ahead(a, br, 4))
 
2167
          goto truncated_data;
 
2168
        zerocount = rar_br_bits(br, 4);
 
2169
        rar_br_consume(br, 4);
 
2170
        if (zerocount)
 
2171
        {
 
2172
          i--;
 
2173
          for (j = 0; j < zerocount + 2 && i < MAX_SYMBOLS; j++)
 
2174
            bitlengths[i++] = 0;
 
2175
        }
 
2176
      }
 
2177
    }
 
2178
 
 
2179
    memset(&precode, 0, sizeof(precode));
 
2180
    r = create_code(a, &precode, bitlengths, MAX_SYMBOLS, MAX_SYMBOL_LENGTH);
 
2181
    if (r != ARCHIVE_OK) {
 
2182
      free(precode.tree);
 
2183
      free(precode.table);
 
2184
      return (r);
 
2185
    }
 
2186
 
 
2187
    for (i = 0; i < HUFFMAN_TABLE_SIZE;)
 
2188
    {
 
2189
      if ((val = read_next_symbol(a, &precode)) < 0) {
 
2190
        free(precode.tree);
 
2191
        free(precode.table);
 
2192
        return (ARCHIVE_FATAL);
 
2193
      }
 
2194
      if (val < 16)
 
2195
      {
 
2196
        rar->lengthtable[i] = (rar->lengthtable[i] + val) & 0xF;
 
2197
        i++;
 
2198
      }
 
2199
      else if (val < 18)
 
2200
      {
 
2201
        if (i == 0)
 
2202
        {
 
2203
          free(precode.tree);
 
2204
          free(precode.table);
 
2205
          archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2206
                            "Internal error extracting RAR file.");
 
2207
          return (ARCHIVE_FATAL);
 
2208
        }
 
2209
 
 
2210
        if(val == 16) {
 
2211
          if (!rar_br_read_ahead(a, br, 3)) {
 
2212
            free(precode.tree);
 
2213
            free(precode.table);
 
2214
            goto truncated_data;
 
2215
          }
 
2216
          n = rar_br_bits(br, 3) + 3;
 
2217
          rar_br_consume(br, 3);
 
2218
        } else {
 
2219
          if (!rar_br_read_ahead(a, br, 7)) {
 
2220
            free(precode.tree);
 
2221
            free(precode.table);
 
2222
            goto truncated_data;
 
2223
          }
 
2224
          n = rar_br_bits(br, 7) + 11;
 
2225
          rar_br_consume(br, 7);
 
2226
        }
 
2227
 
 
2228
        for (j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
 
2229
        {
 
2230
          rar->lengthtable[i] = rar->lengthtable[i-1];
 
2231
          i++;
 
2232
        }
 
2233
      }
 
2234
      else
 
2235
      {
 
2236
        if(val == 18) {
 
2237
          if (!rar_br_read_ahead(a, br, 3)) {
 
2238
            free(precode.tree);
 
2239
            free(precode.table);
 
2240
            goto truncated_data;
 
2241
          }
 
2242
          n = rar_br_bits(br, 3) + 3;
 
2243
          rar_br_consume(br, 3);
 
2244
        } else {
 
2245
          if (!rar_br_read_ahead(a, br, 7)) {
 
2246
            free(precode.tree);
 
2247
            free(precode.table);
 
2248
            goto truncated_data;
 
2249
          }
 
2250
          n = rar_br_bits(br, 7) + 11;
 
2251
          rar_br_consume(br, 7);
 
2252
        }
 
2253
 
 
2254
        for(j = 0; j < n && i < HUFFMAN_TABLE_SIZE; j++)
 
2255
          rar->lengthtable[i++] = 0;
 
2256
      }
 
2257
    }
 
2258
    free(precode.tree);
 
2259
    free(precode.table);
 
2260
 
 
2261
    r = create_code(a, &rar->maincode, &rar->lengthtable[0], MAINCODE_SIZE,
 
2262
                MAX_SYMBOL_LENGTH);
 
2263
    if (r != ARCHIVE_OK)
 
2264
      return (r);
 
2265
    r = create_code(a, &rar->offsetcode, &rar->lengthtable[MAINCODE_SIZE],
 
2266
                OFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
 
2267
    if (r != ARCHIVE_OK)
 
2268
      return (r);
 
2269
    r = create_code(a, &rar->lowoffsetcode,
 
2270
                &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE],
 
2271
                LOWOFFSETCODE_SIZE, MAX_SYMBOL_LENGTH);
 
2272
    if (r != ARCHIVE_OK)
 
2273
      return (r);
 
2274
    r = create_code(a, &rar->lengthcode,
 
2275
                &rar->lengthtable[MAINCODE_SIZE + OFFSETCODE_SIZE +
 
2276
                LOWOFFSETCODE_SIZE], LENGTHCODE_SIZE, MAX_SYMBOL_LENGTH);
 
2277
    if (r != ARCHIVE_OK)
 
2278
      return (r);
 
2279
  }
 
2280
 
 
2281
  if (!rar->dictionary_size || !rar->lzss.window)
 
2282
  {
 
2283
    /* Seems as though dictionary sizes are not used. Even so, minimize
 
2284
     * memory usage as much as possible.
 
2285
     */
 
2286
    void *new_window;
 
2287
    unsigned int new_size;
 
2288
 
 
2289
    if (rar->unp_size >= DICTIONARY_MAX_SIZE)
 
2290
      new_size = DICTIONARY_MAX_SIZE;
 
2291
    else
 
2292
      new_size = rar_fls((unsigned int)rar->unp_size) << 1;
 
2293
    new_window = realloc(rar->lzss.window, new_size);
 
2294
    if (new_window == NULL) {
 
2295
      archive_set_error(&a->archive, ENOMEM,
 
2296
                        "Unable to allocate memory for uncompressed data.");
 
2297
      return (ARCHIVE_FATAL);
 
2298
    }
 
2299
    rar->lzss.window = (unsigned char *)new_window;
 
2300
    rar->dictionary_size = new_size;
 
2301
    memset(rar->lzss.window, 0, rar->dictionary_size);
 
2302
    rar->lzss.mask = rar->dictionary_size - 1;
 
2303
  }
 
2304
 
 
2305
  rar->start_new_table = 0;
 
2306
  return (ARCHIVE_OK);
 
2307
truncated_data:
 
2308
  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2309
                    "Truncated RAR file data");
 
2310
  rar->valid = 0;
 
2311
  return (ARCHIVE_FATAL);
 
2312
}
 
2313
 
 
2314
static void
 
2315
free_codes(struct archive_read *a)
 
2316
{
 
2317
  struct rar *rar = (struct rar *)(a->format->data);
 
2318
  free(rar->maincode.tree);
 
2319
  free(rar->offsetcode.tree);
 
2320
  free(rar->lowoffsetcode.tree);
 
2321
  free(rar->lengthcode.tree);
 
2322
  free(rar->maincode.table);
 
2323
  free(rar->offsetcode.table);
 
2324
  free(rar->lowoffsetcode.table);
 
2325
  free(rar->lengthcode.table);
 
2326
  memset(&rar->maincode, 0, sizeof(rar->maincode));
 
2327
  memset(&rar->offsetcode, 0, sizeof(rar->offsetcode));
 
2328
  memset(&rar->lowoffsetcode, 0, sizeof(rar->lowoffsetcode));
 
2329
  memset(&rar->lengthcode, 0, sizeof(rar->lengthcode));
 
2330
}
 
2331
 
 
2332
 
 
2333
static int
 
2334
read_next_symbol(struct archive_read *a, struct huffman_code *code)
 
2335
{
 
2336
  unsigned char bit;
 
2337
  unsigned int bits;
 
2338
  int length, value, node;
 
2339
  struct rar *rar;
 
2340
  struct rar_br *br;
 
2341
 
 
2342
  if (!code->table)
 
2343
  {
 
2344
    if (make_table(a, code) != (ARCHIVE_OK))
 
2345
      return -1;
 
2346
  }
 
2347
 
 
2348
  rar = (struct rar *)(a->format->data);
 
2349
  br = &(rar->br);
 
2350
 
 
2351
  /* Look ahead (peek) at bits */
 
2352
  if (!rar_br_read_ahead(a, br, code->tablesize)) {
 
2353
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2354
                      "Truncated RAR file data");
 
2355
    rar->valid = 0;
 
2356
    return -1;
 
2357
  }
 
2358
  bits = rar_br_bits(br, code->tablesize);
 
2359
 
 
2360
  length = code->table[bits].length;
 
2361
  value = code->table[bits].value;
 
2362
 
 
2363
  if (length < 0)
 
2364
  {
 
2365
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2366
                      "Invalid prefix code in bitstream");
 
2367
    return -1;
 
2368
  }
 
2369
 
 
2370
  if (length <= code->tablesize)
 
2371
  {
 
2372
    /* Skip length bits */
 
2373
    rar_br_consume(br, length);
 
2374
    return value;
 
2375
  }
 
2376
 
 
2377
  /* Skip tablesize bits */
 
2378
  rar_br_consume(br, code->tablesize);
 
2379
 
 
2380
  node = value;
 
2381
  while (!(code->tree[node].branches[0] ==
 
2382
    code->tree[node].branches[1]))
 
2383
  {
 
2384
    if (!rar_br_read_ahead(a, br, 1)) {
 
2385
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2386
                        "Truncated RAR file data");
 
2387
      rar->valid = 0;
 
2388
      return -1;
 
2389
    }
 
2390
    bit = rar_br_bits(br, 1);
 
2391
    rar_br_consume(br, 1);
 
2392
 
 
2393
    if (code->tree[node].branches[bit] < 0)
 
2394
    {
 
2395
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2396
                        "Invalid prefix code in bitstream");
 
2397
      return -1;
 
2398
    }
 
2399
    node = code->tree[node].branches[bit];
 
2400
  }
 
2401
 
 
2402
  return code->tree[node].branches[0];
 
2403
}
 
2404
 
 
2405
static int
 
2406
create_code(struct archive_read *a, struct huffman_code *code,
 
2407
            unsigned char *lengths, int numsymbols, char maxlength)
 
2408
{
 
2409
  int i, j, codebits = 0, symbolsleft = numsymbols;
 
2410
 
 
2411
  code->numentries = 0;
 
2412
  code->numallocatedentries = 0;
 
2413
  if (new_node(code) < 0) {
 
2414
    archive_set_error(&a->archive, ENOMEM,
 
2415
                      "Unable to allocate memory for node data.");
 
2416
    return (ARCHIVE_FATAL);
 
2417
  }
 
2418
  code->numentries = 1;
 
2419
  code->minlength = INT_MAX;
 
2420
  code->maxlength = INT_MIN;
 
2421
  codebits = 0;
 
2422
  for(i = 1; i <= maxlength; i++)
 
2423
  {
 
2424
    for(j = 0; j < numsymbols; j++)
 
2425
    {
 
2426
      if (lengths[j] != i) continue;
 
2427
      if (add_value(a, code, j, codebits, i) != ARCHIVE_OK)
 
2428
        return (ARCHIVE_FATAL);
 
2429
      codebits++;
 
2430
      if (--symbolsleft <= 0) { break; break; }
 
2431
    }
 
2432
    codebits <<= 1;
 
2433
  }
 
2434
  return (ARCHIVE_OK);
 
2435
}
 
2436
 
 
2437
static int
 
2438
add_value(struct archive_read *a, struct huffman_code *code, int value,
 
2439
          int codebits, int length)
 
2440
{
 
2441
  int repeatpos, lastnode, bitpos, bit, repeatnode, nextnode;
 
2442
 
 
2443
  free(code->table);
 
2444
  code->table = NULL;
 
2445
 
 
2446
  if(length > code->maxlength)
 
2447
    code->maxlength = length;
 
2448
  if(length < code->minlength)
 
2449
    code->minlength = length;
 
2450
 
 
2451
  repeatpos = -1;
 
2452
  if (repeatpos == 0 || (repeatpos >= 0
 
2453
    && (((codebits >> (repeatpos - 1)) & 3) == 0
 
2454
    || ((codebits >> (repeatpos - 1)) & 3) == 3)))
 
2455
  {
 
2456
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2457
                      "Invalid repeat position");
 
2458
    return (ARCHIVE_FATAL);
 
2459
  }
 
2460
 
 
2461
  lastnode = 0;
 
2462
  for (bitpos = length - 1; bitpos >= 0; bitpos--)
 
2463
  {
 
2464
    bit = (codebits >> bitpos) & 1;
 
2465
 
 
2466
    /* Leaf node check */
 
2467
    if (code->tree[lastnode].branches[0] ==
 
2468
      code->tree[lastnode].branches[1])
 
2469
    {
 
2470
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2471
                        "Prefix found");
 
2472
      return (ARCHIVE_FATAL);
 
2473
    }
 
2474
 
 
2475
    if (bitpos == repeatpos)
 
2476
    {
 
2477
      /* Open branch check */
 
2478
      if (!(code->tree[lastnode].branches[bit] < 0))
 
2479
      {
 
2480
        archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2481
                          "Invalid repeating code");
 
2482
        return (ARCHIVE_FATAL);
 
2483
      }
 
2484
 
 
2485
      if ((repeatnode = new_node(code)) < 0) {
 
2486
        archive_set_error(&a->archive, ENOMEM,
 
2487
                          "Unable to allocate memory for node data.");
 
2488
        return (ARCHIVE_FATAL);
 
2489
      }
 
2490
      if ((nextnode = new_node(code)) < 0) {
 
2491
        archive_set_error(&a->archive, ENOMEM,
 
2492
                          "Unable to allocate memory for node data.");
 
2493
        return (ARCHIVE_FATAL);
 
2494
      }
 
2495
 
 
2496
      /* Set branches */
 
2497
      code->tree[lastnode].branches[bit] = repeatnode;
 
2498
      code->tree[repeatnode].branches[bit] = repeatnode;
 
2499
      code->tree[repeatnode].branches[bit^1] = nextnode;
 
2500
      lastnode = nextnode;
 
2501
 
 
2502
      bitpos++; /* terminating bit already handled, skip it */
 
2503
    }
 
2504
    else
 
2505
    {
 
2506
      /* Open branch check */
 
2507
      if (code->tree[lastnode].branches[bit] < 0)
 
2508
      {
 
2509
        if (new_node(code) < 0) {
 
2510
          archive_set_error(&a->archive, ENOMEM,
 
2511
                            "Unable to allocate memory for node data.");
 
2512
          return (ARCHIVE_FATAL);
 
2513
        }
 
2514
        code->tree[lastnode].branches[bit] = code->numentries++;
 
2515
      }
 
2516
 
 
2517
      /* set to branch */
 
2518
      lastnode = code->tree[lastnode].branches[bit];
 
2519
    }
 
2520
  }
 
2521
 
 
2522
  if (!(code->tree[lastnode].branches[0] == -1
 
2523
    && code->tree[lastnode].branches[1] == -2))
 
2524
  {
 
2525
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2526
                      "Prefix found");
 
2527
    return (ARCHIVE_FATAL);
 
2528
  }
 
2529
 
 
2530
  /* Set leaf value */
 
2531
  code->tree[lastnode].branches[0] = value;
 
2532
  code->tree[lastnode].branches[1] = value;
 
2533
 
 
2534
  return (ARCHIVE_OK);
 
2535
}
 
2536
 
 
2537
static int
 
2538
new_node(struct huffman_code *code)
 
2539
{
 
2540
  void *new_tree;
 
2541
  if (code->numallocatedentries == code->numentries) {
 
2542
    int new_num_entries = 256;
 
2543
    if (code->numentries > 0) {
 
2544
        new_num_entries = code->numentries * 2;
 
2545
    }
 
2546
    new_tree = realloc(code->tree, new_num_entries * sizeof(*code->tree));
 
2547
    if (new_tree == NULL)
 
2548
        return (-1);
 
2549
    code->tree = (struct huffman_tree_node *)new_tree;
 
2550
    code->numallocatedentries = new_num_entries;
 
2551
  }
 
2552
  code->tree[code->numentries].branches[0] = -1;
 
2553
  code->tree[code->numentries].branches[1] = -2;
 
2554
  return 1;
 
2555
}
 
2556
 
 
2557
static int
 
2558
make_table(struct archive_read *a, struct huffman_code *code)
 
2559
{
 
2560
  if (code->maxlength < code->minlength || code->maxlength > 10)
 
2561
    code->tablesize = 10;
 
2562
  else
 
2563
    code->tablesize = code->maxlength;
 
2564
 
 
2565
  code->table =
 
2566
    (struct huffman_table_entry *)calloc(1, sizeof(*code->table)
 
2567
    * ((size_t)1 << code->tablesize));
 
2568
 
 
2569
  return make_table_recurse(a, code, 0, code->table, 0, code->tablesize);
 
2570
}
 
2571
 
 
2572
static int
 
2573
make_table_recurse(struct archive_read *a, struct huffman_code *code, int node,
 
2574
                   struct huffman_table_entry *table, int depth,
 
2575
                   int maxdepth)
 
2576
{
 
2577
  int currtablesize, i, ret = (ARCHIVE_OK);
 
2578
 
 
2579
  if (!code->tree)
 
2580
  {
 
2581
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2582
                      "Huffman tree was not created.");
 
2583
    return (ARCHIVE_FATAL);
 
2584
  }
 
2585
  if (node < 0 || node >= code->numentries)
 
2586
  {
 
2587
    archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2588
                      "Invalid location to Huffman tree specified.");
 
2589
    return (ARCHIVE_FATAL);
 
2590
  }
 
2591
 
 
2592
  currtablesize = 1 << (maxdepth - depth);
 
2593
 
 
2594
  if (code->tree[node].branches[0] ==
 
2595
    code->tree[node].branches[1])
 
2596
  {
 
2597
    for(i = 0; i < currtablesize; i++)
 
2598
    {
 
2599
      table[i].length = depth;
 
2600
      table[i].value = code->tree[node].branches[0];
 
2601
    }
 
2602
  }
 
2603
  else if (node < 0)
 
2604
  {
 
2605
    for(i = 0; i < currtablesize; i++)
 
2606
      table[i].length = -1;
 
2607
  }
 
2608
  else
 
2609
  {
 
2610
    if(depth == maxdepth)
 
2611
    {
 
2612
      table[0].length = maxdepth + 1;
 
2613
      table[0].value = node;
 
2614
    }
 
2615
    else
 
2616
    {
 
2617
      ret |= make_table_recurse(a, code, code->tree[node].branches[0], table,
 
2618
                                depth + 1, maxdepth);
 
2619
      ret |= make_table_recurse(a, code, code->tree[node].branches[1],
 
2620
                         table + currtablesize / 2, depth + 1, maxdepth);
 
2621
    }
 
2622
  }
 
2623
  return ret;
 
2624
}
 
2625
 
 
2626
static int64_t
 
2627
expand(struct archive_read *a, int64_t end)
 
2628
{
 
2629
  static const unsigned char lengthbases[] =
 
2630
    {   0,   1,   2,   3,   4,   5,   6,
 
2631
        7,   8,  10,  12,  14,  16,  20,
 
2632
       24,  28,  32,  40,  48,  56,  64,
 
2633
       80,  96, 112, 128, 160, 192, 224 };
 
2634
  static const unsigned char lengthbits[] =
 
2635
    { 0, 0, 0, 0, 0, 0, 0,
 
2636
      0, 1, 1, 1, 1, 2, 2,
 
2637
      2, 2, 3, 3, 3, 3, 4,
 
2638
      4, 4, 4, 5, 5, 5, 5 };
 
2639
  static const unsigned int offsetbases[] =
 
2640
    {       0,       1,       2,       3,       4,       6,
 
2641
            8,      12,      16,      24,      32,      48,
 
2642
           64,      96,     128,     192,     256,     384,
 
2643
          512,     768,    1024,    1536,    2048,    3072,
 
2644
         4096,    6144,    8192,   12288,   16384,   24576,
 
2645
        32768,   49152,   65536,   98304,  131072,  196608,
 
2646
       262144,  327680,  393216,  458752,  524288,  589824,
 
2647
       655360,  720896,  786432,  851968,  917504,  983040,
 
2648
      1048576, 1310720, 1572864, 1835008, 2097152, 2359296,
 
2649
      2621440, 2883584, 3145728, 3407872, 3670016, 3932160 };
 
2650
  static const unsigned char offsetbits[] =
 
2651
    {  0,  0,  0,  0,  1,  1,  2,  2,  3,  3,  4,  4,
 
2652
       5,  5,  6,  6,  7,  7,  8,  8,  9,  9, 10, 10,
 
2653
      11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16,
 
2654
      16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
 
2655
      18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18 };
 
2656
  static const unsigned char shortbases[] =
 
2657
    { 0, 4, 8, 16, 32, 64, 128, 192 };
 
2658
  static const unsigned char shortbits[] =
 
2659
    { 2, 2, 3, 4, 5, 6, 6, 6 };
 
2660
 
 
2661
  int symbol, offs, len, offsindex, lensymbol, i, offssymbol, lowoffsetsymbol;
 
2662
  unsigned char newfile;
 
2663
  struct rar *rar = (struct rar *)(a->format->data);
 
2664
  struct rar_br *br = &(rar->br);
 
2665
 
 
2666
  if (rar->filterstart < end)
 
2667
    end = rar->filterstart;
 
2668
 
 
2669
  while (1)
 
2670
  {
 
2671
    if (rar->output_last_match &&
 
2672
      lzss_position(&rar->lzss) + rar->lastlength <= end)
 
2673
    {
 
2674
      lzss_emit_match(rar, rar->lastoffset, rar->lastlength);
 
2675
      rar->output_last_match = 0;
 
2676
    }
 
2677
 
 
2678
    if(rar->is_ppmd_block || rar->output_last_match ||
 
2679
      lzss_position(&rar->lzss) >= end)
 
2680
      return lzss_position(&rar->lzss);
 
2681
 
 
2682
    if ((symbol = read_next_symbol(a, &rar->maincode)) < 0)
 
2683
      return (ARCHIVE_FATAL);
 
2684
    rar->output_last_match = 0;
 
2685
 
 
2686
    if (symbol < 256)
 
2687
    {
 
2688
      lzss_emit_literal(rar, symbol);
 
2689
      continue;
 
2690
    }
 
2691
    else if (symbol == 256)
 
2692
    {
 
2693
      if (!rar_br_read_ahead(a, br, 1))
 
2694
        goto truncated_data;
 
2695
      newfile = !rar_br_bits(br, 1);
 
2696
      rar_br_consume(br, 1);
 
2697
 
 
2698
      if(newfile)
 
2699
      {
 
2700
        rar->start_new_block = 1;
 
2701
        if (!rar_br_read_ahead(a, br, 1))
 
2702
          goto truncated_data;
 
2703
        rar->start_new_table = rar_br_bits(br, 1);
 
2704
        rar_br_consume(br, 1);
 
2705
        return lzss_position(&rar->lzss);
 
2706
      }
 
2707
      else
 
2708
      {
 
2709
        if (parse_codes(a) != ARCHIVE_OK)
 
2710
          return (ARCHIVE_FATAL);
 
2711
        continue;
 
2712
      }
 
2713
    }
 
2714
    else if(symbol==257)
 
2715
    {
 
2716
      archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
 
2717
                        "Parsing filters is unsupported.");
 
2718
      return (ARCHIVE_FAILED);
 
2719
    }
 
2720
    else if(symbol==258)
 
2721
    {
 
2722
      if(rar->lastlength == 0)
 
2723
        continue;
 
2724
 
 
2725
      offs = rar->lastoffset;
 
2726
      len = rar->lastlength;
 
2727
    }
 
2728
    else if (symbol <= 262)
 
2729
    {
 
2730
      offsindex = symbol - 259;
 
2731
      offs = rar->oldoffset[offsindex];
 
2732
 
 
2733
      if ((lensymbol = read_next_symbol(a, &rar->lengthcode)) < 0)
 
2734
        goto bad_data;
 
2735
      if (lensymbol > (int)(sizeof(lengthbases)/sizeof(lengthbases[0])))
 
2736
        goto bad_data;
 
2737
      if (lensymbol > (int)(sizeof(lengthbits)/sizeof(lengthbits[0])))
 
2738
        goto bad_data;
 
2739
      len = lengthbases[lensymbol] + 2;
 
2740
      if (lengthbits[lensymbol] > 0) {
 
2741
        if (!rar_br_read_ahead(a, br, lengthbits[lensymbol]))
 
2742
          goto truncated_data;
 
2743
        len += rar_br_bits(br, lengthbits[lensymbol]);
 
2744
        rar_br_consume(br, lengthbits[lensymbol]);
 
2745
      }
 
2746
 
 
2747
      for (i = offsindex; i > 0; i--)
 
2748
        rar->oldoffset[i] = rar->oldoffset[i-1];
 
2749
      rar->oldoffset[0] = offs;
 
2750
    }
 
2751
    else if(symbol<=270)
 
2752
    {
 
2753
      offs = shortbases[symbol-263] + 1;
 
2754
      if(shortbits[symbol-263] > 0) {
 
2755
        if (!rar_br_read_ahead(a, br, shortbits[symbol-263]))
 
2756
          goto truncated_data;
 
2757
        offs += rar_br_bits(br, shortbits[symbol-263]);
 
2758
        rar_br_consume(br, shortbits[symbol-263]);
 
2759
      }
 
2760
 
 
2761
      len = 2;
 
2762
 
 
2763
      for(i = 3; i > 0; i--)
 
2764
        rar->oldoffset[i] = rar->oldoffset[i-1];
 
2765
      rar->oldoffset[0] = offs;
 
2766
    }
 
2767
    else
 
2768
    {
 
2769
      if (symbol-271 > (int)(sizeof(lengthbases)/sizeof(lengthbases[0])))
 
2770
        goto bad_data;
 
2771
      if (symbol-271 > (int)(sizeof(lengthbits)/sizeof(lengthbits[0])))
 
2772
        goto bad_data;
 
2773
      len = lengthbases[symbol-271]+3;
 
2774
      if(lengthbits[symbol-271] > 0) {
 
2775
        if (!rar_br_read_ahead(a, br, lengthbits[symbol-271]))
 
2776
          goto truncated_data;
 
2777
        len += rar_br_bits(br, lengthbits[symbol-271]);
 
2778
        rar_br_consume(br, lengthbits[symbol-271]);
 
2779
      }
 
2780
 
 
2781
      if ((offssymbol = read_next_symbol(a, &rar->offsetcode)) < 0)
 
2782
        goto bad_data;
 
2783
      if (offssymbol > (int)(sizeof(offsetbases)/sizeof(offsetbases[0])))
 
2784
        goto bad_data;
 
2785
      if (offssymbol > (int)(sizeof(offsetbits)/sizeof(offsetbits[0])))
 
2786
        goto bad_data;
 
2787
      offs = offsetbases[offssymbol]+1;
 
2788
      if(offsetbits[offssymbol] > 0)
 
2789
      {
 
2790
        if(offssymbol > 9)
 
2791
        {
 
2792
          if(offsetbits[offssymbol] > 4) {
 
2793
            if (!rar_br_read_ahead(a, br, offsetbits[offssymbol] - 4))
 
2794
              goto truncated_data;
 
2795
            offs += rar_br_bits(br, offsetbits[offssymbol] - 4) << 4;
 
2796
            rar_br_consume(br, offsetbits[offssymbol] - 4);
 
2797
          }
 
2798
 
 
2799
          if(rar->numlowoffsetrepeats > 0)
 
2800
          {
 
2801
            rar->numlowoffsetrepeats--;
 
2802
            offs += rar->lastlowoffset;
 
2803
          }
 
2804
          else
 
2805
          {
 
2806
            if ((lowoffsetsymbol =
 
2807
              read_next_symbol(a, &rar->lowoffsetcode)) < 0)
 
2808
              return (ARCHIVE_FATAL);
 
2809
            if(lowoffsetsymbol == 16)
 
2810
            {
 
2811
              rar->numlowoffsetrepeats = 15;
 
2812
              offs += rar->lastlowoffset;
 
2813
            }
 
2814
            else
 
2815
            {
 
2816
              offs += lowoffsetsymbol;
 
2817
              rar->lastlowoffset = lowoffsetsymbol;
 
2818
            }
 
2819
          }
 
2820
        }
 
2821
        else {
 
2822
          if (!rar_br_read_ahead(a, br, offsetbits[offssymbol]))
 
2823
            goto truncated_data;
 
2824
          offs += rar_br_bits(br, offsetbits[offssymbol]);
 
2825
          rar_br_consume(br, offsetbits[offssymbol]);
 
2826
        }
 
2827
      }
 
2828
 
 
2829
      if (offs >= 0x40000)
 
2830
        len++;
 
2831
      if (offs >= 0x2000)
 
2832
        len++;
 
2833
 
 
2834
      for(i = 3; i > 0; i--)
 
2835
        rar->oldoffset[i] = rar->oldoffset[i-1];
 
2836
      rar->oldoffset[0] = offs;
 
2837
    }
 
2838
 
 
2839
    rar->lastoffset = offs;
 
2840
    rar->lastlength = len;
 
2841
    rar->output_last_match = 1;
 
2842
  }
 
2843
truncated_data:
 
2844
  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2845
                    "Truncated RAR file data");
 
2846
  rar->valid = 0;
 
2847
  return (ARCHIVE_FATAL);
 
2848
bad_data:
 
2849
  archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2850
                    "Bad RAR file data");
 
2851
  return (ARCHIVE_FATAL);
 
2852
}
 
2853
 
 
2854
static int
 
2855
copy_from_lzss_window(struct archive_read *a, const void **buffer,
 
2856
                        int64_t startpos, int length)
 
2857
{
 
2858
  int windowoffs, firstpart;
 
2859
  struct rar *rar = (struct rar *)(a->format->data);
 
2860
 
 
2861
  if (!rar->unp_buffer)
 
2862
  {
 
2863
    if ((rar->unp_buffer = malloc(rar->unp_buffer_size)) == NULL)
 
2864
    {
 
2865
      archive_set_error(&a->archive, ENOMEM,
 
2866
                        "Unable to allocate memory for uncompressed data.");
 
2867
      return (ARCHIVE_FATAL);
 
2868
    }
 
2869
  }
 
2870
 
 
2871
  windowoffs = lzss_offset_for_position(&rar->lzss, startpos);
 
2872
  if(windowoffs + length <= lzss_size(&rar->lzss))
 
2873
    memcpy(&rar->unp_buffer[rar->unp_offset], &rar->lzss.window[windowoffs],
 
2874
           length);
 
2875
  else
 
2876
  {
 
2877
    firstpart = lzss_size(&rar->lzss) - windowoffs;
 
2878
    if (firstpart < 0) {
 
2879
      archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
 
2880
                        "Bad RAR file data");
 
2881
      return (ARCHIVE_FATAL);
 
2882
    }
 
2883
    if (firstpart < length) {
 
2884
      memcpy(&rar->unp_buffer[rar->unp_offset],
 
2885
             &rar->lzss.window[windowoffs], firstpart);
 
2886
      memcpy(&rar->unp_buffer[rar->unp_offset + firstpart],
 
2887
             &rar->lzss.window[0], length - firstpart);
 
2888
    } else
 
2889
      memcpy(&rar->unp_buffer[rar->unp_offset],
 
2890
             &rar->lzss.window[windowoffs], length);
 
2891
  }
 
2892
  rar->unp_offset += length;
 
2893
  if (rar->unp_offset >= rar->unp_buffer_size)
 
2894
    *buffer = rar->unp_buffer;
 
2895
  else
 
2896
    *buffer = NULL;
 
2897
  return (ARCHIVE_OK);
 
2898
}
 
2899
 
 
2900
static const void *
 
2901
rar_read_ahead(struct archive_read *a, size_t min, ssize_t *avail)
 
2902
{
 
2903
  struct rar *rar = (struct rar *)(a->format->data);
 
2904
  const void *h = __archive_read_ahead(a, min, avail);
 
2905
  int ret;
 
2906
  if (avail)
 
2907
  {
 
2908
    if (a->archive.read_data_is_posix_read && *avail > (ssize_t)a->archive.read_data_requested)
 
2909
      *avail = a->archive.read_data_requested;
 
2910
    if (*avail > rar->bytes_remaining)
 
2911
      *avail = (ssize_t)rar->bytes_remaining;
 
2912
    if (*avail < 0)
 
2913
      return NULL;
 
2914
    else if (*avail == 0 && rar->main_flags & MHD_VOLUME &&
 
2915
      rar->file_flags & FHD_SPLIT_AFTER)
 
2916
    {
 
2917
      ret = archive_read_format_rar_read_header(a, a->entry);
 
2918
      if (ret == (ARCHIVE_EOF))
 
2919
      {
 
2920
        rar->has_endarc_header = 1;
 
2921
        ret = archive_read_format_rar_read_header(a, a->entry);
 
2922
      }
 
2923
      if (ret != (ARCHIVE_OK))
 
2924
        return NULL;
 
2925
      return rar_read_ahead(a, min, avail);
 
2926
    }
 
2927
  }
 
2928
  return h;
 
2929
}