2 * Copyright (c) 2004-2013 Tim Kientzle
3 * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
4 * Copyright (c) 2013 Konrad Kleine
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
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.
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.
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD$");
32 * The definitive documentation of the Zip file format is:
33 * http://www.pkware.com/documents/casestudies/APPNOTE.TXT
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
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.
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"
68 #include "archive_crc32.h"
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;
79 struct archive_string rsrcname;
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 */
91 /* WinZip AES encryption extra field should be available
92 * when compression is 99. */
94 /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
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. */
101 /* Actual compression method. */
102 unsigned char compression;
106 struct trad_enc_ctx {
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)
119 /* Bits used in flags. */
120 #define LA_USED_ZIP64 (1 << 0)
121 #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
124 * See "WinZip - AES Encryption Information"
125 * http://www.winzip.com/aes_info.htm
127 /* Value used in compression method. */
128 #define WINZIP_AES_ENCRYPTION 99
129 /* Authentication code size. */
130 #define AUTH_CODE_SIZE 10
132 #define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
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;
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;
147 /* Bytes read but not yet consumed via __archive_read_consume() */
150 /* Information about entry we're currently reading. */
151 struct zip_entry *entry;
152 int64_t entry_bytes_remaining;
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;
158 /* Running CRC32 of the decompressed data */
159 unsigned long entry_crc32;
160 unsigned long (*crc32func)(unsigned long, const void *,
164 /* Flags to mark progress of decompression. */
165 char decompress_init;
169 unsigned char *uncompressed_buffer;
170 size_t uncompressed_buffer_size;
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;
181 char init_decryption;
183 /* Decryption buffer. */
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.
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;
198 /* Traditional PKWARE decryption. */
199 struct trad_enc_ctx tctx;
202 /* WinZip AES decyption. */
203 /* Contexts used for AES decryption. */
204 archive_crypto_ctx cctx;
206 archive_hmac_sha1_ctx hctx;
209 /* Strong encryption's decryption header information. */
222 /* Many systems define min or MIN, but not all. */
223 #define zipmin(a,b) ((a) < (b) ? (a) : (b))
225 /* ------------------------------------------------------------------------ */
228 Traditional PKWARE Decryption functions.
232 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
235 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
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);
245 trad_enc_decypt_byte(struct trad_enc_ctx *ctx)
247 unsigned temp = ctx->keys[2] | 2;
248 return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
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)
257 max = (unsigned)((in_len < out_len)? in_len: out_len);
259 for (i = 0; i < max; i++) {
260 uint8_t t = in[i] ^ trad_enc_decypt_byte(ctx);
262 trad_enc_update_keys(ctx, t);
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)
277 ctx->keys[0] = 305419896L;
278 ctx->keys[1] = 591751049L;
279 ctx->keys[2] = 878082192L;
281 for (;pw_len; --pw_len)
282 trad_enc_update_keys(ctx, *pw++);
284 trad_enc_decrypt_update(ctx, key, 12, header, 12);
285 /* Return the last byte for CRC check. */
286 *crcchk = header[11];
292 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
296 archive_sha1_ctx ctx;
297 unsigned char md1[MD_SIZE];
298 unsigned char md2[MD_SIZE * 2];
299 unsigned char mkb[64];
302 archive_sha1_init(&ctx);
303 archive_sha1_update(&ctx, p, size);
304 archive_sha1_final(&ctx, md1);
306 memset(mkb, 0x36, sizeof(mkb));
307 for (i = 0; i < MD_SIZE; i++)
309 archive_sha1_init(&ctx);
310 archive_sha1_update(&ctx, mkb, sizeof(mkb));
311 archive_sha1_final(&ctx, md2);
313 memset(mkb, 0x5C, sizeof(mkb));
314 for (i = 0; i < MD_SIZE; i++)
316 archive_sha1_init(&ctx);
317 archive_sha1_update(&ctx, mkb, sizeof(mkb));
318 archive_sha1_final(&ctx, md2 + MD_SIZE);
322 memcpy(key, md2, key_size);
328 * Common code for streaming or seeking modes.
330 * Includes code to read local file headers, decompress data
331 * from entry bodies, and common API.
335 real_crc32(unsigned long crc, const void *buff, size_t len)
337 return crc32(crc, buff, (unsigned int)len);
340 /* Used by "ignorecrc32" option to speed up tests. */
342 fake_crc32(unsigned long crc, const void *buff, size_t len)
344 (void)crc; /* UNUSED */
345 (void)buff; /* UNUSED */
346 (void)len; /* UNUSED */
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
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 */
381 compression_name(const int compression)
383 static const int num_compression_methods =
384 sizeof(compression_methods)/sizeof(compression_methods[0]);
387 while(compression >= 0 && i < num_compression_methods) {
388 if (compression_methods[i].id == compression)
389 return compression_methods[i].name;
395 /* Convert an MSDOS-style date/time into Unix-style time. */
397 zip_time(const char *p)
402 msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
403 msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
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;
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.
422 process_extra(const char *p, size_t extra_length, struct zip_entry* zip_entry)
426 while (offset < extra_length - 4) {
427 unsigned short headerid = archive_le16dec(p + offset);
428 unsigned short datasize = archive_le16dec(p + offset + 2);
431 if (offset + datasize > extra_length) {
435 fprintf(stderr, "Header id 0x%04x, length %d\n",
440 /* Zip64 extended information extra field. */
441 zip_entry->flags |= LA_USED_ZIP64;
442 if (zip_entry->uncompressed_size == 0xffffffff) {
445 zip_entry->uncompressed_size =
446 archive_le64dec(p + offset);
450 if (zip_entry->compressed_size == 0xffffffff) {
453 zip_entry->compressed_size =
454 archive_le64dec(p + offset);
458 if (zip_entry->local_header_offset == 0xffffffff) {
461 zip_entry->local_header_offset =
462 archive_le64dec(p + offset);
466 /* archive_le32dec(p + offset) gives disk
467 * on which file starts, but we don't handle
468 * multi-volume Zip files. */
473 /* Strong encryption field. */
474 if (archive_le16dec(p + offset) == 2) {
476 archive_le16dec(p + offset + 2);
478 archive_le16dec(p + offset + 4);
480 archive_le16dec(p + offset + 6);
481 fprintf(stderr, "algId=0x%04x, bitLen=%u, "
482 "flgas=%d\n", algId, bitLen,flags);
489 /* Extended time field "UT". */
490 int flags = p[offset];
493 /* Flag bits indicate which dates are present. */
497 fprintf(stderr, "mtime: %lld -> %d\n",
498 (long long)zip_entry->mtime,
499 archive_le32dec(p + offset));
503 zip_entry->mtime = archive_le32dec(p + offset);
511 zip_entry->atime = archive_le32dec(p + offset);
519 zip_entry->ctime = archive_le32dec(p + offset);
527 /* Info-ZIP Unix Extra Field (old version) "UX". */
529 zip_entry->atime = archive_le32dec(p + offset);
531 archive_le32dec(p + offset + 4);
533 if (datasize >= 12) {
535 archive_le16dec(p + offset + 8);
537 archive_le16dec(p + offset + 10);
543 /* Experimental 'xl' field */
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.
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
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.
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
570 int bitmap, bitmap_last;
574 bitmap_last = bitmap = 0xff & p[offset];
578 /* We only support first 7 bits of bitmap; skip rest. */
579 while ((bitmap_last & 0x80) != 0
581 bitmap_last = p[offset];
587 /* 2 byte "version made by" */
591 = archive_le16dec(p + offset) >> 8;
596 /* 2 byte "internal file attributes" */
597 uint32_t internal_attributes;
601 = archive_le16dec(p + offset);
602 /* Not used by libarchive at present. */
603 (void)internal_attributes; /* UNUSED */
608 /* 4 byte "external file attributes" */
609 uint32_t external_attributes;
613 = archive_le32dec(p + offset);
614 if (zip_entry->system == 3) {
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;
622 zip_entry->mode = AE_IFREG | 0664;
624 if (0x01 == (external_attributes & 0x01)) {
625 // Read-only bit; strip write permissions
626 zip_entry->mode &= 0555;
635 /* 2 byte comment length + comment */
636 uint32_t comment_length;
640 = archive_le16dec(p + offset);
644 if (datasize < comment_length)
646 /* Comment is not supported by libarchive */
647 offset += comment_length;
648 datasize -= comment_length;
653 /* Info-ZIP Unix Extra Field (type 2) "Ux". */
655 fprintf(stderr, "uid %d gid %d\n",
656 archive_le16dec(p + offset),
657 archive_le16dec(p + offset + 2));
660 zip_entry->uid = archive_le16dec(p + offset);
663 archive_le16dec(p + offset + 2);
667 /* Info-Zip Unix Extra Field (type 3) "ux". */
668 int uidsize = 0, gidsize = 0;
670 /* TODO: support arbitrary uidsize/gidsize. */
671 if (datasize >= 1 && p[offset] == 1) {/* version=1 */
673 /* get a uid size. */
674 uidsize = 0xff & (int)p[offset+1];
679 else if (uidsize == 4 && datasize >= 6)
684 if (datasize >= (2 + uidsize + 3)) {
685 /* get a gid size. */
686 gidsize = 0xff & (int)p[offset+2+uidsize];
690 p+offset+2+uidsize+1);
691 else if (gidsize == 4 &&
692 datasize >= (2 + uidsize + 5))
695 p+offset+2+uidsize+1);
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 =
719 if (offset != extra_length)
722 "Extra data field contents do not match reported size!\n");
728 * Assumes file pointer is at beginning of local file header.
731 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
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;
745 /* Save a copy of the original for consistency checks. */
746 zip_entry_central_dir = *zip_entry;
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);
754 /* Setup default conversion. */
755 if (zip->sconv == NULL && !zip->init_default_conversion) {
757 archive_string_default_conversion_for_read(&(a->archive));
758 zip->init_default_conversion = 1;
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);
767 if (memcmp(p, "PK\003\004", 4) != 0) {
768 archive_set_error(&a->archive, -1, "Damaged Zip archive");
769 return ARCHIVE_FATAL;
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;
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];
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);
797 __archive_read_consume(a, 30);
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);
805 if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
806 /* The filename is stored to be UTF-8. */
807 if (zip->sconv_utf8 == NULL) {
809 archive_string_conversion_from_charset(
810 &a->archive, "UTF-8", 1);
811 if (zip->sconv_utf8 == NULL)
812 return (ARCHIVE_FATAL);
814 sconv = zip->sconv_utf8;
815 } else if (zip->sconv != NULL)
818 sconv = zip->sconv_default;
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);
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));
834 __archive_read_consume(a, filename_length);
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);
843 process_extra(h, extra_length, zip_entry);
844 __archive_read_consume(a, extra_length);
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;
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);
860 if (len > 0 && wp[len - 1] == L'/')
861 zip_entry->mode |= AE_IFDIR;
863 zip_entry->mode |= AE_IFREG;
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;
870 zip_entry->mode |= AE_IFREG;
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;
879 /* Make sure directories end in '/' */
880 if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
881 wp = archive_entry_pathname_w(entry);
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);
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);
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
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");
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);
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);
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);
956 if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
957 size_t linkname_length;
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;
965 linkname_length = (size_t)zip_entry->compressed_size;
967 archive_entry_set_size(entry, 0);
968 p = __archive_read_ahead(a, linkname_length, NULL);
970 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
971 "Truncated Zip file");
972 return ARCHIVE_FATAL;
976 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
977 sconv = zip->sconv_utf8;
979 sconv = zip->sconv_default;
980 if (archive_entry_copy_symlink_l(entry, p, linkname_length,
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);
992 * Since there is no character-set regulation for
993 * symlink name, do not report the conversion error
994 * in an automatic conversion.
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(
1007 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
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;
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);
1019 zip->entry_bytes_remaining = zip_entry->compressed_size;
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;
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;
1036 check_authentication_code(struct archive_read *a, const void *_p)
1038 struct zip *zip = (struct zip *)(a->format->data);
1040 /* Check authentication code. */
1041 if (zip->hctx_valid) {
1044 size_t hmac_len = 20;
1047 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1049 /* Read authentication code. */
1050 p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1052 archive_set_error(&a->archive,
1053 ARCHIVE_ERRNO_FILE_FORMAT,
1054 "Truncated ZIP file data");
1055 return (ARCHIVE_FATAL);
1060 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1061 __archive_read_consume(a, AUTH_CODE_SIZE);
1063 archive_set_error(&a->archive,
1065 "ZIP bad Authentication code");
1066 return (ARCHIVE_WARN);
1069 return (ARCHIVE_OK);
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.
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.
1090 * For uncompressed data, the PK\007\010 marker seems essential
1091 * to be sure we've actually seen the end of the entry.
1093 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1094 * zip->end_of_entry if it consumes all of the data.
1097 zip_read_data_none(struct archive_read *a, const void **_buff,
1098 size_t *size, int64_t *offset)
1102 ssize_t bytes_avail;
1105 (void)offset; /* UNUSED */
1107 zip = (struct zip *)(a->format->data);
1109 if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1111 ssize_t grabbing_bytes = 24;
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
1122 archive_set_error(&a->archive,
1123 ARCHIVE_ERRNO_FILE_FORMAT,
1124 "Truncated ZIP file data");
1125 return (ARCHIVE_FATAL);
1127 /* Check for a complete PK\007\010 signature, followed
1128 * by the correct 4-byte CRC. */
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
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;
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;
1153 if (zip->hctx_valid) {
1154 r = check_authentication_code(a, buff);
1155 if (r != ARCHIVE_OK)
1158 zip->end_of_entry = 1;
1159 return (ARCHIVE_OK);
1161 /* If not at EOF, ensure we consume at least one byte. */
1164 /* Scan forward until we see where a PK\007\010 signature
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;
1179 bytes_avail = p - buff;
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)
1188 return (ARCHIVE_OK);
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);
1198 if (bytes_avail > zip->entry_bytes_remaining)
1199 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1201 if (zip->tctx_valid || zip->cctx_valid) {
1202 size_t dec_size = bytes_avail;
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);
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);
1218 bytes_avail = dec_size;
1219 buff = (const char *)zip->decrypted_buffer;
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;
1227 return (ARCHIVE_OK);
1232 zip_deflate_init(struct archive_read *a, struct zip *zip)
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);
1241 r = inflateInit2(&zip->stream,
1242 -15 /* Don't check for zlib header */);
1244 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1245 "Can't initialize ZIP decompression.");
1246 return (ARCHIVE_FATAL);
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;
1253 return (ARCHIVE_OK);
1257 zip_read_data_deflate(struct archive_read *a, const void **buff,
1258 size_t *size, int64_t *offset)
1261 ssize_t bytes_avail;
1262 const void *compressed_buff, *sp;
1265 (void)offset; /* UNUSED */
1267 zip = (struct zip *)(a->format->data);
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);
1281 r = zip_deflate_init(a, zip);
1282 if (r != ARCHIVE_OK)
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.
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;
1296 if (bytes_avail <= 0) {
1297 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1298 "Truncated ZIP file body");
1299 return (ARCHIVE_FATAL);
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);
1308 if (buff_remaining > (size_t)bytes_avail)
1309 buff_remaining = (size_t)bytes_avail;
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
1315 > zip->entry_bytes_remaining) {
1316 if (zip->entry_bytes_remaining <
1317 (int64_t)zip->decrypted_bytes_remaining)
1321 (size_t)zip->entry_bytes_remaining
1322 - zip->decrypted_bytes_remaining;
1325 if (buff_remaining > 0) {
1326 if (zip->tctx_valid) {
1327 trad_enc_decrypt_update(&zip->tctx,
1328 compressed_buff, buff_remaining,
1330 + zip->decrypted_bytes_remaining,
1333 size_t dsize = buff_remaining;
1334 archive_decrypto_aes_ctr_update(
1336 compressed_buff, buff_remaining,
1338 + zip->decrypted_bytes_remaining,
1341 zip->decrypted_bytes_remaining += buff_remaining;
1344 bytes_avail = zip->decrypted_bytes_remaining;
1345 compressed_buff = (const char *)zip->decrypted_ptr;
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'.
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;
1361 r = inflate(&zip->stream, 0);
1366 zip->end_of_entry = 1;
1369 archive_set_error(&a->archive, ENOMEM,
1370 "Out of memory for ZIP decompression");
1371 return (ARCHIVE_FATAL);
1373 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1374 "ZIP decompression failed (%d)", r);
1375 return (ARCHIVE_FATAL);
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;
1385 zip->decrypted_ptr += bytes_avail;
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;
1394 *size = zip->stream.total_out;
1395 zip->entry_uncompressed_bytes_read += zip->stream.total_out;
1396 *buff = zip->uncompressed_buffer;
1398 if (zip->end_of_entry && zip->hctx_valid) {
1399 r = check_authentication_code(a, NULL);
1400 if (r != ARCHIVE_OK)
1404 if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
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);
1413 /* Consume the optional PK\007\010 marker. */
1414 if (p[0] == 'P' && p[1] == 'K' &&
1415 p[2] == '\007' && p[3] == '\010') {
1417 zip->unconsumed = 4;
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;
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;
1432 return (ARCHIVE_OK);
1437 read_decryption_header(struct archive_read *a)
1439 struct zip *zip = (struct zip *)(a->format->data);
1441 unsigned int remaining_size;
1445 * Read an initialization vector data field.
1447 p = __archive_read_ahead(a, 2, NULL);
1451 zip->iv_size = archive_le16dec(p);
1452 __archive_read_consume(a, 2);
1453 if (ts < zip->iv_size) {
1457 p = __archive_read_ahead(a, zip->iv_size, NULL);
1460 if (zip->iv == NULL) {
1461 zip->iv = malloc(zip->iv_size);
1462 if (zip->iv == NULL)
1465 memcpy(zip->iv, p, zip->iv_size);
1466 __archive_read_consume(a, zip->iv_size);
1469 * Read a size of remaining decryption header field.
1471 p = __archive_read_ahead(a, 14, NULL);
1474 remaining_size = archive_le32dec(p);
1475 if (remaining_size < 16 || remaining_size > (1 << 18))
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);
1488 * Read an encryption algorithm field.
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. */
1506 archive_set_error(&a->archive,
1507 ARCHIVE_ERRNO_FILE_FORMAT,
1508 "Unknown encryption algorithm: %u", zip->alg_id);
1509 return (ARCHIVE_FAILED);
1513 * Read a bit length field.
1515 zip->bit_len = archive_le16dec(p+8);
1518 * Read a flags field.
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. */
1527 archive_set_error(&a->archive,
1528 ARCHIVE_ERRNO_FILE_FORMAT,
1529 "Unknown encryption flag: %u", zip->flags);
1530 return (ARCHIVE_FAILED);
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);
1541 * Read an encrypted random data field.
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)
1551 if (ts < zip->erd_size) {
1555 p = __archive_read_ahead(a, zip->erd_size, NULL);
1558 if (zip->erd == NULL) {
1559 zip->erd = malloc(zip->erd_size);
1560 if (zip->erd == NULL)
1563 memcpy(zip->erd, p, zip->erd_size);
1564 __archive_read_consume(a, zip->erd_size);
1567 * Read a reserved data field.
1569 p = __archive_read_ahead(a, 4, NULL);
1572 /* Reserved data size should be zero. */
1573 if (archive_le32dec(p) != 0)
1575 __archive_read_consume(a, 4);
1578 * Read a password validation data field.
1580 p = __archive_read_ahead(a, 2, NULL);
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))
1590 if (ts < zip->v_size) {
1594 p = __archive_read_ahead(a, zip->v_size, NULL);
1597 if (zip->v_data == NULL) {
1598 zip->v_data = malloc(zip->v_size);
1599 if (zip->v_data == NULL)
1602 memcpy(zip->v_data, p, zip->v_size);
1603 __archive_read_consume(a, zip->v_size);
1605 p = __archive_read_ahead(a, 4, NULL);
1608 zip->v_crc32 = archive_le32dec(p);
1609 __archive_read_consume(a, 4);
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);
1617 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1618 "Truncated ZIP file data");
1619 return (ARCHIVE_FATAL);
1621 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1622 "Corrupted ZIP file data");
1623 return (ARCHIVE_FATAL);
1625 archive_set_error(&a->archive, ENOMEM,
1626 "No memory for ZIP decryption");
1627 return (ARCHIVE_FATAL);
1631 zip_alloc_decryption_buffer(struct archive_read *a)
1633 struct zip *zip = (struct zip *)(a->format->data);
1634 size_t bs = 256 * 1024;
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);
1645 zip->decrypted_ptr = zip->decrypted_buffer;
1646 return (ARCHIVE_OK);
1650 init_traditional_PKWARE_decryption(struct archive_read *a)
1652 struct zip *zip = (struct zip *)(a->format->data);
1657 if (zip->tctx_valid)
1658 return (ARCHIVE_OK);
1661 Read the 12 bytes encryption header stored at
1662 the start of the data area.
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);
1673 p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
1675 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1676 "Truncated ZIP file data");
1677 return (ARCHIVE_FATAL);
1680 for (retry = 0;; retry++) {
1681 const char *passphrase;
1684 passphrase = __archive_read_next_passphrase(a);
1685 if (passphrase == NULL) {
1686 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1688 "Incorrect passphrase":
1689 "Passphrase required for this entry");
1690 return (ARCHIVE_FAILED);
1694 * Initialize ctx for Traditional PKWARE Decyption.
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);
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;
1713 /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
1714 zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
1715 zip->decrypted_bytes_remaining = 0;
1717 return (zip_alloc_decryption_buffer(a));
1718 #undef ENC_HEADER_SIZE
1722 init_WinZip_AES_decryption(struct archive_read *a)
1724 struct zip *zip = (struct zip *)(a->format->data);
1727 size_t key_len, salt_len;
1728 uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
1732 if (zip->cctx_valid || zip->hctx_valid)
1733 return (ARCHIVE_OK);
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;
1741 p = __archive_read_ahead(a, salt_len + 2, NULL);
1745 for (retry = 0;; retry++) {
1746 const char *passphrase;
1748 passphrase = __archive_read_next_passphrase(a);
1749 if (passphrase == NULL) {
1750 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1752 "Incorrect passphrase":
1753 "Passphrase required for this entry");
1754 return (ARCHIVE_FAILED);
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);
1760 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1761 "Decryption is unsupported due to lack of "
1763 return (ARCHIVE_FAILED);
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);
1779 r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
1781 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1782 "Decryption is unsupported due to lack of crypto library");
1783 return (ARCHIVE_FAILED);
1785 r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
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);
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)
1798 zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
1799 zip->decrypted_bytes_remaining = 0;
1801 zip->entry->compression = zip->entry->aes_extra.compression;
1802 return (zip_alloc_decryption_buffer(a));
1805 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1806 "Truncated ZIP file data");
1807 return (ARCHIVE_FATAL);
1809 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1810 "Corrupted ZIP file data");
1811 return (ARCHIVE_FATAL);
1815 archive_read_format_zip_read_data(struct archive_read *a,
1816 const void **buff, size_t *size, int64_t *offset)
1819 struct zip *zip = (struct zip *)(a->format->data);
1821 if (zip->has_encrypted_entries ==
1822 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
1823 zip->has_encrypted_entries = 0;
1826 *offset = zip->entry_uncompressed_bytes_read;
1830 /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
1831 if (zip->end_of_entry)
1832 return (ARCHIVE_EOF);
1834 /* Return EOF immediately if this is a non-regular file. */
1835 if (AE_IFREG != (zip->entry->mode & AE_IFMT))
1836 return (ARCHIVE_EOF);
1838 __archive_read_consume(a, zip->unconsumed);
1839 zip->unconsumed = 0;
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);
1848 r = init_traditional_PKWARE_decryption(a);
1849 if (r != ARCHIVE_OK)
1851 zip->init_decryption = 0;
1854 switch(zip->entry->compression) {
1855 case 0: /* No compression. */
1856 r = zip_read_data_none(a, buff, size, offset);
1859 case 8: /* Deflate compression. */
1860 r = zip_read_data_deflate(a, buff, size, offset);
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);
1873 if (r != ARCHIVE_OK)
1875 /* Update checksum */
1877 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
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);
1891 /* Size field only stores the lower 32 bits of the actual
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);
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);
1915 return (ARCHIVE_OK);
1919 archive_read_format_zip_cleanup(struct archive_read *a)
1922 struct zip_entry *zip_entry, *next_zip_entry;
1924 zip = (struct zip *)(a->format->data);
1926 if (zip->stream_valid)
1927 inflateEnd(&zip->stream);
1928 free(zip->uncompressed_buffer);
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);
1936 zip_entry = next_zip_entry;
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);
1947 archive_string_free(&zip->format_name);
1949 (a->format->data) = NULL;
1950 return (ARCHIVE_OK);
1954 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
1956 if (_a && _a->format) {
1957 struct zip * zip = (struct zip *)_a->format->data;
1959 return zip->has_encrypted_entries;
1962 return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
1966 archive_read_format_zip_options(struct archive_read *a,
1967 const char *key, const char *val)
1970 int ret = ARCHIVE_FAILED;
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"
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;
1990 ret = ARCHIVE_FATAL;
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;
1999 zip->crc32func = fake_crc32;
2000 zip->ignore_crc32 = 1;
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);
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);
2015 archive_read_support_format_zip(struct archive *a)
2018 r = archive_read_support_format_zip_streamable(a);
2019 if (r != ARCHIVE_OK)
2021 return (archive_read_support_format_zip_seekable(a));
2024 /* ------------------------------------------------------------------------ */
2027 * Streaming-mode support
2032 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
2034 (void)a; /* UNUSED */
2035 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2036 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2040 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
2044 (void)best_bid; /* UNUSED */
2046 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
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
2055 * So we've effectively verified ~29 total bits of check data.
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'))
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. */
2076 archive_read_format_zip_streamable_read_header(struct archive_read *a,
2077 struct archive_entry *entry)
2081 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
2082 if (a->archive.archive_format_name == NULL)
2083 a->archive.archive_format_name = "ZIP";
2085 zip = (struct zip *)(a->format->data);
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
2094 if (zip->has_encrypted_entries ==
2095 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
2096 zip->has_encrypted_entries = 0;
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,
2104 return ARCHIVE_FATAL;
2107 zip->entry = zip->zip_entries;
2108 memset(zip->entry, 0, sizeof(struct zip_entry));
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);
2117 /* Search ahead for the next local file header. */
2118 __archive_read_consume(a, zip->unconsumed);
2119 zip->unconsumed = 0;
2121 int64_t skipped = 0;
2122 const char *p, *end;
2125 p = __archive_read_ahead(a, 4, &bytes);
2127 return (ARCHIVE_FATAL);
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,
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.
2148 * This won't help us fix symlinks
2149 * and may not help with regular file
2150 * permissions, either. <sigh>
2152 if (p[2] == '\001' && p[3] == '\002') {
2153 return (ARCHIVE_EOF);
2156 /* End of central directory? Must be an
2158 if ((p[2] == '\005' && p[3] == '\006')
2159 || (p[2] == '\006' && p[3] == '\006'))
2160 return (ARCHIVE_EOF);
2165 __archive_read_consume(a, skipped);
2170 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
2173 int64_t bytes_skipped;
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);
2181 /* If we've already read to end of data, we're done. */
2182 if (zip->end_of_entry)
2183 return (ARCHIVE_OK);
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);
2196 if (zip->init_decryption) {
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);
2205 r = init_traditional_PKWARE_decryption(a);
2206 if (r != ARCHIVE_OK)
2208 zip->init_decryption = 0;
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) {
2216 case 8: /* Deflate compression. */
2217 while (!zip->end_of_entry) {
2219 const void *buff = NULL;
2222 r = zip_read_data_deflate(a, &buff, &size, &offset);
2223 if (r != ARCHIVE_OK)
2228 default: /* Uncompressed or unknown. */
2229 /* Scan for a PK\007\010 signature. */
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);
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,
2251 __archive_read_consume(a,
2256 __archive_read_consume(a, p - buff);
2262 archive_read_support_format_zip_streamable(struct archive *_a)
2264 struct archive_read *a = (struct archive_read *)_a;
2268 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
2269 ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
2271 zip = (struct zip *)calloc(1, sizeof(*zip));
2273 archive_set_error(&a->archive, ENOMEM,
2274 "Can't allocate zip data");
2275 return (ARCHIVE_FATAL);
2278 /* Streamable reader doesn't support mac extensions. */
2279 zip->process_mac_extensions = 0;
2282 * Until enough data has been read, we cannot tell about
2283 * any encrypted entries yet.
2285 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2286 zip->crc32func = real_crc32;
2288 r = __archive_read_register_format(a,
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,
2297 archive_read_format_zip_cleanup,
2298 archive_read_support_format_zip_capabilities_streamable,
2299 archive_read_format_zip_has_encrypted_entries);
2301 if (r != ARCHIVE_OK)
2303 return (ARCHIVE_OK);
2306 /* ------------------------------------------------------------------------ */
2309 * Seeking-mode support
2313 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
2315 (void)a; /* UNUSED */
2316 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2317 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
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.
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...
2330 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
2332 /* Sanity-check the EOCD we've found. */
2334 /* This must be the first volume. */
2335 if (archive_le16dec(p + 4) != 0)
2337 /* Central directory must be on this volume. */
2338 if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
2340 /* All central directory entries must be on this volume. */
2341 if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
2343 /* Central directory can't extend beyond start of EOCD record. */
2344 if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
2348 /* Save the central directory location for later use. */
2349 zip->central_directory_offset = archive_le32dec(p + 16);
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. */
2359 * Examine Zip64 EOCD locator: If it's valid, store the information
2363 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
2365 int64_t eocd64_offset;
2366 int64_t eocd64_size;
2368 /* Sanity-check the locator record. */
2370 /* Central dir must be on first volume. */
2371 if (archive_le32dec(p + 4) != 0)
2373 /* Must be only a single volume. */
2374 if (archive_le32dec(p + 16) != 1)
2377 /* Find the Zip64 EOCD record. */
2378 eocd64_offset = archive_le64dec(p + 8);
2379 if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
2381 if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
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)
2387 if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
2390 /* Sanity-check the EOCD64 */
2391 if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
2393 if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
2395 /* CD can't be split. */
2396 if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
2399 /* Save the central directory offset for later use. */
2400 zip->central_directory_offset = archive_le64dec(p + 48);
2404 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
2406 struct zip *zip = (struct zip *)a->format->data;
2407 int64_t file_size, current_offset;
2411 /* If someone has already bid more than 32, then avoid
2412 trashing the look-ahead buffers with a seek. */
2416 file_size = __archive_read_seek(a, 0, SEEK_END);
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)
2426 if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
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;) {
2435 if (memcmp(p + i, "PK\005\006", 4) == 0) {
2436 int ret = read_eocd(zip, p + i,
2437 current_offset + i);
2439 /* Zip64 EOCD locator precedes
2440 * regular EOCD if present. */
2442 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
2443 read_zip64_eocd(a, zip, p + i - 20);
2450 case 'K': i -= 1; break;
2451 case 005: i -= 2; break;
2452 case 006: i -= 3; break;
2453 default: i -= 4; break;
2459 /* The red-black trees are only used in seeking mode to manage
2460 * the in-memory copy of the central directory. */
2463 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
2465 const struct zip_entry *e1 = (const struct zip_entry *)n1;
2466 const struct zip_entry *e2 = (const struct zip_entry *)n2;
2468 if (e1->local_header_offset > e2->local_header_offset)
2470 if (e1->local_header_offset < e2->local_header_offset)
2476 cmp_key(const struct archive_rb_node *n, const void *key)
2478 /* This function won't be called */
2479 (void)n; /* UNUSED */
2480 (void)key; /* UNUSED */
2484 static const struct archive_rb_tree_ops rb_ops = {
2489 rsrc_cmp_node(const struct archive_rb_node *n1,
2490 const struct archive_rb_node *n2)
2492 const struct zip_entry *e1 = (const struct zip_entry *)n1;
2493 const struct zip_entry *e2 = (const struct zip_entry *)n2;
2495 return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
2499 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
2501 const struct zip_entry *e = (const struct zip_entry *)n;
2502 return (strcmp((const char *)key, e->rsrcname.s));
2505 static const struct archive_rb_tree_ops rb_rsrc_ops = {
2506 &rsrc_cmp_node, &rsrc_cmp_key
2510 rsrc_basename(const char *name, size_t name_length)
2516 s = memchr(s, '/', name_length - (s - name));
2525 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
2527 struct archive_string str;
2528 struct zip_entry *dir;
2531 archive_string_init(&str);
2532 archive_strncpy(&str, name, name_length);
2534 s = strrchr(str.s, '/');
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);
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);
2548 archive_string_free(&str);
2552 slurp_central_directory(struct archive_read *a, struct zip *zip)
2557 ssize_t bytes_avail;
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
2570 if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
2571 return ARCHIVE_FATAL;
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;) {
2579 case 'P': i += 3; break;
2580 case 'K': i += 2; break;
2581 case 001: i += 1; break;
2583 if (memcmp(p + i, "PK\001\002", 4) == 0) {
2589 case 005: i += 1; break;
2591 if (memcmp(p + i, "PK\005\006", 4) == 0) {
2594 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
2600 default: i += 4; break;
2603 __archive_read_consume(a, i);
2605 correction = archive_filter_bytes(&a->archive, 0)
2606 - zip->central_directory_offset;
2608 __archive_rb_tree_init(&zip->tree, &rb_ops);
2609 __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
2611 zip->central_directory_entries_total = 0;
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;
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) {
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;
2628 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
2629 return ARCHIVE_FATAL;
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++;
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;
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];
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;
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;
2673 zip_entry->mode = AE_IFREG | 0664;
2675 if (0x01 == (external_attributes & 0x01)) {
2676 // Read-only bit; strip write permissions
2677 zip_entry->mode &= 0555;
2680 zip_entry->mode = 0;
2683 /* We're done with the regular data; get the filename and
2685 __archive_read_consume(a, 46);
2686 p = __archive_read_ahead(a, filename_length + extra_length,
2689 archive_set_error(&a->archive,
2690 ARCHIVE_ERRNO_FILE_FORMAT,
2691 "Truncated ZIP file header");
2692 return ARCHIVE_FATAL;
2694 process_extra(p + filename_length, extra_length, zip_entry);
2697 * Mac resource fork files are stored under the
2698 * "__MACOSX/" directory, so we should check if
2701 if (!zip->process_mac_extensions) {
2702 /* Treat every entry as a regular entry. */
2703 __archive_rb_tree_insert_node(&zip->tree,
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,
2721 /* This file is a resource fork file or
2723 archive_strncpy(&(zip_entry->rsrcname),
2724 name, filename_length);
2725 __archive_rb_tree_insert_node(
2726 &zip->tree_rsrc, &zip_entry->node);
2729 /* Generate resource fork name to find its
2730 * resource file at zip->tree_rsrc. */
2731 archive_strcpy(&(zip_entry->rsrcname),
2733 archive_strncat(&(zip_entry->rsrcname),
2735 archive_strcat(&(zip_entry->rsrcname), "._");
2736 archive_strncat(&(zip_entry->rsrcname),
2738 filename_length - (r - name));
2739 /* Register an entry to RB tree to sort it by
2741 __archive_rb_tree_insert_node(&zip->tree,
2746 /* Skip the comment too ... */
2747 __archive_read_consume(a,
2748 filename_length + extra_length + comment_length);
2755 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
2758 ssize_t filename_length, extra_length;
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);
2767 if (memcmp(p, "PK\003\004", 4) != 0) {
2768 archive_set_error(&a->archive, -1, "Damaged Zip archive");
2769 return ARCHIVE_WARN;
2771 filename_length = archive_le16dec(p + 26);
2772 extra_length = archive_le16dec(p + 28);
2774 return (30 + filename_length + extra_length);
2778 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
2779 struct zip_entry *rsrc)
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;
2786 int ret = ARCHIVE_OK, eof;
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);
2796 case 8: /* Deflate compression. */
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);
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);
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);
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);
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);
2835 hsize = zip_get_local_file_header_size(a, 0);
2836 __archive_read_consume(a, hsize);
2838 remaining_bytes = (size_t)rsrc->compressed_size;
2839 metadata_bytes = (size_t)rsrc->uncompressed_size;
2842 while (!eof && remaining_bytes) {
2843 const unsigned char *p;
2844 ssize_t bytes_avail;
2847 p = __archive_read_ahead(a, 1, &bytes_avail);
2849 archive_set_error(&a->archive,
2850 ARCHIVE_ERRNO_FILE_FORMAT,
2851 "Truncated ZIP file header");
2853 goto exit_mac_metadata;
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;
2865 if (metadata_bytes == 0)
2869 case 8: /* Deflate compression. */
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;
2884 r = inflate(&zip->stream, 0);
2892 archive_set_error(&a->archive, ENOMEM,
2893 "Out of memory for ZIP decompression");
2894 ret = ARCHIVE_FATAL;
2895 goto exit_mac_metadata;
2897 archive_set_error(&a->archive,
2899 "ZIP decompression failed (%d)", r);
2900 ret = ARCHIVE_FATAL;
2901 goto exit_mac_metadata;
2903 bytes_used = zip->stream.total_in;
2904 metadata_bytes -= zip->stream.total_out;
2905 mp += zip->stream.total_out;
2913 __archive_read_consume(a, bytes_used);
2914 remaining_bytes -= bytes_used;
2916 archive_entry_copy_mac_metadata(entry, metadata,
2917 (size_t)rsrc->uncompressed_size - metadata_bytes);
2920 __archive_read_seek(a, offset, SEEK_SET);
2921 zip->decompress_init = 0;
2927 archive_read_format_zip_seekable_read_header(struct archive_read *a,
2928 struct archive_entry *entry)
2930 struct zip *zip = (struct zip *)a->format->data;
2931 struct zip_entry *rsrc;
2933 int r, ret = ARCHIVE_OK;
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
2942 if (zip->has_encrypted_entries ==
2943 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
2944 zip->has_encrypted_entries = 0;
2946 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
2947 if (a->archive.archive_format_name == NULL)
2948 a->archive.archive_format_name = "ZIP";
2950 if (zip->zip_entries == NULL) {
2951 r = slurp_central_directory(a, zip);
2952 if (r != ARCHIVE_OK)
2954 /* Get first entry whose local header offset is lower than
2955 * other entries in the archive file. */
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);
2964 if (zip->entry == NULL)
2967 if (zip->entry->rsrcname.s)
2968 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
2969 &zip->tree_rsrc, zip->entry->rsrcname.s);
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);
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
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,
2991 zip->unconsumed = 0;
2992 r = zip_read_local_file_header(a, entry, zip);
2993 if (r != ARCHIVE_OK)
2996 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
3004 * We're going to seek for the next header anyway, so we don't
3005 * need to bother doing anything here.
3008 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
3011 zip = (struct zip *)(a->format->data);
3013 zip->unconsumed = 0;
3014 return (ARCHIVE_OK);
3018 archive_read_support_format_zip_seekable(struct archive *_a)
3020 struct archive_read *a = (struct archive_read *)_a;
3024 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3025 ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
3027 zip = (struct zip *)calloc(1, sizeof(*zip));
3029 archive_set_error(&a->archive, ENOMEM,
3030 "Can't allocate zip data");
3031 return (ARCHIVE_FATAL);
3034 #ifdef HAVE_COPYFILE_H
3035 /* Set this by default on Mac OS. */
3036 zip->process_mac_extensions = 1;
3040 * Until enough data has been read, we cannot tell about
3041 * any encrypted entries yet.
3043 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3044 zip->crc32func = real_crc32;
3046 r = __archive_read_register_format(a,
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,
3055 archive_read_format_zip_cleanup,
3056 archive_read_support_format_zip_capabilities_seekable,
3057 archive_read_format_zip_has_encrypted_entries);
3059 if (r != ARCHIVE_OK)
3061 return (ARCHIVE_OK);