]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/libarchive/archive_read_support_format_zip.c
MFC r345497:
[FreeBSD/stable/10.git] / contrib / libarchive / libarchive / archive_read_support_format_zip.c
1 /*-
2  * Copyright (c) 2004-2013 Tim Kientzle
3  * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
4  * Copyright (c) 2013 Konrad Kleine
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD$");
30
31 /*
32  * The definitive documentation of the Zip file format is:
33  *   http://www.pkware.com/documents/casestudies/APPNOTE.TXT
34  *
35  * The Info-Zip project has pioneered various extensions to better
36  * support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
37  * "Ux", and 0x7875 "ux" extensions for time and ownership
38  * information.
39  *
40  * History of this code: The streaming Zip reader was first added to
41  * libarchive in January 2005.  Support for seekable input sources was
42  * added in Nov 2011.  Zip64 support (including a significant code
43  * refactoring) was added in 2014.
44  */
45
46 #ifdef HAVE_ERRNO_H
47 #include <errno.h>
48 #endif
49 #ifdef HAVE_STDLIB_H
50 #include <stdlib.h>
51 #endif
52 #ifdef HAVE_ZLIB_H
53 #include <zlib.h>
54 #endif
55 #ifdef HAVE_BZLIB_H
56 #include <bzlib.h>
57 #endif
58 #ifdef HAVE_LZMA_H
59 #include <lzma.h>
60 #endif
61
62 #include "archive.h"
63 #include "archive_digest_private.h"
64 #include "archive_cryptor_private.h"
65 #include "archive_endian.h"
66 #include "archive_entry.h"
67 #include "archive_entry_locale.h"
68 #include "archive_hmac_private.h"
69 #include "archive_private.h"
70 #include "archive_rb.h"
71 #include "archive_read_private.h"
72 #include "archive_ppmd8_private.h"
73
74 #ifndef HAVE_ZLIB_H
75 #include "archive_crc32.h"
76 #endif
77
78 struct zip_entry {
79         struct archive_rb_node  node;
80         struct zip_entry        *next;
81         int64_t                 local_header_offset;
82         int64_t                 compressed_size;
83         int64_t                 uncompressed_size;
84         int64_t                 gid;
85         int64_t                 uid;
86         struct archive_string   rsrcname;
87         time_t                  mtime;
88         time_t                  atime;
89         time_t                  ctime;
90         uint32_t                crc32;
91         uint16_t                mode;
92         uint16_t                zip_flags; /* From GP Flags Field */
93         unsigned char           compression;
94         unsigned char           system; /* From "version written by" */
95         unsigned char           flags; /* Our extra markers. */
96         unsigned char           decdat;/* Used for Decryption check */
97
98         /* WinZip AES encryption extra field should be available
99          * when compression is 99. */
100         struct {
101                 /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
102                 unsigned        vendor;
103 #define AES_VENDOR_AE_1 0x0001
104 #define AES_VENDOR_AE_2 0x0002
105                 /* AES encryption strength:
106                  * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
107                 unsigned        strength;
108                 /* Actual compression method. */
109                 unsigned char   compression;
110         }                       aes_extra;
111 };
112
113 struct trad_enc_ctx {
114         uint32_t        keys[3];
115 };
116
117 /* Bits used in zip_flags. */
118 #define ZIP_ENCRYPTED   (1 << 0)
119 #define ZIP_LENGTH_AT_END       (1 << 3)
120 #define ZIP_STRONG_ENCRYPTED    (1 << 6)
121 #define ZIP_UTF8_NAME   (1 << 11)
122 /* See "7.2 Single Password Symmetric Encryption Method"
123    in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
124 #define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
125
126 /* Bits used in flags. */
127 #define LA_USED_ZIP64   (1 << 0)
128 #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
129
130 /*
131  * See "WinZip - AES Encryption Information"
132  *     http://www.winzip.com/aes_info.htm
133  */
134 /* Value used in compression method. */
135 #define WINZIP_AES_ENCRYPTION   99
136 /* Authentication code size. */
137 #define AUTH_CODE_SIZE  10
138 /**/
139 #define MAX_DERIVED_KEY_BUF_SIZE        (AES_MAX_KEY_SIZE * 2 + 2)
140
141 struct zip {
142         /* Structural information about the archive. */
143         struct archive_string   format_name;
144         int64_t                 central_directory_offset;
145         size_t                  central_directory_entries_total;
146         size_t                  central_directory_entries_on_this_disk;
147         int                     has_encrypted_entries;
148
149         /* List of entries (seekable Zip only) */
150         struct zip_entry        *zip_entries;
151         struct archive_rb_tree  tree;
152         struct archive_rb_tree  tree_rsrc;
153
154         /* Bytes read but not yet consumed via __archive_read_consume() */
155         size_t                  unconsumed;
156
157         /* Information about entry we're currently reading. */
158         struct zip_entry        *entry;
159         int64_t                 entry_bytes_remaining;
160
161         /* These count the number of bytes actually read for the entry. */
162         int64_t                 entry_compressed_bytes_read;
163         int64_t                 entry_uncompressed_bytes_read;
164
165         /* Running CRC32 of the decompressed data */
166         unsigned long           entry_crc32;
167         unsigned long           (*crc32func)(unsigned long, const void *,
168                                     size_t);
169         char                    ignore_crc32;
170
171         /* Flags to mark progress of decompression. */
172         char                    decompress_init;
173         char                    end_of_entry;
174
175         unsigned char           *uncompressed_buffer;
176         size_t                  uncompressed_buffer_size;
177
178 #ifdef HAVE_ZLIB_H
179         z_stream                stream;
180         char                    stream_valid;
181 #endif
182
183 #if HAVE_LZMA_H && HAVE_LIBLZMA
184         lzma_stream             zipx_lzma_stream;
185         char            zipx_lzma_valid;
186 #endif
187
188 #ifdef HAVE_BZLIB_H
189         bz_stream               bzstream;
190         char            bzstream_valid;
191 #endif
192
193         IByteIn                 zipx_ppmd_stream;
194         ssize_t                 zipx_ppmd_read_compressed;
195         CPpmd8                  ppmd8;
196         char                    ppmd8_valid;
197         char                    ppmd8_stream_failed;
198
199         struct archive_string_conv *sconv;
200         struct archive_string_conv *sconv_default;
201         struct archive_string_conv *sconv_utf8;
202         int                     init_default_conversion;
203         int                     process_mac_extensions;
204
205         char                    init_decryption;
206
207         /* Decryption buffer. */
208         /*
209          * The decrypted data starts at decrypted_ptr and
210          * extends for decrypted_bytes_remaining.  Decryption
211          * adds new data to the end of this block, data is returned
212          * to clients from the beginning.  When the block hits the
213          * end of decrypted_buffer, it has to be shuffled back to
214          * the beginning of the buffer.
215          */
216         unsigned char           *decrypted_buffer;
217         unsigned char           *decrypted_ptr;
218         size_t                  decrypted_buffer_size;
219         size_t                  decrypted_bytes_remaining;
220         size_t                  decrypted_unconsumed_bytes;
221
222         /* Traditional PKWARE decryption. */
223         struct trad_enc_ctx     tctx;
224         char                    tctx_valid;
225
226         /* WinZip AES decryption. */
227         /* Contexts used for AES decryption. */
228         archive_crypto_ctx      cctx;
229         char                    cctx_valid;
230         archive_hmac_sha1_ctx   hctx;
231         char                    hctx_valid;
232
233         /* Strong encryption's decryption header information. */
234         unsigned                iv_size;
235         unsigned                alg_id;
236         unsigned                bit_len;
237         unsigned                flags;
238         unsigned                erd_size;
239         unsigned                v_size;
240         unsigned                v_crc32;
241         uint8_t                 *iv;
242         uint8_t                 *erd;
243         uint8_t                 *v_data;
244 };
245
246 /* Many systems define min or MIN, but not all. */
247 #define zipmin(a,b) ((a) < (b) ? (a) : (b))
248
249 /* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8
250  * streams inside ZIP files. It has 2 purposes: one is to fetch the next
251  * compressed byte from the stream, second one is to increase the counter how
252  * many compressed bytes were read. */
253 static Byte
254 ppmd_read(void* p) {
255         /* Get the handle to current decompression context. */
256         struct archive_read *a = ((IByteIn*)p)->a;
257         struct zip *zip = (struct zip*) a->format->data;
258         ssize_t bytes_avail = 0;
259
260         /* Fetch next byte. */
261         const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail);
262         if(bytes_avail < 1) {
263                 zip->ppmd8_stream_failed = 1;
264                 return 0;
265         }
266
267         __archive_read_consume(a, 1);
268
269         /* Increment the counter. */
270         ++zip->zipx_ppmd_read_compressed;
271
272         /* Return the next compressed byte. */
273         return data[0];
274 }
275
276 /* ------------------------------------------------------------------------ */
277
278 /*
279   Traditional PKWARE Decryption functions.
280  */
281
282 static void
283 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
284 {
285         uint8_t t;
286 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
287
288         ctx->keys[0] = CRC32(ctx->keys[0], c);
289         ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
290         t = (ctx->keys[1] >> 24) & 0xff;
291         ctx->keys[2] = CRC32(ctx->keys[2], t);
292 #undef CRC32
293 }
294
295 static uint8_t
296 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
297 {
298         unsigned temp = ctx->keys[2] | 2;
299         return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
300 }
301
302 static void
303 trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
304     size_t in_len, uint8_t *out, size_t out_len)
305 {
306         unsigned i, max;
307
308         max = (unsigned)((in_len < out_len)? in_len: out_len);
309
310         for (i = 0; i < max; i++) {
311                 uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
312                 out[i] = t;
313                 trad_enc_update_keys(ctx, t);
314         }
315 }
316
317 static int
318 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
319     const uint8_t *key, size_t key_len, uint8_t *crcchk)
320 {
321         uint8_t header[12];
322
323         if (key_len < 12) {
324                 *crcchk = 0xff;
325                 return -1;
326         }
327
328         ctx->keys[0] = 305419896L;
329         ctx->keys[1] = 591751049L;
330         ctx->keys[2] = 878082192L;
331
332         for (;pw_len; --pw_len)
333                 trad_enc_update_keys(ctx, *pw++);
334
335         trad_enc_decrypt_update(ctx, key, 12, header, 12);
336         /* Return the last byte for CRC check. */
337         *crcchk = header[11];
338         return 0;
339 }
340
341 #if 0
342 static void
343 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
344     int key_size)
345 {
346 #define MD_SIZE 20
347         archive_sha1_ctx ctx;
348         unsigned char md1[MD_SIZE];
349         unsigned char md2[MD_SIZE * 2];
350         unsigned char mkb[64];
351         int i;
352
353         archive_sha1_init(&ctx);
354         archive_sha1_update(&ctx, p, size);
355         archive_sha1_final(&ctx, md1);
356
357         memset(mkb, 0x36, sizeof(mkb));
358         for (i = 0; i < MD_SIZE; i++)
359                 mkb[i] ^= md1[i];
360         archive_sha1_init(&ctx);
361         archive_sha1_update(&ctx, mkb, sizeof(mkb));
362         archive_sha1_final(&ctx, md2);
363
364         memset(mkb, 0x5C, sizeof(mkb));
365         for (i = 0; i < MD_SIZE; i++)
366                 mkb[i] ^= md1[i];
367         archive_sha1_init(&ctx);
368         archive_sha1_update(&ctx, mkb, sizeof(mkb));
369         archive_sha1_final(&ctx, md2 + MD_SIZE);
370
371         if (key_size > 32)
372                 key_size = 32;
373         memcpy(key, md2, key_size);
374 #undef MD_SIZE
375 }
376 #endif
377
378 /*
379  * Common code for streaming or seeking modes.
380  *
381  * Includes code to read local file headers, decompress data
382  * from entry bodies, and common API.
383  */
384
385 static unsigned long
386 real_crc32(unsigned long crc, const void *buff, size_t len)
387 {
388         return crc32(crc, buff, (unsigned int)len);
389 }
390
391 /* Used by "ignorecrc32" option to speed up tests. */
392 static unsigned long
393 fake_crc32(unsigned long crc, const void *buff, size_t len)
394 {
395         (void)crc; /* UNUSED */
396         (void)buff; /* UNUSED */
397         (void)len; /* UNUSED */
398         return 0;
399 }
400
401 static const struct {
402         int id;
403         const char * name;
404 } compression_methods[] = {
405         {0, "uncompressed"}, /* The file is stored (no compression) */
406         {1, "shrinking"}, /* The file is Shrunk */
407         {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
408         {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
409         {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
410         {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
411         {6, "imploded"},  /* The file is Imploded */
412         {7, "reserved"},  /* Reserved for Tokenizing compression algorithm */
413         {8, "deflation"}, /* The file is Deflated */
414         {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
415         {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
416                            * (old IBM TERSE) */
417         {11, "reserved"}, /* Reserved by PKWARE */
418         {12, "bzip"},     /* File is compressed using BZIP2 algorithm */
419         {13, "reserved"}, /* Reserved by PKWARE */
420         {14, "lzma"},     /* LZMA (EFS) */
421         {15, "reserved"}, /* Reserved by PKWARE */
422         {16, "reserved"}, /* Reserved by PKWARE */
423         {17, "reserved"}, /* Reserved by PKWARE */
424         {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
425         {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
426         {95, "xz"},       /* XZ compressed data */
427         {96, "jpeg"},     /* JPEG compressed data */
428         {97, "wav-pack"}, /* WavPack compressed data */
429         {98, "ppmd-1"},   /* PPMd version I, Rev 1 */
430         {99, "aes"}       /* WinZip AES encryption  */
431 };
432
433 static const char *
434 compression_name(const int compression)
435 {
436         static const int num_compression_methods =
437                 sizeof(compression_methods)/sizeof(compression_methods[0]);
438         int i=0;
439
440         while(compression >= 0 && i < num_compression_methods) {
441                 if (compression_methods[i].id == compression)
442                         return compression_methods[i].name;
443                 i++;
444         }
445         return "??";
446 }
447
448 /* Convert an MSDOS-style date/time into Unix-style time. */
449 static time_t
450 zip_time(const char *p)
451 {
452         int msTime, msDate;
453         struct tm ts;
454
455         msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
456         msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
457
458         memset(&ts, 0, sizeof(ts));
459         ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
460         ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
461         ts.tm_mday = msDate & 0x1f; /* Day of month. */
462         ts.tm_hour = (msTime >> 11) & 0x1f;
463         ts.tm_min = (msTime >> 5) & 0x3f;
464         ts.tm_sec = (msTime << 1) & 0x3e;
465         ts.tm_isdst = -1;
466         return mktime(&ts);
467 }
468
469 /*
470  * The extra data is stored as a list of
471  *      id1+size1+data1 + id2+size2+data2 ...
472  *  triplets.  id and size are 2 bytes each.
473  */
474 static int
475 process_extra(struct archive_read *a, const char *p, size_t extra_length, struct zip_entry* zip_entry)
476 {
477         unsigned offset = 0;
478
479         if (extra_length == 0) {
480                 return ARCHIVE_OK;
481         }
482
483         if (extra_length < 4) {
484                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
485                     "Too-small extra data: Need at least 4 bytes, but only found %d bytes", (int)extra_length);
486                 return ARCHIVE_FAILED;
487         }
488         while (offset <= extra_length - 4) {
489                 unsigned short headerid = archive_le16dec(p + offset);
490                 unsigned short datasize = archive_le16dec(p + offset + 2);
491
492                 offset += 4;
493                 if (offset + datasize > extra_length) {
494                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
495                             "Extra data overflow: Need %d bytes but only found %d bytes",
496                             (int)datasize, (int)(extra_length - offset));
497                         return ARCHIVE_FAILED;
498                 }
499 #ifdef DEBUG
500                 fprintf(stderr, "Header id 0x%04x, length %d\n",
501                     headerid, datasize);
502 #endif
503                 switch (headerid) {
504                 case 0x0001:
505                         /* Zip64 extended information extra field. */
506                         zip_entry->flags |= LA_USED_ZIP64;
507                         if (zip_entry->uncompressed_size == 0xffffffff) {
508                                 uint64_t t = 0;
509                                 if (datasize < 8
510                                     || (t = archive_le64dec(p + offset)) > INT64_MAX) {
511                                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
512                                             "Malformed 64-bit uncompressed size");
513                                         return ARCHIVE_FAILED;
514                                 }
515                                 zip_entry->uncompressed_size = t;
516                                 offset += 8;
517                                 datasize -= 8;
518                         }
519                         if (zip_entry->compressed_size == 0xffffffff) {
520                                 uint64_t t = 0;
521                                 if (datasize < 8
522                                     || (t = archive_le64dec(p + offset)) > INT64_MAX) {
523                                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
524                                             "Malformed 64-bit compressed size");
525                                         return ARCHIVE_FAILED;
526                                 }
527                                 zip_entry->compressed_size = t;
528                                 offset += 8;
529                                 datasize -= 8;
530                         }
531                         if (zip_entry->local_header_offset == 0xffffffff) {
532                                 uint64_t t = 0;
533                                 if (datasize < 8
534                                     || (t = archive_le64dec(p + offset)) > INT64_MAX) {
535                                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
536                                             "Malformed 64-bit local header offset");
537                                         return ARCHIVE_FAILED;
538                                 }
539                                 zip_entry->local_header_offset = t;
540                                 offset += 8;
541                                 datasize -= 8;
542                         }
543                         /* archive_le32dec(p + offset) gives disk
544                          * on which file starts, but we don't handle
545                          * multi-volume Zip files. */
546                         break;
547 #ifdef DEBUG
548                 case 0x0017:
549                 {
550                         /* Strong encryption field. */
551                         if (archive_le16dec(p + offset) == 2) {
552                                 unsigned algId =
553                                         archive_le16dec(p + offset + 2);
554                                 unsigned bitLen =
555                                         archive_le16dec(p + offset + 4);
556                                 int      flags =
557                                         archive_le16dec(p + offset + 6);
558                                 fprintf(stderr, "algId=0x%04x, bitLen=%u, "
559                                     "flgas=%d\n", algId, bitLen,flags);
560                         }
561                         break;
562                 }
563 #endif
564                 case 0x5455:
565                 {
566                         /* Extended time field "UT". */
567                         int flags;
568                         if (datasize == 0) {
569                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
570                                     "Incomplete extended time field");
571                                 return ARCHIVE_FAILED;
572                         }
573                         flags = p[offset];
574                         offset++;
575                         datasize--;
576                         /* Flag bits indicate which dates are present. */
577                         if (flags & 0x01)
578                         {
579 #ifdef DEBUG
580                                 fprintf(stderr, "mtime: %lld -> %d\n",
581                                     (long long)zip_entry->mtime,
582                                     archive_le32dec(p + offset));
583 #endif
584                                 if (datasize < 4)
585                                         break;
586                                 zip_entry->mtime = archive_le32dec(p + offset);
587                                 offset += 4;
588                                 datasize -= 4;
589                         }
590                         if (flags & 0x02)
591                         {
592                                 if (datasize < 4)
593                                         break;
594                                 zip_entry->atime = archive_le32dec(p + offset);
595                                 offset += 4;
596                                 datasize -= 4;
597                         }
598                         if (flags & 0x04)
599                         {
600                                 if (datasize < 4)
601                                         break;
602                                 zip_entry->ctime = archive_le32dec(p + offset);
603                                 offset += 4;
604                                 datasize -= 4;
605                         }
606                         break;
607                 }
608                 case 0x5855:
609                 {
610                         /* Info-ZIP Unix Extra Field (old version) "UX". */
611                         if (datasize >= 8) {
612                                 zip_entry->atime = archive_le32dec(p + offset);
613                                 zip_entry->mtime =
614                                     archive_le32dec(p + offset + 4);
615                         }
616                         if (datasize >= 12) {
617                                 zip_entry->uid =
618                                     archive_le16dec(p + offset + 8);
619                                 zip_entry->gid =
620                                     archive_le16dec(p + offset + 10);
621                         }
622                         break;
623                 }
624                 case 0x6c78:
625                 {
626                         /* Experimental 'xl' field */
627                         /*
628                          * Introduced Dec 2013 to provide a way to
629                          * include external file attributes (and other
630                          * fields that ordinarily appear only in
631                          * central directory) in local file header.
632                          * This provides file type and permission
633                          * information necessary to support full
634                          * streaming extraction.  Currently being
635                          * discussed with other Zip developers
636                          * ... subject to change.
637                          *
638                          * Format:
639                          *  The field starts with a bitmap that specifies
640                          *  which additional fields are included.  The
641                          *  bitmap is variable length and can be extended in
642                          *  the future.
643                          *
644                          *  n bytes - feature bitmap: first byte has low-order
645                          *    7 bits.  If high-order bit is set, a subsequent
646                          *    byte holds the next 7 bits, etc.
647                          *
648                          *  if bitmap & 1, 2 byte "version made by"
649                          *  if bitmap & 2, 2 byte "internal file attributes"
650                          *  if bitmap & 4, 4 byte "external file attributes"
651                          *  if bitmap & 8, 2 byte comment length + n byte comment
652                          */
653                         int bitmap, bitmap_last;
654
655                         if (datasize < 1)
656                                 break;
657                         bitmap_last = bitmap = 0xff & p[offset];
658                         offset += 1;
659                         datasize -= 1;
660
661                         /* We only support first 7 bits of bitmap; skip rest. */
662                         while ((bitmap_last & 0x80) != 0
663                             && datasize >= 1) {
664                                 bitmap_last = p[offset];
665                                 offset += 1;
666                                 datasize -= 1;
667                         }
668
669                         if (bitmap & 1) {
670                                 /* 2 byte "version made by" */
671                                 if (datasize < 2)
672                                         break;
673                                 zip_entry->system
674                                     = archive_le16dec(p + offset) >> 8;
675                                 offset += 2;
676                                 datasize -= 2;
677                         }
678                         if (bitmap & 2) {
679                                 /* 2 byte "internal file attributes" */
680                                 uint32_t internal_attributes;
681                                 if (datasize < 2)
682                                         break;
683                                 internal_attributes
684                                     = archive_le16dec(p + offset);
685                                 /* Not used by libarchive at present. */
686                                 (void)internal_attributes; /* UNUSED */
687                                 offset += 2;
688                                 datasize -= 2;
689                         }
690                         if (bitmap & 4) {
691                                 /* 4 byte "external file attributes" */
692                                 uint32_t external_attributes;
693                                 if (datasize < 4)
694                                         break;
695                                 external_attributes
696                                     = archive_le32dec(p + offset);
697                                 if (zip_entry->system == 3) {
698                                         zip_entry->mode
699                                             = external_attributes >> 16;
700                                 } else if (zip_entry->system == 0) {
701                                         // Interpret MSDOS directory bit
702                                         if (0x10 == (external_attributes & 0x10)) {
703                                                 zip_entry->mode = AE_IFDIR | 0775;
704                                         } else {
705                                                 zip_entry->mode = AE_IFREG | 0664;
706                                         }
707                                         if (0x01 == (external_attributes & 0x01)) {
708                                                 // Read-only bit; strip write permissions
709                                                 zip_entry->mode &= 0555;
710                                         }
711                                 } else {
712                                         zip_entry->mode = 0;
713                                 }
714                                 offset += 4;
715                                 datasize -= 4;
716                         }
717                         if (bitmap & 8) {
718                                 /* 2 byte comment length + comment */
719                                 uint32_t comment_length;
720                                 if (datasize < 2)
721                                         break;
722                                 comment_length
723                                     = archive_le16dec(p + offset);
724                                 offset += 2;
725                                 datasize -= 2;
726
727                                 if (datasize < comment_length)
728                                         break;
729                                 /* Comment is not supported by libarchive */
730                                 offset += comment_length;
731                                 datasize -= comment_length;
732                         }
733                         break;
734                 }
735                 case 0x7855:
736                         /* Info-ZIP Unix Extra Field (type 2) "Ux". */
737 #ifdef DEBUG
738                         fprintf(stderr, "uid %d gid %d\n",
739                             archive_le16dec(p + offset),
740                             archive_le16dec(p + offset + 2));
741 #endif
742                         if (datasize >= 2)
743                                 zip_entry->uid = archive_le16dec(p + offset);
744                         if (datasize >= 4)
745                                 zip_entry->gid =
746                                     archive_le16dec(p + offset + 2);
747                         break;
748                 case 0x7875:
749                 {
750                         /* Info-Zip Unix Extra Field (type 3) "ux". */
751                         int uidsize = 0, gidsize = 0;
752
753                         /* TODO: support arbitrary uidsize/gidsize. */
754                         if (datasize >= 1 && p[offset] == 1) {/* version=1 */
755                                 if (datasize >= 4) {
756                                         /* get a uid size. */
757                                         uidsize = 0xff & (int)p[offset+1];
758                                         if (uidsize == 2)
759                                                 zip_entry->uid =
760                                                     archive_le16dec(
761                                                         p + offset + 2);
762                                         else if (uidsize == 4 && datasize >= 6)
763                                                 zip_entry->uid =
764                                                     archive_le32dec(
765                                                         p + offset + 2);
766                                 }
767                                 if (datasize >= (2 + uidsize + 3)) {
768                                         /* get a gid size. */
769                                         gidsize = 0xff & (int)p[offset+2+uidsize];
770                                         if (gidsize == 2)
771                                                 zip_entry->gid =
772                                                     archive_le16dec(
773                                                         p+offset+2+uidsize+1);
774                                         else if (gidsize == 4 &&
775                                             datasize >= (2 + uidsize + 5))
776                                                 zip_entry->gid =
777                                                     archive_le32dec(
778                                                         p+offset+2+uidsize+1);
779                                 }
780                         }
781                         break;
782                 }
783                 case 0x9901:
784                         /* WinZip AES extra data field. */
785                         if (datasize < 6) {
786                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
787                                     "Incomplete AES field");
788                                 return ARCHIVE_FAILED;
789                         }
790                         if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
791                                 /* Vendor version. */
792                                 zip_entry->aes_extra.vendor =
793                                     archive_le16dec(p + offset);
794                                 /* AES encryption strength. */
795                                 zip_entry->aes_extra.strength = p[offset + 4];
796                                 /* Actual compression method. */
797                                 zip_entry->aes_extra.compression =
798                                     p[offset + 5];
799                         }
800                         break;
801                 default:
802                         break;
803                 }
804                 offset += datasize;
805         }
806         if (offset != extra_length) {
807                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
808                     "Malformed extra data: Consumed %d bytes of %d bytes",
809                     (int)offset, (int)extra_length);
810                 return ARCHIVE_FAILED;
811         }
812         return ARCHIVE_OK;
813 }
814
815 /*
816  * Assumes file pointer is at beginning of local file header.
817  */
818 static int
819 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
820     struct zip *zip)
821 {
822         const char *p;
823         const void *h;
824         const wchar_t *wp;
825         const char *cp;
826         size_t len, filename_length, extra_length;
827         struct archive_string_conv *sconv;
828         struct zip_entry *zip_entry = zip->entry;
829         struct zip_entry zip_entry_central_dir;
830         int ret = ARCHIVE_OK;
831         char version;
832
833         /* Save a copy of the original for consistency checks. */
834         zip_entry_central_dir = *zip_entry;
835
836         zip->decompress_init = 0;
837         zip->end_of_entry = 0;
838         zip->entry_uncompressed_bytes_read = 0;
839         zip->entry_compressed_bytes_read = 0;
840         zip->entry_crc32 = zip->crc32func(0, NULL, 0);
841
842         /* Setup default conversion. */
843         if (zip->sconv == NULL && !zip->init_default_conversion) {
844                 zip->sconv_default =
845                     archive_string_default_conversion_for_read(&(a->archive));
846                 zip->init_default_conversion = 1;
847         }
848
849         if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
850                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
851                     "Truncated ZIP file header");
852                 return (ARCHIVE_FATAL);
853         }
854
855         if (memcmp(p, "PK\003\004", 4) != 0) {
856                 archive_set_error(&a->archive, -1, "Damaged Zip archive");
857                 return ARCHIVE_FATAL;
858         }
859         version = p[4];
860         zip_entry->system = p[5];
861         zip_entry->zip_flags = archive_le16dec(p + 6);
862         if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
863                 zip->has_encrypted_entries = 1;
864                 archive_entry_set_is_data_encrypted(entry, 1);
865                 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
866                         zip_entry->zip_flags & ZIP_ENCRYPTED &&
867                         zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
868                         archive_entry_set_is_metadata_encrypted(entry, 1);
869                         return ARCHIVE_FATAL;
870                 }
871         }
872         zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
873         zip_entry->compression = (char)archive_le16dec(p + 8);
874         zip_entry->mtime = zip_time(p + 10);
875         zip_entry->crc32 = archive_le32dec(p + 14);
876         if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
877                 zip_entry->decdat = p[11];
878         else
879                 zip_entry->decdat = p[17];
880         zip_entry->compressed_size = archive_le32dec(p + 18);
881         zip_entry->uncompressed_size = archive_le32dec(p + 22);
882         filename_length = archive_le16dec(p + 26);
883         extra_length = archive_le16dec(p + 28);
884
885         __archive_read_consume(a, 30);
886
887         /* Read the filename. */
888         if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
889                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
890                     "Truncated ZIP file header");
891                 return (ARCHIVE_FATAL);
892         }
893         if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
894                 /* The filename is stored to be UTF-8. */
895                 if (zip->sconv_utf8 == NULL) {
896                         zip->sconv_utf8 =
897                             archive_string_conversion_from_charset(
898                                 &a->archive, "UTF-8", 1);
899                         if (zip->sconv_utf8 == NULL)
900                                 return (ARCHIVE_FATAL);
901                 }
902                 sconv = zip->sconv_utf8;
903         } else if (zip->sconv != NULL)
904                 sconv = zip->sconv;
905         else
906                 sconv = zip->sconv_default;
907
908         if (archive_entry_copy_pathname_l(entry,
909             h, filename_length, sconv) != 0) {
910                 if (errno == ENOMEM) {
911                         archive_set_error(&a->archive, ENOMEM,
912                             "Can't allocate memory for Pathname");
913                         return (ARCHIVE_FATAL);
914                 }
915                 archive_set_error(&a->archive,
916                     ARCHIVE_ERRNO_FILE_FORMAT,
917                     "Pathname cannot be converted "
918                     "from %s to current locale.",
919                     archive_string_conversion_charset_name(sconv));
920                 ret = ARCHIVE_WARN;
921         }
922         __archive_read_consume(a, filename_length);
923
924         /* Read the extra data. */
925         if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
926                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
927                     "Truncated ZIP file header");
928                 return (ARCHIVE_FATAL);
929         }
930
931         if (ARCHIVE_OK != process_extra(a, h, extra_length, zip_entry)) {
932                 return ARCHIVE_FATAL;
933         }
934         __archive_read_consume(a, extra_length);
935
936         /* Work around a bug in Info-Zip: When reading from a pipe, it
937          * stats the pipe instead of synthesizing a file entry. */
938         if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
939                 zip_entry->mode &= ~ AE_IFMT;
940                 zip_entry->mode |= AE_IFREG;
941         }
942
943         /* If the mode is totally empty, set some sane default. */
944         if (zip_entry->mode == 0) {
945                 zip_entry->mode |= 0664;
946         }
947
948         /* Windows archivers sometimes use backslash as the directory separator.
949            Normalize to slash. */
950         if (zip_entry->system == 0 &&
951             (wp = archive_entry_pathname_w(entry)) != NULL) {
952                 if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
953                         size_t i;
954                         struct archive_wstring s;
955                         archive_string_init(&s);
956                         archive_wstrcpy(&s, wp);
957                         for (i = 0; i < archive_strlen(&s); i++) {
958                                 if (s.s[i] == '\\')
959                                         s.s[i] = '/';
960                         }
961                         archive_entry_copy_pathname_w(entry, s.s);
962                         archive_wstring_free(&s);
963                 }
964         }
965
966         /* Make sure that entries with a trailing '/' are marked as directories
967          * even if the External File Attributes contains bogus values.  If this
968          * is not a directory and there is no type, assume regularfile. */
969         if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
970                 int has_slash;
971
972                 wp = archive_entry_pathname_w(entry);
973                 if (wp != NULL) {
974                         len = wcslen(wp);
975                         has_slash = len > 0 && wp[len - 1] == L'/';
976                 } else {
977                         cp = archive_entry_pathname(entry);
978                         len = (cp != NULL)?strlen(cp):0;
979                         has_slash = len > 0 && cp[len - 1] == '/';
980                 }
981                 /* Correct file type as needed. */
982                 if (has_slash) {
983                         zip_entry->mode &= ~AE_IFMT;
984                         zip_entry->mode |= AE_IFDIR;
985                         zip_entry->mode |= 0111;
986                 } else if ((zip_entry->mode & AE_IFMT) == 0) {
987                         zip_entry->mode |= AE_IFREG;
988                 }
989         }
990
991         /* Make sure directories end in '/' */
992         if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
993                 wp = archive_entry_pathname_w(entry);
994                 if (wp != NULL) {
995                         len = wcslen(wp);
996                         if (len > 0 && wp[len - 1] != L'/') {
997                                 struct archive_wstring s;
998                                 archive_string_init(&s);
999                                 archive_wstrcat(&s, wp);
1000                                 archive_wstrappend_wchar(&s, L'/');
1001                                 archive_entry_copy_pathname_w(entry, s.s);
1002                                 archive_wstring_free(&s);
1003                         }
1004                 } else {
1005                         cp = archive_entry_pathname(entry);
1006                         len = (cp != NULL)?strlen(cp):0;
1007                         if (len > 0 && cp[len - 1] != '/') {
1008                                 struct archive_string s;
1009                                 archive_string_init(&s);
1010                                 archive_strcat(&s, cp);
1011                                 archive_strappend_char(&s, '/');
1012                                 archive_entry_set_pathname(entry, s.s);
1013                                 archive_string_free(&s);
1014                         }
1015                 }
1016         }
1017
1018         if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1019                 /* If this came from the central dir, it's size info
1020                  * is definitive, so ignore the length-at-end flag. */
1021                 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1022                 /* If local header is missing a value, use the one from
1023                    the central directory.  If both have it, warn about
1024                    mismatches. */
1025                 if (zip_entry->crc32 == 0) {
1026                         zip_entry->crc32 = zip_entry_central_dir.crc32;
1027                 } else if (!zip->ignore_crc32
1028                     && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1029                         archive_set_error(&a->archive,
1030                             ARCHIVE_ERRNO_FILE_FORMAT,
1031                             "Inconsistent CRC32 values");
1032                         ret = ARCHIVE_WARN;
1033                 }
1034                 if (zip_entry->compressed_size == 0) {
1035                         zip_entry->compressed_size
1036                             = zip_entry_central_dir.compressed_size;
1037                 } else if (zip_entry->compressed_size
1038                     != zip_entry_central_dir.compressed_size) {
1039                         archive_set_error(&a->archive,
1040                             ARCHIVE_ERRNO_FILE_FORMAT,
1041                             "Inconsistent compressed size: "
1042                             "%jd in central directory, %jd in local header",
1043                             (intmax_t)zip_entry_central_dir.compressed_size,
1044                             (intmax_t)zip_entry->compressed_size);
1045                         ret = ARCHIVE_WARN;
1046                 }
1047                 if (zip_entry->uncompressed_size == 0) {
1048                         zip_entry->uncompressed_size
1049                             = zip_entry_central_dir.uncompressed_size;
1050                 } else if (zip_entry->uncompressed_size
1051                     != zip_entry_central_dir.uncompressed_size) {
1052                         archive_set_error(&a->archive,
1053                             ARCHIVE_ERRNO_FILE_FORMAT,
1054                             "Inconsistent uncompressed size: "
1055                             "%jd in central directory, %jd in local header",
1056                             (intmax_t)zip_entry_central_dir.uncompressed_size,
1057                             (intmax_t)zip_entry->uncompressed_size);
1058                         ret = ARCHIVE_WARN;
1059                 }
1060         }
1061
1062         /* Populate some additional entry fields: */
1063         archive_entry_set_mode(entry, zip_entry->mode);
1064         archive_entry_set_uid(entry, zip_entry->uid);
1065         archive_entry_set_gid(entry, zip_entry->gid);
1066         archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1067         archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1068         archive_entry_set_atime(entry, zip_entry->atime, 0);
1069
1070         if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1071                 size_t linkname_length;
1072
1073                 if (zip_entry->compressed_size > 64 * 1024) {
1074                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1075                             "Zip file with oversized link entry");
1076                         return ARCHIVE_FATAL;
1077                 }
1078
1079                 linkname_length = (size_t)zip_entry->compressed_size;
1080
1081                 archive_entry_set_size(entry, 0);
1082                 p = __archive_read_ahead(a, linkname_length, NULL);
1083                 if (p == NULL) {
1084                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1085                             "Truncated Zip file");
1086                         return ARCHIVE_FATAL;
1087                 }
1088
1089                 sconv = zip->sconv;
1090                 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1091                         sconv = zip->sconv_utf8;
1092                 if (sconv == NULL)
1093                         sconv = zip->sconv_default;
1094                 if (archive_entry_copy_symlink_l(entry, p, linkname_length,
1095                     sconv) != 0) {
1096                         if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1097                             (zip->entry->zip_flags & ZIP_UTF8_NAME))
1098                             archive_entry_copy_symlink_l(entry, p,
1099                                 linkname_length, NULL);
1100                         if (errno == ENOMEM) {
1101                                 archive_set_error(&a->archive, ENOMEM,
1102                                     "Can't allocate memory for Symlink");
1103                                 return (ARCHIVE_FATAL);
1104                         }
1105                         /*
1106                          * Since there is no character-set regulation for
1107                          * symlink name, do not report the conversion error
1108                          * in an automatic conversion.
1109                          */
1110                         if (sconv != zip->sconv_utf8 ||
1111                             (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1112                                 archive_set_error(&a->archive,
1113                                     ARCHIVE_ERRNO_FILE_FORMAT,
1114                                     "Symlink cannot be converted "
1115                                     "from %s to current locale.",
1116                                     archive_string_conversion_charset_name(
1117                                         sconv));
1118                                 ret = ARCHIVE_WARN;
1119                         }
1120                 }
1121                 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1122
1123                 if (__archive_read_consume(a, linkname_length) < 0) {
1124                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1125                             "Read error skipping symlink target name");
1126                         return ARCHIVE_FATAL;
1127                 }
1128         } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1129             || zip_entry->uncompressed_size > 0) {
1130                 /* Set the size only if it's meaningful. */
1131                 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1132         }
1133         zip->entry_bytes_remaining = zip_entry->compressed_size;
1134
1135         /* If there's no body, force read_data() to return EOF immediately. */
1136         if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1137             && zip->entry_bytes_remaining < 1)
1138                 zip->end_of_entry = 1;
1139
1140         /* Set up a more descriptive format name. */
1141         archive_string_empty(&zip->format_name);
1142         archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1143             version / 10, version % 10,
1144             compression_name(zip->entry->compression));
1145         a->archive.archive_format_name = zip->format_name.s;
1146
1147         return (ret);
1148 }
1149
1150 static int
1151 check_authentication_code(struct archive_read *a, const void *_p)
1152 {
1153         struct zip *zip = (struct zip *)(a->format->data);
1154
1155         /* Check authentication code. */
1156         if (zip->hctx_valid) {
1157                 const void *p;
1158                 uint8_t hmac[20];
1159                 size_t hmac_len = 20;
1160                 int cmp;
1161
1162                 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1163                 if (_p == NULL) {
1164                         /* Read authentication code. */
1165                         p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1166                         if (p == NULL) {
1167                                 archive_set_error(&a->archive,
1168                                     ARCHIVE_ERRNO_FILE_FORMAT,
1169                                     "Truncated ZIP file data");
1170                                 return (ARCHIVE_FATAL);
1171                         }
1172                 } else {
1173                         p = _p;
1174                 }
1175                 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1176                 __archive_read_consume(a, AUTH_CODE_SIZE);
1177                 if (cmp != 0) {
1178                         archive_set_error(&a->archive,
1179                             ARCHIVE_ERRNO_MISC,
1180                             "ZIP bad Authentication code");
1181                         return (ARCHIVE_WARN);
1182                 }
1183         }
1184         return (ARCHIVE_OK);
1185 }
1186
1187 /*
1188  * Read "uncompressed" data.  There are three cases:
1189  *  1) We know the size of the data.  This is always true for the
1190  * seeking reader (we've examined the Central Directory already).
1191  *  2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1192  * Info-ZIP seems to do this; we know the size but have to grab
1193  * the CRC from the data descriptor afterwards.
1194  *  3) We're streaming and ZIP_LENGTH_AT_END was specified and
1195  * we have no size information.  In this case, we can do pretty
1196  * well by watching for the data descriptor record.  The data
1197  * descriptor is 16 bytes and includes a computed CRC that should
1198  * provide a strong check.
1199  *
1200  * TODO: Technically, the PK\007\010 signature is optional.
1201  * In the original spec, the data descriptor contained CRC
1202  * and size fields but had no leading signature.  In practice,
1203  * newer writers seem to provide the signature pretty consistently.
1204  *
1205  * For uncompressed data, the PK\007\010 marker seems essential
1206  * to be sure we've actually seen the end of the entry.
1207  *
1208  * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1209  * zip->end_of_entry if it consumes all of the data.
1210  */
1211 static int
1212 zip_read_data_none(struct archive_read *a, const void **_buff,
1213     size_t *size, int64_t *offset)
1214 {
1215         struct zip *zip;
1216         const char *buff;
1217         ssize_t bytes_avail;
1218         int r;
1219
1220         (void)offset; /* UNUSED */
1221
1222         zip = (struct zip *)(a->format->data);
1223
1224         if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1225                 const char *p;
1226                 ssize_t grabbing_bytes = 24;
1227
1228                 if (zip->hctx_valid)
1229                         grabbing_bytes += AUTH_CODE_SIZE;
1230                 /* Grab at least 24 bytes. */
1231                 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1232                 if (bytes_avail < grabbing_bytes) {
1233                         /* Zip archives have end-of-archive markers
1234                            that are longer than this, so a failure to get at
1235                            least 24 bytes really does indicate a truncated
1236                            file. */
1237                         archive_set_error(&a->archive,
1238                             ARCHIVE_ERRNO_FILE_FORMAT,
1239                             "Truncated ZIP file data");
1240                         return (ARCHIVE_FATAL);
1241                 }
1242                 /* Check for a complete PK\007\010 signature, followed
1243                  * by the correct 4-byte CRC. */
1244                 p = buff;
1245                 if (zip->hctx_valid)
1246                         p += AUTH_CODE_SIZE;
1247                 if (p[0] == 'P' && p[1] == 'K'
1248                     && p[2] == '\007' && p[3] == '\010'
1249                     && (archive_le32dec(p + 4) == zip->entry_crc32
1250                         || zip->ignore_crc32
1251                         || (zip->hctx_valid
1252                          && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1253                         if (zip->entry->flags & LA_USED_ZIP64) {
1254                                 uint64_t compressed, uncompressed;
1255                                 zip->entry->crc32 = archive_le32dec(p + 4);
1256                                 compressed = archive_le64dec(p + 8);
1257                                 uncompressed = archive_le64dec(p + 16);
1258                                 if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1259                                         archive_set_error(&a->archive,
1260                                             ARCHIVE_ERRNO_FILE_FORMAT,
1261                                             "Overflow of 64-bit file sizes");
1262                                         return ARCHIVE_FAILED;
1263                                 }
1264                                 zip->entry->compressed_size = compressed;
1265                                 zip->entry->uncompressed_size = uncompressed;
1266                                 zip->unconsumed = 24;
1267                         } else {
1268                                 zip->entry->crc32 = archive_le32dec(p + 4);
1269                                 zip->entry->compressed_size =
1270                                         archive_le32dec(p + 8);
1271                                 zip->entry->uncompressed_size =
1272                                         archive_le32dec(p + 12);
1273                                 zip->unconsumed = 16;
1274                         }
1275                         if (zip->hctx_valid) {
1276                                 r = check_authentication_code(a, buff);
1277                                 if (r != ARCHIVE_OK)
1278                                         return (r);
1279                         }
1280                         zip->end_of_entry = 1;
1281                         return (ARCHIVE_OK);
1282                 }
1283                 /* If not at EOF, ensure we consume at least one byte. */
1284                 ++p;
1285
1286                 /* Scan forward until we see where a PK\007\010 signature
1287                  * might be. */
1288                 /* Return bytes up until that point.  On the next call,
1289                  * the code above will verify the data descriptor. */
1290                 while (p < buff + bytes_avail - 4) {
1291                         if (p[3] == 'P') { p += 3; }
1292                         else if (p[3] == 'K') { p += 2; }
1293                         else if (p[3] == '\007') { p += 1; }
1294                         else if (p[3] == '\010' && p[2] == '\007'
1295                             && p[1] == 'K' && p[0] == 'P') {
1296                                 if (zip->hctx_valid)
1297                                         p -= AUTH_CODE_SIZE;
1298                                 break;
1299                         } else { p += 4; }
1300                 }
1301                 bytes_avail = p - buff;
1302         } else {
1303                 if (zip->entry_bytes_remaining == 0) {
1304                         zip->end_of_entry = 1;
1305                         if (zip->hctx_valid) {
1306                                 r = check_authentication_code(a, NULL);
1307                                 if (r != ARCHIVE_OK)
1308                                         return (r);
1309                         }
1310                         return (ARCHIVE_OK);
1311                 }
1312                 /* Grab a bunch of bytes. */
1313                 buff = __archive_read_ahead(a, 1, &bytes_avail);
1314                 if (bytes_avail <= 0) {
1315                         archive_set_error(&a->archive,
1316                             ARCHIVE_ERRNO_FILE_FORMAT,
1317                             "Truncated ZIP file data");
1318                         return (ARCHIVE_FATAL);
1319                 }
1320                 if (bytes_avail > zip->entry_bytes_remaining)
1321                         bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1322         }
1323         if (zip->tctx_valid || zip->cctx_valid) {
1324                 size_t dec_size = bytes_avail;
1325
1326                 if (dec_size > zip->decrypted_buffer_size)
1327                         dec_size = zip->decrypted_buffer_size;
1328                 if (zip->tctx_valid) {
1329                         trad_enc_decrypt_update(&zip->tctx,
1330                             (const uint8_t *)buff, dec_size,
1331                             zip->decrypted_buffer, dec_size);
1332                 } else {
1333                         size_t dsize = dec_size;
1334                         archive_hmac_sha1_update(&zip->hctx,
1335                             (const uint8_t *)buff, dec_size);
1336                         archive_decrypto_aes_ctr_update(&zip->cctx,
1337                             (const uint8_t *)buff, dec_size,
1338                             zip->decrypted_buffer, &dsize);
1339                 }
1340                 bytes_avail = dec_size;
1341                 buff = (const char *)zip->decrypted_buffer;
1342         }
1343         *size = bytes_avail;
1344         zip->entry_bytes_remaining -= bytes_avail;
1345         zip->entry_uncompressed_bytes_read += bytes_avail;
1346         zip->entry_compressed_bytes_read += bytes_avail;
1347         zip->unconsumed += bytes_avail;
1348         *_buff = buff;
1349         return (ARCHIVE_OK);
1350 }
1351
1352 static int
1353 consume_optional_marker(struct archive_read *a, struct zip *zip)
1354 {
1355         if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1356                 const char *p;
1357
1358                 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1359                         archive_set_error(&a->archive,
1360                             ARCHIVE_ERRNO_FILE_FORMAT,
1361                             "Truncated ZIP end-of-file record");
1362                         return (ARCHIVE_FATAL);
1363                 }
1364                 /* Consume the optional PK\007\010 marker. */
1365                 if (p[0] == 'P' && p[1] == 'K' &&
1366                     p[2] == '\007' && p[3] == '\010') {
1367                         p += 4;
1368                         zip->unconsumed = 4;
1369                 }
1370                 if (zip->entry->flags & LA_USED_ZIP64) {
1371                         uint64_t compressed, uncompressed;
1372                         zip->entry->crc32 = archive_le32dec(p);
1373                         compressed = archive_le64dec(p + 4);
1374                         uncompressed = archive_le64dec(p + 12);
1375                         if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1376                                 archive_set_error(&a->archive,
1377                                     ARCHIVE_ERRNO_FILE_FORMAT,
1378                                     "Overflow of 64-bit file sizes");
1379                                 return ARCHIVE_FAILED;
1380                         }
1381                         zip->entry->compressed_size = compressed;
1382                         zip->entry->uncompressed_size = uncompressed;
1383                         zip->unconsumed += 20;
1384                 } else {
1385                         zip->entry->crc32 = archive_le32dec(p);
1386                         zip->entry->compressed_size = archive_le32dec(p + 4);
1387                         zip->entry->uncompressed_size = archive_le32dec(p + 8);
1388                         zip->unconsumed += 12;
1389                 }
1390         }
1391
1392     return (ARCHIVE_OK);
1393 }
1394
1395 #if HAVE_LZMA_H && HAVE_LIBLZMA
1396 static int
1397 zipx_xz_init(struct archive_read *a, struct zip *zip)
1398 {
1399         lzma_ret r;
1400
1401         if(zip->zipx_lzma_valid) {
1402                 lzma_end(&zip->zipx_lzma_stream);
1403                 zip->zipx_lzma_valid = 0;
1404         }
1405
1406         memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1407         r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1408         if (r != LZMA_OK) {
1409                 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1410                     "xz initialization failed(%d)",
1411                     r);
1412
1413                 return (ARCHIVE_FAILED);
1414         }
1415
1416         zip->zipx_lzma_valid = 1;
1417
1418         free(zip->uncompressed_buffer);
1419
1420         zip->uncompressed_buffer_size = 256 * 1024;
1421         zip->uncompressed_buffer =
1422             (uint8_t*) malloc(zip->uncompressed_buffer_size);
1423         if (zip->uncompressed_buffer == NULL) {
1424                 archive_set_error(&a->archive, ENOMEM,
1425                     "No memory for xz decompression");
1426                     return (ARCHIVE_FATAL);
1427         }
1428
1429         zip->decompress_init = 1;
1430         return (ARCHIVE_OK);
1431 }
1432
1433 static int
1434 zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1435 {
1436         lzma_ret r;
1437         const uint8_t* p;
1438
1439 #pragma pack(push)
1440 #pragma pack(1)
1441         struct _alone_header {
1442             uint8_t bytes[5];
1443             uint64_t uncompressed_size;
1444         } alone_header;
1445 #pragma pack(pop)
1446
1447         /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma that
1448          * is a part of XZ Utils. The stream format stored inside ZIPX file is a
1449          * modified "lzma alone" file format, that was used by the `lzma` utility
1450          * which was later deprecated in favour of `xz` utility. Since those
1451          * formats are nearly the same, we can use a standard "lzma alone" decoder
1452          * from XZ Utils. */
1453
1454         memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1455         r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1456         if (r != LZMA_OK) {
1457                 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1458                     "lzma initialization failed(%d)", r);
1459
1460                 return (ARCHIVE_FAILED);
1461         }
1462
1463         /* Flag the cleanup function that we want our lzma-related structures
1464          * to be freed later. */
1465         zip->zipx_lzma_valid = 1;
1466
1467         /* The "lzma alone" file format and the stream format inside ZIPx are
1468          * almost the same. Here's an example of a structure of "lzma alone"
1469          * format:
1470          *
1471          * $ cat /bin/ls | lzma | xxd | head -n 1
1472          * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1473          *
1474          *    5 bytes        8 bytes        n bytes
1475          * <lzma_params><uncompressed_size><data...>
1476          *
1477          * lzma_params is a 5-byte blob that has to be decoded to extract
1478          * parameters of this LZMA stream. The uncompressed_size field is an
1479          * uint64_t value that contains information about the size of the
1480          * uncompressed file, or UINT64_MAX if this value is unknown. The <data...>
1481          * part is the actual lzma-compressed data stream.
1482          *
1483          * Now here's the structure of the stream inside the ZIPX file:
1484          *
1485          * $ cat stream_inside_zipx | xxd | head -n 1
1486          * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1487          *
1488          *  2byte   2byte    5 bytes     n bytes
1489          * <magic1><magic2><lzma_params><data...>
1490          *
1491          * This means that the ZIPX file contains an additional magic1 and magic2
1492          * headers, the lzma_params field contains the same parameter set as in the
1493          * "lzma alone" format, and the <data...> field is the same as in the "lzma
1494          * alone" format as well. Note that also the zipx format is missing the
1495          * uncompressed_size field.
1496          *
1497          * So, in order to use the "lzma alone" decoder for the zipx lzma stream,
1498          * we simply need to shuffle around some fields, prepare a new lzma alone
1499          * header, feed it into lzma alone decoder so it will initialize itself
1500          * properly, and then we can start feeding normal zipx lzma stream into the
1501          * decoder.
1502          */
1503
1504         /* Read magic1,magic2,lzma_params from the ZIPX stream. */
1505         if((p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1506                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1507                     "Truncated lzma data");
1508                 return (ARCHIVE_FATAL);
1509         }
1510
1511         if(p[2] != 0x05 || p[3] != 0x00) {
1512                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1513                     "Invalid lzma data");
1514                 return (ARCHIVE_FATAL);
1515         }
1516
1517         /* Prepare an lzma alone header: copy the lzma_params blob into a proper
1518          * place into the lzma alone header. */
1519         memcpy(&alone_header.bytes[0], p + 4, 5);
1520
1521         /* Initialize the 'uncompressed size' field to unknown; we'll manually
1522          * monitor how many bytes there are still to be uncompressed. */
1523         alone_header.uncompressed_size = UINT64_MAX;
1524
1525         if(!zip->uncompressed_buffer) {
1526                 zip->uncompressed_buffer_size = 256 * 1024;
1527                 zip->uncompressed_buffer =
1528                         (uint8_t*) malloc(zip->uncompressed_buffer_size);
1529
1530                 if (zip->uncompressed_buffer == NULL) {
1531                         archive_set_error(&a->archive, ENOMEM,
1532                             "No memory for lzma decompression");
1533                         return (ARCHIVE_FATAL);
1534                 }
1535         }
1536
1537         zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1538         zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1539         zip->zipx_lzma_stream.total_in = 0;
1540         zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1541         zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1542         zip->zipx_lzma_stream.total_out = 0;
1543
1544         /* Feed only the header into the lzma alone decoder. This will effectively
1545          * initialize the decoder, and will not produce any output bytes yet. */
1546         r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1547         if (r != LZMA_OK) {
1548                 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1549                     "lzma stream initialization error");
1550                 return ARCHIVE_FATAL;
1551         }
1552
1553         /* We've already consumed some bytes, so take this into account. */
1554         __archive_read_consume(a, 9);
1555         zip->entry_bytes_remaining -= 9;
1556         zip->entry_compressed_bytes_read += 9;
1557
1558         zip->decompress_init = 1;
1559         return (ARCHIVE_OK);
1560 }
1561
1562 static int
1563 zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1564         size_t *size, int64_t *offset)
1565 {
1566         struct zip* zip = (struct zip *)(a->format->data);
1567         int ret;
1568         lzma_ret lz_ret;
1569         const void* compressed_buf;
1570         ssize_t bytes_avail, in_bytes, to_consume = 0;
1571
1572         (void) offset; /* UNUSED */
1573
1574         /* Initialize decompressor if not yet initialized. */
1575         if (!zip->decompress_init) {
1576                 ret = zipx_xz_init(a, zip);
1577                 if (ret != ARCHIVE_OK)
1578                         return (ret);
1579         }
1580
1581         compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1582         if (bytes_avail < 0) {
1583                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1584                     "Truncated xz file body");
1585                 return (ARCHIVE_FATAL);
1586         }
1587
1588         in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1589         zip->zipx_lzma_stream.next_in = compressed_buf;
1590         zip->zipx_lzma_stream.avail_in = in_bytes;
1591         zip->zipx_lzma_stream.total_in = 0;
1592         zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1593         zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1594         zip->zipx_lzma_stream.total_out = 0;
1595
1596         /* Perform the decompression. */
1597         lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1598         switch(lz_ret) {
1599                 case LZMA_DATA_ERROR:
1600                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1601                             "xz data error (error %d)", (int) lz_ret);
1602                         return (ARCHIVE_FATAL);
1603
1604                 case LZMA_NO_CHECK:
1605                 case LZMA_OK:
1606                         break;
1607
1608                 default:
1609                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1610                             "xz unknown error %d", (int) lz_ret);
1611                         return (ARCHIVE_FATAL);
1612
1613                 case LZMA_STREAM_END:
1614                         lzma_end(&zip->zipx_lzma_stream);
1615                         zip->zipx_lzma_valid = 0;
1616
1617                         if((int64_t) zip->zipx_lzma_stream.total_in !=
1618                             zip->entry_bytes_remaining)
1619                         {
1620                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1621                                     "xz premature end of stream");
1622                                 return (ARCHIVE_FATAL);
1623                         }
1624
1625                         zip->end_of_entry = 1;
1626                         break;
1627         }
1628
1629         to_consume = zip->zipx_lzma_stream.total_in;
1630
1631         __archive_read_consume(a, to_consume);
1632         zip->entry_bytes_remaining -= to_consume;
1633         zip->entry_compressed_bytes_read += to_consume;
1634         zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1635
1636         *size = zip->zipx_lzma_stream.total_out;
1637         *buff = zip->uncompressed_buffer;
1638
1639         ret = consume_optional_marker(a, zip);
1640         if (ret != ARCHIVE_OK)
1641                 return (ret);
1642
1643         return (ARCHIVE_OK);
1644 }
1645
1646 static int
1647 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1648     size_t *size, int64_t *offset)
1649 {
1650         struct zip* zip = (struct zip *)(a->format->data);
1651         int ret;
1652         lzma_ret lz_ret;
1653         const void* compressed_buf;
1654         ssize_t bytes_avail, in_bytes, to_consume;
1655
1656         (void) offset; /* UNUSED */
1657
1658         /* Initialize decompressor if not yet initialized. */
1659         if (!zip->decompress_init) {
1660                 ret = zipx_lzma_alone_init(a, zip);
1661                 if (ret != ARCHIVE_OK)
1662                         return (ret);
1663         }
1664
1665         /* Fetch more compressed data. The same note as in deflate handler applies
1666          * here as well:
1667          *
1668          * Note: '1' here is a performance optimization. Recall that the
1669          * decompression layer returns a count of available bytes; asking for more
1670          * than that forces the decompressor to combine reads by copying data.
1671          */
1672         compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1673         if (bytes_avail < 0) {
1674                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1675                     "Truncated lzma file body");
1676                 return (ARCHIVE_FATAL);
1677         }
1678
1679         /* Set decompressor parameters. */
1680         in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1681
1682         zip->zipx_lzma_stream.next_in = compressed_buf;
1683         zip->zipx_lzma_stream.avail_in = in_bytes;
1684         zip->zipx_lzma_stream.total_in = 0;
1685         zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1686         zip->zipx_lzma_stream.avail_out =
1687                 /* These lzma_alone streams lack end of stream marker, so let's make
1688                  * sure the unpacker won't try to unpack more than it's supposed to. */
1689                 zipmin((int64_t) zip->uncompressed_buffer_size,
1690                     zip->entry->uncompressed_size -
1691                     zip->entry_uncompressed_bytes_read);
1692         zip->zipx_lzma_stream.total_out = 0;
1693
1694         /* Perform the decompression. */
1695         lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1696         switch(lz_ret) {
1697                 case LZMA_DATA_ERROR:
1698                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1699                             "lzma data error (error %d)", (int) lz_ret);
1700                         return (ARCHIVE_FATAL);
1701
1702                 case LZMA_OK:
1703                         break;
1704
1705                 default:
1706                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1707                             "lzma unknown error %d", (int) lz_ret);
1708                         return (ARCHIVE_FATAL);
1709         }
1710
1711         to_consume = zip->zipx_lzma_stream.total_in;
1712
1713         /* Update pointers. */
1714         __archive_read_consume(a, to_consume);
1715         zip->entry_bytes_remaining -= to_consume;
1716         zip->entry_compressed_bytes_read += to_consume;
1717         zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1718
1719         if(zip->entry_bytes_remaining == 0) {
1720                 zip->end_of_entry = 1;
1721         }
1722
1723         /* Return values. */
1724         *size = zip->zipx_lzma_stream.total_out;
1725         *buff = zip->uncompressed_buffer;
1726
1727         /* Behave the same way as during deflate decompression. */
1728         ret = consume_optional_marker(a, zip);
1729         if (ret != ARCHIVE_OK)
1730                 return (ret);
1731
1732         /* Free lzma decoder handle because we'll no longer need it. */
1733         if(zip->end_of_entry) {
1734                 lzma_end(&zip->zipx_lzma_stream);
1735                 zip->zipx_lzma_valid = 0;
1736         }
1737
1738         /* If we're here, then we're good! */
1739         return (ARCHIVE_OK);
1740 }
1741 #endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1742
1743 static int
1744 zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1745 {
1746         const void* p;
1747         uint32_t val;
1748         uint32_t order;
1749         uint32_t mem;
1750         uint32_t restore_method;
1751
1752         /* Remove previous decompression context if it exists. */
1753         if(zip->ppmd8_valid) {
1754                 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1755                 zip->ppmd8_valid = 0;
1756         }
1757
1758         /* Create a new decompression context. */
1759         __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1760         zip->ppmd8_stream_failed = 0;
1761
1762         /* Setup function pointers required by Ppmd8 decompressor. The
1763          * 'ppmd_read' function will feed new bytes to the decompressor,
1764          * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
1765         zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
1766         zip->zipx_ppmd_stream.a = a;
1767         zip->zipx_ppmd_stream.Read = &ppmd_read;
1768
1769         /* Reset number of read bytes to 0. */
1770         zip->zipx_ppmd_read_compressed = 0;
1771
1772         /* Read Ppmd8 header (2 bytes). */
1773         p = __archive_read_ahead(a, 2, NULL);
1774         if(!p) {
1775                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1776                     "Truncated file data in PPMd8 stream");
1777                 return (ARCHIVE_FATAL);
1778         }
1779         __archive_read_consume(a, 2);
1780
1781         /* Decode the stream's compression parameters. */
1782         val = archive_le16dec(p);
1783         order = (val & 15) + 1;
1784         mem = ((val >> 4) & 0xff) + 1;
1785         restore_method = (val >> 12);
1786
1787         if(order < 2 || restore_method > 2) {
1788                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1789                     "Invalid parameter set in PPMd8 stream (order=%d, "
1790                     "restore=%d)", order, restore_method);
1791                 return (ARCHIVE_FAILED);
1792         }
1793
1794         /* Allocate the memory needed to properly decompress the file. */
1795         if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
1796                 archive_set_error(&a->archive, ENOMEM,
1797                     "Unable to allocate memory for PPMd8 stream: %d bytes",
1798                     mem << 20);
1799                 return (ARCHIVE_FATAL);
1800         }
1801
1802         /* Signal the cleanup function to release Ppmd8 context in the
1803          * cleanup phase. */
1804         zip->ppmd8_valid = 1;
1805
1806         /* Perform further Ppmd8 initialization. */
1807         if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
1808                 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1809                     "PPMd8 stream range decoder initialization error");
1810                 return (ARCHIVE_FATAL);
1811         }
1812
1813         __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order, restore_method);
1814
1815         /* Allocate the buffer that will hold uncompressed data. */
1816         free(zip->uncompressed_buffer);
1817
1818         zip->uncompressed_buffer_size = 256 * 1024;
1819         zip->uncompressed_buffer =
1820             (uint8_t*) malloc(zip->uncompressed_buffer_size);
1821
1822         if(zip->uncompressed_buffer == NULL) {
1823                 archive_set_error(&a->archive, ENOMEM,
1824                     "No memory for PPMd8 decompression");
1825                 return ARCHIVE_FATAL;
1826         }
1827
1828         /* Ppmd8 initialization is done. */
1829         zip->decompress_init = 1;
1830
1831         /* We've already read 2 bytes in the output stream. Additionally,
1832          * Ppmd8 initialization code could read some data as well. So we
1833          * are advancing the stream by 2 bytes plus whatever number of
1834          * bytes Ppmd8 init function used. */
1835         zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
1836
1837         return ARCHIVE_OK;
1838 }
1839
1840 static int
1841 zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
1842     size_t *size, int64_t *offset)
1843 {
1844         struct zip* zip = (struct zip *)(a->format->data);
1845         int ret;
1846         size_t consumed_bytes = 0;
1847         ssize_t bytes_avail = 0;
1848
1849         (void) offset; /* UNUSED */
1850
1851         /* If we're here for the first time, initialize Ppmd8 decompression
1852          * context first. */
1853         if(!zip->decompress_init) {
1854                 ret = zipx_ppmd8_init(a, zip);
1855                 if(ret != ARCHIVE_OK)
1856                         return ret;
1857         }
1858
1859         /* Fetch for more data. We're reading 1 byte here, but libarchive should
1860          * prefetch more bytes. */
1861         (void) __archive_read_ahead(a, 1, &bytes_avail);
1862         if(bytes_avail < 0) {
1863                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1864                     "Truncated PPMd8 file body");
1865                 return (ARCHIVE_FATAL);
1866         }
1867
1868         /* This counter will be updated inside ppmd_read(), which at one
1869          * point will be called by Ppmd8_DecodeSymbol. */
1870         zip->zipx_ppmd_read_compressed = 0;
1871
1872         /* Decompression loop. */
1873         do {
1874                 int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(&zip->ppmd8);
1875                 if(sym < 0) {
1876                         zip->end_of_entry = 1;
1877                         break;
1878                 }
1879
1880                 /* This field is set by ppmd_read() when there was no more data
1881                  * to be read. */
1882                 if(zip->ppmd8_stream_failed) {
1883                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1884                                 "Truncated PPMd8 file body");
1885                         return (ARCHIVE_FATAL);
1886                 }
1887
1888                 zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
1889                 ++consumed_bytes;
1890         } while(consumed_bytes < zip->uncompressed_buffer_size);
1891
1892         /* Update pointers for libarchive. */
1893         *buff = zip->uncompressed_buffer;
1894         *size = consumed_bytes;
1895
1896         /* Update pointers so we can continue decompression in another call. */
1897         zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
1898         zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
1899         zip->entry_uncompressed_bytes_read += consumed_bytes;
1900
1901         /* If we're at the end of stream, deinitialize Ppmd8 context. */
1902         if(zip->end_of_entry) {
1903                 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1904                 zip->ppmd8_valid = 0;
1905         }
1906
1907         /* Seek for optional marker, same way as in each zip entry. */
1908         ret = consume_optional_marker(a, zip);
1909         if (ret != ARCHIVE_OK)
1910                 return ret;
1911
1912         return ARCHIVE_OK;
1913 }
1914
1915 #ifdef HAVE_BZLIB_H
1916 static int
1917 zipx_bzip2_init(struct archive_read *a, struct zip *zip)
1918 {
1919         int r;
1920
1921         /* Deallocate already existing BZ2 decompression context if it
1922          * exists. */
1923         if(zip->bzstream_valid) {
1924                 BZ2_bzDecompressEnd(&zip->bzstream);
1925                 zip->bzstream_valid = 0;
1926         }
1927
1928         /* Allocate a new BZ2 decompression context. */
1929         memset(&zip->bzstream, 0, sizeof(bz_stream));
1930         r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
1931         if(r != BZ_OK) {
1932                 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1933                     "bzip2 initialization failed(%d)",
1934                     r);
1935
1936                 return ARCHIVE_FAILED;
1937         }
1938
1939         /* Mark the bzstream field to be released in cleanup phase. */
1940         zip->bzstream_valid = 1;
1941
1942         /* (Re)allocate the buffer that will contain decompressed bytes. */
1943         free(zip->uncompressed_buffer);
1944
1945         zip->uncompressed_buffer_size = 256 * 1024;
1946         zip->uncompressed_buffer =
1947             (uint8_t*) malloc(zip->uncompressed_buffer_size);
1948         if (zip->uncompressed_buffer == NULL) {
1949                 archive_set_error(&a->archive, ENOMEM,
1950                     "No memory for bzip2 decompression");
1951                     return ARCHIVE_FATAL;
1952         }
1953
1954         /* Initialization done. */
1955         zip->decompress_init = 1;
1956         return ARCHIVE_OK;
1957 }
1958
1959 static int
1960 zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
1961     size_t *size, int64_t *offset)
1962 {
1963         struct zip *zip = (struct zip *)(a->format->data);
1964         ssize_t bytes_avail = 0, in_bytes, to_consume;
1965         const void *compressed_buff;
1966         int r;
1967         uint64_t total_out;
1968
1969         (void) offset; /* UNUSED */
1970
1971         /* Initialize decompression context if we're here for the first time. */
1972         if(!zip->decompress_init) {
1973                 r = zipx_bzip2_init(a, zip);
1974                 if(r != ARCHIVE_OK)
1975                         return r;
1976         }
1977
1978         /* Fetch more compressed bytes. */
1979         compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
1980         if(bytes_avail < 0) {
1981                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1982                     "Truncated bzip2 file body");
1983                 return (ARCHIVE_FATAL);
1984         }
1985
1986         in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1987         if(in_bytes < 1) {
1988                 /* libbz2 doesn't complain when caller feeds avail_in == 0. It will
1989                  * actually return success in this case, which is undesirable. This is
1990                  * why we need to make this check manually. */
1991
1992                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1993                     "Truncated bzip2 file body");
1994                 return (ARCHIVE_FATAL);
1995         }
1996
1997         /* Setup buffer boundaries. */
1998         zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
1999         zip->bzstream.avail_in = in_bytes;
2000         zip->bzstream.total_in_hi32 = 0;
2001         zip->bzstream.total_in_lo32 = 0;
2002         zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2003         zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2004         zip->bzstream.total_out_hi32 = 0;
2005         zip->bzstream.total_out_lo32 = 0;
2006
2007         /* Perform the decompression. */
2008         r = BZ2_bzDecompress(&zip->bzstream);
2009         switch(r) {
2010                 case BZ_STREAM_END:
2011                         /* If we're at the end of the stream, deinitialize the
2012                          * decompression context now. */
2013                         switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2014                                 case BZ_OK:
2015                                         break;
2016                                 default:
2017                                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2018                                             "Failed to clean up bzip2 decompressor");
2019                                         return ARCHIVE_FATAL;
2020                         }
2021
2022                         zip->end_of_entry = 1;
2023                         break;
2024                 case BZ_OK:
2025                         /* The decompressor has successfully decoded this chunk of
2026                          * data, but more data is still in queue. */
2027                         break;
2028                 default:
2029                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2030                             "bzip2 decompression failed");
2031                         return ARCHIVE_FATAL;
2032         }
2033
2034         /* Update the pointers so decompressor can continue decoding. */
2035         to_consume = zip->bzstream.total_in_lo32;
2036         __archive_read_consume(a, to_consume);
2037
2038         total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2039             zip->bzstream.total_out_lo32;
2040
2041         zip->entry_bytes_remaining -= to_consume;
2042         zip->entry_compressed_bytes_read += to_consume;
2043         zip->entry_uncompressed_bytes_read += total_out;
2044
2045         /* Give libarchive its due. */
2046         *size = total_out;
2047         *buff = zip->uncompressed_buffer;
2048
2049         /* Seek for optional marker, like in other entries. */
2050         r = consume_optional_marker(a, zip);
2051         if(r != ARCHIVE_OK)
2052                 return r;
2053
2054         return ARCHIVE_OK;
2055 }
2056
2057 #endif
2058
2059 #ifdef HAVE_ZLIB_H
2060 static int
2061 zip_deflate_init(struct archive_read *a, struct zip *zip)
2062 {
2063         int r;
2064
2065         /* If we haven't yet read any data, initialize the decompressor. */
2066         if (!zip->decompress_init) {
2067                 if (zip->stream_valid)
2068                         r = inflateReset(&zip->stream);
2069                 else
2070                         r = inflateInit2(&zip->stream,
2071                             -15 /* Don't check for zlib header */);
2072                 if (r != Z_OK) {
2073                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2074                             "Can't initialize ZIP decompression.");
2075                         return (ARCHIVE_FATAL);
2076                 }
2077                 /* Stream structure has been set up. */
2078                 zip->stream_valid = 1;
2079                 /* We've initialized decompression for this stream. */
2080                 zip->decompress_init = 1;
2081         }
2082         return (ARCHIVE_OK);
2083 }
2084
2085 static int
2086 zip_read_data_deflate(struct archive_read *a, const void **buff,
2087     size_t *size, int64_t *offset)
2088 {
2089         struct zip *zip;
2090         ssize_t bytes_avail;
2091         const void *compressed_buff, *sp;
2092         int r;
2093
2094         (void)offset; /* UNUSED */
2095
2096         zip = (struct zip *)(a->format->data);
2097
2098         /* If the buffer hasn't been allocated, allocate it now. */
2099         if (zip->uncompressed_buffer == NULL) {
2100                 zip->uncompressed_buffer_size = 256 * 1024;
2101                 zip->uncompressed_buffer
2102                     = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2103                 if (zip->uncompressed_buffer == NULL) {
2104                         archive_set_error(&a->archive, ENOMEM,
2105                             "No memory for ZIP decompression");
2106                         return (ARCHIVE_FATAL);
2107                 }
2108         }
2109
2110         r = zip_deflate_init(a, zip);
2111         if (r != ARCHIVE_OK)
2112                 return (r);
2113
2114         /*
2115          * Note: '1' here is a performance optimization.
2116          * Recall that the decompression layer returns a count of
2117          * available bytes; asking for more than that forces the
2118          * decompressor to combine reads by copying data.
2119          */
2120         compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2121         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2122             && bytes_avail > zip->entry_bytes_remaining) {
2123                 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2124         }
2125         if (bytes_avail < 0) {
2126                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2127                     "Truncated ZIP file body");
2128                 return (ARCHIVE_FATAL);
2129         }
2130
2131         if (zip->tctx_valid || zip->cctx_valid) {
2132                 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2133                         size_t buff_remaining =
2134                             (zip->decrypted_buffer + zip->decrypted_buffer_size)
2135                             - (zip->decrypted_ptr + zip->decrypted_bytes_remaining);
2136
2137                         if (buff_remaining > (size_t)bytes_avail)
2138                                 buff_remaining = (size_t)bytes_avail;
2139
2140                         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2141                               zip->entry_bytes_remaining > 0) {
2142                                 if ((int64_t)(zip->decrypted_bytes_remaining
2143                                     + buff_remaining)
2144                                       > zip->entry_bytes_remaining) {
2145                                         if (zip->entry_bytes_remaining <
2146                                               (int64_t)zip->decrypted_bytes_remaining)
2147                                                 buff_remaining = 0;
2148                                         else
2149                                                 buff_remaining =
2150                                                     (size_t)zip->entry_bytes_remaining
2151                                                       - zip->decrypted_bytes_remaining;
2152                                 }
2153                         }
2154                         if (buff_remaining > 0) {
2155                                 if (zip->tctx_valid) {
2156                                         trad_enc_decrypt_update(&zip->tctx,
2157                                             compressed_buff, buff_remaining,
2158                                             zip->decrypted_ptr
2159                                               + zip->decrypted_bytes_remaining,
2160                                             buff_remaining);
2161                                 } else {
2162                                         size_t dsize = buff_remaining;
2163                                         archive_decrypto_aes_ctr_update(
2164                                             &zip->cctx,
2165                                             compressed_buff, buff_remaining,
2166                                             zip->decrypted_ptr
2167                                               + zip->decrypted_bytes_remaining,
2168                                             &dsize);
2169                                 }
2170                                 zip->decrypted_bytes_remaining += buff_remaining;
2171                         }
2172                 }
2173                 bytes_avail = zip->decrypted_bytes_remaining;
2174                 compressed_buff = (const char *)zip->decrypted_ptr;
2175         }
2176
2177         /*
2178          * A bug in zlib.h: stream.next_in should be marked 'const'
2179          * but isn't (the library never alters data through the
2180          * next_in pointer, only reads it).  The result: this ugly
2181          * cast to remove 'const'.
2182          */
2183         zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2184         zip->stream.avail_in = (uInt)bytes_avail;
2185         zip->stream.total_in = 0;
2186         zip->stream.next_out = zip->uncompressed_buffer;
2187         zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2188         zip->stream.total_out = 0;
2189
2190         r = inflate(&zip->stream, 0);
2191         switch (r) {
2192         case Z_OK:
2193                 break;
2194         case Z_STREAM_END:
2195                 zip->end_of_entry = 1;
2196                 break;
2197         case Z_MEM_ERROR:
2198                 archive_set_error(&a->archive, ENOMEM,
2199                     "Out of memory for ZIP decompression");
2200                 return (ARCHIVE_FATAL);
2201         default:
2202                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2203                     "ZIP decompression failed (%d)", r);
2204                 return (ARCHIVE_FATAL);
2205         }
2206
2207         /* Consume as much as the compressor actually used. */
2208         bytes_avail = zip->stream.total_in;
2209         if (zip->tctx_valid || zip->cctx_valid) {
2210                 zip->decrypted_bytes_remaining -= bytes_avail;
2211                 if (zip->decrypted_bytes_remaining == 0)
2212                         zip->decrypted_ptr = zip->decrypted_buffer;
2213                 else
2214                         zip->decrypted_ptr += bytes_avail;
2215         }
2216         /* Calculate compressed data as much as we used.*/
2217         if (zip->hctx_valid)
2218                 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2219         __archive_read_consume(a, bytes_avail);
2220         zip->entry_bytes_remaining -= bytes_avail;
2221         zip->entry_compressed_bytes_read += bytes_avail;
2222
2223         *size = zip->stream.total_out;
2224         zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2225         *buff = zip->uncompressed_buffer;
2226
2227         if (zip->end_of_entry && zip->hctx_valid) {
2228                 r = check_authentication_code(a, NULL);
2229                 if (r != ARCHIVE_OK)
2230                         return (r);
2231         }
2232
2233         r = consume_optional_marker(a, zip);
2234         if (r != ARCHIVE_OK)
2235                 return (r);
2236
2237         return (ARCHIVE_OK);
2238 }
2239 #endif
2240
2241 static int
2242 read_decryption_header(struct archive_read *a)
2243 {
2244         struct zip *zip = (struct zip *)(a->format->data);
2245         const char *p;
2246         unsigned int remaining_size;
2247         unsigned int ts;
2248
2249         /*
2250          * Read an initialization vector data field.
2251          */
2252         p = __archive_read_ahead(a, 2, NULL);
2253         if (p == NULL)
2254                 goto truncated;
2255         ts = zip->iv_size;
2256         zip->iv_size = archive_le16dec(p);
2257         __archive_read_consume(a, 2);
2258         if (ts < zip->iv_size) {
2259                 free(zip->iv);
2260                 zip->iv = NULL;
2261         }
2262         p = __archive_read_ahead(a, zip->iv_size, NULL);
2263         if (p == NULL)
2264                 goto truncated;
2265         if (zip->iv == NULL) {
2266                 zip->iv = malloc(zip->iv_size);
2267                 if (zip->iv == NULL)
2268                         goto nomem;
2269         }
2270         memcpy(zip->iv, p, zip->iv_size);
2271         __archive_read_consume(a, zip->iv_size);
2272
2273         /*
2274          * Read a size of remaining decryption header field.
2275          */
2276         p = __archive_read_ahead(a, 14, NULL);
2277         if (p == NULL)
2278                 goto truncated;
2279         remaining_size = archive_le32dec(p);
2280         if (remaining_size < 16 || remaining_size > (1 << 18))
2281                 goto corrupted;
2282
2283         /* Check if format version is supported. */
2284         if (archive_le16dec(p+4) != 3) {
2285                 archive_set_error(&a->archive,
2286                     ARCHIVE_ERRNO_FILE_FORMAT,
2287                     "Unsupported encryption format version: %u",
2288                     archive_le16dec(p+4));
2289                 return (ARCHIVE_FAILED);
2290         }
2291
2292         /*
2293          * Read an encryption algorithm field.
2294          */
2295         zip->alg_id = archive_le16dec(p+6);
2296         switch (zip->alg_id) {
2297         case 0x6601:/* DES */
2298         case 0x6602:/* RC2 */
2299         case 0x6603:/* 3DES 168 */
2300         case 0x6609:/* 3DES 112 */
2301         case 0x660E:/* AES 128 */
2302         case 0x660F:/* AES 192 */
2303         case 0x6610:/* AES 256 */
2304         case 0x6702:/* RC2 (version >= 5.2) */
2305         case 0x6720:/* Blowfish */
2306         case 0x6721:/* Twofish */
2307         case 0x6801:/* RC4 */
2308                 /* Supported encryption algorithm. */
2309                 break;
2310         default:
2311                 archive_set_error(&a->archive,
2312                     ARCHIVE_ERRNO_FILE_FORMAT,
2313                     "Unknown encryption algorithm: %u", zip->alg_id);
2314                 return (ARCHIVE_FAILED);
2315         }
2316
2317         /*
2318          * Read a bit length field.
2319          */
2320         zip->bit_len = archive_le16dec(p+8);
2321
2322         /*
2323          * Read a flags field.
2324          */
2325         zip->flags = archive_le16dec(p+10);
2326         switch (zip->flags & 0xf000) {
2327         case 0x0001: /* Password is required to decrypt. */
2328         case 0x0002: /* Certificates only. */
2329         case 0x0003: /* Password or certificate required to decrypt. */
2330                 break;
2331         default:
2332                 archive_set_error(&a->archive,
2333                     ARCHIVE_ERRNO_FILE_FORMAT,
2334                     "Unknown encryption flag: %u", zip->flags);
2335                 return (ARCHIVE_FAILED);
2336         }
2337         if ((zip->flags & 0xf000) == 0 ||
2338             (zip->flags & 0xf000) == 0x4000) {
2339                 archive_set_error(&a->archive,
2340                     ARCHIVE_ERRNO_FILE_FORMAT,
2341                     "Unknown encryption flag: %u", zip->flags);
2342                 return (ARCHIVE_FAILED);
2343         }
2344
2345         /*
2346          * Read an encrypted random data field.
2347          */
2348         ts = zip->erd_size;
2349         zip->erd_size = archive_le16dec(p+12);
2350         __archive_read_consume(a, 14);
2351         if ((zip->erd_size & 0xf) != 0 ||
2352             (zip->erd_size + 16) > remaining_size ||
2353             (zip->erd_size + 16) < zip->erd_size)
2354                 goto corrupted;
2355
2356         if (ts < zip->erd_size) {
2357                 free(zip->erd);
2358                 zip->erd = NULL;
2359         }
2360         p = __archive_read_ahead(a, zip->erd_size, NULL);
2361         if (p == NULL)
2362                 goto truncated;
2363         if (zip->erd == NULL) {
2364                 zip->erd = malloc(zip->erd_size);
2365                 if (zip->erd == NULL)
2366                         goto nomem;
2367         }
2368         memcpy(zip->erd, p, zip->erd_size);
2369         __archive_read_consume(a, zip->erd_size);
2370
2371         /*
2372          * Read a reserved data field.
2373          */
2374         p = __archive_read_ahead(a, 4, NULL);
2375         if (p == NULL)
2376                 goto truncated;
2377         /* Reserved data size should be zero. */
2378         if (archive_le32dec(p) != 0)
2379                 goto corrupted;
2380         __archive_read_consume(a, 4);
2381
2382         /*
2383          * Read a password validation data field.
2384          */
2385         p = __archive_read_ahead(a, 2, NULL);
2386         if (p == NULL)
2387                 goto truncated;
2388         ts = zip->v_size;
2389         zip->v_size = archive_le16dec(p);
2390         __archive_read_consume(a, 2);
2391         if ((zip->v_size & 0x0f) != 0 ||
2392             (zip->erd_size + zip->v_size + 16) > remaining_size ||
2393             (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2394                 goto corrupted;
2395         if (ts < zip->v_size) {
2396                 free(zip->v_data);
2397                 zip->v_data = NULL;
2398         }
2399         p = __archive_read_ahead(a, zip->v_size, NULL);
2400         if (p == NULL)
2401                 goto truncated;
2402         if (zip->v_data == NULL) {
2403                 zip->v_data = malloc(zip->v_size);
2404                 if (zip->v_data == NULL)
2405                         goto nomem;
2406         }
2407         memcpy(zip->v_data, p, zip->v_size);
2408         __archive_read_consume(a, zip->v_size);
2409
2410         p = __archive_read_ahead(a, 4, NULL);
2411         if (p == NULL)
2412                 goto truncated;
2413         zip->v_crc32 = archive_le32dec(p);
2414         __archive_read_consume(a, 4);
2415
2416         /*return (ARCHIVE_OK);
2417          * This is not fully implemented yet.*/
2418         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2419             "Encrypted file is unsupported");
2420         return (ARCHIVE_FAILED);
2421 truncated:
2422         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2423             "Truncated ZIP file data");
2424         return (ARCHIVE_FATAL);
2425 corrupted:
2426         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2427             "Corrupted ZIP file data");
2428         return (ARCHIVE_FATAL);
2429 nomem:
2430         archive_set_error(&a->archive, ENOMEM,
2431             "No memory for ZIP decryption");
2432         return (ARCHIVE_FATAL);
2433 }
2434
2435 static int
2436 zip_alloc_decryption_buffer(struct archive_read *a)
2437 {
2438         struct zip *zip = (struct zip *)(a->format->data);
2439         size_t bs = 256 * 1024;
2440
2441         if (zip->decrypted_buffer == NULL) {
2442                 zip->decrypted_buffer_size = bs;
2443                 zip->decrypted_buffer = malloc(bs);
2444                 if (zip->decrypted_buffer == NULL) {
2445                         archive_set_error(&a->archive, ENOMEM,
2446                             "No memory for ZIP decryption");
2447                         return (ARCHIVE_FATAL);
2448                 }
2449         }
2450         zip->decrypted_ptr = zip->decrypted_buffer;
2451         return (ARCHIVE_OK);
2452 }
2453
2454 static int
2455 init_traditional_PKWARE_decryption(struct archive_read *a)
2456 {
2457         struct zip *zip = (struct zip *)(a->format->data);
2458         const void *p;
2459         int retry;
2460         int r;
2461
2462         if (zip->tctx_valid)
2463                 return (ARCHIVE_OK);
2464
2465         /*
2466            Read the 12 bytes encryption header stored at
2467            the start of the data area.
2468          */
2469 #define ENC_HEADER_SIZE 12
2470         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2471             && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2472                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2473                     "Truncated Zip encrypted body: only %jd bytes available",
2474                     (intmax_t)zip->entry_bytes_remaining);
2475                 return (ARCHIVE_FATAL);
2476         }
2477
2478         p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2479         if (p == NULL) {
2480                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2481                     "Truncated ZIP file data");
2482                 return (ARCHIVE_FATAL);
2483         }
2484
2485         for (retry = 0;; retry++) {
2486                 const char *passphrase;
2487                 uint8_t crcchk;
2488
2489                 passphrase = __archive_read_next_passphrase(a);
2490                 if (passphrase == NULL) {
2491                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2492                             (retry > 0)?
2493                                 "Incorrect passphrase":
2494                                 "Passphrase required for this entry");
2495                         return (ARCHIVE_FAILED);
2496                 }
2497
2498                 /*
2499                  * Initialize ctx for Traditional PKWARE Decryption.
2500                  */
2501                 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2502                         p, ENC_HEADER_SIZE, &crcchk);
2503                 if (r == 0 && crcchk == zip->entry->decdat)
2504                         break;/* The passphrase is OK. */
2505                 if (retry > 10000) {
2506                         /* Avoid infinity loop. */
2507                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2508                             "Too many incorrect passphrases");
2509                         return (ARCHIVE_FAILED);
2510                 }
2511         }
2512
2513         __archive_read_consume(a, ENC_HEADER_SIZE);
2514         zip->tctx_valid = 1;
2515         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2516             zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2517         }
2518         /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2519         zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2520         zip->decrypted_bytes_remaining = 0;
2521
2522         return (zip_alloc_decryption_buffer(a));
2523 #undef ENC_HEADER_SIZE
2524 }
2525
2526 static int
2527 init_WinZip_AES_decryption(struct archive_read *a)
2528 {
2529         struct zip *zip = (struct zip *)(a->format->data);
2530         const void *p;
2531         const uint8_t *pv;
2532         size_t key_len, salt_len;
2533         uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2534         int retry;
2535         int r;
2536
2537         if (zip->cctx_valid || zip->hctx_valid)
2538                 return (ARCHIVE_OK);
2539
2540         switch (zip->entry->aes_extra.strength) {
2541         case 1: salt_len = 8;  key_len = 16; break;
2542         case 2: salt_len = 12; key_len = 24; break;
2543         case 3: salt_len = 16; key_len = 32; break;
2544         default: goto corrupted;
2545         }
2546         p = __archive_read_ahead(a, salt_len + 2, NULL);
2547         if (p == NULL)
2548                 goto truncated;
2549
2550         for (retry = 0;; retry++) {
2551                 const char *passphrase;
2552
2553                 passphrase = __archive_read_next_passphrase(a);
2554                 if (passphrase == NULL) {
2555                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2556                             (retry > 0)?
2557                                 "Incorrect passphrase":
2558                                 "Passphrase required for this entry");
2559                         return (ARCHIVE_FAILED);
2560                 }
2561                 memset(derived_key, 0, sizeof(derived_key));
2562                 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2563                     p, salt_len, 1000, derived_key, key_len * 2 + 2);
2564                 if (r != 0) {
2565                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2566                             "Decryption is unsupported due to lack of "
2567                             "crypto library");
2568                         return (ARCHIVE_FAILED);
2569                 }
2570
2571                 /* Check password verification value. */
2572                 pv = ((const uint8_t *)p) + salt_len;
2573                 if (derived_key[key_len * 2] == pv[0] &&
2574                     derived_key[key_len * 2 + 1] == pv[1])
2575                         break;/* The passphrase is OK. */
2576                 if (retry > 10000) {
2577                         /* Avoid infinity loop. */
2578                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2579                             "Too many incorrect passphrases");
2580                         return (ARCHIVE_FAILED);
2581                 }
2582         }
2583
2584         r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2585         if (r != 0) {
2586                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2587                     "Decryption is unsupported due to lack of crypto library");
2588                 return (ARCHIVE_FAILED);
2589         }
2590         r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2591         if (r != 0) {
2592                 archive_decrypto_aes_ctr_release(&zip->cctx);
2593                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2594                     "Failed to initialize HMAC-SHA1");
2595                 return (ARCHIVE_FAILED);
2596         }
2597         zip->cctx_valid = zip->hctx_valid = 1;
2598         __archive_read_consume(a, salt_len + 2);
2599         zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2600         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2601             && zip->entry_bytes_remaining < 0)
2602                 goto corrupted;
2603         zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2604         zip->decrypted_bytes_remaining = 0;
2605
2606         zip->entry->compression = zip->entry->aes_extra.compression;
2607         return (zip_alloc_decryption_buffer(a));
2608
2609 truncated:
2610         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2611             "Truncated ZIP file data");
2612         return (ARCHIVE_FATAL);
2613 corrupted:
2614         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2615             "Corrupted ZIP file data");
2616         return (ARCHIVE_FATAL);
2617 }
2618
2619 static int
2620 archive_read_format_zip_read_data(struct archive_read *a,
2621     const void **buff, size_t *size, int64_t *offset)
2622 {
2623         int r;
2624         struct zip *zip = (struct zip *)(a->format->data);
2625
2626         if (zip->has_encrypted_entries ==
2627                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2628                 zip->has_encrypted_entries = 0;
2629         }
2630
2631         *offset = zip->entry_uncompressed_bytes_read;
2632         *size = 0;
2633         *buff = NULL;
2634
2635         /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2636         if (zip->end_of_entry)
2637                 return (ARCHIVE_EOF);
2638
2639         /* Return EOF immediately if this is a non-regular file. */
2640         if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2641                 return (ARCHIVE_EOF);
2642
2643         __archive_read_consume(a, zip->unconsumed);
2644         zip->unconsumed = 0;
2645
2646         if (zip->init_decryption) {
2647                 zip->has_encrypted_entries = 1;
2648                 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2649                         r = read_decryption_header(a);
2650                 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2651                         r = init_WinZip_AES_decryption(a);
2652                 else
2653                         r = init_traditional_PKWARE_decryption(a);
2654                 if (r != ARCHIVE_OK)
2655                         return (r);
2656                 zip->init_decryption = 0;
2657         }
2658
2659         switch(zip->entry->compression) {
2660         case 0:  /* No compression. */
2661                 r =  zip_read_data_none(a, buff, size, offset);
2662                 break;
2663 #ifdef HAVE_BZLIB_H
2664         case 12: /* ZIPx bzip2 compression. */
2665                 r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2666                 break;
2667 #endif
2668 #if HAVE_LZMA_H && HAVE_LIBLZMA
2669         case 14: /* ZIPx LZMA compression. */
2670                 r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
2671                 break;
2672         case 95: /* ZIPx XZ compression. */
2673                 r = zip_read_data_zipx_xz(a, buff, size, offset);
2674                 break;
2675 #endif
2676         /* PPMd support is built-in, so we don't need any #if guards. */
2677         case 98: /* ZIPx PPMd compression. */
2678                 r = zip_read_data_zipx_ppmd(a, buff, size, offset);
2679                 break;
2680
2681 #ifdef HAVE_ZLIB_H
2682         case 8: /* Deflate compression. */
2683                 r =  zip_read_data_deflate(a, buff, size, offset);
2684                 break;
2685 #endif
2686         default: /* Unsupported compression. */
2687                 /* Return a warning. */
2688                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2689                     "Unsupported ZIP compression method (%d: %s)",
2690                     zip->entry->compression, compression_name(zip->entry->compression));
2691                 /* We can't decompress this entry, but we will
2692                  * be able to skip() it and try the next entry. */
2693                 return (ARCHIVE_FAILED);
2694                 break;
2695         }
2696         if (r != ARCHIVE_OK)
2697                 return (r);
2698         /* Update checksum */
2699         if (*size)
2700                 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
2701                     (unsigned)*size);
2702         /* If we hit the end, swallow any end-of-data marker. */
2703         if (zip->end_of_entry) {
2704                 /* Check file size, CRC against these values. */
2705                 if (zip->entry->compressed_size !=
2706                     zip->entry_compressed_bytes_read) {
2707                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2708                             "ZIP compressed data is wrong size "
2709                             "(read %jd, expected %jd)",
2710                             (intmax_t)zip->entry_compressed_bytes_read,
2711                             (intmax_t)zip->entry->compressed_size);
2712                         return (ARCHIVE_WARN);
2713                 }
2714                 /* Size field only stores the lower 32 bits of the actual
2715                  * size. */
2716                 if ((zip->entry->uncompressed_size & UINT32_MAX)
2717                     != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
2718                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2719                             "ZIP uncompressed data is wrong size "
2720                             "(read %jd, expected %jd)\n",
2721                             (intmax_t)zip->entry_uncompressed_bytes_read,
2722                             (intmax_t)zip->entry->uncompressed_size);
2723                         return (ARCHIVE_WARN);
2724                 }
2725                 /* Check computed CRC against header */
2726                 if ((!zip->hctx_valid ||
2727                       zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
2728                    zip->entry->crc32 != zip->entry_crc32
2729                     && !zip->ignore_crc32) {
2730                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2731                             "ZIP bad CRC: 0x%lx should be 0x%lx",
2732                             (unsigned long)zip->entry_crc32,
2733                             (unsigned long)zip->entry->crc32);
2734                         return (ARCHIVE_WARN);
2735                 }
2736         }
2737
2738         return (ARCHIVE_OK);
2739 }
2740
2741 static int
2742 archive_read_format_zip_cleanup(struct archive_read *a)
2743 {
2744         struct zip *zip;
2745         struct zip_entry *zip_entry, *next_zip_entry;
2746
2747         zip = (struct zip *)(a->format->data);
2748
2749 #ifdef HAVE_ZLIB_H
2750         if (zip->stream_valid)
2751                 inflateEnd(&zip->stream);
2752 #endif
2753
2754 #if HAVA_LZMA_H && HAVE_LIBLZMA
2755     if (zip->zipx_lzma_valid) {
2756                 lzma_end(&zip->zipx_lzma_stream);
2757         }
2758 #endif
2759
2760 #ifdef HAVE_BZLIB_H
2761         if (zip->bzstream_valid) {
2762                 BZ2_bzDecompressEnd(&zip->bzstream);
2763         }
2764 #endif
2765
2766         free(zip->uncompressed_buffer);
2767
2768         if (zip->ppmd8_valid)
2769                 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2770
2771         if (zip->zip_entries) {
2772                 zip_entry = zip->zip_entries;
2773                 while (zip_entry != NULL) {
2774                         next_zip_entry = zip_entry->next;
2775                         archive_string_free(&zip_entry->rsrcname);
2776                         free(zip_entry);
2777                         zip_entry = next_zip_entry;
2778                 }
2779         }
2780         free(zip->decrypted_buffer);
2781         if (zip->cctx_valid)
2782                 archive_decrypto_aes_ctr_release(&zip->cctx);
2783         if (zip->hctx_valid)
2784                 archive_hmac_sha1_cleanup(&zip->hctx);
2785         free(zip->iv);
2786         free(zip->erd);
2787         free(zip->v_data);
2788         archive_string_free(&zip->format_name);
2789         free(zip);
2790         (a->format->data) = NULL;
2791         return (ARCHIVE_OK);
2792 }
2793
2794 static int
2795 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
2796 {
2797         if (_a && _a->format) {
2798                 struct zip * zip = (struct zip *)_a->format->data;
2799                 if (zip) {
2800                         return zip->has_encrypted_entries;
2801                 }
2802         }
2803         return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2804 }
2805
2806 static int
2807 archive_read_format_zip_options(struct archive_read *a,
2808     const char *key, const char *val)
2809 {
2810         struct zip *zip;
2811         int ret = ARCHIVE_FAILED;
2812
2813         zip = (struct zip *)(a->format->data);
2814         if (strcmp(key, "compat-2x")  == 0) {
2815                 /* Handle filenames as libarchive 2.x */
2816                 zip->init_default_conversion = (val != NULL) ? 1 : 0;
2817                 return (ARCHIVE_OK);
2818         } else if (strcmp(key, "hdrcharset")  == 0) {
2819                 if (val == NULL || val[0] == 0)
2820                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2821                             "zip: hdrcharset option needs a character-set name"
2822                         );
2823                 else {
2824                         zip->sconv = archive_string_conversion_from_charset(
2825                             &a->archive, val, 0);
2826                         if (zip->sconv != NULL) {
2827                                 if (strcmp(val, "UTF-8") == 0)
2828                                         zip->sconv_utf8 = zip->sconv;
2829                                 ret = ARCHIVE_OK;
2830                         } else
2831                                 ret = ARCHIVE_FATAL;
2832                 }
2833                 return (ret);
2834         } else if (strcmp(key, "ignorecrc32") == 0) {
2835                 /* Mostly useful for testing. */
2836                 if (val == NULL || val[0] == 0) {
2837                         zip->crc32func = real_crc32;
2838                         zip->ignore_crc32 = 0;
2839                 } else {
2840                         zip->crc32func = fake_crc32;
2841                         zip->ignore_crc32 = 1;
2842                 }
2843                 return (ARCHIVE_OK);
2844         } else if (strcmp(key, "mac-ext") == 0) {
2845                 zip->process_mac_extensions = (val != NULL && val[0] != 0);
2846                 return (ARCHIVE_OK);
2847         }
2848
2849         /* Note: The "warn" return is just to inform the options
2850          * supervisor that we didn't handle it.  It will generate
2851          * a suitable error if no one used this option. */
2852         return (ARCHIVE_WARN);
2853 }
2854
2855 int
2856 archive_read_support_format_zip(struct archive *a)
2857 {
2858         int r;
2859         r = archive_read_support_format_zip_streamable(a);
2860         if (r != ARCHIVE_OK)
2861                 return r;
2862         return (archive_read_support_format_zip_seekable(a));
2863 }
2864
2865 /* ------------------------------------------------------------------------ */
2866
2867 /*
2868  * Streaming-mode support
2869  */
2870
2871
2872 static int
2873 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
2874 {
2875         (void)a; /* UNUSED */
2876         return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2877                 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2878 }
2879
2880 static int
2881 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
2882 {
2883         const char *p;
2884
2885         (void)best_bid; /* UNUSED */
2886
2887         if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
2888                 return (-1);
2889
2890         /*
2891          * Bid of 29 here comes from:
2892          *  + 16 bits for "PK",
2893          *  + next 16-bit field has 6 options so contributes
2894          *    about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
2895          *
2896          * So we've effectively verified ~29 total bits of check data.
2897          */
2898         if (p[0] == 'P' && p[1] == 'K') {
2899                 if ((p[2] == '\001' && p[3] == '\002')
2900                     || (p[2] == '\003' && p[3] == '\004')
2901                     || (p[2] == '\005' && p[3] == '\006')
2902                     || (p[2] == '\006' && p[3] == '\006')
2903                     || (p[2] == '\007' && p[3] == '\010')
2904                     || (p[2] == '0' && p[3] == '0'))
2905                         return (29);
2906         }
2907
2908         /* TODO: It's worth looking ahead a little bit for a valid
2909          * PK signature.  In particular, that would make it possible
2910          * to read some UUEncoded SFX files or SFX files coming from
2911          * a network socket. */
2912
2913         return (0);
2914 }
2915
2916 static int
2917 archive_read_format_zip_streamable_read_header(struct archive_read *a,
2918     struct archive_entry *entry)
2919 {
2920         struct zip *zip;
2921
2922         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
2923         if (a->archive.archive_format_name == NULL)
2924                 a->archive.archive_format_name = "ZIP";
2925
2926         zip = (struct zip *)(a->format->data);
2927
2928         /*
2929          * It should be sufficient to call archive_read_next_header() for
2930          * a reader to determine if an entry is encrypted or not. If the
2931          * encryption of an entry is only detectable when calling
2932          * archive_read_data(), so be it. We'll do the same check there
2933          * as well.
2934          */
2935         if (zip->has_encrypted_entries ==
2936                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
2937                 zip->has_encrypted_entries = 0;
2938
2939         /* Make sure we have a zip_entry structure to use. */
2940         if (zip->zip_entries == NULL) {
2941                 zip->zip_entries = malloc(sizeof(struct zip_entry));
2942                 if (zip->zip_entries == NULL) {
2943                         archive_set_error(&a->archive, ENOMEM,
2944                             "Out  of memory");
2945                         return ARCHIVE_FATAL;
2946                 }
2947         }
2948         zip->entry = zip->zip_entries;
2949         memset(zip->entry, 0, sizeof(struct zip_entry));
2950
2951         if (zip->cctx_valid)
2952                 archive_decrypto_aes_ctr_release(&zip->cctx);
2953         if (zip->hctx_valid)
2954                 archive_hmac_sha1_cleanup(&zip->hctx);
2955         zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
2956         __archive_read_reset_passphrase(a);
2957
2958         /* Search ahead for the next local file header. */
2959         __archive_read_consume(a, zip->unconsumed);
2960         zip->unconsumed = 0;
2961         for (;;) {
2962                 int64_t skipped = 0;
2963                 const char *p, *end;
2964                 ssize_t bytes;
2965
2966                 p = __archive_read_ahead(a, 4, &bytes);
2967                 if (p == NULL)
2968                         return (ARCHIVE_FATAL);
2969                 end = p + bytes;
2970
2971                 while (p + 4 <= end) {
2972                         if (p[0] == 'P' && p[1] == 'K') {
2973                                 if (p[2] == '\003' && p[3] == '\004') {
2974                                         /* Regular file entry. */
2975                                         __archive_read_consume(a, skipped);
2976                                         return zip_read_local_file_header(a,
2977                                             entry, zip);
2978                                 }
2979
2980                               /*
2981                                * TODO: We cannot restore permissions
2982                                * based only on the local file headers.
2983                                * Consider scanning the central
2984                                * directory and returning additional
2985                                * entries for at least directories.
2986                                * This would allow us to properly set
2987                                * directory permissions.
2988                                *
2989                                * This won't help us fix symlinks
2990                                * and may not help with regular file
2991                                * permissions, either.  <sigh>
2992                                */
2993                               if (p[2] == '\001' && p[3] == '\002') {
2994                                       return (ARCHIVE_EOF);
2995                               }
2996
2997                               /* End of central directory?  Must be an
2998                                * empty archive. */
2999                               if ((p[2] == '\005' && p[3] == '\006')
3000                                   || (p[2] == '\006' && p[3] == '\006'))
3001                                       return (ARCHIVE_EOF);
3002                         }
3003                         ++p;
3004                         ++skipped;
3005                 }
3006                 __archive_read_consume(a, skipped);
3007         }
3008 }
3009
3010 static int
3011 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3012 {
3013         struct zip *zip;
3014         int64_t bytes_skipped;
3015
3016         zip = (struct zip *)(a->format->data);
3017         bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3018         zip->unconsumed = 0;
3019         if (bytes_skipped < 0)
3020                 return (ARCHIVE_FATAL);
3021
3022         /* If we've already read to end of data, we're done. */
3023         if (zip->end_of_entry)
3024                 return (ARCHIVE_OK);
3025
3026         /* So we know we're streaming... */
3027         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3028             || zip->entry->compressed_size > 0) {
3029                 /* We know the compressed length, so we can just skip. */
3030                 bytes_skipped = __archive_read_consume(a,
3031                                         zip->entry_bytes_remaining);
3032                 if (bytes_skipped < 0)
3033                         return (ARCHIVE_FATAL);
3034                 return (ARCHIVE_OK);
3035         }
3036
3037         if (zip->init_decryption) {
3038                 int r;
3039
3040                 zip->has_encrypted_entries = 1;
3041                 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3042                         r = read_decryption_header(a);
3043                 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3044                         r = init_WinZip_AES_decryption(a);
3045                 else
3046                         r = init_traditional_PKWARE_decryption(a);
3047                 if (r != ARCHIVE_OK)
3048                         return (r);
3049                 zip->init_decryption = 0;
3050         }
3051
3052         /* We're streaming and we don't know the length. */
3053         /* If the body is compressed and we know the format, we can
3054          * find an exact end-of-entry by decompressing it. */
3055         switch (zip->entry->compression) {
3056 #ifdef HAVE_ZLIB_H
3057         case 8: /* Deflate compression. */
3058                 while (!zip->end_of_entry) {
3059                         int64_t offset = 0;
3060                         const void *buff = NULL;
3061                         size_t size = 0;
3062                         int r;
3063                         r =  zip_read_data_deflate(a, &buff, &size, &offset);
3064                         if (r != ARCHIVE_OK)
3065                                 return (r);
3066                 }
3067                 return ARCHIVE_OK;
3068 #endif
3069         default: /* Uncompressed or unknown. */
3070                 /* Scan for a PK\007\010 signature. */
3071                 for (;;) {
3072                         const char *p, *buff;
3073                         ssize_t bytes_avail;
3074                         buff = __archive_read_ahead(a, 16, &bytes_avail);
3075                         if (bytes_avail < 16) {
3076                                 archive_set_error(&a->archive,
3077                                     ARCHIVE_ERRNO_FILE_FORMAT,
3078                                     "Truncated ZIP file data");
3079                                 return (ARCHIVE_FATAL);
3080                         }
3081                         p = buff;
3082                         while (p <= buff + bytes_avail - 16) {
3083                                 if (p[3] == 'P') { p += 3; }
3084                                 else if (p[3] == 'K') { p += 2; }
3085                                 else if (p[3] == '\007') { p += 1; }
3086                                 else if (p[3] == '\010' && p[2] == '\007'
3087                                     && p[1] == 'K' && p[0] == 'P') {
3088                                         if (zip->entry->flags & LA_USED_ZIP64)
3089                                                 __archive_read_consume(a,
3090                                                     p - buff + 24);
3091                                         else
3092                                                 __archive_read_consume(a,
3093                                                     p - buff + 16);
3094                                         return ARCHIVE_OK;
3095                                 } else { p += 4; }
3096                         }
3097                         __archive_read_consume(a, p - buff);
3098                 }
3099         }
3100 }
3101
3102 int
3103 archive_read_support_format_zip_streamable(struct archive *_a)
3104 {
3105         struct archive_read *a = (struct archive_read *)_a;
3106         struct zip *zip;
3107         int r;
3108
3109         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3110             ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3111
3112         zip = (struct zip *)calloc(1, sizeof(*zip));
3113         if (zip == NULL) {
3114                 archive_set_error(&a->archive, ENOMEM,
3115                     "Can't allocate zip data");
3116                 return (ARCHIVE_FATAL);
3117         }
3118
3119         /* Streamable reader doesn't support mac extensions. */
3120         zip->process_mac_extensions = 0;
3121
3122         /*
3123          * Until enough data has been read, we cannot tell about
3124          * any encrypted entries yet.
3125          */
3126         zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3127         zip->crc32func = real_crc32;
3128
3129         r = __archive_read_register_format(a,
3130             zip,
3131             "zip",
3132             archive_read_format_zip_streamable_bid,
3133             archive_read_format_zip_options,
3134             archive_read_format_zip_streamable_read_header,
3135             archive_read_format_zip_read_data,
3136             archive_read_format_zip_read_data_skip_streamable,
3137             NULL,
3138             archive_read_format_zip_cleanup,
3139             archive_read_support_format_zip_capabilities_streamable,
3140             archive_read_format_zip_has_encrypted_entries);
3141
3142         if (r != ARCHIVE_OK)
3143                 free(zip);
3144         return (ARCHIVE_OK);
3145 }
3146
3147 /* ------------------------------------------------------------------------ */
3148
3149 /*
3150  * Seeking-mode support
3151  */
3152
3153 static int
3154 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3155 {
3156         (void)a; /* UNUSED */
3157         return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3158                 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3159 }
3160
3161 /*
3162  * TODO: This is a performance sink because it forces the read core to
3163  * drop buffered data from the start of file, which will then have to
3164  * be re-read again if this bidder loses.
3165  *
3166  * We workaround this a little by passing in the best bid so far so
3167  * that later bidders can do nothing if they know they'll never
3168  * outbid.  But we can certainly do better...
3169  */
3170 static int
3171 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3172 {
3173         /* Sanity-check the EOCD we've found. */
3174
3175         /* This must be the first volume. */
3176         if (archive_le16dec(p + 4) != 0)
3177                 return 0;
3178         /* Central directory must be on this volume. */
3179         if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
3180                 return 0;
3181         /* All central directory entries must be on this volume. */
3182         if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3183                 return 0;
3184         /* Central directory can't extend beyond start of EOCD record. */
3185         if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
3186             > current_offset)
3187                 return 0;
3188
3189         /* Save the central directory location for later use. */
3190         zip->central_directory_offset = archive_le32dec(p + 16);
3191
3192         /* This is just a tiny bit higher than the maximum
3193            returned by the streaming Zip bidder.  This ensures
3194            that the more accurate seeking Zip parser wins
3195            whenever seek is available. */
3196         return 32;
3197 }
3198
3199 /*
3200  * Examine Zip64 EOCD locator:  If it's valid, store the information
3201  * from it.
3202  */
3203 static int
3204 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3205 {
3206         int64_t eocd64_offset;
3207         int64_t eocd64_size;
3208
3209         /* Sanity-check the locator record. */
3210
3211         /* Central dir must be on first volume. */
3212         if (archive_le32dec(p + 4) != 0)
3213                 return 0;
3214         /* Must be only a single volume. */
3215         if (archive_le32dec(p + 16) != 1)
3216                 return 0;
3217
3218         /* Find the Zip64 EOCD record. */
3219         eocd64_offset = archive_le64dec(p + 8);
3220         if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3221                 return 0;
3222         if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3223                 return 0;
3224         /* Make sure we can read all of it. */
3225         eocd64_size = archive_le64dec(p + 4) + 12;
3226         if (eocd64_size < 56 || eocd64_size > 16384)
3227                 return 0;
3228         if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3229                 return 0;
3230
3231         /* Sanity-check the EOCD64 */
3232         if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3233                 return 0;
3234         if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3235                 return 0;
3236         /* CD can't be split. */
3237         if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3238                 return 0;
3239
3240         /* Save the central directory offset for later use. */
3241         zip->central_directory_offset = archive_le64dec(p + 48);
3242
3243         return 32;
3244 }
3245
3246 static int
3247 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3248 {
3249         struct zip *zip = (struct zip *)a->format->data;
3250         int64_t file_size, current_offset;
3251         const char *p;
3252         int i, tail;
3253
3254         /* If someone has already bid more than 32, then avoid
3255            trashing the look-ahead buffers with a seek. */
3256         if (best_bid > 32)
3257                 return (-1);
3258
3259         file_size = __archive_read_seek(a, 0, SEEK_END);
3260         if (file_size <= 0)
3261                 return 0;
3262
3263         /* Search last 16k of file for end-of-central-directory
3264          * record (which starts with PK\005\006) */
3265         tail = (int)zipmin(1024 * 16, file_size);
3266         current_offset = __archive_read_seek(a, -tail, SEEK_END);
3267         if (current_offset < 0)
3268                 return 0;
3269         if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3270                 return 0;
3271         /* Boyer-Moore search backwards from the end, since we want
3272          * to match the last EOCD in the file (there can be more than
3273          * one if there is an uncompressed Zip archive as a member
3274          * within this Zip archive). */
3275         for (i = tail - 22; i > 0;) {
3276                 switch (p[i]) {
3277                 case 'P':
3278                         if (memcmp(p + i, "PK\005\006", 4) == 0) {
3279                                 int ret = read_eocd(zip, p + i,
3280                                     current_offset + i);
3281                                 /* Zip64 EOCD locator precedes
3282                                  * regular EOCD if present. */
3283                                 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3284                                         int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3285                                         if (ret_zip64 > ret)
3286                                                 ret = ret_zip64;
3287                                 }
3288                                 return (ret);
3289                         }
3290                         i -= 4;
3291                         break;
3292                 case 'K': i -= 1; break;
3293                 case 005: i -= 2; break;
3294                 case 006: i -= 3; break;
3295                 default: i -= 4; break;
3296                 }
3297         }
3298         return 0;
3299 }
3300
3301 /* The red-black trees are only used in seeking mode to manage
3302  * the in-memory copy of the central directory. */
3303
3304 static int
3305 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3306 {
3307         const struct zip_entry *e1 = (const struct zip_entry *)n1;
3308         const struct zip_entry *e2 = (const struct zip_entry *)n2;
3309
3310         if (e1->local_header_offset > e2->local_header_offset)
3311                 return -1;
3312         if (e1->local_header_offset < e2->local_header_offset)
3313                 return 1;
3314         return 0;
3315 }
3316
3317 static int
3318 cmp_key(const struct archive_rb_node *n, const void *key)
3319 {
3320         /* This function won't be called */
3321         (void)n; /* UNUSED */
3322         (void)key; /* UNUSED */
3323         return 1;
3324 }
3325
3326 static const struct archive_rb_tree_ops rb_ops = {
3327         &cmp_node, &cmp_key
3328 };
3329
3330 static int
3331 rsrc_cmp_node(const struct archive_rb_node *n1,
3332     const struct archive_rb_node *n2)
3333 {
3334         const struct zip_entry *e1 = (const struct zip_entry *)n1;
3335         const struct zip_entry *e2 = (const struct zip_entry *)n2;
3336
3337         return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3338 }
3339
3340 static int
3341 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3342 {
3343         const struct zip_entry *e = (const struct zip_entry *)n;
3344         return (strcmp((const char *)key, e->rsrcname.s));
3345 }
3346
3347 static const struct archive_rb_tree_ops rb_rsrc_ops = {
3348         &rsrc_cmp_node, &rsrc_cmp_key
3349 };
3350
3351 static const char *
3352 rsrc_basename(const char *name, size_t name_length)
3353 {
3354         const char *s, *r;
3355
3356         r = s = name;
3357         for (;;) {
3358                 s = memchr(s, '/', name_length - (s - name));
3359                 if (s == NULL)
3360                         break;
3361                 r = ++s;
3362         }
3363         return (r);
3364 }
3365
3366 static void
3367 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3368 {
3369         struct archive_string str;
3370         struct zip_entry *dir;
3371         char *s;
3372
3373         archive_string_init(&str);
3374         archive_strncpy(&str, name, name_length);
3375         for (;;) {
3376                 s = strrchr(str.s, '/');
3377                 if (s == NULL)
3378                         break;
3379                 *s = '\0';
3380                 /* Transfer the parent directory from zip->tree_rsrc RB
3381                  * tree to zip->tree RB tree to expose. */
3382                 dir = (struct zip_entry *)
3383                     __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3384                 if (dir == NULL)
3385                         break;
3386                 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3387                 archive_string_free(&dir->rsrcname);
3388                 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
3389         }
3390         archive_string_free(&str);
3391 }
3392
3393 static int
3394 slurp_central_directory(struct archive_read *a, struct zip *zip)
3395 {
3396         ssize_t i;
3397         unsigned found;
3398         int64_t correction;
3399         ssize_t bytes_avail;
3400         const char *p;
3401
3402         /*
3403          * Find the start of the central directory.  The end-of-CD
3404          * record has our starting point, but there are lots of
3405          * Zip archives which have had other data prepended to the
3406          * file, which makes the recorded offsets all too small.
3407          * So we search forward from the specified offset until we
3408          * find the real start of the central directory.  Then we
3409          * know the correction we need to apply to account for leading
3410          * padding.
3411          */
3412         if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
3413                 return ARCHIVE_FATAL;
3414
3415         found = 0;
3416         while (!found) {
3417                 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3418                         return ARCHIVE_FATAL;
3419                 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3420                         switch (p[i + 3]) {
3421                         case 'P': i += 3; break;
3422                         case 'K': i += 2; break;
3423                         case 001: i += 1; break;
3424                         case 002:
3425                                 if (memcmp(p + i, "PK\001\002", 4) == 0) {
3426                                         p += i;
3427                                         found = 1;
3428                                 } else
3429                                         i += 4;
3430                                 break;
3431                         case 005: i += 1; break;
3432                         case 006:
3433                                 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3434                                         p += i;
3435                                         found = 1;
3436                                 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3437                                         p += i;
3438                                         found = 1;
3439                                 } else
3440                                         i += 1;
3441                                 break;
3442                         default: i += 4; break;
3443                         }
3444                 }
3445                 __archive_read_consume(a, i);
3446         }
3447         correction = archive_filter_bytes(&a->archive, 0)
3448                         - zip->central_directory_offset;
3449
3450         __archive_rb_tree_init(&zip->tree, &rb_ops);
3451         __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3452
3453         zip->central_directory_entries_total = 0;
3454         while (1) {
3455                 struct zip_entry *zip_entry;
3456                 size_t filename_length, extra_length, comment_length;
3457                 uint32_t external_attributes;
3458                 const char *name, *r;
3459
3460                 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3461                         return ARCHIVE_FATAL;
3462                 if (memcmp(p, "PK\006\006", 4) == 0
3463                     || memcmp(p, "PK\005\006", 4) == 0) {
3464                         break;
3465                 } else if (memcmp(p, "PK\001\002", 4) != 0) {
3466                         archive_set_error(&a->archive,
3467                             -1, "Invalid central directory signature");
3468                         return ARCHIVE_FATAL;
3469                 }
3470                 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3471                         return ARCHIVE_FATAL;
3472
3473                 zip_entry = calloc(1, sizeof(struct zip_entry));
3474                 if (zip_entry == NULL) {
3475                         archive_set_error(&a->archive, ENOMEM,
3476                                 "Can't allocate zip entry");
3477                         return ARCHIVE_FATAL;
3478                 }
3479                 zip_entry->next = zip->zip_entries;
3480                 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3481                 zip->zip_entries = zip_entry;
3482                 zip->central_directory_entries_total++;
3483
3484                 /* version = p[4]; */
3485                 zip_entry->system = p[5];
3486                 /* version_required = archive_le16dec(p + 6); */
3487                 zip_entry->zip_flags = archive_le16dec(p + 8);
3488                 if (zip_entry->zip_flags
3489                       & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3490                         zip->has_encrypted_entries = 1;
3491                 }
3492                 zip_entry->compression = (char)archive_le16dec(p + 10);
3493                 zip_entry->mtime = zip_time(p + 12);
3494                 zip_entry->crc32 = archive_le32dec(p + 16);
3495                 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3496                         zip_entry->decdat = p[13];
3497                 else
3498                         zip_entry->decdat = p[19];
3499                 zip_entry->compressed_size = archive_le32dec(p + 20);
3500                 zip_entry->uncompressed_size = archive_le32dec(p + 24);
3501                 filename_length = archive_le16dec(p + 28);
3502                 extra_length = archive_le16dec(p + 30);
3503                 comment_length = archive_le16dec(p + 32);
3504                 /* disk_start = archive_le16dec(p + 34); */ /* Better be zero. */
3505                 /* internal_attributes = archive_le16dec(p + 36); */ /* text bit */
3506                 external_attributes = archive_le32dec(p + 38);
3507                 zip_entry->local_header_offset =
3508                     archive_le32dec(p + 42) + correction;
3509
3510                 /* If we can't guess the mode, leave it zero here;
3511                    when we read the local file header we might get
3512                    more information. */
3513                 if (zip_entry->system == 3) {
3514                         zip_entry->mode = external_attributes >> 16;
3515                 } else if (zip_entry->system == 0) {
3516                         // Interpret MSDOS directory bit
3517                         if (0x10 == (external_attributes & 0x10)) {
3518                                 zip_entry->mode = AE_IFDIR | 0775;
3519                         } else {
3520                                 zip_entry->mode = AE_IFREG | 0664;
3521                         }
3522                         if (0x01 == (external_attributes & 0x01)) {
3523                                 // Read-only bit; strip write permissions
3524                                 zip_entry->mode &= 0555;
3525                         }
3526                 } else {
3527                         zip_entry->mode = 0;
3528                 }
3529
3530                 /* We're done with the regular data; get the filename and
3531                  * extra data. */
3532                 __archive_read_consume(a, 46);
3533                 p = __archive_read_ahead(a, filename_length + extra_length,
3534                         NULL);
3535                 if (p == NULL) {
3536                         archive_set_error(&a->archive,
3537                             ARCHIVE_ERRNO_FILE_FORMAT,
3538                             "Truncated ZIP file header");
3539                         return ARCHIVE_FATAL;
3540                 }
3541                 if (ARCHIVE_OK != process_extra(a, p + filename_length, extra_length, zip_entry)) {
3542                         return ARCHIVE_FATAL;
3543                 }
3544
3545                 /*
3546                  * Mac resource fork files are stored under the
3547                  * "__MACOSX/" directory, so we should check if
3548                  * it is.
3549                  */
3550                 if (!zip->process_mac_extensions) {
3551                         /* Treat every entry as a regular entry. */
3552                         __archive_rb_tree_insert_node(&zip->tree,
3553                             &zip_entry->node);
3554                 } else {
3555                         name = p;
3556                         r = rsrc_basename(name, filename_length);
3557                         if (filename_length >= 9 &&
3558                             strncmp("__MACOSX/", name, 9) == 0) {
3559                                 /* If this file is not a resource fork nor
3560                                  * a directory. We should treat it as a non
3561                                  * resource fork file to expose it. */
3562                                 if (name[filename_length-1] != '/' &&
3563                                     (r - name < 3 || r[0] != '.' || r[1] != '_')) {
3564                                         __archive_rb_tree_insert_node(
3565                                             &zip->tree, &zip_entry->node);
3566                                         /* Expose its parent directories. */
3567                                         expose_parent_dirs(zip, name,
3568                                             filename_length);
3569                                 } else {
3570                                         /* This file is a resource fork file or
3571                                          * a directory. */
3572                                         archive_strncpy(&(zip_entry->rsrcname),
3573                                              name, filename_length);
3574                                         __archive_rb_tree_insert_node(
3575                                             &zip->tree_rsrc, &zip_entry->node);
3576                                 }
3577                         } else {
3578                                 /* Generate resource fork name to find its
3579                                  * resource file at zip->tree_rsrc. */
3580                                 archive_strcpy(&(zip_entry->rsrcname),
3581                                     "__MACOSX/");
3582                                 archive_strncat(&(zip_entry->rsrcname),
3583                                     name, r - name);
3584                                 archive_strcat(&(zip_entry->rsrcname), "._");
3585                                 archive_strncat(&(zip_entry->rsrcname),
3586                                     name + (r - name),
3587                                     filename_length - (r - name));
3588                                 /* Register an entry to RB tree to sort it by
3589                                  * file offset. */
3590                                 __archive_rb_tree_insert_node(&zip->tree,
3591                                     &zip_entry->node);
3592                         }
3593                 }
3594
3595                 /* Skip the comment too ... */
3596                 __archive_read_consume(a,
3597                     filename_length + extra_length + comment_length);
3598         }
3599
3600         return ARCHIVE_OK;
3601 }
3602
3603 static ssize_t
3604 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3605 {
3606         const char *p;
3607         ssize_t filename_length, extra_length;
3608
3609         if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3610                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3611                     "Truncated ZIP file header");
3612                 return (ARCHIVE_WARN);
3613         }
3614         p += extra;
3615
3616         if (memcmp(p, "PK\003\004", 4) != 0) {
3617                 archive_set_error(&a->archive, -1, "Damaged Zip archive");
3618                 return ARCHIVE_WARN;
3619         }
3620         filename_length = archive_le16dec(p + 26);
3621         extra_length = archive_le16dec(p + 28);
3622
3623         return (30 + filename_length + extra_length);
3624 }
3625
3626 static int
3627 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3628     struct zip_entry *rsrc)
3629 {
3630         struct zip *zip = (struct zip *)a->format->data;
3631         unsigned char *metadata, *mp;
3632         int64_t offset = archive_filter_bytes(&a->archive, 0);
3633         size_t remaining_bytes, metadata_bytes;
3634         ssize_t hsize;
3635         int ret = ARCHIVE_OK, eof;
3636
3637         switch(rsrc->compression) {
3638         case 0:  /* No compression. */
3639                 if (rsrc->uncompressed_size != rsrc->compressed_size) {
3640                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3641                             "Malformed OS X metadata entry: inconsistent size");
3642                         return (ARCHIVE_FATAL);
3643                 }
3644 #ifdef HAVE_ZLIB_H
3645         case 8: /* Deflate compression. */
3646 #endif
3647                 break;
3648         default: /* Unsupported compression. */
3649                 /* Return a warning. */
3650                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3651                     "Unsupported ZIP compression method (%s)",
3652                     compression_name(rsrc->compression));
3653                 /* We can't decompress this entry, but we will
3654                  * be able to skip() it and try the next entry. */
3655                 return (ARCHIVE_WARN);
3656         }
3657
3658         if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
3659                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3660                     "Mac metadata is too large: %jd > 4M bytes",
3661                     (intmax_t)rsrc->uncompressed_size);
3662                 return (ARCHIVE_WARN);
3663         }
3664         if (rsrc->compressed_size > (4 * 1024 * 1024)) {
3665                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3666                     "Mac metadata is too large: %jd > 4M bytes",
3667                     (intmax_t)rsrc->compressed_size);
3668                 return (ARCHIVE_WARN);
3669         }
3670
3671         metadata = malloc((size_t)rsrc->uncompressed_size);
3672         if (metadata == NULL) {
3673                 archive_set_error(&a->archive, ENOMEM,
3674                     "Can't allocate memory for Mac metadata");
3675                 return (ARCHIVE_FATAL);
3676         }
3677
3678         if (offset < rsrc->local_header_offset)
3679                 __archive_read_consume(a, rsrc->local_header_offset - offset);
3680         else if (offset != rsrc->local_header_offset) {
3681                 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
3682         }
3683
3684         hsize = zip_get_local_file_header_size(a, 0);
3685         __archive_read_consume(a, hsize);
3686
3687         remaining_bytes = (size_t)rsrc->compressed_size;
3688         metadata_bytes = (size_t)rsrc->uncompressed_size;
3689         mp = metadata;
3690         eof = 0;
3691         while (!eof && remaining_bytes) {
3692                 const unsigned char *p;
3693                 ssize_t bytes_avail;
3694                 size_t bytes_used;
3695
3696                 p = __archive_read_ahead(a, 1, &bytes_avail);
3697                 if (p == NULL) {
3698                         archive_set_error(&a->archive,
3699                             ARCHIVE_ERRNO_FILE_FORMAT,
3700                             "Truncated ZIP file header");
3701                         ret = ARCHIVE_WARN;
3702                         goto exit_mac_metadata;
3703                 }
3704                 if ((size_t)bytes_avail > remaining_bytes)
3705                         bytes_avail = remaining_bytes;
3706                 switch(rsrc->compression) {
3707                 case 0:  /* No compression. */
3708                         if ((size_t)bytes_avail > metadata_bytes)
3709                                 bytes_avail = metadata_bytes;
3710                         memcpy(mp, p, bytes_avail);
3711                         bytes_used = (size_t)bytes_avail;
3712                         metadata_bytes -= bytes_used;
3713                         mp += bytes_used;
3714                         if (metadata_bytes == 0)
3715                                 eof = 1;
3716                         break;
3717 #ifdef HAVE_ZLIB_H
3718                 case 8: /* Deflate compression. */
3719                 {
3720                         int r;
3721
3722                         ret = zip_deflate_init(a, zip);
3723                         if (ret != ARCHIVE_OK)
3724                                 goto exit_mac_metadata;
3725                         zip->stream.next_in =
3726                             (Bytef *)(uintptr_t)(const void *)p;
3727                         zip->stream.avail_in = (uInt)bytes_avail;
3728                         zip->stream.total_in = 0;
3729                         zip->stream.next_out = mp;
3730                         zip->stream.avail_out = (uInt)metadata_bytes;
3731                         zip->stream.total_out = 0;
3732
3733                         r = inflate(&zip->stream, 0);
3734                         switch (r) {
3735                         case Z_OK:
3736                                 break;
3737                         case Z_STREAM_END:
3738                                 eof = 1;
3739                                 break;
3740                         case Z_MEM_ERROR:
3741                                 archive_set_error(&a->archive, ENOMEM,
3742                                     "Out of memory for ZIP decompression");
3743                                 ret = ARCHIVE_FATAL;
3744                                 goto exit_mac_metadata;
3745                         default:
3746                                 archive_set_error(&a->archive,
3747                                     ARCHIVE_ERRNO_MISC,
3748                                     "ZIP decompression failed (%d)", r);
3749                                 ret = ARCHIVE_FATAL;
3750                                 goto exit_mac_metadata;
3751                         }
3752                         bytes_used = zip->stream.total_in;
3753                         metadata_bytes -= zip->stream.total_out;
3754                         mp += zip->stream.total_out;
3755                         break;
3756                 }
3757 #endif
3758                 default:
3759                         bytes_used = 0;
3760                         break;
3761                 }
3762                 __archive_read_consume(a, bytes_used);
3763                 remaining_bytes -= bytes_used;
3764         }
3765         archive_entry_copy_mac_metadata(entry, metadata,
3766             (size_t)rsrc->uncompressed_size - metadata_bytes);
3767
3768 exit_mac_metadata:
3769         __archive_read_seek(a, offset, SEEK_SET);
3770         zip->decompress_init = 0;
3771         free(metadata);
3772         return (ret);
3773 }
3774
3775 static int
3776 archive_read_format_zip_seekable_read_header(struct archive_read *a,
3777         struct archive_entry *entry)
3778 {
3779         struct zip *zip = (struct zip *)a->format->data;
3780         struct zip_entry *rsrc;
3781         int64_t offset;
3782         int r, ret = ARCHIVE_OK;
3783
3784         /*
3785          * It should be sufficient to call archive_read_next_header() for
3786          * a reader to determine if an entry is encrypted or not. If the
3787          * encryption of an entry is only detectable when calling
3788          * archive_read_data(), so be it. We'll do the same check there
3789          * as well.
3790          */
3791         if (zip->has_encrypted_entries ==
3792                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3793                 zip->has_encrypted_entries = 0;
3794
3795         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3796         if (a->archive.archive_format_name == NULL)
3797                 a->archive.archive_format_name = "ZIP";
3798
3799         if (zip->zip_entries == NULL) {
3800                 r = slurp_central_directory(a, zip);
3801                 if (r != ARCHIVE_OK)
3802                         return r;
3803                 /* Get first entry whose local header offset is lower than
3804                  * other entries in the archive file. */
3805                 zip->entry =
3806                     (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
3807         } else if (zip->entry != NULL) {
3808                 /* Get next entry in local header offset order. */
3809                 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
3810                     &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
3811         }
3812
3813         if (zip->entry == NULL)
3814                 return ARCHIVE_EOF;
3815
3816         if (zip->entry->rsrcname.s)
3817                 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
3818                     &zip->tree_rsrc, zip->entry->rsrcname.s);
3819         else
3820                 rsrc = NULL;
3821
3822         if (zip->cctx_valid)
3823                 archive_decrypto_aes_ctr_release(&zip->cctx);
3824         if (zip->hctx_valid)
3825                 archive_hmac_sha1_cleanup(&zip->hctx);
3826         zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3827         __archive_read_reset_passphrase(a);
3828
3829         /* File entries are sorted by the header offset, we should mostly
3830          * use __archive_read_consume to advance a read point to avoid redundant
3831          * data reading.  */
3832         offset = archive_filter_bytes(&a->archive, 0);
3833         if (offset < zip->entry->local_header_offset)
3834                 __archive_read_consume(a,
3835                     zip->entry->local_header_offset - offset);
3836         else if (offset != zip->entry->local_header_offset) {
3837                 __archive_read_seek(a, zip->entry->local_header_offset,
3838                     SEEK_SET);
3839         }
3840         zip->unconsumed = 0;
3841         r = zip_read_local_file_header(a, entry, zip);
3842         if (r != ARCHIVE_OK)
3843                 return r;
3844         if (rsrc) {
3845                 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
3846                 if (ret2 < ret)
3847                         ret = ret2;
3848         }
3849         return (ret);
3850 }
3851
3852 /*
3853  * We're going to seek for the next header anyway, so we don't
3854  * need to bother doing anything here.
3855  */
3856 static int
3857 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
3858 {
3859         struct zip *zip;
3860         zip = (struct zip *)(a->format->data);
3861
3862         zip->unconsumed = 0;
3863         return (ARCHIVE_OK);
3864 }
3865
3866 int
3867 archive_read_support_format_zip_seekable(struct archive *_a)
3868 {
3869         struct archive_read *a = (struct archive_read *)_a;
3870         struct zip *zip;
3871         int r;
3872
3873         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3874             ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
3875
3876         zip = (struct zip *)calloc(1, sizeof(*zip));
3877         if (zip == NULL) {
3878                 archive_set_error(&a->archive, ENOMEM,
3879                     "Can't allocate zip data");
3880                 return (ARCHIVE_FATAL);
3881         }
3882
3883 #ifdef HAVE_COPYFILE_H
3884         /* Set this by default on Mac OS. */
3885         zip->process_mac_extensions = 1;
3886 #endif
3887
3888         /*
3889          * Until enough data has been read, we cannot tell about
3890          * any encrypted entries yet.
3891          */
3892         zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3893         zip->crc32func = real_crc32;
3894
3895         r = __archive_read_register_format(a,
3896             zip,
3897             "zip",
3898             archive_read_format_zip_seekable_bid,
3899             archive_read_format_zip_options,
3900             archive_read_format_zip_seekable_read_header,
3901             archive_read_format_zip_read_data,
3902             archive_read_format_zip_read_data_skip_seekable,
3903             NULL,
3904             archive_read_format_zip_cleanup,
3905             archive_read_support_format_zip_capabilities_seekable,
3906             archive_read_format_zip_has_encrypted_entries);
3907
3908         if (r != ARCHIVE_OK)
3909                 free(zip);
3910         return (ARCHIVE_OK);
3911 }
3912
3913 /*# vim:set noet:*/