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