]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - contrib/libarchive/libarchive/archive_read_support_format_zip.c
MFC r315636,315876,316095:
[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 (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
727                                 /* Vendor version. */
728                                 zip_entry->aes_extra.vendor =
729                                     archive_le16dec(p + offset);
730                                 /* AES encryption strength. */
731                                 zip_entry->aes_extra.strength = p[offset + 4];
732                                 /* Actual compression method. */
733                                 zip_entry->aes_extra.compression =
734                                     p[offset + 5];
735                         }
736                         break;
737                 default:
738                         break;
739                 }
740                 offset += datasize;
741         }
742         if (offset != extra_length) {
743                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
744                     "Malformed extra data: Consumed %d bytes of %d bytes",
745                     (int)offset, (int)extra_length);
746                 return ARCHIVE_FAILED;
747         }
748         return ARCHIVE_OK;
749 }
750
751 /*
752  * Assumes file pointer is at beginning of local file header.
753  */
754 static int
755 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
756     struct zip *zip)
757 {
758         const char *p;
759         const void *h;
760         const wchar_t *wp;
761         const char *cp;
762         size_t len, filename_length, extra_length;
763         struct archive_string_conv *sconv;
764         struct zip_entry *zip_entry = zip->entry;
765         struct zip_entry zip_entry_central_dir;
766         int ret = ARCHIVE_OK;
767         char version;
768
769         /* Save a copy of the original for consistency checks. */
770         zip_entry_central_dir = *zip_entry;
771
772         zip->decompress_init = 0;
773         zip->end_of_entry = 0;
774         zip->entry_uncompressed_bytes_read = 0;
775         zip->entry_compressed_bytes_read = 0;
776         zip->entry_crc32 = zip->crc32func(0, NULL, 0);
777
778         /* Setup default conversion. */
779         if (zip->sconv == NULL && !zip->init_default_conversion) {
780                 zip->sconv_default =
781                     archive_string_default_conversion_for_read(&(a->archive));
782                 zip->init_default_conversion = 1;
783         }
784
785         if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
786                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
787                     "Truncated ZIP file header");
788                 return (ARCHIVE_FATAL);
789         }
790
791         if (memcmp(p, "PK\003\004", 4) != 0) {
792                 archive_set_error(&a->archive, -1, "Damaged Zip archive");
793                 return ARCHIVE_FATAL;
794         }
795         version = p[4];
796         zip_entry->system = p[5];
797         zip_entry->zip_flags = archive_le16dec(p + 6);
798         if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
799                 zip->has_encrypted_entries = 1;
800                 archive_entry_set_is_data_encrypted(entry, 1);
801                 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
802                         zip_entry->zip_flags & ZIP_ENCRYPTED &&
803                         zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
804                         archive_entry_set_is_metadata_encrypted(entry, 1);
805                         return ARCHIVE_FATAL;
806                 }
807         }
808         zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
809         zip_entry->compression = (char)archive_le16dec(p + 8);
810         zip_entry->mtime = zip_time(p + 10);
811         zip_entry->crc32 = archive_le32dec(p + 14);
812         if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
813                 zip_entry->decdat = p[11];
814         else
815                 zip_entry->decdat = p[17];
816         zip_entry->compressed_size = archive_le32dec(p + 18);
817         zip_entry->uncompressed_size = archive_le32dec(p + 22);
818         filename_length = archive_le16dec(p + 26);
819         extra_length = archive_le16dec(p + 28);
820
821         __archive_read_consume(a, 30);
822
823         /* Read the filename. */
824         if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
825                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
826                     "Truncated ZIP file header");
827                 return (ARCHIVE_FATAL);
828         }
829         if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
830                 /* The filename is stored to be UTF-8. */
831                 if (zip->sconv_utf8 == NULL) {
832                         zip->sconv_utf8 =
833                             archive_string_conversion_from_charset(
834                                 &a->archive, "UTF-8", 1);
835                         if (zip->sconv_utf8 == NULL)
836                                 return (ARCHIVE_FATAL);
837                 }
838                 sconv = zip->sconv_utf8;
839         } else if (zip->sconv != NULL)
840                 sconv = zip->sconv;
841         else
842                 sconv = zip->sconv_default;
843
844         if (archive_entry_copy_pathname_l(entry,
845             h, filename_length, sconv) != 0) {
846                 if (errno == ENOMEM) {
847                         archive_set_error(&a->archive, ENOMEM,
848                             "Can't allocate memory for Pathname");
849                         return (ARCHIVE_FATAL);
850                 }
851                 archive_set_error(&a->archive,
852                     ARCHIVE_ERRNO_FILE_FORMAT,
853                     "Pathname cannot be converted "
854                     "from %s to current locale.",
855                     archive_string_conversion_charset_name(sconv));
856                 ret = ARCHIVE_WARN;
857         }
858         __archive_read_consume(a, filename_length);
859
860         /* Read the extra data. */
861         if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
862                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
863                     "Truncated ZIP file header");
864                 return (ARCHIVE_FATAL);
865         }
866
867         if (ARCHIVE_OK != process_extra(a, h, extra_length, zip_entry)) {
868                 return ARCHIVE_FATAL;
869         }
870         __archive_read_consume(a, extra_length);
871
872         /* Work around a bug in Info-Zip: When reading from a pipe, it
873          * stats the pipe instead of synthesizing a file entry. */
874         if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
875                 zip_entry->mode &= ~ AE_IFMT;
876                 zip_entry->mode |= AE_IFREG;
877         }
878
879         /* If the mode is totally empty, set some sane default. */
880         if (zip_entry->mode == 0) {
881                 zip_entry->mode |= 0664;
882         }
883
884         /* Make sure that entries with a trailing '/' are marked as directories
885          * even if the External File Attributes contains bogus values.  If this
886          * is not a directory and there is no type, assume regularfile. */
887         if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
888                 int has_slash;
889
890                 wp = archive_entry_pathname_w(entry);
891                 if (wp != NULL) {
892                         len = wcslen(wp);
893                         has_slash = len > 0 && wp[len - 1] == L'/';
894                 } else {
895                         cp = archive_entry_pathname(entry);
896                         len = (cp != NULL)?strlen(cp):0;
897                         has_slash = len > 0 && cp[len - 1] == '/';
898                 }
899                 /* Correct file type as needed. */
900                 if (has_slash) {
901                         zip_entry->mode &= ~AE_IFMT;
902                         zip_entry->mode |= AE_IFDIR;
903                         zip_entry->mode |= 0111;
904                 } else if ((zip_entry->mode & AE_IFMT) == 0) {
905                         zip_entry->mode |= AE_IFREG;
906                 }
907         }
908
909         /* Make sure directories end in '/' */
910         if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
911                 wp = archive_entry_pathname_w(entry);
912                 if (wp != NULL) {
913                         len = wcslen(wp);
914                         if (len > 0 && wp[len - 1] != L'/') {
915                                 struct archive_wstring s;
916                                 archive_string_init(&s);
917                                 archive_wstrcat(&s, wp);
918                                 archive_wstrappend_wchar(&s, L'/');
919                                 archive_entry_copy_pathname_w(entry, s.s);
920                                 archive_wstring_free(&s);
921                         }
922                 } else {
923                         cp = archive_entry_pathname(entry);
924                         len = (cp != NULL)?strlen(cp):0;
925                         if (len > 0 && cp[len - 1] != '/') {
926                                 struct archive_string s;
927                                 archive_string_init(&s);
928                                 archive_strcat(&s, cp);
929                                 archive_strappend_char(&s, '/');
930                                 archive_entry_set_pathname(entry, s.s);
931                                 archive_string_free(&s);
932                         }
933                 }
934         }
935
936         if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
937                 /* If this came from the central dir, it's size info
938                  * is definitive, so ignore the length-at-end flag. */
939                 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
940                 /* If local header is missing a value, use the one from
941                    the central directory.  If both have it, warn about
942                    mismatches. */
943                 if (zip_entry->crc32 == 0) {
944                         zip_entry->crc32 = zip_entry_central_dir.crc32;
945                 } else if (!zip->ignore_crc32
946                     && zip_entry->crc32 != zip_entry_central_dir.crc32) {
947                         archive_set_error(&a->archive,
948                             ARCHIVE_ERRNO_FILE_FORMAT,
949                             "Inconsistent CRC32 values");
950                         ret = ARCHIVE_WARN;
951                 }
952                 if (zip_entry->compressed_size == 0) {
953                         zip_entry->compressed_size
954                             = zip_entry_central_dir.compressed_size;
955                 } else if (zip_entry->compressed_size
956                     != zip_entry_central_dir.compressed_size) {
957                         archive_set_error(&a->archive,
958                             ARCHIVE_ERRNO_FILE_FORMAT,
959                             "Inconsistent compressed size: "
960                             "%jd in central directory, %jd in local header",
961                             (intmax_t)zip_entry_central_dir.compressed_size,
962                             (intmax_t)zip_entry->compressed_size);
963                         ret = ARCHIVE_WARN;
964                 }
965                 if (zip_entry->uncompressed_size == 0) {
966                         zip_entry->uncompressed_size
967                             = zip_entry_central_dir.uncompressed_size;
968                 } else if (zip_entry->uncompressed_size
969                     != zip_entry_central_dir.uncompressed_size) {
970                         archive_set_error(&a->archive,
971                             ARCHIVE_ERRNO_FILE_FORMAT,
972                             "Inconsistent uncompressed size: "
973                             "%jd in central directory, %jd in local header",
974                             (intmax_t)zip_entry_central_dir.uncompressed_size,
975                             (intmax_t)zip_entry->uncompressed_size);
976                         ret = ARCHIVE_WARN;
977                 }
978         }
979
980         /* Populate some additional entry fields: */
981         archive_entry_set_mode(entry, zip_entry->mode);
982         archive_entry_set_uid(entry, zip_entry->uid);
983         archive_entry_set_gid(entry, zip_entry->gid);
984         archive_entry_set_mtime(entry, zip_entry->mtime, 0);
985         archive_entry_set_ctime(entry, zip_entry->ctime, 0);
986         archive_entry_set_atime(entry, zip_entry->atime, 0);
987
988         if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
989                 size_t linkname_length;
990
991                 if (zip_entry->compressed_size > 64 * 1024) {
992                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
993                             "Zip file with oversized link entry");
994                         return ARCHIVE_FATAL;
995                 }
996
997                 linkname_length = (size_t)zip_entry->compressed_size;
998
999                 archive_entry_set_size(entry, 0);
1000                 p = __archive_read_ahead(a, linkname_length, NULL);
1001                 if (p == NULL) {
1002                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1003                             "Truncated Zip file");
1004                         return ARCHIVE_FATAL;
1005                 }
1006
1007                 sconv = zip->sconv;
1008                 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1009                         sconv = zip->sconv_utf8;
1010                 if (sconv == NULL)
1011                         sconv = zip->sconv_default;
1012                 if (archive_entry_copy_symlink_l(entry, p, linkname_length,
1013                     sconv) != 0) {
1014                         if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1015                             (zip->entry->zip_flags & ZIP_UTF8_NAME))
1016                             archive_entry_copy_symlink_l(entry, p,
1017                                 linkname_length, NULL);
1018                         if (errno == ENOMEM) {
1019                                 archive_set_error(&a->archive, ENOMEM,
1020                                     "Can't allocate memory for Symlink");
1021                                 return (ARCHIVE_FATAL);
1022                         }
1023                         /*
1024                          * Since there is no character-set regulation for
1025                          * symlink name, do not report the conversion error
1026                          * in an automatic conversion.
1027                          */
1028                         if (sconv != zip->sconv_utf8 ||
1029                             (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1030                                 archive_set_error(&a->archive,
1031                                     ARCHIVE_ERRNO_FILE_FORMAT,
1032                                     "Symlink cannot be converted "
1033                                     "from %s to current locale.",
1034                                     archive_string_conversion_charset_name(
1035                                         sconv));
1036                                 ret = ARCHIVE_WARN;
1037                         }
1038                 }
1039                 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1040
1041                 if (__archive_read_consume(a, linkname_length) < 0) {
1042                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1043                             "Read error skipping symlink target name");
1044                         return ARCHIVE_FATAL;
1045                 }
1046         } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1047             || zip_entry->uncompressed_size > 0) {
1048                 /* Set the size only if it's meaningful. */
1049                 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1050         }
1051         zip->entry_bytes_remaining = zip_entry->compressed_size;
1052
1053         /* If there's no body, force read_data() to return EOF immediately. */
1054         if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1055             && zip->entry_bytes_remaining < 1)
1056                 zip->end_of_entry = 1;
1057
1058         /* Set up a more descriptive format name. */
1059         archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1060             version / 10, version % 10,
1061             compression_name(zip->entry->compression));
1062         a->archive.archive_format_name = zip->format_name.s;
1063
1064         return (ret);
1065 }
1066
1067 static int
1068 check_authentication_code(struct archive_read *a, const void *_p)
1069 {
1070         struct zip *zip = (struct zip *)(a->format->data);
1071
1072         /* Check authentication code. */
1073         if (zip->hctx_valid) {
1074                 const void *p;
1075                 uint8_t hmac[20];
1076                 size_t hmac_len = 20;
1077                 int cmp;
1078
1079                 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1080                 if (_p == NULL) {
1081                         /* Read authentication code. */
1082                         p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1083                         if (p == NULL) {
1084                                 archive_set_error(&a->archive,
1085                                     ARCHIVE_ERRNO_FILE_FORMAT,
1086                                     "Truncated ZIP file data");
1087                                 return (ARCHIVE_FATAL);
1088                         }
1089                 } else {
1090                         p = _p;
1091                 }
1092                 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1093                 __archive_read_consume(a, AUTH_CODE_SIZE);
1094                 if (cmp != 0) {
1095                         archive_set_error(&a->archive,
1096                             ARCHIVE_ERRNO_MISC,
1097                             "ZIP bad Authentication code");
1098                         return (ARCHIVE_WARN);
1099                 }
1100         }
1101         return (ARCHIVE_OK);
1102 }
1103
1104 /*
1105  * Read "uncompressed" data.  There are three cases:
1106  *  1) We know the size of the data.  This is always true for the
1107  * seeking reader (we've examined the Central Directory already).
1108  *  2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1109  * Info-ZIP seems to do this; we know the size but have to grab
1110  * the CRC from the data descriptor afterwards.
1111  *  3) We're streaming and ZIP_LENGTH_AT_END was specified and
1112  * we have no size information.  In this case, we can do pretty
1113  * well by watching for the data descriptor record.  The data
1114  * descriptor is 16 bytes and includes a computed CRC that should
1115  * provide a strong check.
1116  *
1117  * TODO: Technically, the PK\007\010 signature is optional.
1118  * In the original spec, the data descriptor contained CRC
1119  * and size fields but had no leading signature.  In practice,
1120  * newer writers seem to provide the signature pretty consistently.
1121  *
1122  * For uncompressed data, the PK\007\010 marker seems essential
1123  * to be sure we've actually seen the end of the entry.
1124  *
1125  * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1126  * zip->end_of_entry if it consumes all of the data.
1127  */
1128 static int
1129 zip_read_data_none(struct archive_read *a, const void **_buff,
1130     size_t *size, int64_t *offset)
1131 {
1132         struct zip *zip;
1133         const char *buff;
1134         ssize_t bytes_avail;
1135         int r;
1136
1137         (void)offset; /* UNUSED */
1138
1139         zip = (struct zip *)(a->format->data);
1140
1141         if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1142                 const char *p;
1143                 ssize_t grabbing_bytes = 24;
1144
1145                 if (zip->hctx_valid)
1146                         grabbing_bytes += AUTH_CODE_SIZE;
1147                 /* Grab at least 24 bytes. */
1148                 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1149                 if (bytes_avail < grabbing_bytes) {
1150                         /* Zip archives have end-of-archive markers
1151                            that are longer than this, so a failure to get at
1152                            least 24 bytes really does indicate a truncated
1153                            file. */
1154                         archive_set_error(&a->archive,
1155                             ARCHIVE_ERRNO_FILE_FORMAT,
1156                             "Truncated ZIP file data");
1157                         return (ARCHIVE_FATAL);
1158                 }
1159                 /* Check for a complete PK\007\010 signature, followed
1160                  * by the correct 4-byte CRC. */
1161                 p = buff;
1162                 if (zip->hctx_valid)
1163                         p += AUTH_CODE_SIZE;
1164                 if (p[0] == 'P' && p[1] == 'K'
1165                     && p[2] == '\007' && p[3] == '\010'
1166                     && (archive_le32dec(p + 4) == zip->entry_crc32
1167                         || zip->ignore_crc32
1168                         || (zip->hctx_valid
1169                          && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1170                         if (zip->entry->flags & LA_USED_ZIP64) {
1171                                 uint64_t compressed, uncompressed;
1172                                 zip->entry->crc32 = archive_le32dec(p + 4);
1173                                 compressed = archive_le64dec(p + 8);
1174                                 uncompressed = archive_le64dec(p + 16);
1175                                 if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1176                                         archive_set_error(&a->archive,
1177                                             ARCHIVE_ERRNO_FILE_FORMAT,
1178                                             "Overflow of 64-bit file sizes");
1179                                         return ARCHIVE_FAILED;
1180                                 }
1181                                 zip->entry->compressed_size = compressed;
1182                                 zip->entry->uncompressed_size = uncompressed;
1183                                 zip->unconsumed = 24;
1184                         } else {
1185                                 zip->entry->crc32 = archive_le32dec(p + 4);
1186                                 zip->entry->compressed_size =
1187                                         archive_le32dec(p + 8);
1188                                 zip->entry->uncompressed_size =
1189                                         archive_le32dec(p + 12);
1190                                 zip->unconsumed = 16;
1191                         }
1192                         if (zip->hctx_valid) {
1193                                 r = check_authentication_code(a, buff);
1194                                 if (r != ARCHIVE_OK)
1195                                         return (r);
1196                         }
1197                         zip->end_of_entry = 1;
1198                         return (ARCHIVE_OK);
1199                 }
1200                 /* If not at EOF, ensure we consume at least one byte. */
1201                 ++p;
1202
1203                 /* Scan forward until we see where a PK\007\010 signature
1204                  * might be. */
1205                 /* Return bytes up until that point.  On the next call,
1206                  * the code above will verify the data descriptor. */
1207                 while (p < buff + bytes_avail - 4) {
1208                         if (p[3] == 'P') { p += 3; }
1209                         else if (p[3] == 'K') { p += 2; }
1210                         else if (p[3] == '\007') { p += 1; }
1211                         else if (p[3] == '\010' && p[2] == '\007'
1212                             && p[1] == 'K' && p[0] == 'P') {
1213                                 if (zip->hctx_valid)
1214                                         p -= AUTH_CODE_SIZE;
1215                                 break;
1216                         } else { p += 4; }
1217                 }
1218                 bytes_avail = p - buff;
1219         } else {
1220                 if (zip->entry_bytes_remaining == 0) {
1221                         zip->end_of_entry = 1;
1222                         if (zip->hctx_valid) {
1223                                 r = check_authentication_code(a, NULL);
1224                                 if (r != ARCHIVE_OK)
1225                                         return (r);
1226                         }
1227                         return (ARCHIVE_OK);
1228                 }
1229                 /* Grab a bunch of bytes. */
1230                 buff = __archive_read_ahead(a, 1, &bytes_avail);
1231                 if (bytes_avail <= 0) {
1232                         archive_set_error(&a->archive,
1233                             ARCHIVE_ERRNO_FILE_FORMAT,
1234                             "Truncated ZIP file data");
1235                         return (ARCHIVE_FATAL);
1236                 }
1237                 if (bytes_avail > zip->entry_bytes_remaining)
1238                         bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1239         }
1240         if (zip->tctx_valid || zip->cctx_valid) {
1241                 size_t dec_size = bytes_avail;
1242
1243                 if (dec_size > zip->decrypted_buffer_size)
1244                         dec_size = zip->decrypted_buffer_size;
1245                 if (zip->tctx_valid) {
1246                         trad_enc_decrypt_update(&zip->tctx,
1247                             (const uint8_t *)buff, dec_size,
1248                             zip->decrypted_buffer, dec_size);
1249                 } else {
1250                         size_t dsize = dec_size;
1251                         archive_hmac_sha1_update(&zip->hctx,
1252                             (const uint8_t *)buff, dec_size);
1253                         archive_decrypto_aes_ctr_update(&zip->cctx,
1254                             (const uint8_t *)buff, dec_size,
1255                             zip->decrypted_buffer, &dsize);
1256                 }
1257                 bytes_avail = dec_size;
1258                 buff = (const char *)zip->decrypted_buffer;
1259         }
1260         *size = bytes_avail;
1261         zip->entry_bytes_remaining -= bytes_avail;
1262         zip->entry_uncompressed_bytes_read += bytes_avail;
1263         zip->entry_compressed_bytes_read += bytes_avail;
1264         zip->unconsumed += bytes_avail;
1265         *_buff = buff;
1266         return (ARCHIVE_OK);
1267 }
1268
1269 #ifdef HAVE_ZLIB_H
1270 static int
1271 zip_deflate_init(struct archive_read *a, struct zip *zip)
1272 {
1273         int r;
1274
1275         /* If we haven't yet read any data, initialize the decompressor. */
1276         if (!zip->decompress_init) {
1277                 if (zip->stream_valid)
1278                         r = inflateReset(&zip->stream);
1279                 else
1280                         r = inflateInit2(&zip->stream,
1281                             -15 /* Don't check for zlib header */);
1282                 if (r != Z_OK) {
1283                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1284                             "Can't initialize ZIP decompression.");
1285                         return (ARCHIVE_FATAL);
1286                 }
1287                 /* Stream structure has been set up. */
1288                 zip->stream_valid = 1;
1289                 /* We've initialized decompression for this stream. */
1290                 zip->decompress_init = 1;
1291         }
1292         return (ARCHIVE_OK);
1293 }
1294
1295 static int
1296 zip_read_data_deflate(struct archive_read *a, const void **buff,
1297     size_t *size, int64_t *offset)
1298 {
1299         struct zip *zip;
1300         ssize_t bytes_avail;
1301         const void *compressed_buff, *sp;
1302         int r;
1303
1304         (void)offset; /* UNUSED */
1305
1306         zip = (struct zip *)(a->format->data);
1307
1308         /* If the buffer hasn't been allocated, allocate it now. */
1309         if (zip->uncompressed_buffer == NULL) {
1310                 zip->uncompressed_buffer_size = 256 * 1024;
1311                 zip->uncompressed_buffer
1312                     = (unsigned char *)malloc(zip->uncompressed_buffer_size);
1313                 if (zip->uncompressed_buffer == NULL) {
1314                         archive_set_error(&a->archive, ENOMEM,
1315                             "No memory for ZIP decompression");
1316                         return (ARCHIVE_FATAL);
1317                 }
1318         }
1319
1320         r = zip_deflate_init(a, zip);
1321         if (r != ARCHIVE_OK)
1322                 return (r);
1323
1324         /*
1325          * Note: '1' here is a performance optimization.
1326          * Recall that the decompression layer returns a count of
1327          * available bytes; asking for more than that forces the
1328          * decompressor to combine reads by copying data.
1329          */
1330         compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
1331         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1332             && bytes_avail > zip->entry_bytes_remaining) {
1333                 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1334         }
1335         if (bytes_avail < 0) {
1336                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1337                     "Truncated ZIP file body");
1338                 return (ARCHIVE_FATAL);
1339         }
1340
1341         if (zip->tctx_valid || zip->cctx_valid) {
1342                 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
1343                         size_t buff_remaining =
1344                             (zip->decrypted_buffer + zip->decrypted_buffer_size)
1345                             - (zip->decrypted_ptr + zip->decrypted_bytes_remaining);
1346
1347                         if (buff_remaining > (size_t)bytes_avail)
1348                                 buff_remaining = (size_t)bytes_avail;
1349
1350                         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
1351                               zip->entry_bytes_remaining > 0) {
1352                                 if ((int64_t)(zip->decrypted_bytes_remaining
1353                                     + buff_remaining)
1354                                       > zip->entry_bytes_remaining) {
1355                                         if (zip->entry_bytes_remaining <
1356                                               (int64_t)zip->decrypted_bytes_remaining)
1357                                                 buff_remaining = 0;
1358                                         else
1359                                                 buff_remaining =
1360                                                     (size_t)zip->entry_bytes_remaining
1361                                                       - zip->decrypted_bytes_remaining;
1362                                 }
1363                         }
1364                         if (buff_remaining > 0) {
1365                                 if (zip->tctx_valid) {
1366                                         trad_enc_decrypt_update(&zip->tctx,
1367                                             compressed_buff, buff_remaining,
1368                                             zip->decrypted_ptr
1369                                               + zip->decrypted_bytes_remaining,
1370                                             buff_remaining);
1371                                 } else {
1372                                         size_t dsize = buff_remaining;
1373                                         archive_decrypto_aes_ctr_update(
1374                                             &zip->cctx,
1375                                             compressed_buff, buff_remaining,
1376                                             zip->decrypted_ptr
1377                                               + zip->decrypted_bytes_remaining,
1378                                             &dsize);
1379                                 }
1380                                 zip->decrypted_bytes_remaining += buff_remaining;
1381                         }
1382                 }
1383                 bytes_avail = zip->decrypted_bytes_remaining;
1384                 compressed_buff = (const char *)zip->decrypted_ptr;
1385         }
1386
1387         /*
1388          * A bug in zlib.h: stream.next_in should be marked 'const'
1389          * but isn't (the library never alters data through the
1390          * next_in pointer, only reads it).  The result: this ugly
1391          * cast to remove 'const'.
1392          */
1393         zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
1394         zip->stream.avail_in = (uInt)bytes_avail;
1395         zip->stream.total_in = 0;
1396         zip->stream.next_out = zip->uncompressed_buffer;
1397         zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
1398         zip->stream.total_out = 0;
1399
1400         r = inflate(&zip->stream, 0);
1401         switch (r) {
1402         case Z_OK:
1403                 break;
1404         case Z_STREAM_END:
1405                 zip->end_of_entry = 1;
1406                 break;
1407         case Z_MEM_ERROR:
1408                 archive_set_error(&a->archive, ENOMEM,
1409                     "Out of memory for ZIP decompression");
1410                 return (ARCHIVE_FATAL);
1411         default:
1412                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1413                     "ZIP decompression failed (%d)", r);
1414                 return (ARCHIVE_FATAL);
1415         }
1416
1417         /* Consume as much as the compressor actually used. */
1418         bytes_avail = zip->stream.total_in;
1419         if (zip->tctx_valid || zip->cctx_valid) {
1420                 zip->decrypted_bytes_remaining -= bytes_avail;
1421                 if (zip->decrypted_bytes_remaining == 0)
1422                         zip->decrypted_ptr = zip->decrypted_buffer;
1423                 else
1424                         zip->decrypted_ptr += bytes_avail;
1425         }
1426         /* Calculate compressed data as much as we used.*/
1427         if (zip->hctx_valid)
1428                 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
1429         __archive_read_consume(a, bytes_avail);
1430         zip->entry_bytes_remaining -= bytes_avail;
1431         zip->entry_compressed_bytes_read += bytes_avail;
1432
1433         *size = zip->stream.total_out;
1434         zip->entry_uncompressed_bytes_read += zip->stream.total_out;
1435         *buff = zip->uncompressed_buffer;
1436
1437         if (zip->end_of_entry && zip->hctx_valid) {
1438                 r = check_authentication_code(a, NULL);
1439                 if (r != ARCHIVE_OK)
1440                         return (r);
1441         }
1442
1443         if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1444                 const char *p;
1445
1446                 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1447                         archive_set_error(&a->archive,
1448                             ARCHIVE_ERRNO_FILE_FORMAT,
1449                             "Truncated ZIP end-of-file record");
1450                         return (ARCHIVE_FATAL);
1451                 }
1452                 /* Consume the optional PK\007\010 marker. */
1453                 if (p[0] == 'P' && p[1] == 'K' &&
1454                     p[2] == '\007' && p[3] == '\010') {
1455                         p += 4;
1456                         zip->unconsumed = 4;
1457                 }
1458                 if (zip->entry->flags & LA_USED_ZIP64) {
1459                         uint64_t compressed, uncompressed;
1460                         zip->entry->crc32 = archive_le32dec(p);
1461                         compressed = archive_le64dec(p + 4);
1462                         uncompressed = archive_le64dec(p + 12);
1463                         if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1464                                 archive_set_error(&a->archive,
1465                                     ARCHIVE_ERRNO_FILE_FORMAT,
1466                                     "Overflow of 64-bit file sizes");
1467                                 return ARCHIVE_FAILED;
1468                         }
1469                         zip->entry->compressed_size = compressed;
1470                         zip->entry->uncompressed_size = uncompressed;
1471                         zip->unconsumed += 20;
1472                 } else {
1473                         zip->entry->crc32 = archive_le32dec(p);
1474                         zip->entry->compressed_size = archive_le32dec(p + 4);
1475                         zip->entry->uncompressed_size = archive_le32dec(p + 8);
1476                         zip->unconsumed += 12;
1477                 }
1478         }
1479
1480         return (ARCHIVE_OK);
1481 }
1482 #endif
1483
1484 static int
1485 read_decryption_header(struct archive_read *a)
1486 {
1487         struct zip *zip = (struct zip *)(a->format->data);
1488         const char *p;
1489         unsigned int remaining_size;
1490         unsigned int ts;
1491
1492         /*
1493          * Read an initialization vector data field.
1494          */
1495         p = __archive_read_ahead(a, 2, NULL);
1496         if (p == NULL)
1497                 goto truncated;
1498         ts = zip->iv_size;
1499         zip->iv_size = archive_le16dec(p);
1500         __archive_read_consume(a, 2);
1501         if (ts < zip->iv_size) {
1502                 free(zip->iv);
1503                 zip->iv = NULL;
1504         }
1505         p = __archive_read_ahead(a, zip->iv_size, NULL);
1506         if (p == NULL)
1507                 goto truncated;
1508         if (zip->iv == NULL) {
1509                 zip->iv = malloc(zip->iv_size);
1510                 if (zip->iv == NULL)
1511                         goto nomem;
1512         }
1513         memcpy(zip->iv, p, zip->iv_size);
1514         __archive_read_consume(a, zip->iv_size);
1515
1516         /*
1517          * Read a size of remaining decryption header field.
1518          */
1519         p = __archive_read_ahead(a, 14, NULL);
1520         if (p == NULL)
1521                 goto truncated;
1522         remaining_size = archive_le32dec(p);
1523         if (remaining_size < 16 || remaining_size > (1 << 18))
1524                 goto corrupted;
1525
1526         /* Check if format version is supported. */
1527         if (archive_le16dec(p+4) != 3) {
1528                 archive_set_error(&a->archive,
1529                     ARCHIVE_ERRNO_FILE_FORMAT,
1530                     "Unsupported encryption format version: %u",
1531                     archive_le16dec(p+4));
1532                 return (ARCHIVE_FAILED);
1533         }
1534
1535         /*
1536          * Read an encryption algorithm field.
1537          */
1538         zip->alg_id = archive_le16dec(p+6);
1539         switch (zip->alg_id) {
1540         case 0x6601:/* DES */
1541         case 0x6602:/* RC2 */
1542         case 0x6603:/* 3DES 168 */
1543         case 0x6609:/* 3DES 112 */
1544         case 0x660E:/* AES 128 */
1545         case 0x660F:/* AES 192 */
1546         case 0x6610:/* AES 256 */
1547         case 0x6702:/* RC2 (version >= 5.2) */
1548         case 0x6720:/* Blowfish */
1549         case 0x6721:/* Twofish */
1550         case 0x6801:/* RC4 */
1551                 /* Supported encryption algorithm. */
1552                 break;
1553         default:
1554                 archive_set_error(&a->archive,
1555                     ARCHIVE_ERRNO_FILE_FORMAT,
1556                     "Unknown encryption algorithm: %u", zip->alg_id);
1557                 return (ARCHIVE_FAILED);
1558         }
1559
1560         /*
1561          * Read a bit length field.
1562          */
1563         zip->bit_len = archive_le16dec(p+8);
1564
1565         /*
1566          * Read a flags field.
1567          */
1568         zip->flags = archive_le16dec(p+10);
1569         switch (zip->flags & 0xf000) {
1570         case 0x0001: /* Password is required to decrypt. */
1571         case 0x0002: /* Certificates only. */
1572         case 0x0003: /* Password or certificate required to decrypt. */
1573                 break;
1574         default:
1575                 archive_set_error(&a->archive,
1576                     ARCHIVE_ERRNO_FILE_FORMAT,
1577                     "Unknown encryption flag: %u", zip->flags);
1578                 return (ARCHIVE_FAILED);
1579         }
1580         if ((zip->flags & 0xf000) == 0 ||
1581             (zip->flags & 0xf000) == 0x4000) {
1582                 archive_set_error(&a->archive,
1583                     ARCHIVE_ERRNO_FILE_FORMAT,
1584                     "Unknown encryption flag: %u", zip->flags);
1585                 return (ARCHIVE_FAILED);
1586         }
1587
1588         /*
1589          * Read an encrypted random data field.
1590          */
1591         ts = zip->erd_size;
1592         zip->erd_size = archive_le16dec(p+12);
1593         __archive_read_consume(a, 14);
1594         if ((zip->erd_size & 0xf) != 0 ||
1595             (zip->erd_size + 16) > remaining_size ||
1596             (zip->erd_size + 16) < zip->erd_size)
1597                 goto corrupted;
1598
1599         if (ts < zip->erd_size) {
1600                 free(zip->erd);
1601                 zip->erd = NULL;
1602         }
1603         p = __archive_read_ahead(a, zip->erd_size, NULL);
1604         if (p == NULL)
1605                 goto truncated;
1606         if (zip->erd == NULL) {
1607                 zip->erd = malloc(zip->erd_size);
1608                 if (zip->erd == NULL)
1609                         goto nomem;
1610         }
1611         memcpy(zip->erd, p, zip->erd_size);
1612         __archive_read_consume(a, zip->erd_size);
1613
1614         /*
1615          * Read a reserved data field.
1616          */
1617         p = __archive_read_ahead(a, 4, NULL);
1618         if (p == NULL)
1619                 goto truncated;
1620         /* Reserved data size should be zero. */
1621         if (archive_le32dec(p) != 0)
1622                 goto corrupted;
1623         __archive_read_consume(a, 4);
1624
1625         /*
1626          * Read a password validation data field.
1627          */
1628         p = __archive_read_ahead(a, 2, NULL);
1629         if (p == NULL)
1630                 goto truncated;
1631         ts = zip->v_size;
1632         zip->v_size = archive_le16dec(p);
1633         __archive_read_consume(a, 2);
1634         if ((zip->v_size & 0x0f) != 0 ||
1635             (zip->erd_size + zip->v_size + 16) > remaining_size ||
1636             (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
1637                 goto corrupted;
1638         if (ts < zip->v_size) {
1639                 free(zip->v_data);
1640                 zip->v_data = NULL;
1641         }
1642         p = __archive_read_ahead(a, zip->v_size, NULL);
1643         if (p == NULL)
1644                 goto truncated;
1645         if (zip->v_data == NULL) {
1646                 zip->v_data = malloc(zip->v_size);
1647                 if (zip->v_data == NULL)
1648                         goto nomem;
1649         }
1650         memcpy(zip->v_data, p, zip->v_size);
1651         __archive_read_consume(a, zip->v_size);
1652
1653         p = __archive_read_ahead(a, 4, NULL);
1654         if (p == NULL)
1655                 goto truncated;
1656         zip->v_crc32 = archive_le32dec(p);
1657         __archive_read_consume(a, 4);
1658
1659         /*return (ARCHIVE_OK);
1660          * This is not fully implemented yet.*/
1661         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1662             "Encrypted file is unsupported");
1663         return (ARCHIVE_FAILED);
1664 truncated:
1665         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1666             "Truncated ZIP file data");
1667         return (ARCHIVE_FATAL);
1668 corrupted:
1669         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1670             "Corrupted ZIP file data");
1671         return (ARCHIVE_FATAL);
1672 nomem:
1673         archive_set_error(&a->archive, ENOMEM,
1674             "No memory for ZIP decryption");
1675         return (ARCHIVE_FATAL);
1676 }
1677
1678 static int
1679 zip_alloc_decryption_buffer(struct archive_read *a)
1680 {
1681         struct zip *zip = (struct zip *)(a->format->data);
1682         size_t bs = 256 * 1024;
1683
1684         if (zip->decrypted_buffer == NULL) {
1685                 zip->decrypted_buffer_size = bs;
1686                 zip->decrypted_buffer = malloc(bs);
1687                 if (zip->decrypted_buffer == NULL) {
1688                         archive_set_error(&a->archive, ENOMEM,
1689                             "No memory for ZIP decryption");
1690                         return (ARCHIVE_FATAL);
1691                 }
1692         }
1693         zip->decrypted_ptr = zip->decrypted_buffer;
1694         return (ARCHIVE_OK);
1695 }
1696
1697 static int
1698 init_traditional_PKWARE_decryption(struct archive_read *a)
1699 {
1700         struct zip *zip = (struct zip *)(a->format->data);
1701         const void *p;
1702         int retry;
1703         int r;
1704
1705         if (zip->tctx_valid)
1706                 return (ARCHIVE_OK);
1707
1708         /*
1709            Read the 12 bytes encryption header stored at
1710            the start of the data area.
1711          */
1712 #define ENC_HEADER_SIZE 12
1713         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1714             && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
1715                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1716                     "Truncated Zip encrypted body: only %jd bytes available",
1717                     (intmax_t)zip->entry_bytes_remaining);
1718                 return (ARCHIVE_FATAL);
1719         }
1720
1721         p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
1722         if (p == NULL) {
1723                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1724                     "Truncated ZIP file data");
1725                 return (ARCHIVE_FATAL);
1726         }
1727
1728         for (retry = 0;; retry++) {
1729                 const char *passphrase;
1730                 uint8_t crcchk;
1731
1732                 passphrase = __archive_read_next_passphrase(a);
1733                 if (passphrase == NULL) {
1734                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1735                             (retry > 0)?
1736                                 "Incorrect passphrase":
1737                                 "Passphrase required for this entry");
1738                         return (ARCHIVE_FAILED);
1739                 }
1740
1741                 /*
1742                  * Initialize ctx for Traditional PKWARE Decryption.
1743                  */
1744                 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
1745                         p, ENC_HEADER_SIZE, &crcchk);
1746                 if (r == 0 && crcchk == zip->entry->decdat)
1747                         break;/* The passphrase is OK. */
1748                 if (retry > 10000) {
1749                         /* Avoid infinity loop. */
1750                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1751                             "Too many incorrect passphrases");
1752                         return (ARCHIVE_FAILED);
1753                 }
1754         }
1755
1756         __archive_read_consume(a, ENC_HEADER_SIZE);
1757         zip->tctx_valid = 1;
1758         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1759             zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
1760         }
1761         /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
1762         zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
1763         zip->decrypted_bytes_remaining = 0;
1764
1765         return (zip_alloc_decryption_buffer(a));
1766 #undef ENC_HEADER_SIZE
1767 }
1768
1769 static int
1770 init_WinZip_AES_decryption(struct archive_read *a)
1771 {
1772         struct zip *zip = (struct zip *)(a->format->data);
1773         const void *p;
1774         const uint8_t *pv;
1775         size_t key_len, salt_len;
1776         uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
1777         int retry;
1778         int r;
1779
1780         if (zip->cctx_valid || zip->hctx_valid)
1781                 return (ARCHIVE_OK);
1782
1783         switch (zip->entry->aes_extra.strength) {
1784         case 1: salt_len = 8;  key_len = 16; break;
1785         case 2: salt_len = 12; key_len = 24; break;
1786         case 3: salt_len = 16; key_len = 32; break;
1787         default: goto corrupted;
1788         }
1789         p = __archive_read_ahead(a, salt_len + 2, NULL);
1790         if (p == NULL)
1791                 goto truncated;
1792
1793         for (retry = 0;; retry++) {
1794                 const char *passphrase;
1795
1796                 passphrase = __archive_read_next_passphrase(a);
1797                 if (passphrase == NULL) {
1798                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1799                             (retry > 0)?
1800                                 "Incorrect passphrase":
1801                                 "Passphrase required for this entry");
1802                         return (ARCHIVE_FAILED);
1803                 }
1804                 memset(derived_key, 0, sizeof(derived_key));
1805                 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
1806                     p, salt_len, 1000, derived_key, key_len * 2 + 2);
1807                 if (r != 0) {
1808                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1809                             "Decryption is unsupported due to lack of "
1810                             "crypto library");
1811                         return (ARCHIVE_FAILED);
1812                 }
1813
1814                 /* Check password verification value. */
1815                 pv = ((const uint8_t *)p) + salt_len;
1816                 if (derived_key[key_len * 2] == pv[0] &&
1817                     derived_key[key_len * 2 + 1] == pv[1])
1818                         break;/* The passphrase is OK. */
1819                 if (retry > 10000) {
1820                         /* Avoid infinity loop. */
1821                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1822                             "Too many incorrect passphrases");
1823                         return (ARCHIVE_FAILED);
1824                 }
1825         }
1826
1827         r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
1828         if (r != 0) {
1829                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1830                     "Decryption is unsupported due to lack of crypto library");
1831                 return (ARCHIVE_FAILED);
1832         }
1833         r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
1834         if (r != 0) {
1835                 archive_decrypto_aes_ctr_release(&zip->cctx);
1836                 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1837                     "Failed to initialize HMAC-SHA1");
1838                 return (ARCHIVE_FAILED);
1839         }
1840         zip->cctx_valid = zip->hctx_valid = 1;
1841         __archive_read_consume(a, salt_len + 2);
1842         zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
1843         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1844             && zip->entry_bytes_remaining < 0)
1845                 goto corrupted;
1846         zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
1847         zip->decrypted_bytes_remaining = 0;
1848
1849         zip->entry->compression = zip->entry->aes_extra.compression;
1850         return (zip_alloc_decryption_buffer(a));
1851
1852 truncated:
1853         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1854             "Truncated ZIP file data");
1855         return (ARCHIVE_FATAL);
1856 corrupted:
1857         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1858             "Corrupted ZIP file data");
1859         return (ARCHIVE_FATAL);
1860 }
1861
1862 static int
1863 archive_read_format_zip_read_data(struct archive_read *a,
1864     const void **buff, size_t *size, int64_t *offset)
1865 {
1866         int r;
1867         struct zip *zip = (struct zip *)(a->format->data);
1868
1869         if (zip->has_encrypted_entries ==
1870                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
1871                 zip->has_encrypted_entries = 0;
1872         }
1873
1874         *offset = zip->entry_uncompressed_bytes_read;
1875         *size = 0;
1876         *buff = NULL;
1877
1878         /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
1879         if (zip->end_of_entry)
1880                 return (ARCHIVE_EOF);
1881
1882         /* Return EOF immediately if this is a non-regular file. */
1883         if (AE_IFREG != (zip->entry->mode & AE_IFMT))
1884                 return (ARCHIVE_EOF);
1885
1886         __archive_read_consume(a, zip->unconsumed);
1887         zip->unconsumed = 0;
1888
1889         if (zip->init_decryption) {
1890                 zip->has_encrypted_entries = 1;
1891                 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
1892                         r = read_decryption_header(a);
1893                 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
1894                         r = init_WinZip_AES_decryption(a);
1895                 else
1896                         r = init_traditional_PKWARE_decryption(a);
1897                 if (r != ARCHIVE_OK)
1898                         return (r);
1899                 zip->init_decryption = 0;
1900         }
1901
1902         switch(zip->entry->compression) {
1903         case 0:  /* No compression. */
1904                 r =  zip_read_data_none(a, buff, size, offset);
1905                 break;
1906 #ifdef HAVE_ZLIB_H
1907         case 8: /* Deflate compression. */
1908                 r =  zip_read_data_deflate(a, buff, size, offset);
1909                 break;
1910 #endif
1911         default: /* Unsupported compression. */
1912                 /* Return a warning. */
1913                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1914                     "Unsupported ZIP compression method (%s)",
1915                     compression_name(zip->entry->compression));
1916                 /* We can't decompress this entry, but we will
1917                  * be able to skip() it and try the next entry. */
1918                 return (ARCHIVE_FAILED);
1919                 break;
1920         }
1921         if (r != ARCHIVE_OK)
1922                 return (r);
1923         /* Update checksum */
1924         if (*size)
1925                 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
1926                     (unsigned)*size);
1927         /* If we hit the end, swallow any end-of-data marker. */
1928         if (zip->end_of_entry) {
1929                 /* Check file size, CRC against these values. */
1930                 if (zip->entry->compressed_size !=
1931                     zip->entry_compressed_bytes_read) {
1932                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1933                             "ZIP compressed data is wrong size "
1934                             "(read %jd, expected %jd)",
1935                             (intmax_t)zip->entry_compressed_bytes_read,
1936                             (intmax_t)zip->entry->compressed_size);
1937                         return (ARCHIVE_WARN);
1938                 }
1939                 /* Size field only stores the lower 32 bits of the actual
1940                  * size. */
1941                 if ((zip->entry->uncompressed_size & UINT32_MAX)
1942                     != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
1943                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1944                             "ZIP uncompressed data is wrong size "
1945                             "(read %jd, expected %jd)\n",
1946                             (intmax_t)zip->entry_uncompressed_bytes_read,
1947                             (intmax_t)zip->entry->uncompressed_size);
1948                         return (ARCHIVE_WARN);
1949                 }
1950                 /* Check computed CRC against header */
1951                 if ((!zip->hctx_valid ||
1952                       zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
1953                    zip->entry->crc32 != zip->entry_crc32
1954                     && !zip->ignore_crc32) {
1955                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1956                             "ZIP bad CRC: 0x%lx should be 0x%lx",
1957                             (unsigned long)zip->entry_crc32,
1958                             (unsigned long)zip->entry->crc32);
1959                         return (ARCHIVE_WARN);
1960                 }
1961         }
1962
1963         return (ARCHIVE_OK);
1964 }
1965
1966 static int
1967 archive_read_format_zip_cleanup(struct archive_read *a)
1968 {
1969         struct zip *zip;
1970         struct zip_entry *zip_entry, *next_zip_entry;
1971
1972         zip = (struct zip *)(a->format->data);
1973 #ifdef HAVE_ZLIB_H
1974         if (zip->stream_valid)
1975                 inflateEnd(&zip->stream);
1976         free(zip->uncompressed_buffer);
1977 #endif
1978         if (zip->zip_entries) {
1979                 zip_entry = zip->zip_entries;
1980                 while (zip_entry != NULL) {
1981                         next_zip_entry = zip_entry->next;
1982                         archive_string_free(&zip_entry->rsrcname);
1983                         free(zip_entry);
1984                         zip_entry = next_zip_entry;
1985                 }
1986         }
1987         free(zip->decrypted_buffer);
1988         if (zip->cctx_valid)
1989                 archive_decrypto_aes_ctr_release(&zip->cctx);
1990         if (zip->hctx_valid)
1991                 archive_hmac_sha1_cleanup(&zip->hctx);
1992         free(zip->iv);
1993         free(zip->erd);
1994         free(zip->v_data);
1995         archive_string_free(&zip->format_name);
1996         free(zip);
1997         (a->format->data) = NULL;
1998         return (ARCHIVE_OK);
1999 }
2000
2001 static int
2002 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
2003 {
2004         if (_a && _a->format) {
2005                 struct zip * zip = (struct zip *)_a->format->data;
2006                 if (zip) {
2007                         return zip->has_encrypted_entries;
2008                 }
2009         }
2010         return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2011 }
2012
2013 static int
2014 archive_read_format_zip_options(struct archive_read *a,
2015     const char *key, const char *val)
2016 {
2017         struct zip *zip;
2018         int ret = ARCHIVE_FAILED;
2019
2020         zip = (struct zip *)(a->format->data);
2021         if (strcmp(key, "compat-2x")  == 0) {
2022                 /* Handle filenames as libarchive 2.x */
2023                 zip->init_default_conversion = (val != NULL) ? 1 : 0;
2024                 return (ARCHIVE_OK);
2025         } else if (strcmp(key, "hdrcharset")  == 0) {
2026                 if (val == NULL || val[0] == 0)
2027                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2028                             "zip: hdrcharset option needs a character-set name"
2029                         );
2030                 else {
2031                         zip->sconv = archive_string_conversion_from_charset(
2032                             &a->archive, val, 0);
2033                         if (zip->sconv != NULL) {
2034                                 if (strcmp(val, "UTF-8") == 0)
2035                                         zip->sconv_utf8 = zip->sconv;
2036                                 ret = ARCHIVE_OK;
2037                         } else
2038                                 ret = ARCHIVE_FATAL;
2039                 }
2040                 return (ret);
2041         } else if (strcmp(key, "ignorecrc32") == 0) {
2042                 /* Mostly useful for testing. */
2043                 if (val == NULL || val[0] == 0) {
2044                         zip->crc32func = real_crc32;
2045                         zip->ignore_crc32 = 0;
2046                 } else {
2047                         zip->crc32func = fake_crc32;
2048                         zip->ignore_crc32 = 1;
2049                 }
2050                 return (ARCHIVE_OK);
2051         } else if (strcmp(key, "mac-ext") == 0) {
2052                 zip->process_mac_extensions = (val != NULL && val[0] != 0);
2053                 return (ARCHIVE_OK);
2054         }
2055
2056         /* Note: The "warn" return is just to inform the options
2057          * supervisor that we didn't handle it.  It will generate
2058          * a suitable error if no one used this option. */
2059         return (ARCHIVE_WARN);
2060 }
2061
2062 int
2063 archive_read_support_format_zip(struct archive *a)
2064 {
2065         int r;
2066         r = archive_read_support_format_zip_streamable(a);
2067         if (r != ARCHIVE_OK)
2068                 return r;
2069         return (archive_read_support_format_zip_seekable(a));
2070 }
2071
2072 /* ------------------------------------------------------------------------ */
2073
2074 /*
2075  * Streaming-mode support
2076  */
2077
2078
2079 static int
2080 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
2081 {
2082         (void)a; /* UNUSED */
2083         return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2084                 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2085 }
2086
2087 static int
2088 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
2089 {
2090         const char *p;
2091
2092         (void)best_bid; /* UNUSED */
2093
2094         if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
2095                 return (-1);
2096
2097         /*
2098          * Bid of 29 here comes from:
2099          *  + 16 bits for "PK",
2100          *  + next 16-bit field has 6 options so contributes
2101          *    about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
2102          *
2103          * So we've effectively verified ~29 total bits of check data.
2104          */
2105         if (p[0] == 'P' && p[1] == 'K') {
2106                 if ((p[2] == '\001' && p[3] == '\002')
2107                     || (p[2] == '\003' && p[3] == '\004')
2108                     || (p[2] == '\005' && p[3] == '\006')
2109                     || (p[2] == '\006' && p[3] == '\006')
2110                     || (p[2] == '\007' && p[3] == '\010')
2111                     || (p[2] == '0' && p[3] == '0'))
2112                         return (29);
2113         }
2114
2115         /* TODO: It's worth looking ahead a little bit for a valid
2116          * PK signature.  In particular, that would make it possible
2117          * to read some UUEncoded SFX files or SFX files coming from
2118          * a network socket. */
2119
2120         return (0);
2121 }
2122
2123 static int
2124 archive_read_format_zip_streamable_read_header(struct archive_read *a,
2125     struct archive_entry *entry)
2126 {
2127         struct zip *zip;
2128
2129         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
2130         if (a->archive.archive_format_name == NULL)
2131                 a->archive.archive_format_name = "ZIP";
2132
2133         zip = (struct zip *)(a->format->data);
2134
2135         /*
2136          * It should be sufficient to call archive_read_next_header() for
2137          * a reader to determine if an entry is encrypted or not. If the
2138          * encryption of an entry is only detectable when calling
2139          * archive_read_data(), so be it. We'll do the same check there
2140          * as well.
2141          */
2142         if (zip->has_encrypted_entries ==
2143                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
2144                 zip->has_encrypted_entries = 0;
2145
2146         /* Make sure we have a zip_entry structure to use. */
2147         if (zip->zip_entries == NULL) {
2148                 zip->zip_entries = malloc(sizeof(struct zip_entry));
2149                 if (zip->zip_entries == NULL) {
2150                         archive_set_error(&a->archive, ENOMEM,
2151                             "Out  of memory");
2152                         return ARCHIVE_FATAL;
2153                 }
2154         }
2155         zip->entry = zip->zip_entries;
2156         memset(zip->entry, 0, sizeof(struct zip_entry));
2157
2158         if (zip->cctx_valid)
2159                 archive_decrypto_aes_ctr_release(&zip->cctx);
2160         if (zip->hctx_valid)
2161                 archive_hmac_sha1_cleanup(&zip->hctx);
2162         zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
2163         __archive_read_reset_passphrase(a);
2164
2165         /* Search ahead for the next local file header. */
2166         __archive_read_consume(a, zip->unconsumed);
2167         zip->unconsumed = 0;
2168         for (;;) {
2169                 int64_t skipped = 0;
2170                 const char *p, *end;
2171                 ssize_t bytes;
2172
2173                 p = __archive_read_ahead(a, 4, &bytes);
2174                 if (p == NULL)
2175                         return (ARCHIVE_FATAL);
2176                 end = p + bytes;
2177
2178                 while (p + 4 <= end) {
2179                         if (p[0] == 'P' && p[1] == 'K') {
2180                                 if (p[2] == '\003' && p[3] == '\004') {
2181                                         /* Regular file entry. */
2182                                         __archive_read_consume(a, skipped);
2183                                         return zip_read_local_file_header(a,
2184                                             entry, zip);
2185                                 }
2186
2187                               /*
2188                                * TODO: We cannot restore permissions
2189                                * based only on the local file headers.
2190                                * Consider scanning the central
2191                                * directory and returning additional
2192                                * entries for at least directories.
2193                                * This would allow us to properly set
2194                                * directory permissions.
2195                                *
2196                                * This won't help us fix symlinks
2197                                * and may not help with regular file
2198                                * permissions, either.  <sigh>
2199                                */
2200                               if (p[2] == '\001' && p[3] == '\002') {
2201                                       return (ARCHIVE_EOF);
2202                               }
2203
2204                               /* End of central directory?  Must be an
2205                                * empty archive. */
2206                               if ((p[2] == '\005' && p[3] == '\006')
2207                                   || (p[2] == '\006' && p[3] == '\006'))
2208                                       return (ARCHIVE_EOF);
2209                         }
2210                         ++p;
2211                         ++skipped;
2212                 }
2213                 __archive_read_consume(a, skipped);
2214         }
2215 }
2216
2217 static int
2218 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
2219 {
2220         struct zip *zip;
2221         int64_t bytes_skipped;
2222
2223         zip = (struct zip *)(a->format->data);
2224         bytes_skipped = __archive_read_consume(a, zip->unconsumed);
2225         zip->unconsumed = 0;
2226         if (bytes_skipped < 0)
2227                 return (ARCHIVE_FATAL);
2228
2229         /* If we've already read to end of data, we're done. */
2230         if (zip->end_of_entry)
2231                 return (ARCHIVE_OK);
2232
2233         /* So we know we're streaming... */
2234         if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2235             || zip->entry->compressed_size > 0) {
2236                 /* We know the compressed length, so we can just skip. */
2237                 bytes_skipped = __archive_read_consume(a,
2238                                         zip->entry_bytes_remaining);
2239                 if (bytes_skipped < 0)
2240                         return (ARCHIVE_FATAL);
2241                 return (ARCHIVE_OK);
2242         }
2243
2244         if (zip->init_decryption) {
2245                 int r;
2246
2247                 zip->has_encrypted_entries = 1;
2248                 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2249                         r = read_decryption_header(a);
2250                 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2251                         r = init_WinZip_AES_decryption(a);
2252                 else
2253                         r = init_traditional_PKWARE_decryption(a);
2254                 if (r != ARCHIVE_OK)
2255                         return (r);
2256                 zip->init_decryption = 0;
2257         }
2258
2259         /* We're streaming and we don't know the length. */
2260         /* If the body is compressed and we know the format, we can
2261          * find an exact end-of-entry by decompressing it. */
2262         switch (zip->entry->compression) {
2263 #ifdef HAVE_ZLIB_H
2264         case 8: /* Deflate compression. */
2265                 while (!zip->end_of_entry) {
2266                         int64_t offset = 0;
2267                         const void *buff = NULL;
2268                         size_t size = 0;
2269                         int r;
2270                         r =  zip_read_data_deflate(a, &buff, &size, &offset);
2271                         if (r != ARCHIVE_OK)
2272                                 return (r);
2273                 }
2274                 return ARCHIVE_OK;
2275 #endif
2276         default: /* Uncompressed or unknown. */
2277                 /* Scan for a PK\007\010 signature. */
2278                 for (;;) {
2279                         const char *p, *buff;
2280                         ssize_t bytes_avail;
2281                         buff = __archive_read_ahead(a, 16, &bytes_avail);
2282                         if (bytes_avail < 16) {
2283                                 archive_set_error(&a->archive,
2284                                     ARCHIVE_ERRNO_FILE_FORMAT,
2285                                     "Truncated ZIP file data");
2286                                 return (ARCHIVE_FATAL);
2287                         }
2288                         p = buff;
2289                         while (p <= buff + bytes_avail - 16) {
2290                                 if (p[3] == 'P') { p += 3; }
2291                                 else if (p[3] == 'K') { p += 2; }
2292                                 else if (p[3] == '\007') { p += 1; }
2293                                 else if (p[3] == '\010' && p[2] == '\007'
2294                                     && p[1] == 'K' && p[0] == 'P') {
2295                                         if (zip->entry->flags & LA_USED_ZIP64)
2296                                                 __archive_read_consume(a,
2297                                                     p - buff + 24);
2298                                         else
2299                                                 __archive_read_consume(a,
2300                                                     p - buff + 16);
2301                                         return ARCHIVE_OK;
2302                                 } else { p += 4; }
2303                         }
2304                         __archive_read_consume(a, p - buff);
2305                 }
2306         }
2307 }
2308
2309 int
2310 archive_read_support_format_zip_streamable(struct archive *_a)
2311 {
2312         struct archive_read *a = (struct archive_read *)_a;
2313         struct zip *zip;
2314         int r;
2315
2316         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
2317             ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
2318
2319         zip = (struct zip *)calloc(1, sizeof(*zip));
2320         if (zip == NULL) {
2321                 archive_set_error(&a->archive, ENOMEM,
2322                     "Can't allocate zip data");
2323                 return (ARCHIVE_FATAL);
2324         }
2325
2326         /* Streamable reader doesn't support mac extensions. */
2327         zip->process_mac_extensions = 0;
2328
2329         /*
2330          * Until enough data has been read, we cannot tell about
2331          * any encrypted entries yet.
2332          */
2333         zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2334         zip->crc32func = real_crc32;
2335
2336         r = __archive_read_register_format(a,
2337             zip,
2338             "zip",
2339             archive_read_format_zip_streamable_bid,
2340             archive_read_format_zip_options,
2341             archive_read_format_zip_streamable_read_header,
2342             archive_read_format_zip_read_data,
2343             archive_read_format_zip_read_data_skip_streamable,
2344             NULL,
2345             archive_read_format_zip_cleanup,
2346             archive_read_support_format_zip_capabilities_streamable,
2347             archive_read_format_zip_has_encrypted_entries);
2348
2349         if (r != ARCHIVE_OK)
2350                 free(zip);
2351         return (ARCHIVE_OK);
2352 }
2353
2354 /* ------------------------------------------------------------------------ */
2355
2356 /*
2357  * Seeking-mode support
2358  */
2359
2360 static int
2361 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
2362 {
2363         (void)a; /* UNUSED */
2364         return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2365                 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2366 }
2367
2368 /*
2369  * TODO: This is a performance sink because it forces the read core to
2370  * drop buffered data from the start of file, which will then have to
2371  * be re-read again if this bidder loses.
2372  *
2373  * We workaround this a little by passing in the best bid so far so
2374  * that later bidders can do nothing if they know they'll never
2375  * outbid.  But we can certainly do better...
2376  */
2377 static int
2378 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
2379 {
2380         /* Sanity-check the EOCD we've found. */
2381
2382         /* This must be the first volume. */
2383         if (archive_le16dec(p + 4) != 0)
2384                 return 0;
2385         /* Central directory must be on this volume. */
2386         if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
2387                 return 0;
2388         /* All central directory entries must be on this volume. */
2389         if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
2390                 return 0;
2391         /* Central directory can't extend beyond start of EOCD record. */
2392         if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
2393             > current_offset)
2394                 return 0;
2395
2396         /* Save the central directory location for later use. */
2397         zip->central_directory_offset = archive_le32dec(p + 16);
2398
2399         /* This is just a tiny bit higher than the maximum
2400            returned by the streaming Zip bidder.  This ensures
2401            that the more accurate seeking Zip parser wins
2402            whenever seek is available. */
2403         return 32;
2404 }
2405
2406 /*
2407  * Examine Zip64 EOCD locator:  If it's valid, store the information
2408  * from it.
2409  */
2410 static int
2411 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
2412 {
2413         int64_t eocd64_offset;
2414         int64_t eocd64_size;
2415
2416         /* Sanity-check the locator record. */
2417
2418         /* Central dir must be on first volume. */
2419         if (archive_le32dec(p + 4) != 0)
2420                 return 0;
2421         /* Must be only a single volume. */
2422         if (archive_le32dec(p + 16) != 1)
2423                 return 0;
2424
2425         /* Find the Zip64 EOCD record. */
2426         eocd64_offset = archive_le64dec(p + 8);
2427         if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
2428                 return 0;
2429         if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
2430                 return 0;
2431         /* Make sure we can read all of it. */
2432         eocd64_size = archive_le64dec(p + 4) + 12;
2433         if (eocd64_size < 56 || eocd64_size > 16384)
2434                 return 0;
2435         if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
2436                 return 0;
2437
2438         /* Sanity-check the EOCD64 */
2439         if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
2440                 return 0;
2441         if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
2442                 return 0;
2443         /* CD can't be split. */
2444         if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
2445                 return 0;
2446
2447         /* Save the central directory offset for later use. */
2448         zip->central_directory_offset = archive_le64dec(p + 48);
2449
2450         return 32;
2451 }
2452
2453 static int
2454 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
2455 {
2456         struct zip *zip = (struct zip *)a->format->data;
2457         int64_t file_size, current_offset;
2458         const char *p;
2459         int i, tail;
2460
2461         /* If someone has already bid more than 32, then avoid
2462            trashing the look-ahead buffers with a seek. */
2463         if (best_bid > 32)
2464                 return (-1);
2465
2466         file_size = __archive_read_seek(a, 0, SEEK_END);
2467         if (file_size <= 0)
2468                 return 0;
2469
2470         /* Search last 16k of file for end-of-central-directory
2471          * record (which starts with PK\005\006) */
2472         tail = (int)zipmin(1024 * 16, file_size);
2473         current_offset = __archive_read_seek(a, -tail, SEEK_END);
2474         if (current_offset < 0)
2475                 return 0;
2476         if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
2477                 return 0;
2478         /* Boyer-Moore search backwards from the end, since we want
2479          * to match the last EOCD in the file (there can be more than
2480          * one if there is an uncompressed Zip archive as a member
2481          * within this Zip archive). */
2482         for (i = tail - 22; i > 0;) {
2483                 switch (p[i]) {
2484                 case 'P':
2485                         if (memcmp(p + i, "PK\005\006", 4) == 0) {
2486                                 int ret = read_eocd(zip, p + i,
2487                                     current_offset + i);
2488                                 /* Zip64 EOCD locator precedes
2489                                  * regular EOCD if present. */
2490                                 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
2491                                         int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
2492                                         if (ret_zip64 > ret)
2493                                                 ret = ret_zip64;
2494                                 }
2495                                 return (ret);
2496                         }
2497                         i -= 4;
2498                         break;
2499                 case 'K': i -= 1; break;
2500                 case 005: i -= 2; break;
2501                 case 006: i -= 3; break;
2502                 default: i -= 4; break;
2503                 }
2504         }
2505         return 0;
2506 }
2507
2508 /* The red-black trees are only used in seeking mode to manage
2509  * the in-memory copy of the central directory. */
2510
2511 static int
2512 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
2513 {
2514         const struct zip_entry *e1 = (const struct zip_entry *)n1;
2515         const struct zip_entry *e2 = (const struct zip_entry *)n2;
2516
2517         if (e1->local_header_offset > e2->local_header_offset)
2518                 return -1;
2519         if (e1->local_header_offset < e2->local_header_offset)
2520                 return 1;
2521         return 0;
2522 }
2523
2524 static int
2525 cmp_key(const struct archive_rb_node *n, const void *key)
2526 {
2527         /* This function won't be called */
2528         (void)n; /* UNUSED */
2529         (void)key; /* UNUSED */
2530         return 1;
2531 }
2532
2533 static const struct archive_rb_tree_ops rb_ops = {
2534         &cmp_node, &cmp_key
2535 };
2536
2537 static int
2538 rsrc_cmp_node(const struct archive_rb_node *n1,
2539     const struct archive_rb_node *n2)
2540 {
2541         const struct zip_entry *e1 = (const struct zip_entry *)n1;
2542         const struct zip_entry *e2 = (const struct zip_entry *)n2;
2543
2544         return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
2545 }
2546
2547 static int
2548 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
2549 {
2550         const struct zip_entry *e = (const struct zip_entry *)n;
2551         return (strcmp((const char *)key, e->rsrcname.s));
2552 }
2553
2554 static const struct archive_rb_tree_ops rb_rsrc_ops = {
2555         &rsrc_cmp_node, &rsrc_cmp_key
2556 };
2557
2558 static const char *
2559 rsrc_basename(const char *name, size_t name_length)
2560 {
2561         const char *s, *r;
2562
2563         r = s = name;
2564         for (;;) {
2565                 s = memchr(s, '/', name_length - (s - name));
2566                 if (s == NULL)
2567                         break;
2568                 r = ++s;
2569         }
2570         return (r);
2571 }
2572
2573 static void
2574 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
2575 {
2576         struct archive_string str;
2577         struct zip_entry *dir;
2578         char *s;
2579
2580         archive_string_init(&str);
2581         archive_strncpy(&str, name, name_length);
2582         for (;;) {
2583                 s = strrchr(str.s, '/');
2584                 if (s == NULL)
2585                         break;
2586                 *s = '\0';
2587                 /* Transfer the parent directory from zip->tree_rsrc RB
2588                  * tree to zip->tree RB tree to expose. */
2589                 dir = (struct zip_entry *)
2590                     __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
2591                 if (dir == NULL)
2592                         break;
2593                 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
2594                 archive_string_free(&dir->rsrcname);
2595                 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
2596         }
2597         archive_string_free(&str);
2598 }
2599
2600 static int
2601 slurp_central_directory(struct archive_read *a, struct zip *zip)
2602 {
2603         ssize_t i;
2604         unsigned found;
2605         int64_t correction;
2606         ssize_t bytes_avail;
2607         const char *p;
2608
2609         /*
2610          * Find the start of the central directory.  The end-of-CD
2611          * record has our starting point, but there are lots of
2612          * Zip archives which have had other data prepended to the
2613          * file, which makes the recorded offsets all too small.
2614          * So we search forward from the specified offset until we
2615          * find the real start of the central directory.  Then we
2616          * know the correction we need to apply to account for leading
2617          * padding.
2618          */
2619         if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
2620                 return ARCHIVE_FATAL;
2621
2622         found = 0;
2623         while (!found) {
2624                 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
2625                         return ARCHIVE_FATAL;
2626                 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
2627                         switch (p[i + 3]) {
2628                         case 'P': i += 3; break;
2629                         case 'K': i += 2; break;
2630                         case 001: i += 1; break;
2631                         case 002:
2632                                 if (memcmp(p + i, "PK\001\002", 4) == 0) {
2633                                         p += i;
2634                                         found = 1;
2635                                 } else
2636                                         i += 4;
2637                                 break;
2638                         case 005: i += 1; break;
2639                         case 006:
2640                                 if (memcmp(p + i, "PK\005\006", 4) == 0) {
2641                                         p += i;
2642                                         found = 1;
2643                                 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
2644                                         p += i;
2645                                         found = 1;
2646                                 } else
2647                                         i += 1;
2648                                 break;
2649                         default: i += 4; break;
2650                         }
2651                 }
2652                 __archive_read_consume(a, i);
2653         }
2654         correction = archive_filter_bytes(&a->archive, 0)
2655                         - zip->central_directory_offset;
2656
2657         __archive_rb_tree_init(&zip->tree, &rb_ops);
2658         __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
2659
2660         zip->central_directory_entries_total = 0;
2661         while (1) {
2662                 struct zip_entry *zip_entry;
2663                 size_t filename_length, extra_length, comment_length;
2664                 uint32_t external_attributes;
2665                 const char *name, *r;
2666
2667                 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
2668                         return ARCHIVE_FATAL;
2669                 if (memcmp(p, "PK\006\006", 4) == 0
2670                     || memcmp(p, "PK\005\006", 4) == 0) {
2671                         break;
2672                 } else if (memcmp(p, "PK\001\002", 4) != 0) {
2673                         archive_set_error(&a->archive,
2674                             -1, "Invalid central directory signature");
2675                         return ARCHIVE_FATAL;
2676                 }
2677                 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
2678                         return ARCHIVE_FATAL;
2679
2680                 zip_entry = calloc(1, sizeof(struct zip_entry));
2681                 zip_entry->next = zip->zip_entries;
2682                 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
2683                 zip->zip_entries = zip_entry;
2684                 zip->central_directory_entries_total++;
2685
2686                 /* version = p[4]; */
2687                 zip_entry->system = p[5];
2688                 /* version_required = archive_le16dec(p + 6); */
2689                 zip_entry->zip_flags = archive_le16dec(p + 8);
2690                 if (zip_entry->zip_flags
2691                       & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
2692                         zip->has_encrypted_entries = 1;
2693                 }
2694                 zip_entry->compression = (char)archive_le16dec(p + 10);
2695                 zip_entry->mtime = zip_time(p + 12);
2696                 zip_entry->crc32 = archive_le32dec(p + 16);
2697                 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
2698                         zip_entry->decdat = p[13];
2699                 else
2700                         zip_entry->decdat = p[19];
2701                 zip_entry->compressed_size = archive_le32dec(p + 20);
2702                 zip_entry->uncompressed_size = archive_le32dec(p + 24);
2703                 filename_length = archive_le16dec(p + 28);
2704                 extra_length = archive_le16dec(p + 30);
2705                 comment_length = archive_le16dec(p + 32);
2706                 /* disk_start = archive_le16dec(p + 34); */ /* Better be zero. */
2707                 /* internal_attributes = archive_le16dec(p + 36); */ /* text bit */
2708                 external_attributes = archive_le32dec(p + 38);
2709                 zip_entry->local_header_offset =
2710                     archive_le32dec(p + 42) + correction;
2711
2712                 /* If we can't guess the mode, leave it zero here;
2713                    when we read the local file header we might get
2714                    more information. */
2715                 if (zip_entry->system == 3) {
2716                         zip_entry->mode = external_attributes >> 16;
2717                 } else if (zip_entry->system == 0) {
2718                         // Interpret MSDOS directory bit
2719                         if (0x10 == (external_attributes & 0x10)) {
2720                                 zip_entry->mode = AE_IFDIR | 0775;
2721                         } else {
2722                                 zip_entry->mode = AE_IFREG | 0664;
2723                         }
2724                         if (0x01 == (external_attributes & 0x01)) {
2725                                 // Read-only bit; strip write permissions
2726                                 zip_entry->mode &= 0555;
2727                         }
2728                 } else {
2729                         zip_entry->mode = 0;
2730                 }
2731
2732                 /* We're done with the regular data; get the filename and
2733                  * extra data. */
2734                 __archive_read_consume(a, 46);
2735                 p = __archive_read_ahead(a, filename_length + extra_length,
2736                         NULL);
2737                 if (p == NULL) {
2738                         archive_set_error(&a->archive,
2739                             ARCHIVE_ERRNO_FILE_FORMAT,
2740                             "Truncated ZIP file header");
2741                         return ARCHIVE_FATAL;
2742                 }
2743                 if (ARCHIVE_OK != process_extra(a, p + filename_length, extra_length, zip_entry)) {
2744                         return ARCHIVE_FATAL;
2745                 }
2746
2747                 /*
2748                  * Mac resource fork files are stored under the
2749                  * "__MACOSX/" directory, so we should check if
2750                  * it is.
2751                  */
2752                 if (!zip->process_mac_extensions) {
2753                         /* Treat every entry as a regular entry. */
2754                         __archive_rb_tree_insert_node(&zip->tree,
2755                             &zip_entry->node);
2756                 } else {
2757                         name = p;
2758                         r = rsrc_basename(name, filename_length);
2759                         if (filename_length >= 9 &&
2760                             strncmp("__MACOSX/", name, 9) == 0) {
2761                                 /* If this file is not a resource fork nor
2762                                  * a directory. We should treat it as a non
2763                                  * resource fork file to expose it. */
2764                                 if (name[filename_length-1] != '/' &&
2765                                     (r - name < 3 || r[0] != '.' || r[1] != '_')) {
2766                                         __archive_rb_tree_insert_node(
2767                                             &zip->tree, &zip_entry->node);
2768                                         /* Expose its parent directories. */
2769                                         expose_parent_dirs(zip, name,
2770                                             filename_length);
2771                                 } else {
2772                                         /* This file is a resource fork file or
2773                                          * a directory. */
2774                                         archive_strncpy(&(zip_entry->rsrcname),
2775                                              name, filename_length);
2776                                         __archive_rb_tree_insert_node(
2777                                             &zip->tree_rsrc, &zip_entry->node);
2778                                 }
2779                         } else {
2780                                 /* Generate resource fork name to find its
2781                                  * resource file at zip->tree_rsrc. */
2782                                 archive_strcpy(&(zip_entry->rsrcname),
2783                                     "__MACOSX/");
2784                                 archive_strncat(&(zip_entry->rsrcname),
2785                                     name, r - name);
2786                                 archive_strcat(&(zip_entry->rsrcname), "._");
2787                                 archive_strncat(&(zip_entry->rsrcname),
2788                                     name + (r - name),
2789                                     filename_length - (r - name));
2790                                 /* Register an entry to RB tree to sort it by
2791                                  * file offset. */
2792                                 __archive_rb_tree_insert_node(&zip->tree,
2793                                     &zip_entry->node);
2794                         }
2795                 }
2796
2797                 /* Skip the comment too ... */
2798                 __archive_read_consume(a,
2799                     filename_length + extra_length + comment_length);
2800         }
2801
2802         return ARCHIVE_OK;
2803 }
2804
2805 static ssize_t
2806 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
2807 {
2808         const char *p;
2809         ssize_t filename_length, extra_length;
2810
2811         if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
2812                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2813                     "Truncated ZIP file header");
2814                 return (ARCHIVE_WARN);
2815         }
2816         p += extra;
2817
2818         if (memcmp(p, "PK\003\004", 4) != 0) {
2819                 archive_set_error(&a->archive, -1, "Damaged Zip archive");
2820                 return ARCHIVE_WARN;
2821         }
2822         filename_length = archive_le16dec(p + 26);
2823         extra_length = archive_le16dec(p + 28);
2824
2825         return (30 + filename_length + extra_length);
2826 }
2827
2828 static int
2829 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
2830     struct zip_entry *rsrc)
2831 {
2832         struct zip *zip = (struct zip *)a->format->data;
2833         unsigned char *metadata, *mp;
2834         int64_t offset = archive_filter_bytes(&a->archive, 0);
2835         size_t remaining_bytes, metadata_bytes;
2836         ssize_t hsize;
2837         int ret = ARCHIVE_OK, eof;
2838
2839         switch(rsrc->compression) {
2840         case 0:  /* No compression. */
2841                 if (rsrc->uncompressed_size != rsrc->compressed_size) {
2842                         archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2843                             "Malformed OS X metadata entry: inconsistent size");
2844                         return (ARCHIVE_FATAL);
2845                 }
2846 #ifdef HAVE_ZLIB_H
2847         case 8: /* Deflate compression. */
2848 #endif
2849                 break;
2850         default: /* Unsupported compression. */
2851                 /* Return a warning. */
2852                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2853                     "Unsupported ZIP compression method (%s)",
2854                     compression_name(rsrc->compression));
2855                 /* We can't decompress this entry, but we will
2856                  * be able to skip() it and try the next entry. */
2857                 return (ARCHIVE_WARN);
2858         }
2859
2860         if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
2861                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2862                     "Mac metadata is too large: %jd > 4M bytes",
2863                     (intmax_t)rsrc->uncompressed_size);
2864                 return (ARCHIVE_WARN);
2865         }
2866         if (rsrc->compressed_size > (4 * 1024 * 1024)) {
2867                 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2868                     "Mac metadata is too large: %jd > 4M bytes",
2869                     (intmax_t)rsrc->compressed_size);
2870                 return (ARCHIVE_WARN);
2871         }
2872
2873         metadata = malloc((size_t)rsrc->uncompressed_size);
2874         if (metadata == NULL) {
2875                 archive_set_error(&a->archive, ENOMEM,
2876                     "Can't allocate memory for Mac metadata");
2877                 return (ARCHIVE_FATAL);
2878         }
2879
2880         if (offset < rsrc->local_header_offset)
2881                 __archive_read_consume(a, rsrc->local_header_offset - offset);
2882         else if (offset != rsrc->local_header_offset) {
2883                 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
2884         }
2885
2886         hsize = zip_get_local_file_header_size(a, 0);
2887         __archive_read_consume(a, hsize);
2888
2889         remaining_bytes = (size_t)rsrc->compressed_size;
2890         metadata_bytes = (size_t)rsrc->uncompressed_size;
2891         mp = metadata;
2892         eof = 0;
2893         while (!eof && remaining_bytes) {
2894                 const unsigned char *p;
2895                 ssize_t bytes_avail;
2896                 size_t bytes_used;
2897
2898                 p = __archive_read_ahead(a, 1, &bytes_avail);
2899                 if (p == NULL) {
2900                         archive_set_error(&a->archive,
2901                             ARCHIVE_ERRNO_FILE_FORMAT,
2902                             "Truncated ZIP file header");
2903                         ret = ARCHIVE_WARN;
2904                         goto exit_mac_metadata;
2905                 }
2906                 if ((size_t)bytes_avail > remaining_bytes)
2907                         bytes_avail = remaining_bytes;
2908                 switch(rsrc->compression) {
2909                 case 0:  /* No compression. */
2910                         if ((size_t)bytes_avail > metadata_bytes)
2911                                 bytes_avail = metadata_bytes;
2912                         memcpy(mp, p, bytes_avail);
2913                         bytes_used = (size_t)bytes_avail;
2914                         metadata_bytes -= bytes_used;
2915                         mp += bytes_used;
2916                         if (metadata_bytes == 0)
2917                                 eof = 1;
2918                         break;
2919 #ifdef HAVE_ZLIB_H
2920                 case 8: /* Deflate compression. */
2921                 {
2922                         int r;
2923
2924                         ret = zip_deflate_init(a, zip);
2925                         if (ret != ARCHIVE_OK)
2926                                 goto exit_mac_metadata;
2927                         zip->stream.next_in =
2928                             (Bytef *)(uintptr_t)(const void *)p;
2929                         zip->stream.avail_in = (uInt)bytes_avail;
2930                         zip->stream.total_in = 0;
2931                         zip->stream.next_out = mp;
2932                         zip->stream.avail_out = (uInt)metadata_bytes;
2933                         zip->stream.total_out = 0;
2934
2935                         r = inflate(&zip->stream, 0);
2936                         switch (r) {
2937                         case Z_OK:
2938                                 break;
2939                         case Z_STREAM_END:
2940                                 eof = 1;
2941                                 break;
2942                         case Z_MEM_ERROR:
2943                                 archive_set_error(&a->archive, ENOMEM,
2944                                     "Out of memory for ZIP decompression");
2945                                 ret = ARCHIVE_FATAL;
2946                                 goto exit_mac_metadata;
2947                         default:
2948                                 archive_set_error(&a->archive,
2949                                     ARCHIVE_ERRNO_MISC,
2950                                     "ZIP decompression failed (%d)", r);
2951                                 ret = ARCHIVE_FATAL;
2952                                 goto exit_mac_metadata;
2953                         }
2954                         bytes_used = zip->stream.total_in;
2955                         metadata_bytes -= zip->stream.total_out;
2956                         mp += zip->stream.total_out;
2957                         break;
2958                 }
2959 #endif
2960                 default:
2961                         bytes_used = 0;
2962                         break;
2963                 }
2964                 __archive_read_consume(a, bytes_used);
2965                 remaining_bytes -= bytes_used;
2966         }
2967         archive_entry_copy_mac_metadata(entry, metadata,
2968             (size_t)rsrc->uncompressed_size - metadata_bytes);
2969
2970 exit_mac_metadata:
2971         __archive_read_seek(a, offset, SEEK_SET);
2972         zip->decompress_init = 0;
2973         free(metadata);
2974         return (ret);
2975 }
2976
2977 static int
2978 archive_read_format_zip_seekable_read_header(struct archive_read *a,
2979         struct archive_entry *entry)
2980 {
2981         struct zip *zip = (struct zip *)a->format->data;
2982         struct zip_entry *rsrc;
2983         int64_t offset;
2984         int r, ret = ARCHIVE_OK;
2985
2986         /*
2987          * It should be sufficient to call archive_read_next_header() for
2988          * a reader to determine if an entry is encrypted or not. If the
2989          * encryption of an entry is only detectable when calling
2990          * archive_read_data(), so be it. We'll do the same check there
2991          * as well.
2992          */
2993         if (zip->has_encrypted_entries ==
2994                         ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
2995                 zip->has_encrypted_entries = 0;
2996
2997         a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
2998         if (a->archive.archive_format_name == NULL)
2999                 a->archive.archive_format_name = "ZIP";
3000
3001         if (zip->zip_entries == NULL) {
3002                 r = slurp_central_directory(a, zip);
3003                 if (r != ARCHIVE_OK)
3004                         return r;
3005                 /* Get first entry whose local header offset is lower than
3006                  * other entries in the archive file. */
3007                 zip->entry =
3008                     (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
3009         } else if (zip->entry != NULL) {
3010                 /* Get next entry in local header offset order. */
3011                 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
3012                     &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
3013         }
3014
3015         if (zip->entry == NULL)
3016                 return ARCHIVE_EOF;
3017
3018         if (zip->entry->rsrcname.s)
3019                 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
3020                     &zip->tree_rsrc, zip->entry->rsrcname.s);
3021         else
3022                 rsrc = NULL;
3023
3024         if (zip->cctx_valid)
3025                 archive_decrypto_aes_ctr_release(&zip->cctx);
3026         if (zip->hctx_valid)
3027                 archive_hmac_sha1_cleanup(&zip->hctx);
3028         zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3029         __archive_read_reset_passphrase(a);
3030
3031         /* File entries are sorted by the header offset, we should mostly
3032          * use __archive_read_consume to advance a read point to avoid redundant
3033          * data reading.  */
3034         offset = archive_filter_bytes(&a->archive, 0);
3035         if (offset < zip->entry->local_header_offset)
3036                 __archive_read_consume(a,
3037                     zip->entry->local_header_offset - offset);
3038         else if (offset != zip->entry->local_header_offset) {
3039                 __archive_read_seek(a, zip->entry->local_header_offset,
3040                     SEEK_SET);
3041         }
3042         zip->unconsumed = 0;
3043         r = zip_read_local_file_header(a, entry, zip);
3044         if (r != ARCHIVE_OK)
3045                 return r;
3046         if (rsrc) {
3047                 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
3048                 if (ret2 < ret)
3049                         ret = ret2;
3050         }
3051         return (ret);
3052 }
3053
3054 /*
3055  * We're going to seek for the next header anyway, so we don't
3056  * need to bother doing anything here.
3057  */
3058 static int
3059 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
3060 {
3061         struct zip *zip;
3062         zip = (struct zip *)(a->format->data);
3063
3064         zip->unconsumed = 0;
3065         return (ARCHIVE_OK);
3066 }
3067
3068 int
3069 archive_read_support_format_zip_seekable(struct archive *_a)
3070 {
3071         struct archive_read *a = (struct archive_read *)_a;
3072         struct zip *zip;
3073         int r;
3074
3075         archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3076             ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
3077
3078         zip = (struct zip *)calloc(1, sizeof(*zip));
3079         if (zip == NULL) {
3080                 archive_set_error(&a->archive, ENOMEM,
3081                     "Can't allocate zip data");
3082                 return (ARCHIVE_FATAL);
3083         }
3084
3085 #ifdef HAVE_COPYFILE_H
3086         /* Set this by default on Mac OS. */
3087         zip->process_mac_extensions = 1;
3088 #endif
3089
3090         /*
3091          * Until enough data has been read, we cannot tell about
3092          * any encrypted entries yet.
3093          */
3094         zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3095         zip->crc32func = real_crc32;
3096
3097         r = __archive_read_register_format(a,
3098             zip,
3099             "zip",
3100             archive_read_format_zip_seekable_bid,
3101             archive_read_format_zip_options,
3102             archive_read_format_zip_seekable_read_header,
3103             archive_read_format_zip_read_data,
3104             archive_read_format_zip_read_data_skip_seekable,
3105             NULL,
3106             archive_read_format_zip_cleanup,
3107             archive_read_support_format_zip_capabilities_seekable,
3108             archive_read_format_zip_has_encrypted_entries);
3109
3110         if (r != ARCHIVE_OK)
3111                 free(zip);
3112         return (ARCHIVE_OK);
3113 }