]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/libarchive/archive_read_support_format_zip.c
MFH r328332:
[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
56 #include "archive.h"
57 #include "archive_digest_private.h"
58 #include "archive_cryptor_private.h"
59 #include "archive_endian.h"
60 #include "archive_entry.h"
61 #include "archive_entry_locale.h"
62 #include "archive_hmac_private.h"
63 #include "archive_private.h"
64 #include "archive_rb.h"
65 #include "archive_read_private.h"
66
67 #ifndef HAVE_ZLIB_H
68 #include "archive_crc32.h"
69 #endif
70
71 struct zip_entry {
72         struct archive_rb_node  node;
73         struct zip_entry        *next;
74         int64_t                 local_header_offset;
75         int64_t                 compressed_size;
76         int64_t                 uncompressed_size;
77         int64_t                 gid;
78         int64_t                 uid;
79         struct archive_string   rsrcname;
80         time_t                  mtime;
81         time_t                  atime;
82         time_t                  ctime;
83         uint32_t                crc32;
84         uint16_t                mode;
85         uint16_t                zip_flags; /* From GP Flags Field */
86         unsigned char           compression;
87         unsigned char           system; /* From "version written by" */
88         unsigned char           flags; /* Our extra markers. */
89         unsigned char           decdat;/* Used for Decryption check */
90
91         /* WinZip AES encryption extra field should be available
92          * when compression is 99. */
93         struct {
94                 /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
95                 unsigned        vendor;
96 #define AES_VENDOR_AE_1 0x0001
97 #define AES_VENDOR_AE_2 0x0002
98                 /* AES encryption strength:
99                  * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
100                 unsigned        strength;
101                 /* Actual compression method. */
102                 unsigned char   compression;
103         }                       aes_extra;
104 };
105
106 struct trad_enc_ctx {
107         uint32_t        keys[3];
108 };
109
110 /* Bits used in zip_flags. */
111 #define ZIP_ENCRYPTED   (1 << 0)
112 #define ZIP_LENGTH_AT_END       (1 << 3)
113 #define ZIP_STRONG_ENCRYPTED    (1 << 6)
114 #define ZIP_UTF8_NAME   (1 << 11)
115 /* See "7.2 Single Password Symmetric Encryption Method"
116    in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
117 #define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
118
119 /* Bits used in flags. */
120 #define LA_USED_ZIP64   (1 << 0)
121 #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
122
123 /*
124  * See "WinZip - AES Encryption Information"
125  *     http://www.winzip.com/aes_info.htm
126  */
127 /* Value used in compression method. */
128 #define WINZIP_AES_ENCRYPTION   99
129 /* Authentication code size. */
130 #define AUTH_CODE_SIZE  10
131 /**/
132 #define MAX_DERIVED_KEY_BUF_SIZE        (AES_MAX_KEY_SIZE * 2 + 2)
133
134 struct zip {
135         /* Structural information about the archive. */
136         struct archive_string   format_name;
137         int64_t                 central_directory_offset;
138         size_t                  central_directory_entries_total;
139         size_t                  central_directory_entries_on_this_disk;
140         int                     has_encrypted_entries;
141
142         /* List of entries (seekable Zip only) */
143         struct zip_entry        *zip_entries;
144         struct archive_rb_tree  tree;
145         struct archive_rb_tree  tree_rsrc;
146
147         /* Bytes read but not yet consumed via __archive_read_consume() */
148         size_t                  unconsumed;
149
150         /* Information about entry we're currently reading. */
151         struct zip_entry        *entry;
152         int64_t                 entry_bytes_remaining;
153
154         /* These count the number of bytes actually read for the entry. */
155         int64_t                 entry_compressed_bytes_read;
156         int64_t                 entry_uncompressed_bytes_read;
157
158         /* Running CRC32 of the decompressed data */
159         unsigned long           entry_crc32;
160         unsigned long           (*crc32func)(unsigned long, const void *,
161                                     size_t);
162         char                    ignore_crc32;
163
164         /* Flags to mark progress of decompression. */
165         char                    decompress_init;
166         char                    end_of_entry;
167
168 #ifdef HAVE_ZLIB_H
169         unsigned char           *uncompressed_buffer;
170         size_t                  uncompressed_buffer_size;
171         z_stream                stream;
172         char                    stream_valid;
173 #endif
174
175         struct archive_string_conv *sconv;
176         struct archive_string_conv *sconv_default;
177         struct archive_string_conv *sconv_utf8;
178         int                     init_default_conversion;
179         int                     process_mac_extensions;
180
181         char                    init_decryption;
182
183         /* Decryption buffer. */
184         /*
185          * The decrypted data starts at decrypted_ptr and
186          * extends for decrypted_bytes_remaining.  Decryption
187          * adds new data to the end of this block, data is returned
188          * to clients from the beginning.  When the block hits the
189          * end of decrypted_buffer, it has to be shuffled back to
190          * the beginning of the buffer.
191          */
192         unsigned char           *decrypted_buffer;
193         unsigned char           *decrypted_ptr;
194         size_t                  decrypted_buffer_size;
195         size_t                  decrypted_bytes_remaining;
196         size_t                  decrypted_unconsumed_bytes;
197
198         /* Traditional PKWARE decryption. */
199         struct trad_enc_ctx     tctx;
200         char                    tctx_valid;
201
202         /* WinZip AES decryption. */
203         /* Contexts used for AES decryption. */
204         archive_crypto_ctx      cctx;
205         char                    cctx_valid;
206         archive_hmac_sha1_ctx   hctx;
207         char                    hctx_valid;
208
209         /* Strong encryption's decryption header information. */
210         unsigned                iv_size;
211         unsigned                alg_id;
212         unsigned                bit_len;
213         unsigned                flags;
214         unsigned                erd_size;
215         unsigned                v_size;
216         unsigned                v_crc32;
217         uint8_t                 *iv;
218         uint8_t                 *erd;
219         uint8_t                 *v_data;
220 };
221
222 /* Many systems define min or MIN, but not all. */
223 #define zipmin(a,b) ((a) < (b) ? (a) : (b))
224
225 /* ------------------------------------------------------------------------ */
226
227 /*
228   Traditional PKWARE Decryption functions.
229  */
230
231 static void
232 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
233 {
234         uint8_t t;
235 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
236
237         ctx->keys[0] = CRC32(ctx->keys[0], c);
238         ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
239         t = (ctx->keys[1] >> 24) & 0xff;
240         ctx->keys[2] = CRC32(ctx->keys[2], t);
241 #undef CRC32
242 }
243
244 static uint8_t
245 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
246 {
247         unsigned temp = ctx->keys[2] | 2;
248         return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
249 }
250
251 static void
252 trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
253     size_t in_len, uint8_t *out, size_t out_len)
254 {
255         unsigned i, max;
256
257         max = (unsigned)((in_len < out_len)? in_len: out_len);
258
259         for (i = 0; i < max; i++) {
260                 uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
261                 out[i] = t;
262                 trad_enc_update_keys(ctx, t);
263         }
264 }
265
266 static int
267 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
268     const uint8_t *key, size_t key_len, uint8_t *crcchk)
269 {
270         uint8_t header[12];
271
272         if (key_len < 12) {
273                 *crcchk = 0xff;
274                 return -1;
275         }
276
277         ctx->keys[0] = 305419896L;
278         ctx->keys[1] = 591751049L;
279         ctx->keys[2] = 878082192L;
280
281         for (;pw_len; --pw_len)
282                 trad_enc_update_keys(ctx, *pw++);
283
284         trad_enc_decrypt_update(ctx, key, 12, header, 12);
285         /* Return the last byte for CRC check. */
286         *crcchk = header[11];
287         return 0;
288 }
289
290 #if 0
291 static void
292 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
293     int key_size)
294 {
295 #define MD_SIZE 20
296         archive_sha1_ctx ctx;
297         unsigned char md1[MD_SIZE];
298         unsigned char md2[MD_SIZE * 2];
299         unsigned char mkb[64];
300         int i;
301
302         archive_sha1_init(&ctx);
303         archive_sha1_update(&ctx, p, size);
304         archive_sha1_final(&ctx, md1);
305
306         memset(mkb, 0x36, sizeof(mkb));
307         for (i = 0; i < MD_SIZE; i++)
308                 mkb[i] ^= md1[i];
309         archive_sha1_init(&ctx);
310         archive_sha1_update(&ctx, mkb, sizeof(mkb));
311         archive_sha1_final(&ctx, md2);
312
313         memset(mkb, 0x5C, sizeof(mkb));
314         for (i = 0; i < MD_SIZE; i++)
315                 mkb[i] ^= md1[i];
316         archive_sha1_init(&ctx);
317         archive_sha1_update(&ctx, mkb, sizeof(mkb));
318         archive_sha1_final(&ctx, md2 + MD_SIZE);
319
320         if (key_size > 32)
321                 key_size = 32;
322         memcpy(key, md2, key_size);
323 #undef MD_SIZE
324 }
325 #endif
326
327 /*
328  * Common code for streaming or seeking modes.
329  *
330  * Includes code to read local file headers, decompress data
331  * from entry bodies, and common API.
332  */
333
334 static unsigned long
335 real_crc32(unsigned long crc, const void *buff, size_t len)
336 {
337         return crc32(crc, buff, (unsigned int)len);
338 }
339
340 /* Used by "ignorecrc32" option to speed up tests. */
341 static unsigned long
342 fake_crc32(unsigned long crc, const void *buff, size_t len)
343 {
344         (void)crc; /* UNUSED */
345         (void)buff; /* UNUSED */
346         (void)len; /* UNUSED */
347         return 0;
348 }
349
350 static const struct {
351         int id;
352         const char * name;
353 } compression_methods[] = {
354         {0, "uncompressed"}, /* The file is stored (no compression) */
355         {1, "shrinking"}, /* The file is Shrunk */
356         {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
357         {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
358         {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
359         {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
360         {6, "imploded"},  /* The file is Imploded */
361         {7, "reserved"},  /* Reserved for Tokenizing compression algorithm */
362         {8, "deflation"}, /* The file is Deflated */
363         {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
364         {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
365                            * (old IBM TERSE) */
366         {11, "reserved"}, /* Reserved by PKWARE */
367         {12, "bzip"},     /* File is compressed using BZIP2 algorithm */
368         {13, "reserved"}, /* Reserved by PKWARE */
369         {14, "lzma"},     /* LZMA (EFS) */
370         {15, "reserved"}, /* Reserved by PKWARE */
371         {16, "reserved"}, /* Reserved by PKWARE */
372         {17, "reserved"}, /* Reserved by PKWARE */
373         {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
374         {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
375         {97, "wav-pack"}, /* WavPack compressed data */
376         {98, "ppmd-1"},   /* PPMd version I, Rev 1 */
377         {99, "aes"}       /* WinZip AES encryption  */
378 };
379
380 static const char *
381 compression_name(const int compression)
382 {
383         static const int num_compression_methods =
384                 sizeof(compression_methods)/sizeof(compression_methods[0]);
385         int i=0;
386
387         while(compression >= 0 && i < num_compression_methods) {
388                 if (compression_methods[i].id == compression)
389                         return compression_methods[i].name;
390                 i++;
391         }
392         return "??";
393 }
394
395 /* Convert an MSDOS-style date/time into Unix-style time. */
396 static time_t
397 zip_time(const char *p)
398 {
399         int msTime, msDate;
400         struct tm ts;
401
402         msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
403         msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
404
405         memset(&ts, 0, sizeof(ts));
406         ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
407         ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
408         ts.tm_mday = msDate & 0x1f; /* Day of month. */
409         ts.tm_hour = (msTime >> 11) & 0x1f;
410         ts.tm_min = (msTime >> 5) & 0x3f;
411         ts.tm_sec = (msTime << 1) & 0x3e;
412         ts.tm_isdst = -1;
413         return mktime(&ts);
414 }
415
416 /*
417  * The extra data is stored as a list of
418  *      id1+size1+data1 + id2+size2+data2 ...
419  *  triplets.  id and size are 2 bytes each.
420  */
421 static int
422 process_extra(struct archive_read *a, const char *p, size_t extra_length, struct zip_entry* zip_entry)
423 {
424         unsigned offset = 0;
425
426         if (extra_length == 0) {
427                 return ARCHIVE_OK;
428         }
429
430         if (extra_length < 4) {
431                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
432                     "Too-small extra data: Need at least 4 bytes, but only found %d bytes", (int)extra_length);
433                 return ARCHIVE_FAILED;
434         }
435         while (offset <= extra_length - 4) {
436                 unsigned short headerid = archive_le16dec(p + offset);
437                 unsigned short datasize = archive_le16dec(p + offset + 2);
438
439                 offset += 4;
440                 if (offset + datasize > extra_length) {
441                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
442                             "Extra data overflow: Need %d bytes but only found %d bytes",
443                             (int)datasize, (int)(extra_length - offset));
444                         return ARCHIVE_FAILED;
445                 }
446 #ifdef DEBUG
447                 fprintf(stderr, "Header id 0x%04x, length %d\n",
448                     headerid, datasize);
449 #endif
450                 switch (headerid) {
451                 case 0x0001:
452                         /* Zip64 extended information extra field. */
453                         zip_entry->flags |= LA_USED_ZIP64;
454                         if (zip_entry->uncompressed_size == 0xffffffff) {
455                                 uint64_t t = 0;
456                                 if (datasize < 8
457                                     || (t = archive_le64dec(p + offset)) > INT64_MAX) {
458                                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
459                                             "Malformed 64-bit uncompressed size");
460                                         return ARCHIVE_FAILED;
461                                 }
462                                 zip_entry->uncompressed_size = t;
463                                 offset += 8;
464                                 datasize -= 8;
465                         }
466                         if (zip_entry->compressed_size == 0xffffffff) {
467                                 uint64_t t = 0;
468                                 if (datasize < 8
469                                     || (t = archive_le64dec(p + offset)) > INT64_MAX) {
470                                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
471                                             "Malformed 64-bit compressed size");
472                                         return ARCHIVE_FAILED;
473                                 }
474                                 zip_entry->compressed_size = t;
475                                 offset += 8;
476                                 datasize -= 8;
477                         }
478                         if (zip_entry->local_header_offset == 0xffffffff) {
479                                 uint64_t t = 0;
480                                 if (datasize < 8
481                                     || (t = archive_le64dec(p + offset)) > INT64_MAX) {
482                                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
483                                             "Malformed 64-bit local header offset");
484                                         return ARCHIVE_FAILED;
485                                 }
486                                 zip_entry->local_header_offset = t;
487                                 offset += 8;
488                                 datasize -= 8;
489                         }
490                         /* archive_le32dec(p + offset) gives disk
491                          * on which file starts, but we don't handle
492                          * multi-volume Zip files. */
493                         break;
494 #ifdef DEBUG
495                 case 0x0017:
496                 {
497                         /* Strong encryption field. */
498                         if (archive_le16dec(p + offset) == 2) {
499                                 unsigned algId =
500                                         archive_le16dec(p + offset + 2);
501                                 unsigned bitLen =
502                                         archive_le16dec(p + offset + 4);
503                                 int      flags =
504                                         archive_le16dec(p + offset + 6);
505                                 fprintf(stderr, "algId=0x%04x, bitLen=%u, "
506                                     "flgas=%d\n", algId, bitLen,flags);
507                         }
508                         break;
509                 }
510 #endif
511                 case 0x5455:
512                 {
513                         /* Extended time field "UT". */
514                         int flags = p[offset];
515                         offset++;
516                         datasize--;
517                         /* Flag bits indicate which dates are present. */
518                         if (flags & 0x01)
519                         {
520 #ifdef DEBUG
521                                 fprintf(stderr, "mtime: %lld -> %d\n",
522                                     (long long)zip_entry->mtime,
523                                     archive_le32dec(p + offset));
524 #endif
525                                 if (datasize < 4)
526                                         break;
527                                 zip_entry->mtime = archive_le32dec(p + offset);
528                                 offset += 4;
529                                 datasize -= 4;
530                         }
531                         if (flags & 0x02)
532                         {
533                                 if (datasize < 4)
534                                         break;
535                                 zip_entry->atime = archive_le32dec(p + offset);
536                                 offset += 4;
537                                 datasize -= 4;
538                         }
539                         if (flags & 0x04)
540                         {
541                                 if (datasize < 4)
542                                         break;
543                                 zip_entry->ctime = archive_le32dec(p + offset);
544                                 offset += 4;
545                                 datasize -= 4;
546                         }
547                         break;
548                 }
549                 case 0x5855:
550                 {
551                         /* Info-ZIP Unix Extra Field (old version) "UX". */
552                         if (datasize >= 8) {
553                                 zip_entry->atime = archive_le32dec(p + offset);
554                                 zip_entry->mtime =
555                                     archive_le32dec(p + offset + 4);
556                         }
557                         if (datasize >= 12) {
558                                 zip_entry->uid =
559                                     archive_le16dec(p + offset + 8);
560                                 zip_entry->gid =
561                                     archive_le16dec(p + offset + 10);
562                         }
563                         break;
564                 }
565                 case 0x6c78:
566                 {
567                         /* Experimental 'xl' field */
568                         /*
569                          * Introduced Dec 2013 to provide a way to
570                          * include external file attributes (and other
571                          * fields that ordinarily appear only in
572                          * central directory) in local file header.
573                          * This provides file type and permission
574                          * information necessary to support full
575                          * streaming extraction.  Currently being
576                          * discussed with other Zip developers
577                          * ... subject to change.
578                          *
579                          * Format:
580                          *  The field starts with a bitmap that specifies
581                          *  which additional fields are included.  The
582                          *  bitmap is variable length and can be extended in
583                          *  the future.
584                          *
585                          *  n bytes - feature bitmap: first byte has low-order
586                          *    7 bits.  If high-order bit is set, a subsequent
587                          *    byte holds the next 7 bits, etc.
588                          *
589                          *  if bitmap & 1, 2 byte "version made by"
590                          *  if bitmap & 2, 2 byte "internal file attributes"
591                          *  if bitmap & 4, 4 byte "external file attributes"
592                          *  if bitmap & 8, 2 byte comment length + n byte comment
593                          */
594                         int bitmap, bitmap_last;
595
596                         if (datasize < 1)
597                                 break;
598                         bitmap_last = bitmap = 0xff & p[offset];
599                         offset += 1;
600                         datasize -= 1;
601
602                         /* We only support first 7 bits of bitmap; skip rest. */
603                         while ((bitmap_last & 0x80) != 0
604                             && datasize >= 1) {
605                                 bitmap_last = p[offset];
606                                 offset += 1;
607                                 datasize -= 1;
608                         }
609
610                         if (bitmap & 1) {
611                                 /* 2 byte "version made by" */
612                                 if (datasize < 2)
613                                         break;
614                                 zip_entry->system
615                                     = archive_le16dec(p + offset) >> 8;
616                                 offset += 2;
617                                 datasize -= 2;
618                         }
619                         if (bitmap & 2) {
620                                 /* 2 byte "internal file attributes" */
621                                 uint32_t internal_attributes;
622                                 if (datasize < 2)
623                                         break;
624                                 internal_attributes
625                                     = archive_le16dec(p + offset);
626                                 /* Not used by libarchive at present. */
627                                 (void)internal_attributes; /* UNUSED */
628                                 offset += 2;
629                                 datasize -= 2;
630                         }
631                         if (bitmap & 4) {
632                                 /* 4 byte "external file attributes" */
633                                 uint32_t external_attributes;
634                                 if (datasize < 4)
635                                         break;
636                                 external_attributes
637                                     = archive_le32dec(p + offset);
638                                 if (zip_entry->system == 3) {
639                                         zip_entry->mode
640                                             = external_attributes >> 16;
641                                 } else if (zip_entry->system == 0) {
642                                         // Interpret MSDOS directory bit
643                                         if (0x10 == (external_attributes & 0x10)) {
644                                                 zip_entry->mode = AE_IFDIR | 0775;
645                                         } else {
646                                                 zip_entry->mode = AE_IFREG | 0664;
647                                         }
648                                         if (0x01 == (external_attributes & 0x01)) {
649                                                 // Read-only bit; strip write permissions
650                                                 zip_entry->mode &= 0555;
651                                         }
652                                 } else {
653                                         zip_entry->mode = 0;
654                                 }
655                                 offset += 4;
656                                 datasize -= 4;
657                         }
658                         if (bitmap & 8) {
659                                 /* 2 byte comment length + comment */
660                                 uint32_t comment_length;
661                                 if (datasize < 2)
662                                         break;
663                                 comment_length
664                                     = archive_le16dec(p + offset);
665                                 offset += 2;
666                                 datasize -= 2;
667
668                                 if (datasize < comment_length)
669                                         break;
670                                 /* Comment is not supported by libarchive */
671                                 offset += comment_length;
672                                 datasize -= comment_length;
673                         }
674                         break;
675                 }
676                 case 0x7855:
677                         /* Info-ZIP Unix Extra Field (type 2) "Ux". */
678 #ifdef DEBUG
679                         fprintf(stderr, "uid %d gid %d\n",
680                             archive_le16dec(p + offset),
681                             archive_le16dec(p + offset + 2));
682 #endif
683                         if (datasize >= 2)
684                                 zip_entry->uid = archive_le16dec(p + offset);
685                         if (datasize >= 4)
686                                 zip_entry->gid =
687                                     archive_le16dec(p + offset + 2);
688                         break;
689                 case 0x7875:
690                 {
691                         /* Info-Zip Unix Extra Field (type 3) "ux". */
692                         int uidsize = 0, gidsize = 0;
693
694                         /* TODO: support arbitrary uidsize/gidsize. */
695                         if (datasize >= 1 && p[offset] == 1) {/* version=1 */
696                                 if (datasize >= 4) {
697                                         /* get a uid size. */
698                                         uidsize = 0xff & (int)p[offset+1];
699                                         if (uidsize == 2)
700                                                 zip_entry->uid =
701                                                     archive_le16dec(
702                                                         p + offset + 2);
703                                         else if (uidsize == 4 && datasize >= 6)
704                                                 zip_entry->uid =
705                                                     archive_le32dec(
706                                                         p + offset + 2);
707                                 }
708                                 if (datasize >= (2 + uidsize + 3)) {
709                                         /* get a gid size. */
710                                         gidsize = 0xff & (int)p[offset+2+uidsize];
711                                         if (gidsize == 2)
712                                                 zip_entry->gid =
713                                                     archive_le16dec(
714                                                         p+offset+2+uidsize+1);
715                                         else if (gidsize == 4 &&
716                                             datasize >= (2 + uidsize + 5))
717                                                 zip_entry->gid =
718                                                     archive_le32dec(
719                                                         p+offset+2+uidsize+1);
720                                 }
721                         }
722                         break;
723                 }
724                 case 0x9901:
725                         /* WinZip AES extra data field. */
726                         if (datasize < 6) {
727                                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
728                                     "Incomplete AES field");
729                                 return ARCHIVE_FAILED;
730                         }
731                         if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
732                                 /* Vendor version. */
733                                 zip_entry->aes_extra.vendor =
734                                     archive_le16dec(p + offset);
735                                 /* AES encryption strength. */
736                                 zip_entry->aes_extra.strength = p[offset + 4];
737                                 /* Actual compression method. */
738                                 zip_entry->aes_extra.compression =
739                                     p[offset + 5];
740                         }
741                         break;
742                 default:
743                         break;
744                 }
745                 offset += datasize;
746         }
747         if (offset != extra_length) {
748                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
749                     "Malformed extra data: Consumed %d bytes of %d bytes",
750                     (int)offset, (int)extra_length);
751                 return ARCHIVE_FAILED;
752         }
753         return ARCHIVE_OK;
754 }
755
756 /*
757  * Assumes file pointer is at beginning of local file header.
758  */
759 static int
760 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
761     struct zip *zip)
762 {
763         const char *p;
764         const void *h;
765         const wchar_t *wp;
766         const char *cp;
767         size_t len, filename_length, extra_length;
768         struct archive_string_conv *sconv;
769         struct zip_entry *zip_entry = zip->entry;
770         struct zip_entry zip_entry_central_dir;
771         int ret = ARCHIVE_OK;
772         char version;
773
774         /* Save a copy of the original for consistency checks. */
775         zip_entry_central_dir = *zip_entry;
776
777         zip->decompress_init = 0;
778         zip->end_of_entry = 0;
779         zip->entry_uncompressed_bytes_read = 0;
780         zip->entry_compressed_bytes_read = 0;
781         zip->entry_crc32 = zip->crc32func(0, NULL, 0);
782
783         /* Setup default conversion. */
784         if (zip->sconv == NULL && !zip->init_default_conversion) {
785                 zip->sconv_default =
786                     archive_string_default_conversion_for_read(&(a->archive));
787                 zip->init_default_conversion = 1;
788         }
789
790         if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
791                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
792                     "Truncated ZIP file header");
793                 return (ARCHIVE_FATAL);
794         }
795
796         if (memcmp(p, "PK\003\004", 4) != 0) {
797                 archive_set_error(&a->archive, -1, "Damaged Zip archive");
798                 return ARCHIVE_FATAL;
799         }
800         version = p[4];
801         zip_entry->system = p[5];
802         zip_entry->zip_flags = archive_le16dec(p + 6);
803         if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
804                 zip->has_encrypted_entries = 1;
805                 archive_entry_set_is_data_encrypted(entry, 1);
806                 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
807                         zip_entry->zip_flags & ZIP_ENCRYPTED &&
808                         zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
809                         archive_entry_set_is_metadata_encrypted(entry, 1);
810                         return ARCHIVE_FATAL;
811                 }
812         }
813         zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
814         zip_entry->compression = (char)archive_le16dec(p + 8);
815         zip_entry->mtime = zip_time(p + 10);
816         zip_entry->crc32 = archive_le32dec(p + 14);
817         if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
818                 zip_entry->decdat = p[11];
819         else
820                 zip_entry->decdat = p[17];
821         zip_entry->compressed_size = archive_le32dec(p + 18);
822         zip_entry->uncompressed_size = archive_le32dec(p + 22);
823         filename_length = archive_le16dec(p + 26);
824         extra_length = archive_le16dec(p + 28);
825
826         __archive_read_consume(a, 30);
827
828         /* Read the filename. */
829         if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
830                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
831                     "Truncated ZIP file header");
832                 return (ARCHIVE_FATAL);
833         }
834         if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
835                 /* The filename is stored to be UTF-8. */
836                 if (zip->sconv_utf8 == NULL) {
837                         zip->sconv_utf8 =
838                             archive_string_conversion_from_charset(
839                                 &a->archive, "UTF-8", 1);
840                         if (zip->sconv_utf8 == NULL)
841                                 return (ARCHIVE_FATAL);
842                 }
843                 sconv = zip->sconv_utf8;
844         } else if (zip->sconv != NULL)
845                 sconv = zip->sconv;
846         else
847                 sconv = zip->sconv_default;
848
849         if (archive_entry_copy_pathname_l(entry,
850             h, filename_length, sconv) != 0) {
851                 if (errno == ENOMEM) {
852                         archive_set_error(&a->archive, ENOMEM,
853                             "Can't allocate memory for Pathname");
854                         return (ARCHIVE_FATAL);
855                 }
856                 archive_set_error(&a->archive,
857                     ARCHIVE_ERRNO_FILE_FORMAT,
858                     "Pathname cannot be converted "
859                     "from %s to current locale.",
860                     archive_string_conversion_charset_name(sconv));
861                 ret = ARCHIVE_WARN;
862         }
863         __archive_read_consume(a, filename_length);
864
865         /* Read the extra data. */
866         if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
867                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
868                     "Truncated ZIP file header");
869                 return (ARCHIVE_FATAL);
870         }
871
872         if (ARCHIVE_OK != process_extra(a, h, extra_length, zip_entry)) {
873                 return ARCHIVE_FATAL;
874         }
875         __archive_read_consume(a, extra_length);
876
877         /* Work around a bug in Info-Zip: When reading from a pipe, it
878          * stats the pipe instead of synthesizing a file entry. */
879         if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
880                 zip_entry->mode &= ~ AE_IFMT;
881                 zip_entry->mode |= AE_IFREG;
882         }
883
884         /* If the mode is totally empty, set some sane default. */
885         if (zip_entry->mode == 0) {
886                 zip_entry->mode |= 0664;
887         }
888
889         /* Windows archivers sometimes use backslash as the directory separator.
890            Normalize to slash. */
891         if (zip_entry->system == 0 &&
892             (wp = archive_entry_pathname_w(entry)) != NULL) {
893                 if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
894                         size_t i;
895                         struct archive_wstring s;
896                         archive_string_init(&s);
897                         archive_wstrcpy(&s, wp);
898                         for (i = 0; i < archive_strlen(&s); i++) {
899                                 if (s.s[i] == '\\')
900                                         s.s[i] = '/';
901                         }
902                         archive_entry_copy_pathname_w(entry, s.s);
903                         archive_wstring_free(&s);
904                 }
905         }
906
907         /* Make sure that entries with a trailing '/' are marked as directories
908          * even if the External File Attributes contains bogus values.  If this
909          * is not a directory and there is no type, assume regularfile. */
910         if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
911                 int has_slash;
912
913                 wp = archive_entry_pathname_w(entry);
914                 if (wp != NULL) {
915                         len = wcslen(wp);
916                         has_slash = len > 0 && wp[len - 1] == L'/';
917                 } else {
918                         cp = archive_entry_pathname(entry);
919                         len = (cp != NULL)?strlen(cp):0;
920                         has_slash = len > 0 && cp[len - 1] == '/';
921                 }
922                 /* Correct file type as needed. */
923                 if (has_slash) {
924                         zip_entry->mode &= ~AE_IFMT;
925                         zip_entry->mode |= AE_IFDIR;
926                         zip_entry->mode |= 0111;
927                 } else if ((zip_entry->mode & AE_IFMT) == 0) {
928                         zip_entry->mode |= AE_IFREG;
929                 }
930         }
931
932         /* Make sure directories end in '/' */
933         if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
934                 wp = archive_entry_pathname_w(entry);
935                 if (wp != NULL) {
936                         len = wcslen(wp);
937                         if (len > 0 && wp[len - 1] != L'/') {
938                                 struct archive_wstring s;
939                                 archive_string_init(&s);
940                                 archive_wstrcat(&s, wp);
941                                 archive_wstrappend_wchar(&s, L'/');
942                                 archive_entry_copy_pathname_w(entry, s.s);
943                                 archive_wstring_free(&s);
944                         }
945                 } else {
946                         cp = archive_entry_pathname(entry);
947                         len = (cp != NULL)?strlen(cp):0;
948                         if (len > 0 && cp[len - 1] != '/') {
949                                 struct archive_string s;
950                                 archive_string_init(&s);
951                                 archive_strcat(&s, cp);
952                                 archive_strappend_char(&s, '/');
953                                 archive_entry_set_pathname(entry, s.s);
954                                 archive_string_free(&s);
955                         }
956                 }
957         }
958
959         if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
960                 /* If this came from the central dir, it's size info
961                  * is definitive, so ignore the length-at-end flag. */
962                 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
963                 /* If local header is missing a value, use the one from
964                    the central directory.  If both have it, warn about
965                    mismatches. */
966                 if (zip_entry->crc32 == 0) {
967                         zip_entry->crc32 = zip_entry_central_dir.crc32;
968                 } else if (!zip->ignore_crc32
969                     && zip_entry->crc32 != zip_entry_central_dir.crc32) {
970                         archive_set_error(&a->archive,
971                             ARCHIVE_ERRNO_FILE_FORMAT,
972                             "Inconsistent CRC32 values");
973                         ret = ARCHIVE_WARN;
974                 }
975                 if (zip_entry->compressed_size == 0) {
976                         zip_entry->compressed_size
977                             = zip_entry_central_dir.compressed_size;
978                 } else if (zip_entry->compressed_size
979                     != zip_entry_central_dir.compressed_size) {
980                         archive_set_error(&a->archive,
981                             ARCHIVE_ERRNO_FILE_FORMAT,
982                             "Inconsistent compressed size: "
983                             "%jd in central directory, %jd in local header",
984                             (intmax_t)zip_entry_central_dir.compressed_size,
985                             (intmax_t)zip_entry->compressed_size);
986                         ret = ARCHIVE_WARN;
987                 }
988                 if (zip_entry->uncompressed_size == 0) {
989                         zip_entry->uncompressed_size
990                             = zip_entry_central_dir.uncompressed_size;
991                 } else if (zip_entry->uncompressed_size
992                     != zip_entry_central_dir.uncompressed_size) {
993                         archive_set_error(&a->archive,
994                             ARCHIVE_ERRNO_FILE_FORMAT,
995                             "Inconsistent uncompressed size: "
996                             "%jd in central directory, %jd in local header",
997                             (intmax_t)zip_entry_central_dir.uncompressed_size,
998                             (intmax_t)zip_entry->uncompressed_size);
999                         ret = ARCHIVE_WARN;
1000                 }
1001         }
1002
1003         /* Populate some additional entry fields: */
1004         archive_entry_set_mode(entry, zip_entry->mode);
1005         archive_entry_set_uid(entry, zip_entry->uid);
1006         archive_entry_set_gid(entry, zip_entry->gid);
1007         archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1008         archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1009         archive_entry_set_atime(entry, zip_entry->atime, 0);
1010
1011         if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1012                 size_t linkname_length;
1013
1014                 if (zip_entry->compressed_size > 64 * 1024) {
1015                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1016                             "Zip file with oversized link entry");
1017                         return ARCHIVE_FATAL;
1018                 }
1019
1020                 linkname_length = (size_t)zip_entry->compressed_size;
1021
1022                 archive_entry_set_size(entry, 0);
1023                 p = __archive_read_ahead(a, linkname_length, NULL);
1024                 if (p == NULL) {
1025                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1026                             "Truncated Zip file");
1027                         return ARCHIVE_FATAL;
1028                 }
1029
1030                 sconv = zip->sconv;
1031                 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1032                         sconv = zip->sconv_utf8;
1033                 if (sconv == NULL)
1034                         sconv = zip->sconv_default;
1035                 if (archive_entry_copy_symlink_l(entry, p, linkname_length,
1036                     sconv) != 0) {
1037                         if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1038                             (zip->entry->zip_flags & ZIP_UTF8_NAME))
1039                             archive_entry_copy_symlink_l(entry, p,
1040                                 linkname_length, NULL);
1041                         if (errno == ENOMEM) {
1042                                 archive_set_error(&a->archive, ENOMEM,
1043                                     "Can't allocate memory for Symlink");
1044                                 return (ARCHIVE_FATAL);
1045                         }
1046                         /*
1047                          * Since there is no character-set regulation for
1048                          * symlink name, do not report the conversion error
1049                          * in an automatic conversion.
1050                          */
1051                         if (sconv != zip->sconv_utf8 ||
1052                             (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1053                                 archive_set_error(&a->archive,
1054                                     ARCHIVE_ERRNO_FILE_FORMAT,
1055                                     "Symlink cannot be converted "
1056                                     "from %s to current locale.",
1057                                     archive_string_conversion_charset_name(
1058                                         sconv));
1059                                 ret = ARCHIVE_WARN;
1060                         }
1061                 }
1062                 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1063
1064                 if (__archive_read_consume(a, linkname_length) < 0) {
1065                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1066                             "Read error skipping symlink target name");
1067                         return ARCHIVE_FATAL;
1068                 }
1069         } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1070             || zip_entry->uncompressed_size > 0) {
1071                 /* Set the size only if it's meaningful. */
1072                 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1073         }
1074         zip->entry_bytes_remaining = zip_entry->compressed_size;
1075
1076         /* If there's no body, force read_data() to return EOF immediately. */
1077         if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1078             && zip->entry_bytes_remaining < 1)
1079                 zip->end_of_entry = 1;
1080
1081         /* Set up a more descriptive format name. */
1082         archive_string_empty(&zip->format_name);
1083         archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1084             version / 10, version % 10,
1085             compression_name(zip->entry->compression));
1086         a->archive.archive_format_name = zip->format_name.s;
1087
1088         return (ret);
1089 }
1090
1091 static int
1092 check_authentication_code(struct archive_read *a, const void *_p)
1093 {
1094         struct zip *zip = (struct zip *)(a->format->data);
1095
1096         /* Check authentication code. */
1097         if (zip->hctx_valid) {
1098                 const void *p;
1099                 uint8_t hmac[20];
1100                 size_t hmac_len = 20;
1101                 int cmp;
1102
1103                 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1104                 if (_p == NULL) {
1105                         /* Read authentication code. */
1106                         p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1107                         if (p == NULL) {
1108                                 archive_set_error(&a->archive,
1109                                     ARCHIVE_ERRNO_FILE_FORMAT,
1110                                     "Truncated ZIP file data");
1111                                 return (ARCHIVE_FATAL);
1112                         }
1113                 } else {
1114                         p = _p;
1115                 }
1116                 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1117                 __archive_read_consume(a, AUTH_CODE_SIZE);
1118                 if (cmp != 0) {
1119                         archive_set_error(&a->archive,
1120                             ARCHIVE_ERRNO_MISC,
1121                             "ZIP bad Authentication code");
1122                         return (ARCHIVE_WARN);
1123                 }
1124         }
1125         return (ARCHIVE_OK);
1126 }
1127
1128 /*
1129  * Read "uncompressed" data.  There are three cases:
1130  *  1) We know the size of the data.  This is always true for the
1131  * seeking reader (we've examined the Central Directory already).
1132  *  2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1133  * Info-ZIP seems to do this; we know the size but have to grab
1134  * the CRC from the data descriptor afterwards.
1135  *  3) We're streaming and ZIP_LENGTH_AT_END was specified and
1136  * we have no size information.  In this case, we can do pretty
1137  * well by watching for the data descriptor record.  The data
1138  * descriptor is 16 bytes and includes a computed CRC that should
1139  * provide a strong check.
1140  *
1141  * TODO: Technically, the PK\007\010 signature is optional.
1142  * In the original spec, the data descriptor contained CRC
1143  * and size fields but had no leading signature.  In practice,
1144  * newer writers seem to provide the signature pretty consistently.
1145  *
1146  * For uncompressed data, the PK\007\010 marker seems essential
1147  * to be sure we've actually seen the end of the entry.
1148  *
1149  * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1150  * zip->end_of_entry if it consumes all of the data.
1151  */
1152 static int
1153 zip_read_data_none(struct archive_read *a, const void **_buff,
1154     size_t *size, int64_t *offset)
1155 {
1156         struct zip *zip;
1157         const char *buff;
1158         ssize_t bytes_avail;
1159         int r;
1160
1161         (void)offset; /* UNUSED */
1162
1163         zip = (struct zip *)(a->format->data);
1164
1165         if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1166                 const char *p;
1167                 ssize_t grabbing_bytes = 24;
1168
1169                 if (zip->hctx_valid)
1170                         grabbing_bytes += AUTH_CODE_SIZE;
1171                 /* Grab at least 24 bytes. */
1172                 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1173                 if (bytes_avail < grabbing_bytes) {
1174                         /* Zip archives have end-of-archive markers
1175                            that are longer than this, so a failure to get at
1176                            least 24 bytes really does indicate a truncated
1177                            file. */
1178                         archive_set_error(&a->archive,
1179                             ARCHIVE_ERRNO_FILE_FORMAT,
1180                             "Truncated ZIP file data");
1181                         return (ARCHIVE_FATAL);
1182                 }
1183                 /* Check for a complete PK\007\010 signature, followed
1184                  * by the correct 4-byte CRC. */
1185                 p = buff;
1186                 if (zip->hctx_valid)
1187                         p += AUTH_CODE_SIZE;
1188                 if (p[0] == 'P' && p[1] == 'K'
1189                     && p[2] == '\007' && p[3] == '\010'
1190                     && (archive_le32dec(p + 4) == zip->entry_crc32
1191                         || zip->ignore_crc32
1192                         || (zip->hctx_valid
1193                          && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1194                         if (zip->entry->flags & LA_USED_ZIP64) {
1195                                 uint64_t compressed, uncompressed;
1196                                 zip->entry->crc32 = archive_le32dec(p + 4);
1197                                 compressed = archive_le64dec(p + 8);
1198                                 uncompressed = archive_le64dec(p + 16);
1199                                 if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1200                                         archive_set_error(&a->archive,
1201                                             ARCHIVE_ERRNO_FILE_FORMAT,
1202                                             "Overflow of 64-bit file sizes");
1203                                         return ARCHIVE_FAILED;
1204                                 }
1205                                 zip->entry->compressed_size = compressed;
1206                                 zip->entry->uncompressed_size = uncompressed;
1207                                 zip->unconsumed = 24;
1208                         } else {
1209                                 zip->entry->crc32 = archive_le32dec(p + 4);
1210                                 zip->entry->compressed_size =
1211                                         archive_le32dec(p + 8);
1212                                 zip->entry->uncompressed_size =
1213                                         archive_le32dec(p + 12);
1214                                 zip->unconsumed = 16;
1215                         }
1216                         if (zip->hctx_valid) {
1217                                 r = check_authentication_code(a, buff);
1218                                 if (r != ARCHIVE_OK)
1219                                         return (r);
1220                         }
1221                         zip->end_of_entry = 1;
1222                         return (ARCHIVE_OK);
1223                 }
1224                 /* If not at EOF, ensure we consume at least one byte. */
1225                 ++p;
1226
1227                 /* Scan forward until we see where a PK\007\010 signature
1228                  * might be. */
1229                 /* Return bytes up until that point.  On the next call,
1230                  * the code above will verify the data descriptor. */
1231                 while (p < buff + bytes_avail - 4) {
1232                         if (p[3] == 'P') { p += 3; }
1233                         else if (p[3] == 'K') { p += 2; }
1234                         else if (p[3] == '\007') { p += 1; }
1235                         else if (p[3] == '\010' && p[2] == '\007'
1236                             && p[1] == 'K' && p[0] == 'P') {
1237                                 if (zip->hctx_valid)
1238                                         p -= AUTH_CODE_SIZE;
1239                                 break;
1240                         } else { p += 4; }
1241                 }
1242                 bytes_avail = p - buff;
1243         } else {
1244                 if (zip->entry_bytes_remaining == 0) {
1245                         zip->end_of_entry = 1;
1246                         if (zip->hctx_valid) {
1247                                 r = check_authentication_code(a, NULL);
1248                                 if (r != ARCHIVE_OK)
1249                                         return (r);
1250                         }
1251                         return (ARCHIVE_OK);
1252                 }
1253                 /* Grab a bunch of bytes. */
1254                 buff = __archive_read_ahead(a, 1, &bytes_avail);
1255                 if (bytes_avail <= 0) {
1256                         archive_set_error(&a->archive,
1257                             ARCHIVE_ERRNO_FILE_FORMAT,
1258                             "Truncated ZIP file data");
1259                         return (ARCHIVE_FATAL);
1260                 }
1261                 if (bytes_avail > zip->entry_bytes_remaining)
1262                         bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1263         }
1264         if (zip->tctx_valid || zip->cctx_valid) {
1265                 size_t dec_size = bytes_avail;
1266
1267                 if (dec_size > zip->decrypted_buffer_size)
1268                         dec_size = zip->decrypted_buffer_size;
1269                 if (zip->tctx_valid) {
1270                         trad_enc_decrypt_update(&zip->tctx,
1271                             (const uint8_t *)buff, dec_size,
1272                             zip->decrypted_buffer, dec_size);
1273                 } else {
1274                         size_t dsize = dec_size;
1275                         archive_hmac_sha1_update(&zip->hctx,
1276                             (const uint8_t *)buff, dec_size);
1277                         archive_decrypto_aes_ctr_update(&zip->cctx,
1278                             (const uint8_t *)buff, dec_size,
1279                             zip->decrypted_buffer, &dsize);
1280                 }
1281                 bytes_avail = dec_size;
1282                 buff = (const char *)zip->decrypted_buffer;
1283         }
1284         *size = bytes_avail;
1285         zip->entry_bytes_remaining -= bytes_avail;
1286         zip->entry_uncompressed_bytes_read += bytes_avail;
1287         zip->entry_compressed_bytes_read += bytes_avail;
1288         zip->unconsumed += bytes_avail;
1289         *_buff = buff;
1290         return (ARCHIVE_OK);
1291 }
1292
1293 #ifdef HAVE_ZLIB_H
1294 static int
1295 zip_deflate_init(struct archive_read *a, struct zip *zip)
1296 {
1297         int r;
1298
1299         /* If we haven't yet read any data, initialize the decompressor. */
1300         if (!zip->decompress_init) {
1301                 if (zip->stream_valid)
1302                         r = inflateReset(&zip->stream);
1303                 else
1304                         r = inflateInit2(&zip->stream,
1305                             -15 /* Don't check for zlib header */);
1306                 if (r != Z_OK) {
1307                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1308                             "Can't initialize ZIP decompression.");
1309                         return (ARCHIVE_FATAL);
1310                 }
1311                 /* Stream structure has been set up. */
1312                 zip->stream_valid = 1;
1313                 /* We've initialized decompression for this stream. */
1314                 zip->decompress_init = 1;
1315         }
1316         return (ARCHIVE_OK);
1317 }
1318
1319 static int
1320 zip_read_data_deflate(struct archive_read *a, const void **buff,
1321     size_t *size, int64_t *offset)
1322 {
1323         struct zip *zip;
1324         ssize_t bytes_avail;
1325         const void *compressed_buff, *sp;
1326         int r;
1327
1328         (void)offset; /* UNUSED */
1329
1330         zip = (struct zip *)(a->format->data);
1331
1332         /* If the buffer hasn't been allocated, allocate it now. */
1333         if (zip->uncompressed_buffer == NULL) {
1334                 zip->uncompressed_buffer_size = 256 * 1024;
1335                 zip->uncompressed_buffer
1336                     = (unsigned char *)malloc(zip->uncompressed_buffer_size);
1337                 if (zip->uncompressed_buffer == NULL) {
1338                         archive_set_error(&a->archive, ENOMEM,
1339                             "No memory for ZIP decompression");
1340                         return (ARCHIVE_FATAL);
1341                 }
1342         }
1343
1344         r = zip_deflate_init(a, zip);
1345         if (r != ARCHIVE_OK)
1346                 return (r);
1347
1348         /*
1349          * Note: '1' here is a performance optimization.
1350          * Recall that the decompression layer returns a count of
1351          * available bytes; asking for more than that forces the
1352          * decompressor to combine reads by copying data.
1353          */
1354         compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
1355         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1356             && bytes_avail > zip->entry_bytes_remaining) {
1357                 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1358         }
1359         if (bytes_avail < 0) {
1360                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1361                     "Truncated ZIP file body");
1362                 return (ARCHIVE_FATAL);
1363         }
1364
1365         if (zip->tctx_valid || zip->cctx_valid) {
1366                 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
1367                         size_t buff_remaining =
1368                             (zip->decrypted_buffer + zip->decrypted_buffer_size)
1369                             - (zip->decrypted_ptr + zip->decrypted_bytes_remaining);
1370
1371                         if (buff_remaining > (size_t)bytes_avail)
1372                                 buff_remaining = (size_t)bytes_avail;
1373
1374                         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
1375                               zip->entry_bytes_remaining > 0) {
1376                                 if ((int64_t)(zip->decrypted_bytes_remaining
1377                                     + buff_remaining)
1378                                       > zip->entry_bytes_remaining) {
1379                                         if (zip->entry_bytes_remaining <
1380                                               (int64_t)zip->decrypted_bytes_remaining)
1381                                                 buff_remaining = 0;
1382                                         else
1383                                                 buff_remaining =
1384                                                     (size_t)zip->entry_bytes_remaining
1385                                                       - zip->decrypted_bytes_remaining;
1386                                 }
1387                         }
1388                         if (buff_remaining > 0) {
1389                                 if (zip->tctx_valid) {
1390                                         trad_enc_decrypt_update(&zip->tctx,
1391                                             compressed_buff, buff_remaining,
1392                                             zip->decrypted_ptr
1393                                               + zip->decrypted_bytes_remaining,
1394                                             buff_remaining);
1395                                 } else {
1396                                         size_t dsize = buff_remaining;
1397                                         archive_decrypto_aes_ctr_update(
1398                                             &zip->cctx,
1399                                             compressed_buff, buff_remaining,
1400                                             zip->decrypted_ptr
1401                                               + zip->decrypted_bytes_remaining,
1402                                             &dsize);
1403                                 }
1404                                 zip->decrypted_bytes_remaining += buff_remaining;
1405                         }
1406                 }
1407                 bytes_avail = zip->decrypted_bytes_remaining;
1408                 compressed_buff = (const char *)zip->decrypted_ptr;
1409         }
1410
1411         /*
1412          * A bug in zlib.h: stream.next_in should be marked 'const'
1413          * but isn't (the library never alters data through the
1414          * next_in pointer, only reads it).  The result: this ugly
1415          * cast to remove 'const'.
1416          */
1417         zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
1418         zip->stream.avail_in = (uInt)bytes_avail;
1419         zip->stream.total_in = 0;
1420         zip->stream.next_out = zip->uncompressed_buffer;
1421         zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
1422         zip->stream.total_out = 0;
1423
1424         r = inflate(&zip->stream, 0);
1425         switch (r) {
1426         case Z_OK:
1427                 break;
1428         case Z_STREAM_END:
1429                 zip->end_of_entry = 1;
1430                 break;
1431         case Z_MEM_ERROR:
1432                 archive_set_error(&a->archive, ENOMEM,
1433                     "Out of memory for ZIP decompression");
1434                 return (ARCHIVE_FATAL);
1435         default:
1436                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1437                     "ZIP decompression failed (%d)", r);
1438                 return (ARCHIVE_FATAL);
1439         }
1440
1441         /* Consume as much as the compressor actually used. */
1442         bytes_avail = zip->stream.total_in;
1443         if (zip->tctx_valid || zip->cctx_valid) {
1444                 zip->decrypted_bytes_remaining -= bytes_avail;
1445                 if (zip->decrypted_bytes_remaining == 0)
1446                         zip->decrypted_ptr = zip->decrypted_buffer;
1447                 else
1448                         zip->decrypted_ptr += bytes_avail;
1449         }
1450         /* Calculate compressed data as much as we used.*/
1451         if (zip->hctx_valid)
1452                 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
1453         __archive_read_consume(a, bytes_avail);
1454         zip->entry_bytes_remaining -= bytes_avail;
1455         zip->entry_compressed_bytes_read += bytes_avail;
1456
1457         *size = zip->stream.total_out;
1458         zip->entry_uncompressed_bytes_read += zip->stream.total_out;
1459         *buff = zip->uncompressed_buffer;
1460
1461         if (zip->end_of_entry && zip->hctx_valid) {
1462                 r = check_authentication_code(a, NULL);
1463                 if (r != ARCHIVE_OK)
1464                         return (r);
1465         }
1466
1467         if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1468                 const char *p;
1469
1470                 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1471                         archive_set_error(&a->archive,
1472                             ARCHIVE_ERRNO_FILE_FORMAT,
1473                             "Truncated ZIP end-of-file record");
1474                         return (ARCHIVE_FATAL);
1475                 }
1476                 /* Consume the optional PK\007\010 marker. */
1477                 if (p[0] == 'P' && p[1] == 'K' &&
1478                     p[2] == '\007' && p[3] == '\010') {
1479                         p += 4;
1480                         zip->unconsumed = 4;
1481                 }
1482                 if (zip->entry->flags & LA_USED_ZIP64) {
1483                         uint64_t compressed, uncompressed;
1484                         zip->entry->crc32 = archive_le32dec(p);
1485                         compressed = archive_le64dec(p + 4);
1486                         uncompressed = archive_le64dec(p + 12);
1487                         if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1488                                 archive_set_error(&a->archive,
1489                                     ARCHIVE_ERRNO_FILE_FORMAT,
1490                                     "Overflow of 64-bit file sizes");
1491                                 return ARCHIVE_FAILED;
1492                         }
1493                         zip->entry->compressed_size = compressed;
1494                         zip->entry->uncompressed_size = uncompressed;
1495                         zip->unconsumed += 20;
1496                 } else {
1497                         zip->entry->crc32 = archive_le32dec(p);
1498                         zip->entry->compressed_size = archive_le32dec(p + 4);
1499                         zip->entry->uncompressed_size = archive_le32dec(p + 8);
1500                         zip->unconsumed += 12;
1501                 }
1502         }
1503
1504         return (ARCHIVE_OK);
1505 }
1506 #endif
1507
1508 static int
1509 read_decryption_header(struct archive_read *a)
1510 {
1511         struct zip *zip = (struct zip *)(a->format->data);
1512         const char *p;
1513         unsigned int remaining_size;
1514         unsigned int ts;
1515
1516         /*
1517          * Read an initialization vector data field.
1518          */
1519         p = __archive_read_ahead(a, 2, NULL);
1520         if (p == NULL)
1521                 goto truncated;
1522         ts = zip->iv_size;
1523         zip->iv_size = archive_le16dec(p);
1524         __archive_read_consume(a, 2);
1525         if (ts < zip->iv_size) {
1526                 free(zip->iv);
1527                 zip->iv = NULL;
1528         }
1529         p = __archive_read_ahead(a, zip->iv_size, NULL);
1530         if (p == NULL)
1531                 goto truncated;
1532         if (zip->iv == NULL) {
1533                 zip->iv = malloc(zip->iv_size);
1534                 if (zip->iv == NULL)
1535                         goto nomem;
1536         }
1537         memcpy(zip->iv, p, zip->iv_size);
1538         __archive_read_consume(a, zip->iv_size);
1539
1540         /*
1541          * Read a size of remaining decryption header field.
1542          */
1543         p = __archive_read_ahead(a, 14, NULL);
1544         if (p == NULL)
1545                 goto truncated;
1546         remaining_size = archive_le32dec(p);
1547         if (remaining_size < 16 || remaining_size > (1 << 18))
1548                 goto corrupted;
1549
1550         /* Check if format version is supported. */
1551         if (archive_le16dec(p+4) != 3) {
1552                 archive_set_error(&a->archive,
1553                     ARCHIVE_ERRNO_FILE_FORMAT,
1554                     "Unsupported encryption format version: %u",
1555                     archive_le16dec(p+4));
1556                 return (ARCHIVE_FAILED);
1557         }
1558
1559         /*
1560          * Read an encryption algorithm field.
1561          */
1562         zip->alg_id = archive_le16dec(p+6);
1563         switch (zip->alg_id) {
1564         case 0x6601:/* DES */
1565         case 0x6602:/* RC2 */
1566         case 0x6603:/* 3DES 168 */
1567         case 0x6609:/* 3DES 112 */
1568         case 0x660E:/* AES 128 */
1569         case 0x660F:/* AES 192 */
1570         case 0x6610:/* AES 256 */
1571         case 0x6702:/* RC2 (version >= 5.2) */
1572         case 0x6720:/* Blowfish */
1573         case 0x6721:/* Twofish */
1574         case 0x6801:/* RC4 */
1575                 /* Supported encryption algorithm. */
1576                 break;
1577         default:
1578                 archive_set_error(&a->archive,
1579                     ARCHIVE_ERRNO_FILE_FORMAT,
1580                     "Unknown encryption algorithm: %u", zip->alg_id);
1581                 return (ARCHIVE_FAILED);
1582         }
1583
1584         /*
1585          * Read a bit length field.
1586          */
1587         zip->bit_len = archive_le16dec(p+8);
1588
1589         /*
1590          * Read a flags field.
1591          */
1592         zip->flags = archive_le16dec(p+10);
1593         switch (zip->flags & 0xf000) {
1594         case 0x0001: /* Password is required to decrypt. */
1595         case 0x0002: /* Certificates only. */
1596         case 0x0003: /* Password or certificate required to decrypt. */
1597                 break;
1598         default:
1599                 archive_set_error(&a->archive,
1600                     ARCHIVE_ERRNO_FILE_FORMAT,
1601                     "Unknown encryption flag: %u", zip->flags);
1602                 return (ARCHIVE_FAILED);
1603         }
1604         if ((zip->flags & 0xf000) == 0 ||
1605             (zip->flags & 0xf000) == 0x4000) {
1606                 archive_set_error(&a->archive,
1607                     ARCHIVE_ERRNO_FILE_FORMAT,
1608                     "Unknown encryption flag: %u", zip->flags);
1609                 return (ARCHIVE_FAILED);
1610         }
1611
1612         /*
1613          * Read an encrypted random data field.
1614          */
1615         ts = zip->erd_size;
1616         zip->erd_size = archive_le16dec(p+12);
1617         __archive_read_consume(a, 14);
1618         if ((zip->erd_size & 0xf) != 0 ||
1619             (zip->erd_size + 16) > remaining_size ||
1620             (zip->erd_size + 16) < zip->erd_size)
1621                 goto corrupted;
1622
1623         if (ts < zip->erd_size) {
1624                 free(zip->erd);
1625                 zip->erd = NULL;
1626         }
1627         p = __archive_read_ahead(a, zip->erd_size, NULL);
1628         if (p == NULL)
1629                 goto truncated;
1630         if (zip->erd == NULL) {
1631                 zip->erd = malloc(zip->erd_size);
1632                 if (zip->erd == NULL)
1633                         goto nomem;
1634         }
1635         memcpy(zip->erd, p, zip->erd_size);
1636         __archive_read_consume(a, zip->erd_size);
1637
1638         /*
1639          * Read a reserved data field.
1640          */
1641         p = __archive_read_ahead(a, 4, NULL);
1642         if (p == NULL)
1643                 goto truncated;
1644         /* Reserved data size should be zero. */
1645         if (archive_le32dec(p) != 0)
1646                 goto corrupted;
1647         __archive_read_consume(a, 4);
1648
1649         /*
1650          * Read a password validation data field.
1651          */
1652         p = __archive_read_ahead(a, 2, NULL);
1653         if (p == NULL)
1654                 goto truncated;
1655         ts = zip->v_size;
1656         zip->v_size = archive_le16dec(p);
1657         __archive_read_consume(a, 2);
1658         if ((zip->v_size & 0x0f) != 0 ||
1659             (zip->erd_size + zip->v_size + 16) > remaining_size ||
1660             (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
1661                 goto corrupted;
1662         if (ts < zip->v_size) {
1663                 free(zip->v_data);
1664                 zip->v_data = NULL;
1665         }
1666         p = __archive_read_ahead(a, zip->v_size, NULL);
1667         if (p == NULL)
1668                 goto truncated;
1669         if (zip->v_data == NULL) {
1670                 zip->v_data = malloc(zip->v_size);
1671                 if (zip->v_data == NULL)
1672                         goto nomem;
1673         }
1674         memcpy(zip->v_data, p, zip->v_size);
1675         __archive_read_consume(a, zip->v_size);
1676
1677         p = __archive_read_ahead(a, 4, NULL);
1678         if (p == NULL)
1679                 goto truncated;
1680         zip->v_crc32 = archive_le32dec(p);
1681         __archive_read_consume(a, 4);
1682
1683         /*return (ARCHIVE_OK);
1684          * This is not fully implemented yet.*/
1685         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1686             "Encrypted file is unsupported");
1687         return (ARCHIVE_FAILED);
1688 truncated:
1689         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1690             "Truncated ZIP file data");
1691         return (ARCHIVE_FATAL);
1692 corrupted:
1693         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1694             "Corrupted ZIP file data");
1695         return (ARCHIVE_FATAL);
1696 nomem:
1697         archive_set_error(&a->archive, ENOMEM,
1698             "No memory for ZIP decryption");
1699         return (ARCHIVE_FATAL);
1700 }
1701
1702 static int
1703 zip_alloc_decryption_buffer(struct archive_read *a)
1704 {
1705         struct zip *zip = (struct zip *)(a->format->data);
1706         size_t bs = 256 * 1024;
1707
1708         if (zip->decrypted_buffer == NULL) {
1709                 zip->decrypted_buffer_size = bs;
1710                 zip->decrypted_buffer = malloc(bs);
1711                 if (zip->decrypted_buffer == NULL) {
1712                         archive_set_error(&a->archive, ENOMEM,
1713                             "No memory for ZIP decryption");
1714                         return (ARCHIVE_FATAL);
1715                 }
1716         }
1717         zip->decrypted_ptr = zip->decrypted_buffer;
1718         return (ARCHIVE_OK);
1719 }
1720
1721 static int
1722 init_traditional_PKWARE_decryption(struct archive_read *a)
1723 {
1724         struct zip *zip = (struct zip *)(a->format->data);
1725         const void *p;
1726         int retry;
1727         int r;
1728
1729         if (zip->tctx_valid)
1730                 return (ARCHIVE_OK);
1731
1732         /*
1733            Read the 12 bytes encryption header stored at
1734            the start of the data area.
1735          */
1736 #define ENC_HEADER_SIZE 12
1737         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1738             && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
1739                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1740                     "Truncated Zip encrypted body: only %jd bytes available",
1741                     (intmax_t)zip->entry_bytes_remaining);
1742                 return (ARCHIVE_FATAL);
1743         }
1744
1745         p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
1746         if (p == NULL) {
1747                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1748                     "Truncated ZIP file data");
1749                 return (ARCHIVE_FATAL);
1750         }
1751
1752         for (retry = 0;; retry++) {
1753                 const char *passphrase;
1754                 uint8_t crcchk;
1755
1756                 passphrase = __archive_read_next_passphrase(a);
1757                 if (passphrase == NULL) {
1758                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1759                             (retry > 0)?
1760                                 "Incorrect passphrase":
1761                                 "Passphrase required for this entry");
1762                         return (ARCHIVE_FAILED);
1763                 }
1764
1765                 /*
1766                  * Initialize ctx for Traditional PKWARE Decryption.
1767                  */
1768                 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
1769                         p, ENC_HEADER_SIZE, &crcchk);
1770                 if (r == 0 && crcchk == zip->entry->decdat)
1771                         break;/* The passphrase is OK. */
1772                 if (retry > 10000) {
1773                         /* Avoid infinity loop. */
1774                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1775                             "Too many incorrect passphrases");
1776                         return (ARCHIVE_FAILED);
1777                 }
1778         }
1779
1780         __archive_read_consume(a, ENC_HEADER_SIZE);
1781         zip->tctx_valid = 1;
1782         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1783             zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
1784         }
1785         /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
1786         zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
1787         zip->decrypted_bytes_remaining = 0;
1788
1789         return (zip_alloc_decryption_buffer(a));
1790 #undef ENC_HEADER_SIZE
1791 }
1792
1793 static int
1794 init_WinZip_AES_decryption(struct archive_read *a)
1795 {
1796         struct zip *zip = (struct zip *)(a->format->data);
1797         const void *p;
1798         const uint8_t *pv;
1799         size_t key_len, salt_len;
1800         uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
1801         int retry;
1802         int r;
1803
1804         if (zip->cctx_valid || zip->hctx_valid)
1805                 return (ARCHIVE_OK);
1806
1807         switch (zip->entry->aes_extra.strength) {
1808         case 1: salt_len = 8;  key_len = 16; break;
1809         case 2: salt_len = 12; key_len = 24; break;
1810         case 3: salt_len = 16; key_len = 32; break;
1811         default: goto corrupted;
1812         }
1813         p = __archive_read_ahead(a, salt_len + 2, NULL);
1814         if (p == NULL)
1815                 goto truncated;
1816
1817         for (retry = 0;; retry++) {
1818                 const char *passphrase;
1819
1820                 passphrase = __archive_read_next_passphrase(a);
1821                 if (passphrase == NULL) {
1822                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1823                             (retry > 0)?
1824                                 "Incorrect passphrase":
1825                                 "Passphrase required for this entry");
1826                         return (ARCHIVE_FAILED);
1827                 }
1828                 memset(derived_key, 0, sizeof(derived_key));
1829                 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
1830                     p, salt_len, 1000, derived_key, key_len * 2 + 2);
1831                 if (r != 0) {
1832                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1833                             "Decryption is unsupported due to lack of "
1834                             "crypto library");
1835                         return (ARCHIVE_FAILED);
1836                 }
1837
1838                 /* Check password verification value. */
1839                 pv = ((const uint8_t *)p) + salt_len;
1840                 if (derived_key[key_len * 2] == pv[0] &&
1841                     derived_key[key_len * 2 + 1] == pv[1])
1842                         break;/* The passphrase is OK. */
1843                 if (retry > 10000) {
1844                         /* Avoid infinity loop. */
1845                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1846                             "Too many incorrect passphrases");
1847                         return (ARCHIVE_FAILED);
1848                 }
1849         }
1850
1851         r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
1852         if (r != 0) {
1853                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1854                     "Decryption is unsupported due to lack of crypto library");
1855                 return (ARCHIVE_FAILED);
1856         }
1857         r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
1858         if (r != 0) {
1859                 archive_decrypto_aes_ctr_release(&zip->cctx);
1860                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1861                     "Failed to initialize HMAC-SHA1");
1862                 return (ARCHIVE_FAILED);
1863         }
1864         zip->cctx_valid = zip->hctx_valid = 1;
1865         __archive_read_consume(a, salt_len + 2);
1866         zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
1867         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1868             && zip->entry_bytes_remaining < 0)
1869                 goto corrupted;
1870         zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
1871         zip->decrypted_bytes_remaining = 0;
1872
1873         zip->entry->compression = zip->entry->aes_extra.compression;
1874         return (zip_alloc_decryption_buffer(a));
1875
1876 truncated:
1877         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1878             "Truncated ZIP file data");
1879         return (ARCHIVE_FATAL);
1880 corrupted:
1881         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1882             "Corrupted ZIP file data");
1883         return (ARCHIVE_FATAL);
1884 }
1885
1886 static int
1887 archive_read_format_zip_read_data(struct archive_read *a,
1888     const void **buff, size_t *size, int64_t *offset)
1889 {
1890         int r;
1891         struct zip *zip = (struct zip *)(a->format->data);
1892
1893         if (zip->has_encrypted_entries ==
1894                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
1895                 zip->has_encrypted_entries = 0;
1896         }
1897
1898         *offset = zip->entry_uncompressed_bytes_read;
1899         *size = 0;
1900         *buff = NULL;
1901
1902         /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
1903         if (zip->end_of_entry)
1904                 return (ARCHIVE_EOF);
1905
1906         /* Return EOF immediately if this is a non-regular file. */
1907         if (AE_IFREG != (zip->entry->mode & AE_IFMT))
1908                 return (ARCHIVE_EOF);
1909
1910         __archive_read_consume(a, zip->unconsumed);
1911         zip->unconsumed = 0;
1912
1913         if (zip->init_decryption) {
1914                 zip->has_encrypted_entries = 1;
1915                 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
1916                         r = read_decryption_header(a);
1917                 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
1918                         r = init_WinZip_AES_decryption(a);
1919                 else
1920                         r = init_traditional_PKWARE_decryption(a);
1921                 if (r != ARCHIVE_OK)
1922                         return (r);
1923                 zip->init_decryption = 0;
1924         }
1925
1926         switch(zip->entry->compression) {
1927         case 0:  /* No compression. */
1928                 r =  zip_read_data_none(a, buff, size, offset);
1929                 break;
1930 #ifdef HAVE_ZLIB_H
1931         case 8: /* Deflate compression. */
1932                 r =  zip_read_data_deflate(a, buff, size, offset);
1933                 break;
1934 #endif
1935         default: /* Unsupported compression. */
1936                 /* Return a warning. */
1937                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1938                     "Unsupported ZIP compression method (%s)",
1939                     compression_name(zip->entry->compression));
1940                 /* We can't decompress this entry, but we will
1941                  * be able to skip() it and try the next entry. */
1942                 return (ARCHIVE_FAILED);
1943                 break;
1944         }
1945         if (r != ARCHIVE_OK)
1946                 return (r);
1947         /* Update checksum */
1948         if (*size)
1949                 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
1950                     (unsigned)*size);
1951         /* If we hit the end, swallow any end-of-data marker. */
1952         if (zip->end_of_entry) {
1953                 /* Check file size, CRC against these values. */
1954                 if (zip->entry->compressed_size !=
1955                     zip->entry_compressed_bytes_read) {
1956                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1957                             "ZIP compressed data is wrong size "
1958                             "(read %jd, expected %jd)",
1959                             (intmax_t)zip->entry_compressed_bytes_read,
1960                             (intmax_t)zip->entry->compressed_size);
1961                         return (ARCHIVE_WARN);
1962                 }
1963                 /* Size field only stores the lower 32 bits of the actual
1964                  * size. */
1965                 if ((zip->entry->uncompressed_size & UINT32_MAX)
1966                     != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
1967                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1968                             "ZIP uncompressed data is wrong size "
1969                             "(read %jd, expected %jd)\n",
1970                             (intmax_t)zip->entry_uncompressed_bytes_read,
1971                             (intmax_t)zip->entry->uncompressed_size);
1972                         return (ARCHIVE_WARN);
1973                 }
1974                 /* Check computed CRC against header */
1975                 if ((!zip->hctx_valid ||
1976                       zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
1977                    zip->entry->crc32 != zip->entry_crc32
1978                     && !zip->ignore_crc32) {
1979                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1980                             "ZIP bad CRC: 0x%lx should be 0x%lx",
1981                             (unsigned long)zip->entry_crc32,
1982                             (unsigned long)zip->entry->crc32);
1983                         return (ARCHIVE_WARN);
1984                 }
1985         }
1986
1987         return (ARCHIVE_OK);
1988 }
1989
1990 static int
1991 archive_read_format_zip_cleanup(struct archive_read *a)
1992 {
1993         struct zip *zip;
1994         struct zip_entry *zip_entry, *next_zip_entry;
1995
1996         zip = (struct zip *)(a->format->data);
1997 #ifdef HAVE_ZLIB_H
1998         if (zip->stream_valid)
1999                 inflateEnd(&zip->stream);
2000         free(zip->uncompressed_buffer);
2001 #endif
2002         if (zip->zip_entries) {
2003                 zip_entry = zip->zip_entries;
2004                 while (zip_entry != NULL) {
2005                         next_zip_entry = zip_entry->next;
2006                         archive_string_free(&zip_entry->rsrcname);
2007                         free(zip_entry);
2008                         zip_entry = next_zip_entry;
2009                 }
2010         }
2011         free(zip->decrypted_buffer);
2012         if (zip->cctx_valid)
2013                 archive_decrypto_aes_ctr_release(&zip->cctx);
2014         if (zip->hctx_valid)
2015                 archive_hmac_sha1_cleanup(&zip->hctx);
2016         free(zip->iv);
2017         free(zip->erd);
2018         free(zip->v_data);
2019         archive_string_free(&zip->format_name);
2020         free(zip);
2021         (a->format->data) = NULL;
2022         return (ARCHIVE_OK);
2023 }
2024
2025 static int
2026 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
2027 {
2028         if (_a && _a->format) {
2029                 struct zip * zip = (struct zip *)_a->format->data;
2030                 if (zip) {
2031                         return zip->has_encrypted_entries;
2032                 }
2033         }
2034         return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2035 }
2036
2037 static int
2038 archive_read_format_zip_options(struct archive_read *a,
2039     const char *key, const char *val)
2040 {
2041         struct zip *zip;
2042         int ret = ARCHIVE_FAILED;
2043
2044         zip = (struct zip *)(a->format->data);
2045         if (strcmp(key, "compat-2x")  == 0) {
2046                 /* Handle filenames as libarchive 2.x */
2047                 zip->init_default_conversion = (val != NULL) ? 1 : 0;
2048                 return (ARCHIVE_OK);
2049         } else if (strcmp(key, "hdrcharset")  == 0) {
2050                 if (val == NULL || val[0] == 0)
2051                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2052                             "zip: hdrcharset option needs a character-set name"
2053                         );
2054                 else {
2055                         zip->sconv = archive_string_conversion_from_charset(
2056                             &a->archive, val, 0);
2057                         if (zip->sconv != NULL) {
2058                                 if (strcmp(val, "UTF-8") == 0)
2059                                         zip->sconv_utf8 = zip->sconv;
2060                                 ret = ARCHIVE_OK;
2061                         } else
2062                                 ret = ARCHIVE_FATAL;
2063                 }
2064                 return (ret);
2065         } else if (strcmp(key, "ignorecrc32") == 0) {
2066                 /* Mostly useful for testing. */
2067                 if (val == NULL || val[0] == 0) {
2068                         zip->crc32func = real_crc32;
2069                         zip->ignore_crc32 = 0;
2070                 } else {
2071                         zip->crc32func = fake_crc32;
2072                         zip->ignore_crc32 = 1;
2073                 }
2074                 return (ARCHIVE_OK);
2075         } else if (strcmp(key, "mac-ext") == 0) {
2076                 zip->process_mac_extensions = (val != NULL && val[0] != 0);
2077                 return (ARCHIVE_OK);
2078         }
2079
2080         /* Note: The "warn" return is just to inform the options
2081          * supervisor that we didn't handle it.  It will generate
2082          * a suitable error if no one used this option. */
2083         return (ARCHIVE_WARN);
2084 }
2085
2086 int
2087 archive_read_support_format_zip(struct archive *a)
2088 {
2089         int r;
2090         r = archive_read_support_format_zip_streamable(a);
2091         if (r != ARCHIVE_OK)
2092                 return r;
2093         return (archive_read_support_format_zip_seekable(a));
2094 }
2095
2096 /* ------------------------------------------------------------------------ */
2097
2098 /*
2099  * Streaming-mode support
2100  */
2101
2102
2103 static int
2104 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
2105 {
2106         (void)a; /* UNUSED */
2107         return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2108                 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2109 }
2110
2111 static int
2112 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
2113 {
2114         const char *p;
2115
2116         (void)best_bid; /* UNUSED */
2117
2118         if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
2119                 return (-1);
2120
2121         /*
2122          * Bid of 29 here comes from:
2123          *  + 16 bits for "PK",
2124          *  + next 16-bit field has 6 options so contributes
2125          *    about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
2126          *
2127          * So we've effectively verified ~29 total bits of check data.
2128          */
2129         if (p[0] == 'P' && p[1] == 'K') {
2130                 if ((p[2] == '\001' && p[3] == '\002')
2131                     || (p[2] == '\003' && p[3] == '\004')
2132                     || (p[2] == '\005' && p[3] == '\006')
2133                     || (p[2] == '\006' && p[3] == '\006')
2134                     || (p[2] == '\007' && p[3] == '\010')
2135                     || (p[2] == '0' && p[3] == '0'))
2136                         return (29);
2137         }
2138
2139         /* TODO: It's worth looking ahead a little bit for a valid
2140          * PK signature.  In particular, that would make it possible
2141          * to read some UUEncoded SFX files or SFX files coming from
2142          * a network socket. */
2143
2144         return (0);
2145 }
2146
2147 static int
2148 archive_read_format_zip_streamable_read_header(struct archive_read *a,
2149     struct archive_entry *entry)
2150 {
2151         struct zip *zip;
2152
2153         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
2154         if (a->archive.archive_format_name == NULL)
2155                 a->archive.archive_format_name = "ZIP";
2156
2157         zip = (struct zip *)(a->format->data);
2158
2159         /*
2160          * It should be sufficient to call archive_read_next_header() for
2161          * a reader to determine if an entry is encrypted or not. If the
2162          * encryption of an entry is only detectable when calling
2163          * archive_read_data(), so be it. We'll do the same check there
2164          * as well.
2165          */
2166         if (zip->has_encrypted_entries ==
2167                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
2168                 zip->has_encrypted_entries = 0;
2169
2170         /* Make sure we have a zip_entry structure to use. */
2171         if (zip->zip_entries == NULL) {
2172                 zip->zip_entries = malloc(sizeof(struct zip_entry));
2173                 if (zip->zip_entries == NULL) {
2174                         archive_set_error(&a->archive, ENOMEM,
2175                             "Out  of memory");
2176                         return ARCHIVE_FATAL;
2177                 }
2178         }
2179         zip->entry = zip->zip_entries;
2180         memset(zip->entry, 0, sizeof(struct zip_entry));
2181
2182         if (zip->cctx_valid)
2183                 archive_decrypto_aes_ctr_release(&zip->cctx);
2184         if (zip->hctx_valid)
2185                 archive_hmac_sha1_cleanup(&zip->hctx);
2186         zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
2187         __archive_read_reset_passphrase(a);
2188
2189         /* Search ahead for the next local file header. */
2190         __archive_read_consume(a, zip->unconsumed);
2191         zip->unconsumed = 0;
2192         for (;;) {
2193                 int64_t skipped = 0;
2194                 const char *p, *end;
2195                 ssize_t bytes;
2196
2197                 p = __archive_read_ahead(a, 4, &bytes);
2198                 if (p == NULL)
2199                         return (ARCHIVE_FATAL);
2200                 end = p + bytes;
2201
2202                 while (p + 4 <= end) {
2203                         if (p[0] == 'P' && p[1] == 'K') {
2204                                 if (p[2] == '\003' && p[3] == '\004') {
2205                                         /* Regular file entry. */
2206                                         __archive_read_consume(a, skipped);
2207                                         return zip_read_local_file_header(a,
2208                                             entry, zip);
2209                                 }
2210
2211                               /*
2212                                * TODO: We cannot restore permissions
2213                                * based only on the local file headers.
2214                                * Consider scanning the central
2215                                * directory and returning additional
2216                                * entries for at least directories.
2217                                * This would allow us to properly set
2218                                * directory permissions.
2219                                *
2220                                * This won't help us fix symlinks
2221                                * and may not help with regular file
2222                                * permissions, either.  <sigh>
2223                                */
2224                               if (p[2] == '\001' && p[3] == '\002') {
2225                                       return (ARCHIVE_EOF);
2226                               }
2227
2228                               /* End of central directory?  Must be an
2229                                * empty archive. */
2230                               if ((p[2] == '\005' && p[3] == '\006')
2231                                   || (p[2] == '\006' && p[3] == '\006'))
2232                                       return (ARCHIVE_EOF);
2233                         }
2234                         ++p;
2235                         ++skipped;
2236                 }
2237                 __archive_read_consume(a, skipped);
2238         }
2239 }
2240
2241 static int
2242 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
2243 {
2244         struct zip *zip;
2245         int64_t bytes_skipped;
2246
2247         zip = (struct zip *)(a->format->data);
2248         bytes_skipped = __archive_read_consume(a, zip->unconsumed);
2249         zip->unconsumed = 0;
2250         if (bytes_skipped < 0)
2251                 return (ARCHIVE_FATAL);
2252
2253         /* If we've already read to end of data, we're done. */
2254         if (zip->end_of_entry)
2255                 return (ARCHIVE_OK);
2256
2257         /* So we know we're streaming... */
2258         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2259             || zip->entry->compressed_size > 0) {
2260                 /* We know the compressed length, so we can just skip. */
2261                 bytes_skipped = __archive_read_consume(a,
2262                                         zip->entry_bytes_remaining);
2263                 if (bytes_skipped < 0)
2264                         return (ARCHIVE_FATAL);
2265                 return (ARCHIVE_OK);
2266         }
2267
2268         if (zip->init_decryption) {
2269                 int r;
2270
2271                 zip->has_encrypted_entries = 1;
2272                 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2273                         r = read_decryption_header(a);
2274                 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2275                         r = init_WinZip_AES_decryption(a);
2276                 else
2277                         r = init_traditional_PKWARE_decryption(a);
2278                 if (r != ARCHIVE_OK)
2279                         return (r);
2280                 zip->init_decryption = 0;
2281         }
2282
2283         /* We're streaming and we don't know the length. */
2284         /* If the body is compressed and we know the format, we can
2285          * find an exact end-of-entry by decompressing it. */
2286         switch (zip->entry->compression) {
2287 #ifdef HAVE_ZLIB_H
2288         case 8: /* Deflate compression. */
2289                 while (!zip->end_of_entry) {
2290                         int64_t offset = 0;
2291                         const void *buff = NULL;
2292                         size_t size = 0;
2293                         int r;
2294                         r =  zip_read_data_deflate(a, &buff, &size, &offset);
2295                         if (r != ARCHIVE_OK)
2296                                 return (r);
2297                 }
2298                 return ARCHIVE_OK;
2299 #endif
2300         default: /* Uncompressed or unknown. */
2301                 /* Scan for a PK\007\010 signature. */
2302                 for (;;) {
2303                         const char *p, *buff;
2304                         ssize_t bytes_avail;
2305                         buff = __archive_read_ahead(a, 16, &bytes_avail);
2306                         if (bytes_avail < 16) {
2307                                 archive_set_error(&a->archive,
2308                                     ARCHIVE_ERRNO_FILE_FORMAT,
2309                                     "Truncated ZIP file data");
2310                                 return (ARCHIVE_FATAL);
2311                         }
2312                         p = buff;
2313                         while (p <= buff + bytes_avail - 16) {
2314                                 if (p[3] == 'P') { p += 3; }
2315                                 else if (p[3] == 'K') { p += 2; }
2316                                 else if (p[3] == '\007') { p += 1; }
2317                                 else if (p[3] == '\010' && p[2] == '\007'
2318                                     && p[1] == 'K' && p[0] == 'P') {
2319                                         if (zip->entry->flags & LA_USED_ZIP64)
2320                                                 __archive_read_consume(a,
2321                                                     p - buff + 24);
2322                                         else
2323                                                 __archive_read_consume(a,
2324                                                     p - buff + 16);
2325                                         return ARCHIVE_OK;
2326                                 } else { p += 4; }
2327                         }
2328                         __archive_read_consume(a, p - buff);
2329                 }
2330         }
2331 }
2332
2333 int
2334 archive_read_support_format_zip_streamable(struct archive *_a)
2335 {
2336         struct archive_read *a = (struct archive_read *)_a;
2337         struct zip *zip;
2338         int r;
2339
2340         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
2341             ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
2342
2343         zip = (struct zip *)calloc(1, sizeof(*zip));
2344         if (zip == NULL) {
2345                 archive_set_error(&a->archive, ENOMEM,
2346                     "Can't allocate zip data");
2347                 return (ARCHIVE_FATAL);
2348         }
2349
2350         /* Streamable reader doesn't support mac extensions. */
2351         zip->process_mac_extensions = 0;
2352
2353         /*
2354          * Until enough data has been read, we cannot tell about
2355          * any encrypted entries yet.
2356          */
2357         zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2358         zip->crc32func = real_crc32;
2359
2360         r = __archive_read_register_format(a,
2361             zip,
2362             "zip",
2363             archive_read_format_zip_streamable_bid,
2364             archive_read_format_zip_options,
2365             archive_read_format_zip_streamable_read_header,
2366             archive_read_format_zip_read_data,
2367             archive_read_format_zip_read_data_skip_streamable,
2368             NULL,
2369             archive_read_format_zip_cleanup,
2370             archive_read_support_format_zip_capabilities_streamable,
2371             archive_read_format_zip_has_encrypted_entries);
2372
2373         if (r != ARCHIVE_OK)
2374                 free(zip);
2375         return (ARCHIVE_OK);
2376 }
2377
2378 /* ------------------------------------------------------------------------ */
2379
2380 /*
2381  * Seeking-mode support
2382  */
2383
2384 static int
2385 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
2386 {
2387         (void)a; /* UNUSED */
2388         return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2389                 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2390 }
2391
2392 /*
2393  * TODO: This is a performance sink because it forces the read core to
2394  * drop buffered data from the start of file, which will then have to
2395  * be re-read again if this bidder loses.
2396  *
2397  * We workaround this a little by passing in the best bid so far so
2398  * that later bidders can do nothing if they know they'll never
2399  * outbid.  But we can certainly do better...
2400  */
2401 static int
2402 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
2403 {
2404         /* Sanity-check the EOCD we've found. */
2405
2406         /* This must be the first volume. */
2407         if (archive_le16dec(p + 4) != 0)
2408                 return 0;
2409         /* Central directory must be on this volume. */
2410         if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
2411                 return 0;
2412         /* All central directory entries must be on this volume. */
2413         if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
2414                 return 0;
2415         /* Central directory can't extend beyond start of EOCD record. */
2416         if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
2417             > current_offset)
2418                 return 0;
2419
2420         /* Save the central directory location for later use. */
2421         zip->central_directory_offset = archive_le32dec(p + 16);
2422
2423         /* This is just a tiny bit higher than the maximum
2424            returned by the streaming Zip bidder.  This ensures
2425            that the more accurate seeking Zip parser wins
2426            whenever seek is available. */
2427         return 32;
2428 }
2429
2430 /*
2431  * Examine Zip64 EOCD locator:  If it's valid, store the information
2432  * from it.
2433  */
2434 static int
2435 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
2436 {
2437         int64_t eocd64_offset;
2438         int64_t eocd64_size;
2439
2440         /* Sanity-check the locator record. */
2441
2442         /* Central dir must be on first volume. */
2443         if (archive_le32dec(p + 4) != 0)
2444                 return 0;
2445         /* Must be only a single volume. */
2446         if (archive_le32dec(p + 16) != 1)
2447                 return 0;
2448
2449         /* Find the Zip64 EOCD record. */
2450         eocd64_offset = archive_le64dec(p + 8);
2451         if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
2452                 return 0;
2453         if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
2454                 return 0;
2455         /* Make sure we can read all of it. */
2456         eocd64_size = archive_le64dec(p + 4) + 12;
2457         if (eocd64_size < 56 || eocd64_size > 16384)
2458                 return 0;
2459         if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
2460                 return 0;
2461
2462         /* Sanity-check the EOCD64 */
2463         if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
2464                 return 0;
2465         if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
2466                 return 0;
2467         /* CD can't be split. */
2468         if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
2469                 return 0;
2470
2471         /* Save the central directory offset for later use. */
2472         zip->central_directory_offset = archive_le64dec(p + 48);
2473
2474         return 32;
2475 }
2476
2477 static int
2478 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
2479 {
2480         struct zip *zip = (struct zip *)a->format->data;
2481         int64_t file_size, current_offset;
2482         const char *p;
2483         int i, tail;
2484
2485         /* If someone has already bid more than 32, then avoid
2486            trashing the look-ahead buffers with a seek. */
2487         if (best_bid > 32)
2488                 return (-1);
2489
2490         file_size = __archive_read_seek(a, 0, SEEK_END);
2491         if (file_size <= 0)
2492                 return 0;
2493
2494         /* Search last 16k of file for end-of-central-directory
2495          * record (which starts with PK\005\006) */
2496         tail = (int)zipmin(1024 * 16, file_size);
2497         current_offset = __archive_read_seek(a, -tail, SEEK_END);
2498         if (current_offset < 0)
2499                 return 0;
2500         if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
2501                 return 0;
2502         /* Boyer-Moore search backwards from the end, since we want
2503          * to match the last EOCD in the file (there can be more than
2504          * one if there is an uncompressed Zip archive as a member
2505          * within this Zip archive). */
2506         for (i = tail - 22; i > 0;) {
2507                 switch (p[i]) {
2508                 case 'P':
2509                         if (memcmp(p + i, "PK\005\006", 4) == 0) {
2510                                 int ret = read_eocd(zip, p + i,
2511                                     current_offset + i);
2512                                 /* Zip64 EOCD locator precedes
2513                                  * regular EOCD if present. */
2514                                 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
2515                                         int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
2516                                         if (ret_zip64 > ret)
2517                                                 ret = ret_zip64;
2518                                 }
2519                                 return (ret);
2520                         }
2521                         i -= 4;
2522                         break;
2523                 case 'K': i -= 1; break;
2524                 case 005: i -= 2; break;
2525                 case 006: i -= 3; break;
2526                 default: i -= 4; break;
2527                 }
2528         }
2529         return 0;
2530 }
2531
2532 /* The red-black trees are only used in seeking mode to manage
2533  * the in-memory copy of the central directory. */
2534
2535 static int
2536 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
2537 {
2538         const struct zip_entry *e1 = (const struct zip_entry *)n1;
2539         const struct zip_entry *e2 = (const struct zip_entry *)n2;
2540
2541         if (e1->local_header_offset > e2->local_header_offset)
2542                 return -1;
2543         if (e1->local_header_offset < e2->local_header_offset)
2544                 return 1;
2545         return 0;
2546 }
2547
2548 static int
2549 cmp_key(const struct archive_rb_node *n, const void *key)
2550 {
2551         /* This function won't be called */
2552         (void)n; /* UNUSED */
2553         (void)key; /* UNUSED */
2554         return 1;
2555 }
2556
2557 static const struct archive_rb_tree_ops rb_ops = {
2558         &cmp_node, &cmp_key
2559 };
2560
2561 static int
2562 rsrc_cmp_node(const struct archive_rb_node *n1,
2563     const struct archive_rb_node *n2)
2564 {
2565         const struct zip_entry *e1 = (const struct zip_entry *)n1;
2566         const struct zip_entry *e2 = (const struct zip_entry *)n2;
2567
2568         return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
2569 }
2570
2571 static int
2572 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
2573 {
2574         const struct zip_entry *e = (const struct zip_entry *)n;
2575         return (strcmp((const char *)key, e->rsrcname.s));
2576 }
2577
2578 static const struct archive_rb_tree_ops rb_rsrc_ops = {
2579         &rsrc_cmp_node, &rsrc_cmp_key
2580 };
2581
2582 static const char *
2583 rsrc_basename(const char *name, size_t name_length)
2584 {
2585         const char *s, *r;
2586
2587         r = s = name;
2588         for (;;) {
2589                 s = memchr(s, '/', name_length - (s - name));
2590                 if (s == NULL)
2591                         break;
2592                 r = ++s;
2593         }
2594         return (r);
2595 }
2596
2597 static void
2598 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
2599 {
2600         struct archive_string str;
2601         struct zip_entry *dir;
2602         char *s;
2603
2604         archive_string_init(&str);
2605         archive_strncpy(&str, name, name_length);
2606         for (;;) {
2607                 s = strrchr(str.s, '/');
2608                 if (s == NULL)
2609                         break;
2610                 *s = '\0';
2611                 /* Transfer the parent directory from zip->tree_rsrc RB
2612                  * tree to zip->tree RB tree to expose. */
2613                 dir = (struct zip_entry *)
2614                     __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
2615                 if (dir == NULL)
2616                         break;
2617                 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
2618                 archive_string_free(&dir->rsrcname);
2619                 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
2620         }
2621         archive_string_free(&str);
2622 }
2623
2624 static int
2625 slurp_central_directory(struct archive_read *a, struct zip *zip)
2626 {
2627         ssize_t i;
2628         unsigned found;
2629         int64_t correction;
2630         ssize_t bytes_avail;
2631         const char *p;
2632
2633         /*
2634          * Find the start of the central directory.  The end-of-CD
2635          * record has our starting point, but there are lots of
2636          * Zip archives which have had other data prepended to the
2637          * file, which makes the recorded offsets all too small.
2638          * So we search forward from the specified offset until we
2639          * find the real start of the central directory.  Then we
2640          * know the correction we need to apply to account for leading
2641          * padding.
2642          */
2643         if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
2644                 return ARCHIVE_FATAL;
2645
2646         found = 0;
2647         while (!found) {
2648                 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
2649                         return ARCHIVE_FATAL;
2650                 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
2651                         switch (p[i + 3]) {
2652                         case 'P': i += 3; break;
2653                         case 'K': i += 2; break;
2654                         case 001: i += 1; break;
2655                         case 002:
2656                                 if (memcmp(p + i, "PK\001\002", 4) == 0) {
2657                                         p += i;
2658                                         found = 1;
2659                                 } else
2660                                         i += 4;
2661                                 break;
2662                         case 005: i += 1; break;
2663                         case 006:
2664                                 if (memcmp(p + i, "PK\005\006", 4) == 0) {
2665                                         p += i;
2666                                         found = 1;
2667                                 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
2668                                         p += i;
2669                                         found = 1;
2670                                 } else
2671                                         i += 1;
2672                                 break;
2673                         default: i += 4; break;
2674                         }
2675                 }
2676                 __archive_read_consume(a, i);
2677         }
2678         correction = archive_filter_bytes(&a->archive, 0)
2679                         - zip->central_directory_offset;
2680
2681         __archive_rb_tree_init(&zip->tree, &rb_ops);
2682         __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
2683
2684         zip->central_directory_entries_total = 0;
2685         while (1) {
2686                 struct zip_entry *zip_entry;
2687                 size_t filename_length, extra_length, comment_length;
2688                 uint32_t external_attributes;
2689                 const char *name, *r;
2690
2691                 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
2692                         return ARCHIVE_FATAL;
2693                 if (memcmp(p, "PK\006\006", 4) == 0
2694                     || memcmp(p, "PK\005\006", 4) == 0) {
2695                         break;
2696                 } else if (memcmp(p, "PK\001\002", 4) != 0) {
2697                         archive_set_error(&a->archive,
2698                             -1, "Invalid central directory signature");
2699                         return ARCHIVE_FATAL;
2700                 }
2701                 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
2702                         return ARCHIVE_FATAL;
2703
2704                 zip_entry = calloc(1, sizeof(struct zip_entry));
2705                 zip_entry->next = zip->zip_entries;
2706                 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
2707                 zip->zip_entries = zip_entry;
2708                 zip->central_directory_entries_total++;
2709
2710                 /* version = p[4]; */
2711                 zip_entry->system = p[5];
2712                 /* version_required = archive_le16dec(p + 6); */
2713                 zip_entry->zip_flags = archive_le16dec(p + 8);
2714                 if (zip_entry->zip_flags
2715                       & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
2716                         zip->has_encrypted_entries = 1;
2717                 }
2718                 zip_entry->compression = (char)archive_le16dec(p + 10);
2719                 zip_entry->mtime = zip_time(p + 12);
2720                 zip_entry->crc32 = archive_le32dec(p + 16);
2721                 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
2722                         zip_entry->decdat = p[13];
2723                 else
2724                         zip_entry->decdat = p[19];
2725                 zip_entry->compressed_size = archive_le32dec(p + 20);
2726                 zip_entry->uncompressed_size = archive_le32dec(p + 24);
2727                 filename_length = archive_le16dec(p + 28);
2728                 extra_length = archive_le16dec(p + 30);
2729                 comment_length = archive_le16dec(p + 32);
2730                 /* disk_start = archive_le16dec(p + 34); */ /* Better be zero. */
2731                 /* internal_attributes = archive_le16dec(p + 36); */ /* text bit */
2732                 external_attributes = archive_le32dec(p + 38);
2733                 zip_entry->local_header_offset =
2734                     archive_le32dec(p + 42) + correction;
2735
2736                 /* If we can't guess the mode, leave it zero here;
2737                    when we read the local file header we might get
2738                    more information. */
2739                 if (zip_entry->system == 3) {
2740                         zip_entry->mode = external_attributes >> 16;
2741                 } else if (zip_entry->system == 0) {
2742                         // Interpret MSDOS directory bit
2743                         if (0x10 == (external_attributes & 0x10)) {
2744                                 zip_entry->mode = AE_IFDIR | 0775;
2745                         } else {
2746                                 zip_entry->mode = AE_IFREG | 0664;
2747                         }
2748                         if (0x01 == (external_attributes & 0x01)) {
2749                                 // Read-only bit; strip write permissions
2750                                 zip_entry->mode &= 0555;
2751                         }
2752                 } else {
2753                         zip_entry->mode = 0;
2754                 }
2755
2756                 /* We're done with the regular data; get the filename and
2757                  * extra data. */
2758                 __archive_read_consume(a, 46);
2759                 p = __archive_read_ahead(a, filename_length + extra_length,
2760                         NULL);
2761                 if (p == NULL) {
2762                         archive_set_error(&a->archive,
2763                             ARCHIVE_ERRNO_FILE_FORMAT,
2764                             "Truncated ZIP file header");
2765                         return ARCHIVE_FATAL;
2766                 }
2767                 if (ARCHIVE_OK != process_extra(a, p + filename_length, extra_length, zip_entry)) {
2768                         return ARCHIVE_FATAL;
2769                 }
2770
2771                 /*
2772                  * Mac resource fork files are stored under the
2773                  * "__MACOSX/" directory, so we should check if
2774                  * it is.
2775                  */
2776                 if (!zip->process_mac_extensions) {
2777                         /* Treat every entry as a regular entry. */
2778                         __archive_rb_tree_insert_node(&zip->tree,
2779                             &zip_entry->node);
2780                 } else {
2781                         name = p;
2782                         r = rsrc_basename(name, filename_length);
2783                         if (filename_length >= 9 &&
2784                             strncmp("__MACOSX/", name, 9) == 0) {
2785                                 /* If this file is not a resource fork nor
2786                                  * a directory. We should treat it as a non
2787                                  * resource fork file to expose it. */
2788                                 if (name[filename_length-1] != '/' &&
2789                                     (r - name < 3 || r[0] != '.' || r[1] != '_')) {
2790                                         __archive_rb_tree_insert_node(
2791                                             &zip->tree, &zip_entry->node);
2792                                         /* Expose its parent directories. */
2793                                         expose_parent_dirs(zip, name,
2794                                             filename_length);
2795                                 } else {
2796                                         /* This file is a resource fork file or
2797                                          * a directory. */
2798                                         archive_strncpy(&(zip_entry->rsrcname),
2799                                              name, filename_length);
2800                                         __archive_rb_tree_insert_node(
2801                                             &zip->tree_rsrc, &zip_entry->node);
2802                                 }
2803                         } else {
2804                                 /* Generate resource fork name to find its
2805                                  * resource file at zip->tree_rsrc. */
2806                                 archive_strcpy(&(zip_entry->rsrcname),
2807                                     "__MACOSX/");
2808                                 archive_strncat(&(zip_entry->rsrcname),
2809                                     name, r - name);
2810                                 archive_strcat(&(zip_entry->rsrcname), "._");
2811                                 archive_strncat(&(zip_entry->rsrcname),
2812                                     name + (r - name),
2813                                     filename_length - (r - name));
2814                                 /* Register an entry to RB tree to sort it by
2815                                  * file offset. */
2816                                 __archive_rb_tree_insert_node(&zip->tree,
2817                                     &zip_entry->node);
2818                         }
2819                 }
2820
2821                 /* Skip the comment too ... */
2822                 __archive_read_consume(a,
2823                     filename_length + extra_length + comment_length);
2824         }
2825
2826         return ARCHIVE_OK;
2827 }
2828
2829 static ssize_t
2830 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
2831 {
2832         const char *p;
2833         ssize_t filename_length, extra_length;
2834
2835         if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
2836                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2837                     "Truncated ZIP file header");
2838                 return (ARCHIVE_WARN);
2839         }
2840         p += extra;
2841
2842         if (memcmp(p, "PK\003\004", 4) != 0) {
2843                 archive_set_error(&a->archive, -1, "Damaged Zip archive");
2844                 return ARCHIVE_WARN;
2845         }
2846         filename_length = archive_le16dec(p + 26);
2847         extra_length = archive_le16dec(p + 28);
2848
2849         return (30 + filename_length + extra_length);
2850 }
2851
2852 static int
2853 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
2854     struct zip_entry *rsrc)
2855 {
2856         struct zip *zip = (struct zip *)a->format->data;
2857         unsigned char *metadata, *mp;
2858         int64_t offset = archive_filter_bytes(&a->archive, 0);
2859         size_t remaining_bytes, metadata_bytes;
2860         ssize_t hsize;
2861         int ret = ARCHIVE_OK, eof;
2862
2863         switch(rsrc->compression) {
2864         case 0:  /* No compression. */
2865                 if (rsrc->uncompressed_size != rsrc->compressed_size) {
2866                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2867                             "Malformed OS X metadata entry: inconsistent size");
2868                         return (ARCHIVE_FATAL);
2869                 }
2870 #ifdef HAVE_ZLIB_H
2871         case 8: /* Deflate compression. */
2872 #endif
2873                 break;
2874         default: /* Unsupported compression. */
2875                 /* Return a warning. */
2876                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2877                     "Unsupported ZIP compression method (%s)",
2878                     compression_name(rsrc->compression));
2879                 /* We can't decompress this entry, but we will
2880                  * be able to skip() it and try the next entry. */
2881                 return (ARCHIVE_WARN);
2882         }
2883
2884         if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
2885                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2886                     "Mac metadata is too large: %jd > 4M bytes",
2887                     (intmax_t)rsrc->uncompressed_size);
2888                 return (ARCHIVE_WARN);
2889         }
2890         if (rsrc->compressed_size > (4 * 1024 * 1024)) {
2891                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2892                     "Mac metadata is too large: %jd > 4M bytes",
2893                     (intmax_t)rsrc->compressed_size);
2894                 return (ARCHIVE_WARN);
2895         }
2896
2897         metadata = malloc((size_t)rsrc->uncompressed_size);
2898         if (metadata == NULL) {
2899                 archive_set_error(&a->archive, ENOMEM,
2900                     "Can't allocate memory for Mac metadata");
2901                 return (ARCHIVE_FATAL);
2902         }
2903
2904         if (offset < rsrc->local_header_offset)
2905                 __archive_read_consume(a, rsrc->local_header_offset - offset);
2906         else if (offset != rsrc->local_header_offset) {
2907                 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
2908         }
2909
2910         hsize = zip_get_local_file_header_size(a, 0);
2911         __archive_read_consume(a, hsize);
2912
2913         remaining_bytes = (size_t)rsrc->compressed_size;
2914         metadata_bytes = (size_t)rsrc->uncompressed_size;
2915         mp = metadata;
2916         eof = 0;
2917         while (!eof && remaining_bytes) {
2918                 const unsigned char *p;
2919                 ssize_t bytes_avail;
2920                 size_t bytes_used;
2921
2922                 p = __archive_read_ahead(a, 1, &bytes_avail);
2923                 if (p == NULL) {
2924                         archive_set_error(&a->archive,
2925                             ARCHIVE_ERRNO_FILE_FORMAT,
2926                             "Truncated ZIP file header");
2927                         ret = ARCHIVE_WARN;
2928                         goto exit_mac_metadata;
2929                 }
2930                 if ((size_t)bytes_avail > remaining_bytes)
2931                         bytes_avail = remaining_bytes;
2932                 switch(rsrc->compression) {
2933                 case 0:  /* No compression. */
2934                         if ((size_t)bytes_avail > metadata_bytes)
2935                                 bytes_avail = metadata_bytes;
2936                         memcpy(mp, p, bytes_avail);
2937                         bytes_used = (size_t)bytes_avail;
2938                         metadata_bytes -= bytes_used;
2939                         mp += bytes_used;
2940                         if (metadata_bytes == 0)
2941                                 eof = 1;
2942                         break;
2943 #ifdef HAVE_ZLIB_H
2944                 case 8: /* Deflate compression. */
2945                 {
2946                         int r;
2947
2948                         ret = zip_deflate_init(a, zip);
2949                         if (ret != ARCHIVE_OK)
2950                                 goto exit_mac_metadata;
2951                         zip->stream.next_in =
2952                             (Bytef *)(uintptr_t)(const void *)p;
2953                         zip->stream.avail_in = (uInt)bytes_avail;
2954                         zip->stream.total_in = 0;
2955                         zip->stream.next_out = mp;
2956                         zip->stream.avail_out = (uInt)metadata_bytes;
2957                         zip->stream.total_out = 0;
2958
2959                         r = inflate(&zip->stream, 0);
2960                         switch (r) {
2961                         case Z_OK:
2962                                 break;
2963                         case Z_STREAM_END:
2964                                 eof = 1;
2965                                 break;
2966                         case Z_MEM_ERROR:
2967                                 archive_set_error(&a->archive, ENOMEM,
2968                                     "Out of memory for ZIP decompression");
2969                                 ret = ARCHIVE_FATAL;
2970                                 goto exit_mac_metadata;
2971                         default:
2972                                 archive_set_error(&a->archive,
2973                                     ARCHIVE_ERRNO_MISC,
2974                                     "ZIP decompression failed (%d)", r);
2975                                 ret = ARCHIVE_FATAL;
2976                                 goto exit_mac_metadata;
2977                         }
2978                         bytes_used = zip->stream.total_in;
2979                         metadata_bytes -= zip->stream.total_out;
2980                         mp += zip->stream.total_out;
2981                         break;
2982                 }
2983 #endif
2984                 default:
2985                         bytes_used = 0;
2986                         break;
2987                 }
2988                 __archive_read_consume(a, bytes_used);
2989                 remaining_bytes -= bytes_used;
2990         }
2991         archive_entry_copy_mac_metadata(entry, metadata,
2992             (size_t)rsrc->uncompressed_size - metadata_bytes);
2993
2994 exit_mac_metadata:
2995         __archive_read_seek(a, offset, SEEK_SET);
2996         zip->decompress_init = 0;
2997         free(metadata);
2998         return (ret);
2999 }
3000
3001 static int
3002 archive_read_format_zip_seekable_read_header(struct archive_read *a,
3003         struct archive_entry *entry)
3004 {
3005         struct zip *zip = (struct zip *)a->format->data;
3006         struct zip_entry *rsrc;
3007         int64_t offset;
3008         int r, ret = ARCHIVE_OK;
3009
3010         /*
3011          * It should be sufficient to call archive_read_next_header() for
3012          * a reader to determine if an entry is encrypted or not. If the
3013          * encryption of an entry is only detectable when calling
3014          * archive_read_data(), so be it. We'll do the same check there
3015          * as well.
3016          */
3017         if (zip->has_encrypted_entries ==
3018                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3019                 zip->has_encrypted_entries = 0;
3020
3021         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3022         if (a->archive.archive_format_name == NULL)
3023                 a->archive.archive_format_name = "ZIP";
3024
3025         if (zip->zip_entries == NULL) {
3026                 r = slurp_central_directory(a, zip);
3027                 if (r != ARCHIVE_OK)
3028                         return r;
3029                 /* Get first entry whose local header offset is lower than
3030                  * other entries in the archive file. */
3031                 zip->entry =
3032                     (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
3033         } else if (zip->entry != NULL) {
3034                 /* Get next entry in local header offset order. */
3035                 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
3036                     &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
3037         }
3038
3039         if (zip->entry == NULL)
3040                 return ARCHIVE_EOF;
3041
3042         if (zip->entry->rsrcname.s)
3043                 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
3044                     &zip->tree_rsrc, zip->entry->rsrcname.s);
3045         else
3046                 rsrc = NULL;
3047
3048         if (zip->cctx_valid)
3049                 archive_decrypto_aes_ctr_release(&zip->cctx);
3050         if (zip->hctx_valid)
3051                 archive_hmac_sha1_cleanup(&zip->hctx);
3052         zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3053         __archive_read_reset_passphrase(a);
3054
3055         /* File entries are sorted by the header offset, we should mostly
3056          * use __archive_read_consume to advance a read point to avoid redundant
3057          * data reading.  */
3058         offset = archive_filter_bytes(&a->archive, 0);
3059         if (offset < zip->entry->local_header_offset)
3060                 __archive_read_consume(a,
3061                     zip->entry->local_header_offset - offset);
3062         else if (offset != zip->entry->local_header_offset) {
3063                 __archive_read_seek(a, zip->entry->local_header_offset,
3064                     SEEK_SET);
3065         }
3066         zip->unconsumed = 0;
3067         r = zip_read_local_file_header(a, entry, zip);
3068         if (r != ARCHIVE_OK)
3069                 return r;
3070         if (rsrc) {
3071                 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
3072                 if (ret2 < ret)
3073                         ret = ret2;
3074         }
3075         return (ret);
3076 }
3077
3078 /*
3079  * We're going to seek for the next header anyway, so we don't
3080  * need to bother doing anything here.
3081  */
3082 static int
3083 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
3084 {
3085         struct zip *zip;
3086         zip = (struct zip *)(a->format->data);
3087
3088         zip->unconsumed = 0;
3089         return (ARCHIVE_OK);
3090 }
3091
3092 int
3093 archive_read_support_format_zip_seekable(struct archive *_a)
3094 {
3095         struct archive_read *a = (struct archive_read *)_a;
3096         struct zip *zip;
3097         int r;
3098
3099         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3100             ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
3101
3102         zip = (struct zip *)calloc(1, sizeof(*zip));
3103         if (zip == NULL) {
3104                 archive_set_error(&a->archive, ENOMEM,
3105                     "Can't allocate zip data");
3106                 return (ARCHIVE_FATAL);
3107         }
3108
3109 #ifdef HAVE_COPYFILE_H
3110         /* Set this by default on Mac OS. */
3111         zip->process_mac_extensions = 1;
3112 #endif
3113
3114         /*
3115          * Until enough data has been read, we cannot tell about
3116          * any encrypted entries yet.
3117          */
3118         zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3119         zip->crc32func = real_crc32;
3120
3121         r = __archive_read_register_format(a,
3122             zip,
3123             "zip",
3124             archive_read_format_zip_seekable_bid,
3125             archive_read_format_zip_options,
3126             archive_read_format_zip_seekable_read_header,
3127             archive_read_format_zip_read_data,
3128             archive_read_format_zip_read_data_skip_seekable,
3129             NULL,
3130             archive_read_format_zip_cleanup,
3131             archive_read_support_format_zip_capabilities_seekable,
3132             archive_read_format_zip_has_encrypted_entries);
3133
3134         if (r != ARCHIVE_OK)
3135                 free(zip);
3136         return (ARCHIVE_OK);
3137 }