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