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: head/lib/libarchive/archive_read_support_format_zip.c 201102 2009-12-28 03:11:36Z kientzle $");
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.
63 #include "archive_digest_private.h"
64 #include "archive_cryptor_private.h"
65 #include "archive_endian.h"
66 #include "archive_entry.h"
67 #include "archive_entry_locale.h"
68 #include "archive_hmac_private.h"
69 #include "archive_private.h"
70 #include "archive_rb.h"
71 #include "archive_read_private.h"
72 #include "archive_ppmd8_private.h"
75 #include "archive_crc32.h"
79 struct archive_rb_node node;
80 struct zip_entry *next;
81 int64_t local_header_offset;
82 int64_t compressed_size;
83 int64_t uncompressed_size;
86 struct archive_string rsrcname;
92 uint16_t zip_flags; /* From GP Flags Field */
93 unsigned char compression;
94 unsigned char system; /* From "version written by" */
95 unsigned char flags; /* Our extra markers. */
96 unsigned char decdat;/* Used for Decryption check */
98 /* WinZip AES encryption extra field should be available
99 * when compression is 99. */
101 /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
103 #define AES_VENDOR_AE_1 0x0001
104 #define AES_VENDOR_AE_2 0x0002
105 /* AES encryption strength:
106 * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
108 /* Actual compression method. */
109 unsigned char compression;
113 struct trad_enc_ctx {
117 /* Bits used in zip_flags. */
118 #define ZIP_ENCRYPTED (1 << 0)
119 #define ZIP_LENGTH_AT_END (1 << 3)
120 #define ZIP_STRONG_ENCRYPTED (1 << 6)
121 #define ZIP_UTF8_NAME (1 << 11)
122 /* See "7.2 Single Password Symmetric Encryption Method"
123 in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
124 #define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
126 /* Bits used in flags. */
127 #define LA_USED_ZIP64 (1 << 0)
128 #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
131 * See "WinZip - AES Encryption Information"
132 * http://www.winzip.com/aes_info.htm
134 /* Value used in compression method. */
135 #define WINZIP_AES_ENCRYPTION 99
136 /* Authentication code size. */
137 #define AUTH_CODE_SIZE 10
139 #define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
142 /* Structural information about the archive. */
143 struct archive_string format_name;
144 int64_t central_directory_offset;
145 size_t central_directory_entries_total;
146 size_t central_directory_entries_on_this_disk;
147 int has_encrypted_entries;
149 /* List of entries (seekable Zip only) */
150 struct zip_entry *zip_entries;
151 struct archive_rb_tree tree;
152 struct archive_rb_tree tree_rsrc;
154 /* Bytes read but not yet consumed via __archive_read_consume() */
157 /* Information about entry we're currently reading. */
158 struct zip_entry *entry;
159 int64_t entry_bytes_remaining;
161 /* These count the number of bytes actually read for the entry. */
162 int64_t entry_compressed_bytes_read;
163 int64_t entry_uncompressed_bytes_read;
165 /* Running CRC32 of the decompressed data */
166 unsigned long entry_crc32;
167 unsigned long (*crc32func)(unsigned long, const void *,
171 /* Flags to mark progress of decompression. */
172 char decompress_init;
175 unsigned char *uncompressed_buffer;
176 size_t uncompressed_buffer_size;
183 #if HAVE_LZMA_H && HAVE_LIBLZMA
184 lzma_stream zipx_lzma_stream;
185 char zipx_lzma_valid;
193 IByteIn zipx_ppmd_stream;
194 ssize_t zipx_ppmd_read_compressed;
197 char ppmd8_stream_failed;
199 struct archive_string_conv *sconv;
200 struct archive_string_conv *sconv_default;
201 struct archive_string_conv *sconv_utf8;
202 int init_default_conversion;
203 int process_mac_extensions;
205 char init_decryption;
207 /* Decryption buffer. */
209 * The decrypted data starts at decrypted_ptr and
210 * extends for decrypted_bytes_remaining. Decryption
211 * adds new data to the end of this block, data is returned
212 * to clients from the beginning. When the block hits the
213 * end of decrypted_buffer, it has to be shuffled back to
214 * the beginning of the buffer.
216 unsigned char *decrypted_buffer;
217 unsigned char *decrypted_ptr;
218 size_t decrypted_buffer_size;
219 size_t decrypted_bytes_remaining;
220 size_t decrypted_unconsumed_bytes;
222 /* Traditional PKWARE decryption. */
223 struct trad_enc_ctx tctx;
226 /* WinZip AES decryption. */
227 /* Contexts used for AES decryption. */
228 archive_crypto_ctx cctx;
230 archive_hmac_sha1_ctx hctx;
233 /* Strong encryption's decryption header information. */
246 /* Many systems define min or MIN, but not all. */
247 #define zipmin(a,b) ((a) < (b) ? (a) : (b))
249 /* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8
250 * streams inside ZIP files. It has 2 purposes: one is to fetch the next
251 * compressed byte from the stream, second one is to increase the counter how
252 * many compressed bytes were read. */
255 /* Get the handle to current decompression context. */
256 struct archive_read *a = ((IByteIn*)p)->a;
257 struct zip *zip = (struct zip*) a->format->data;
258 ssize_t bytes_avail = 0;
260 /* Fetch next byte. */
261 const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail);
262 if(bytes_avail < 1) {
263 zip->ppmd8_stream_failed = 1;
267 __archive_read_consume(a, 1);
269 /* Increment the counter. */
270 ++zip->zipx_ppmd_read_compressed;
272 /* Return the next compressed byte. */
276 /* ------------------------------------------------------------------------ */
279 Traditional PKWARE Decryption functions.
283 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
286 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
288 ctx->keys[0] = CRC32(ctx->keys[0], c);
289 ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
290 t = (ctx->keys[1] >> 24) & 0xff;
291 ctx->keys[2] = CRC32(ctx->keys[2], t);
296 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
298 unsigned temp = ctx->keys[2] | 2;
299 return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
303 trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
304 size_t in_len, uint8_t *out, size_t out_len)
308 max = (unsigned)((in_len < out_len)? in_len: out_len);
310 for (i = 0; i < max; i++) {
311 uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
313 trad_enc_update_keys(ctx, t);
318 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
319 const uint8_t *key, size_t key_len, uint8_t *crcchk)
328 ctx->keys[0] = 305419896L;
329 ctx->keys[1] = 591751049L;
330 ctx->keys[2] = 878082192L;
332 for (;pw_len; --pw_len)
333 trad_enc_update_keys(ctx, *pw++);
335 trad_enc_decrypt_update(ctx, key, 12, header, 12);
336 /* Return the last byte for CRC check. */
337 *crcchk = header[11];
343 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
347 archive_sha1_ctx ctx;
348 unsigned char md1[MD_SIZE];
349 unsigned char md2[MD_SIZE * 2];
350 unsigned char mkb[64];
353 archive_sha1_init(&ctx);
354 archive_sha1_update(&ctx, p, size);
355 archive_sha1_final(&ctx, md1);
357 memset(mkb, 0x36, sizeof(mkb));
358 for (i = 0; i < MD_SIZE; i++)
360 archive_sha1_init(&ctx);
361 archive_sha1_update(&ctx, mkb, sizeof(mkb));
362 archive_sha1_final(&ctx, md2);
364 memset(mkb, 0x5C, sizeof(mkb));
365 for (i = 0; i < MD_SIZE; i++)
367 archive_sha1_init(&ctx);
368 archive_sha1_update(&ctx, mkb, sizeof(mkb));
369 archive_sha1_final(&ctx, md2 + MD_SIZE);
373 memcpy(key, md2, key_size);
379 * Common code for streaming or seeking modes.
381 * Includes code to read local file headers, decompress data
382 * from entry bodies, and common API.
386 real_crc32(unsigned long crc, const void *buff, size_t len)
388 return crc32(crc, buff, (unsigned int)len);
391 /* Used by "ignorecrc32" option to speed up tests. */
393 fake_crc32(unsigned long crc, const void *buff, size_t len)
395 (void)crc; /* UNUSED */
396 (void)buff; /* UNUSED */
397 (void)len; /* UNUSED */
401 static const struct {
404 } compression_methods[] = {
405 {0, "uncompressed"}, /* The file is stored (no compression) */
406 {1, "shrinking"}, /* The file is Shrunk */
407 {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
408 {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
409 {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
410 {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
411 {6, "imploded"}, /* The file is Imploded */
412 {7, "reserved"}, /* Reserved for Tokenizing compression algorithm */
413 {8, "deflation"}, /* The file is Deflated */
414 {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
415 {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
417 {11, "reserved"}, /* Reserved by PKWARE */
418 {12, "bzip"}, /* File is compressed using BZIP2 algorithm */
419 {13, "reserved"}, /* Reserved by PKWARE */
420 {14, "lzma"}, /* LZMA (EFS) */
421 {15, "reserved"}, /* Reserved by PKWARE */
422 {16, "reserved"}, /* Reserved by PKWARE */
423 {17, "reserved"}, /* Reserved by PKWARE */
424 {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
425 {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
426 {95, "xz"}, /* XZ compressed data */
427 {96, "jpeg"}, /* JPEG compressed data */
428 {97, "wav-pack"}, /* WavPack compressed data */
429 {98, "ppmd-1"}, /* PPMd version I, Rev 1 */
430 {99, "aes"} /* WinZip AES encryption */
434 compression_name(const int compression)
436 static const int num_compression_methods =
437 sizeof(compression_methods)/sizeof(compression_methods[0]);
440 while(compression >= 0 && i < num_compression_methods) {
441 if (compression_methods[i].id == compression)
442 return compression_methods[i].name;
448 /* Convert an MSDOS-style date/time into Unix-style time. */
450 zip_time(const char *p)
455 msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
456 msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
458 memset(&ts, 0, sizeof(ts));
459 ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
460 ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
461 ts.tm_mday = msDate & 0x1f; /* Day of month. */
462 ts.tm_hour = (msTime >> 11) & 0x1f;
463 ts.tm_min = (msTime >> 5) & 0x3f;
464 ts.tm_sec = (msTime << 1) & 0x3e;
470 * The extra data is stored as a list of
471 * id1+size1+data1 + id2+size2+data2 ...
472 * triplets. id and size are 2 bytes each.
475 process_extra(struct archive_read *a, struct archive_entry *entry,
476 const char *p, size_t extra_length, struct zip_entry* zip_entry)
479 struct zip *zip = (struct zip *)(a->format->data);
481 if (extra_length == 0) {
485 if (extra_length < 4) {
487 /* Some ZIP files may have trailing 0 bytes. Let's check they
488 * are all 0 and ignore them instead of returning an error.
490 * This is not technically correct, but some ZIP files look
491 * like this and other tools support those files - so let's
494 for (; i < extra_length; i++) {
496 archive_set_error(&a->archive,
497 ARCHIVE_ERRNO_FILE_FORMAT,
498 "Too-small extra data: "
499 "Need at least 4 bytes, "
500 "but only found %d bytes",
502 return ARCHIVE_FAILED;
509 while (offset <= extra_length - 4) {
510 unsigned short headerid = archive_le16dec(p + offset);
511 unsigned short datasize = archive_le16dec(p + offset + 2);
514 if (offset + datasize > extra_length) {
515 archive_set_error(&a->archive,
516 ARCHIVE_ERRNO_FILE_FORMAT, "Extra data overflow: "
517 "Need %d bytes but only found %d bytes",
518 (int)datasize, (int)(extra_length - offset));
519 return ARCHIVE_FAILED;
522 fprintf(stderr, "Header id 0x%04x, length %d\n",
527 /* Zip64 extended information extra field. */
528 zip_entry->flags |= LA_USED_ZIP64;
529 if (zip_entry->uncompressed_size == 0xffffffff) {
532 || (t = archive_le64dec(p + offset)) >
534 archive_set_error(&a->archive,
535 ARCHIVE_ERRNO_FILE_FORMAT,
537 "uncompressed size");
538 return ARCHIVE_FAILED;
540 zip_entry->uncompressed_size = t;
544 if (zip_entry->compressed_size == 0xffffffff) {
547 || (t = archive_le64dec(p + offset)) >
549 archive_set_error(&a->archive,
550 ARCHIVE_ERRNO_FILE_FORMAT,
553 return ARCHIVE_FAILED;
555 zip_entry->compressed_size = t;
559 if (zip_entry->local_header_offset == 0xffffffff) {
562 || (t = archive_le64dec(p + offset)) >
564 archive_set_error(&a->archive,
565 ARCHIVE_ERRNO_FILE_FORMAT,
567 "local header offset");
568 return ARCHIVE_FAILED;
570 zip_entry->local_header_offset = t;
574 /* archive_le32dec(p + offset) gives disk
575 * on which file starts, but we don't handle
576 * multi-volume Zip files. */
581 /* Strong encryption field. */
582 if (archive_le16dec(p + offset) == 2) {
584 archive_le16dec(p + offset + 2);
586 archive_le16dec(p + offset + 4);
588 archive_le16dec(p + offset + 6);
589 fprintf(stderr, "algId=0x%04x, bitLen=%u, "
590 "flgas=%d\n", algId, bitLen,flags);
597 /* Extended time field "UT". */
600 archive_set_error(&a->archive,
601 ARCHIVE_ERRNO_FILE_FORMAT,
602 "Incomplete extended time field");
603 return ARCHIVE_FAILED;
608 /* Flag bits indicate which dates are present. */
612 fprintf(stderr, "mtime: %lld -> %d\n",
613 (long long)zip_entry->mtime,
614 archive_le32dec(p + offset));
618 zip_entry->mtime = archive_le32dec(p + offset);
626 zip_entry->atime = archive_le32dec(p + offset);
634 zip_entry->ctime = archive_le32dec(p + offset);
642 /* Info-ZIP Unix Extra Field (old version) "UX". */
644 zip_entry->atime = archive_le32dec(p + offset);
646 archive_le32dec(p + offset + 4);
648 if (datasize >= 12) {
650 archive_le16dec(p + offset + 8);
652 archive_le16dec(p + offset + 10);
658 /* Experimental 'xl' field */
660 * Introduced Dec 2013 to provide a way to
661 * include external file attributes (and other
662 * fields that ordinarily appear only in
663 * central directory) in local file header.
664 * This provides file type and permission
665 * information necessary to support full
666 * streaming extraction. Currently being
667 * discussed with other Zip developers
668 * ... subject to change.
671 * The field starts with a bitmap that specifies
672 * which additional fields are included. The
673 * bitmap is variable length and can be extended in
676 * n bytes - feature bitmap: first byte has low-order
677 * 7 bits. If high-order bit is set, a subsequent
678 * byte holds the next 7 bits, etc.
680 * if bitmap & 1, 2 byte "version made by"
681 * if bitmap & 2, 2 byte "internal file attributes"
682 * if bitmap & 4, 4 byte "external file attributes"
683 * if bitmap & 8, 2 byte comment length + n byte
686 int bitmap, bitmap_last;
690 bitmap_last = bitmap = 0xff & p[offset];
694 /* We only support first 7 bits of bitmap; skip rest. */
695 while ((bitmap_last & 0x80) != 0
697 bitmap_last = p[offset];
703 /* 2 byte "version made by" */
707 = archive_le16dec(p + offset) >> 8;
712 /* 2 byte "internal file attributes" */
713 uint32_t internal_attributes;
717 = archive_le16dec(p + offset);
718 /* Not used by libarchive at present. */
719 (void)internal_attributes; /* UNUSED */
724 /* 4 byte "external file attributes" */
725 uint32_t external_attributes;
729 = archive_le32dec(p + offset);
730 if (zip_entry->system == 3) {
732 = external_attributes >> 16;
733 } else if (zip_entry->system == 0) {
734 // Interpret MSDOS directory bit
735 if (0x10 == (external_attributes &
743 if (0x01 == (external_attributes &
746 * strip write permissions */
747 zip_entry->mode &= 0555;
756 /* 2 byte comment length + comment */
757 uint32_t comment_length;
761 = archive_le16dec(p + offset);
765 if (datasize < comment_length)
767 /* Comment is not supported by libarchive */
768 offset += comment_length;
769 datasize -= comment_length;
775 /* Info-ZIP Unicode Path Extra Field. */
776 if (datasize < 5 || entry == NULL)
781 /* The path name in this field is always encoded
783 if (zip->sconv_utf8 == NULL) {
785 archive_string_conversion_from_charset(
786 &a->archive, "UTF-8", 1);
787 /* If the converter from UTF-8 is not
788 * available, then the path name from the main
789 * field will more likely be correct. */
790 if (zip->sconv_utf8 == NULL)
794 /* Make sure the CRC32 of the filename matches. */
795 if (!zip->ignore_crc32) {
796 const char *cp = archive_entry_pathname(entry);
798 unsigned long file_crc =
799 zip->crc32func(0, cp, strlen(cp));
800 unsigned long utf_crc =
801 archive_le32dec(p + offset - 4);
802 if (file_crc != utf_crc) {
805 "CRC filename mismatch; "
806 "CDE is %lx, but UTF8 "
807 "is outdated with %lx\n",
815 if (archive_entry_copy_pathname_l(entry,
816 p + offset, datasize, zip->sconv_utf8) != 0) {
817 /* Ignore the error, and fallback to the path
818 * name from the main field. */
820 fprintf(stderr, "Failed to read the ZIP "
821 "0x7075 extra field path.\n");
827 /* Info-ZIP Unix Extra Field (type 2) "Ux". */
829 fprintf(stderr, "uid %d gid %d\n",
830 archive_le16dec(p + offset),
831 archive_le16dec(p + offset + 2));
834 zip_entry->uid = archive_le16dec(p + offset);
837 archive_le16dec(p + offset + 2);
841 /* Info-Zip Unix Extra Field (type 3) "ux". */
842 int uidsize = 0, gidsize = 0;
844 /* TODO: support arbitrary uidsize/gidsize. */
845 if (datasize >= 1 && p[offset] == 1) {/* version=1 */
847 /* get a uid size. */
848 uidsize = 0xff & (int)p[offset+1];
853 else if (uidsize == 4 && datasize >= 6)
858 if (datasize >= (2 + uidsize + 3)) {
859 /* get a gid size. */
861 (int)p[offset+2+uidsize];
865 p+offset+2+uidsize+1);
866 else if (gidsize == 4 &&
867 datasize >= (2 + uidsize + 5))
870 p+offset+2+uidsize+1);
876 /* WinZip AES extra data field. */
878 archive_set_error(&a->archive,
879 ARCHIVE_ERRNO_FILE_FORMAT,
880 "Incomplete AES field");
881 return ARCHIVE_FAILED;
883 if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
884 /* Vendor version. */
885 zip_entry->aes_extra.vendor =
886 archive_le16dec(p + offset);
887 /* AES encryption strength. */
888 zip_entry->aes_extra.strength = p[offset + 4];
889 /* Actual compression method. */
890 zip_entry->aes_extra.compression =
903 * Assumes file pointer is at beginning of local file header.
906 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
913 size_t len, filename_length, extra_length;
914 struct archive_string_conv *sconv;
915 struct zip_entry *zip_entry = zip->entry;
916 struct zip_entry zip_entry_central_dir;
917 int ret = ARCHIVE_OK;
920 /* Save a copy of the original for consistency checks. */
921 zip_entry_central_dir = *zip_entry;
923 zip->decompress_init = 0;
924 zip->end_of_entry = 0;
925 zip->entry_uncompressed_bytes_read = 0;
926 zip->entry_compressed_bytes_read = 0;
927 zip->entry_crc32 = zip->crc32func(0, NULL, 0);
929 /* Setup default conversion. */
930 if (zip->sconv == NULL && !zip->init_default_conversion) {
932 archive_string_default_conversion_for_read(&(a->archive));
933 zip->init_default_conversion = 1;
936 if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
937 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
938 "Truncated ZIP file header");
939 return (ARCHIVE_FATAL);
942 if (memcmp(p, "PK\003\004", 4) != 0) {
943 archive_set_error(&a->archive, -1, "Damaged Zip archive");
944 return ARCHIVE_FATAL;
947 zip_entry->system = p[5];
948 zip_entry->zip_flags = archive_le16dec(p + 6);
949 if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
950 zip->has_encrypted_entries = 1;
951 archive_entry_set_is_data_encrypted(entry, 1);
952 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
953 zip_entry->zip_flags & ZIP_ENCRYPTED &&
954 zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
955 archive_entry_set_is_metadata_encrypted(entry, 1);
956 return ARCHIVE_FATAL;
959 zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
960 zip_entry->compression = (char)archive_le16dec(p + 8);
961 zip_entry->mtime = zip_time(p + 10);
962 zip_entry->crc32 = archive_le32dec(p + 14);
963 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
964 zip_entry->decdat = p[11];
966 zip_entry->decdat = p[17];
967 zip_entry->compressed_size = archive_le32dec(p + 18);
968 zip_entry->uncompressed_size = archive_le32dec(p + 22);
969 filename_length = archive_le16dec(p + 26);
970 extra_length = archive_le16dec(p + 28);
972 __archive_read_consume(a, 30);
974 /* Read the filename. */
975 if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
976 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
977 "Truncated ZIP file header");
978 return (ARCHIVE_FATAL);
980 if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
981 /* The filename is stored to be UTF-8. */
982 if (zip->sconv_utf8 == NULL) {
984 archive_string_conversion_from_charset(
985 &a->archive, "UTF-8", 1);
986 if (zip->sconv_utf8 == NULL)
987 return (ARCHIVE_FATAL);
989 sconv = zip->sconv_utf8;
990 } else if (zip->sconv != NULL)
993 sconv = zip->sconv_default;
995 if (archive_entry_copy_pathname_l(entry,
996 h, filename_length, sconv) != 0) {
997 if (errno == ENOMEM) {
998 archive_set_error(&a->archive, ENOMEM,
999 "Can't allocate memory for Pathname");
1000 return (ARCHIVE_FATAL);
1002 archive_set_error(&a->archive,
1003 ARCHIVE_ERRNO_FILE_FORMAT,
1004 "Pathname cannot be converted "
1005 "from %s to current locale.",
1006 archive_string_conversion_charset_name(sconv));
1009 __archive_read_consume(a, filename_length);
1011 /* Read the extra data. */
1012 if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
1013 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1014 "Truncated ZIP file header");
1015 return (ARCHIVE_FATAL);
1018 if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
1020 return ARCHIVE_FATAL;
1022 __archive_read_consume(a, extra_length);
1024 /* Work around a bug in Info-Zip: When reading from a pipe, it
1025 * stats the pipe instead of synthesizing a file entry. */
1026 if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
1027 zip_entry->mode &= ~ AE_IFMT;
1028 zip_entry->mode |= AE_IFREG;
1031 /* If the mode is totally empty, set some sane default. */
1032 if (zip_entry->mode == 0) {
1033 zip_entry->mode |= 0664;
1036 /* Windows archivers sometimes use backslash as the directory
1037 * separator. Normalize to slash. */
1038 if (zip_entry->system == 0 &&
1039 (wp = archive_entry_pathname_w(entry)) != NULL) {
1040 if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
1042 struct archive_wstring s;
1043 archive_string_init(&s);
1044 archive_wstrcpy(&s, wp);
1045 for (i = 0; i < archive_strlen(&s); i++) {
1049 archive_entry_copy_pathname_w(entry, s.s);
1050 archive_wstring_free(&s);
1054 /* Make sure that entries with a trailing '/' are marked as directories
1055 * even if the External File Attributes contains bogus values. If this
1056 * is not a directory and there is no type, assume a regular file. */
1057 if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
1060 wp = archive_entry_pathname_w(entry);
1063 has_slash = len > 0 && wp[len - 1] == L'/';
1065 cp = archive_entry_pathname(entry);
1066 len = (cp != NULL)?strlen(cp):0;
1067 has_slash = len > 0 && cp[len - 1] == '/';
1069 /* Correct file type as needed. */
1071 zip_entry->mode &= ~AE_IFMT;
1072 zip_entry->mode |= AE_IFDIR;
1073 zip_entry->mode |= 0111;
1074 } else if ((zip_entry->mode & AE_IFMT) == 0) {
1075 zip_entry->mode |= AE_IFREG;
1079 /* Make sure directories end in '/' */
1080 if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
1081 wp = archive_entry_pathname_w(entry);
1084 if (len > 0 && wp[len - 1] != L'/') {
1085 struct archive_wstring s;
1086 archive_string_init(&s);
1087 archive_wstrcat(&s, wp);
1088 archive_wstrappend_wchar(&s, L'/');
1089 archive_entry_copy_pathname_w(entry, s.s);
1090 archive_wstring_free(&s);
1093 cp = archive_entry_pathname(entry);
1094 len = (cp != NULL)?strlen(cp):0;
1095 if (len > 0 && cp[len - 1] != '/') {
1096 struct archive_string s;
1097 archive_string_init(&s);
1098 archive_strcat(&s, cp);
1099 archive_strappend_char(&s, '/');
1100 archive_entry_set_pathname(entry, s.s);
1101 archive_string_free(&s);
1106 if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1107 /* If this came from the central dir, its size info
1108 * is definitive, so ignore the length-at-end flag. */
1109 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1110 /* If local header is missing a value, use the one from
1111 the central directory. If both have it, warn about
1113 if (zip_entry->crc32 == 0) {
1114 zip_entry->crc32 = zip_entry_central_dir.crc32;
1115 } else if (!zip->ignore_crc32
1116 && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1117 archive_set_error(&a->archive,
1118 ARCHIVE_ERRNO_FILE_FORMAT,
1119 "Inconsistent CRC32 values");
1122 if (zip_entry->compressed_size == 0) {
1123 zip_entry->compressed_size
1124 = zip_entry_central_dir.compressed_size;
1125 } else if (zip_entry->compressed_size
1126 != zip_entry_central_dir.compressed_size) {
1127 archive_set_error(&a->archive,
1128 ARCHIVE_ERRNO_FILE_FORMAT,
1129 "Inconsistent compressed size: "
1130 "%jd in central directory, %jd in local header",
1131 (intmax_t)zip_entry_central_dir.compressed_size,
1132 (intmax_t)zip_entry->compressed_size);
1135 if (zip_entry->uncompressed_size == 0) {
1136 zip_entry->uncompressed_size
1137 = zip_entry_central_dir.uncompressed_size;
1138 } else if (zip_entry->uncompressed_size
1139 != zip_entry_central_dir.uncompressed_size) {
1140 archive_set_error(&a->archive,
1141 ARCHIVE_ERRNO_FILE_FORMAT,
1142 "Inconsistent uncompressed size: "
1143 "%jd in central directory, %jd in local header",
1144 (intmax_t)zip_entry_central_dir.uncompressed_size,
1145 (intmax_t)zip_entry->uncompressed_size);
1150 /* Populate some additional entry fields: */
1151 archive_entry_set_mode(entry, zip_entry->mode);
1152 archive_entry_set_uid(entry, zip_entry->uid);
1153 archive_entry_set_gid(entry, zip_entry->gid);
1154 archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1155 archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1156 archive_entry_set_atime(entry, zip_entry->atime, 0);
1158 if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1159 size_t linkname_length;
1161 if (zip_entry->compressed_size > 64 * 1024) {
1162 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1163 "Zip file with oversized link entry");
1164 return ARCHIVE_FATAL;
1167 linkname_length = (size_t)zip_entry->compressed_size;
1169 archive_entry_set_size(entry, 0);
1170 p = __archive_read_ahead(a, linkname_length, NULL);
1172 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1173 "Truncated Zip file");
1174 return ARCHIVE_FATAL;
1178 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1179 sconv = zip->sconv_utf8;
1181 sconv = zip->sconv_default;
1182 if (archive_entry_copy_symlink_l(entry, p, linkname_length,
1184 if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1185 (zip->entry->zip_flags & ZIP_UTF8_NAME))
1186 archive_entry_copy_symlink_l(entry, p,
1187 linkname_length, NULL);
1188 if (errno == ENOMEM) {
1189 archive_set_error(&a->archive, ENOMEM,
1190 "Can't allocate memory for Symlink");
1191 return (ARCHIVE_FATAL);
1194 * Since there is no character-set regulation for
1195 * symlink name, do not report the conversion error
1196 * in an automatic conversion.
1198 if (sconv != zip->sconv_utf8 ||
1199 (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1200 archive_set_error(&a->archive,
1201 ARCHIVE_ERRNO_FILE_FORMAT,
1202 "Symlink cannot be converted "
1203 "from %s to current locale.",
1204 archive_string_conversion_charset_name(
1209 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1211 if (__archive_read_consume(a, linkname_length) < 0) {
1212 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1213 "Read error skipping symlink target name");
1214 return ARCHIVE_FATAL;
1216 } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1217 || zip_entry->uncompressed_size > 0) {
1218 /* Set the size only if it's meaningful. */
1219 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1221 zip->entry_bytes_remaining = zip_entry->compressed_size;
1223 /* If there's no body, force read_data() to return EOF immediately. */
1224 if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1225 && zip->entry_bytes_remaining < 1)
1226 zip->end_of_entry = 1;
1228 /* Set up a more descriptive format name. */
1229 archive_string_empty(&zip->format_name);
1230 archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1231 version / 10, version % 10,
1232 compression_name(zip->entry->compression));
1233 a->archive.archive_format_name = zip->format_name.s;
1239 check_authentication_code(struct archive_read *a, const void *_p)
1241 struct zip *zip = (struct zip *)(a->format->data);
1243 /* Check authentication code. */
1244 if (zip->hctx_valid) {
1247 size_t hmac_len = 20;
1250 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1252 /* Read authentication code. */
1253 p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1255 archive_set_error(&a->archive,
1256 ARCHIVE_ERRNO_FILE_FORMAT,
1257 "Truncated ZIP file data");
1258 return (ARCHIVE_FATAL);
1263 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1264 __archive_read_consume(a, AUTH_CODE_SIZE);
1266 archive_set_error(&a->archive,
1268 "ZIP bad Authentication code");
1269 return (ARCHIVE_WARN);
1272 return (ARCHIVE_OK);
1276 * Read "uncompressed" data. There are three cases:
1277 * 1) We know the size of the data. This is always true for the
1278 * seeking reader (we've examined the Central Directory already).
1279 * 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1280 * Info-ZIP seems to do this; we know the size but have to grab
1281 * the CRC from the data descriptor afterwards.
1282 * 3) We're streaming and ZIP_LENGTH_AT_END was specified and
1283 * we have no size information. In this case, we can do pretty
1284 * well by watching for the data descriptor record. The data
1285 * descriptor is 16 bytes and includes a computed CRC that should
1286 * provide a strong check.
1288 * TODO: Technically, the PK\007\010 signature is optional.
1289 * In the original spec, the data descriptor contained CRC
1290 * and size fields but had no leading signature. In practice,
1291 * newer writers seem to provide the signature pretty consistently.
1293 * For uncompressed data, the PK\007\010 marker seems essential
1294 * to be sure we've actually seen the end of the entry.
1296 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1297 * zip->end_of_entry if it consumes all of the data.
1300 zip_read_data_none(struct archive_read *a, const void **_buff,
1301 size_t *size, int64_t *offset)
1305 ssize_t bytes_avail;
1308 (void)offset; /* UNUSED */
1310 zip = (struct zip *)(a->format->data);
1312 if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1314 ssize_t grabbing_bytes = 24;
1316 if (zip->hctx_valid)
1317 grabbing_bytes += AUTH_CODE_SIZE;
1318 /* Grab at least 24 bytes. */
1319 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1320 if (bytes_avail < grabbing_bytes) {
1321 /* Zip archives have end-of-archive markers
1322 that are longer than this, so a failure to get at
1323 least 24 bytes really does indicate a truncated
1325 archive_set_error(&a->archive,
1326 ARCHIVE_ERRNO_FILE_FORMAT,
1327 "Truncated ZIP file data");
1328 return (ARCHIVE_FATAL);
1330 /* Check for a complete PK\007\010 signature, followed
1331 * by the correct 4-byte CRC. */
1333 if (zip->hctx_valid)
1334 p += AUTH_CODE_SIZE;
1335 if (p[0] == 'P' && p[1] == 'K'
1336 && p[2] == '\007' && p[3] == '\010'
1337 && (archive_le32dec(p + 4) == zip->entry_crc32
1338 || zip->ignore_crc32
1340 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1341 if (zip->entry->flags & LA_USED_ZIP64) {
1342 uint64_t compressed, uncompressed;
1343 zip->entry->crc32 = archive_le32dec(p + 4);
1344 compressed = archive_le64dec(p + 8);
1345 uncompressed = archive_le64dec(p + 16);
1346 if (compressed > INT64_MAX || uncompressed >
1348 archive_set_error(&a->archive,
1349 ARCHIVE_ERRNO_FILE_FORMAT,
1350 "Overflow of 64-bit file sizes");
1351 return ARCHIVE_FAILED;
1353 zip->entry->compressed_size = compressed;
1354 zip->entry->uncompressed_size = uncompressed;
1355 zip->unconsumed = 24;
1357 zip->entry->crc32 = archive_le32dec(p + 4);
1358 zip->entry->compressed_size =
1359 archive_le32dec(p + 8);
1360 zip->entry->uncompressed_size =
1361 archive_le32dec(p + 12);
1362 zip->unconsumed = 16;
1364 if (zip->hctx_valid) {
1365 r = check_authentication_code(a, buff);
1366 if (r != ARCHIVE_OK)
1369 zip->end_of_entry = 1;
1370 return (ARCHIVE_OK);
1372 /* If not at EOF, ensure we consume at least one byte. */
1375 /* Scan forward until we see where a PK\007\010 signature
1377 /* Return bytes up until that point. On the next call,
1378 * the code above will verify the data descriptor. */
1379 while (p < buff + bytes_avail - 4) {
1380 if (p[3] == 'P') { p += 3; }
1381 else if (p[3] == 'K') { p += 2; }
1382 else if (p[3] == '\007') { p += 1; }
1383 else if (p[3] == '\010' && p[2] == '\007'
1384 && p[1] == 'K' && p[0] == 'P') {
1385 if (zip->hctx_valid)
1386 p -= AUTH_CODE_SIZE;
1390 bytes_avail = p - buff;
1392 if (zip->entry_bytes_remaining == 0) {
1393 zip->end_of_entry = 1;
1394 if (zip->hctx_valid) {
1395 r = check_authentication_code(a, NULL);
1396 if (r != ARCHIVE_OK)
1399 return (ARCHIVE_OK);
1401 /* Grab a bunch of bytes. */
1402 buff = __archive_read_ahead(a, 1, &bytes_avail);
1403 if (bytes_avail <= 0) {
1404 archive_set_error(&a->archive,
1405 ARCHIVE_ERRNO_FILE_FORMAT,
1406 "Truncated ZIP file data");
1407 return (ARCHIVE_FATAL);
1409 if (bytes_avail > zip->entry_bytes_remaining)
1410 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1412 if (zip->tctx_valid || zip->cctx_valid) {
1413 size_t dec_size = bytes_avail;
1415 if (dec_size > zip->decrypted_buffer_size)
1416 dec_size = zip->decrypted_buffer_size;
1417 if (zip->tctx_valid) {
1418 trad_enc_decrypt_update(&zip->tctx,
1419 (const uint8_t *)buff, dec_size,
1420 zip->decrypted_buffer, dec_size);
1422 size_t dsize = dec_size;
1423 archive_hmac_sha1_update(&zip->hctx,
1424 (const uint8_t *)buff, dec_size);
1425 archive_decrypto_aes_ctr_update(&zip->cctx,
1426 (const uint8_t *)buff, dec_size,
1427 zip->decrypted_buffer, &dsize);
1429 bytes_avail = dec_size;
1430 buff = (const char *)zip->decrypted_buffer;
1432 *size = bytes_avail;
1433 zip->entry_bytes_remaining -= bytes_avail;
1434 zip->entry_uncompressed_bytes_read += bytes_avail;
1435 zip->entry_compressed_bytes_read += bytes_avail;
1436 zip->unconsumed += bytes_avail;
1438 return (ARCHIVE_OK);
1442 consume_optional_marker(struct archive_read *a, struct zip *zip)
1444 if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1447 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1448 archive_set_error(&a->archive,
1449 ARCHIVE_ERRNO_FILE_FORMAT,
1450 "Truncated ZIP end-of-file record");
1451 return (ARCHIVE_FATAL);
1453 /* Consume the optional PK\007\010 marker. */
1454 if (p[0] == 'P' && p[1] == 'K' &&
1455 p[2] == '\007' && p[3] == '\010') {
1457 zip->unconsumed = 4;
1459 if (zip->entry->flags & LA_USED_ZIP64) {
1460 uint64_t compressed, uncompressed;
1461 zip->entry->crc32 = archive_le32dec(p);
1462 compressed = archive_le64dec(p + 4);
1463 uncompressed = archive_le64dec(p + 12);
1464 if (compressed > INT64_MAX ||
1465 uncompressed > INT64_MAX) {
1466 archive_set_error(&a->archive,
1467 ARCHIVE_ERRNO_FILE_FORMAT,
1468 "Overflow of 64-bit file sizes");
1469 return ARCHIVE_FAILED;
1471 zip->entry->compressed_size = compressed;
1472 zip->entry->uncompressed_size = uncompressed;
1473 zip->unconsumed += 20;
1475 zip->entry->crc32 = archive_le32dec(p);
1476 zip->entry->compressed_size = archive_le32dec(p + 4);
1477 zip->entry->uncompressed_size = archive_le32dec(p + 8);
1478 zip->unconsumed += 12;
1482 return (ARCHIVE_OK);
1485 #if HAVE_LZMA_H && HAVE_LIBLZMA
1487 zipx_xz_init(struct archive_read *a, struct zip *zip)
1491 if(zip->zipx_lzma_valid) {
1492 lzma_end(&zip->zipx_lzma_stream);
1493 zip->zipx_lzma_valid = 0;
1496 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1497 r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1499 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1500 "xz initialization failed(%d)",
1503 return (ARCHIVE_FAILED);
1506 zip->zipx_lzma_valid = 1;
1508 free(zip->uncompressed_buffer);
1510 zip->uncompressed_buffer_size = 256 * 1024;
1511 zip->uncompressed_buffer =
1512 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1513 if (zip->uncompressed_buffer == NULL) {
1514 archive_set_error(&a->archive, ENOMEM,
1515 "No memory for xz decompression");
1516 return (ARCHIVE_FATAL);
1519 zip->decompress_init = 1;
1520 return (ARCHIVE_OK);
1524 zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1531 struct _alone_header {
1533 uint64_t uncompressed_size;
1537 if(zip->zipx_lzma_valid) {
1538 lzma_end(&zip->zipx_lzma_stream);
1539 zip->zipx_lzma_valid = 0;
1542 /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
1543 * that is a part of XZ Utils. The stream format stored inside ZIPX
1544 * file is a modified "lzma alone" file format, that was used by the
1545 * `lzma` utility which was later deprecated in favour of `xz` utility. * Since those formats are nearly the same, we can use a standard
1546 * "lzma alone" decoder from XZ Utils. */
1548 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1549 r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1551 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1552 "lzma initialization failed(%d)", r);
1554 return (ARCHIVE_FAILED);
1557 /* Flag the cleanup function that we want our lzma-related structures
1558 * to be freed later. */
1559 zip->zipx_lzma_valid = 1;
1561 /* The "lzma alone" file format and the stream format inside ZIPx are
1562 * almost the same. Here's an example of a structure of "lzma alone"
1565 * $ cat /bin/ls | lzma | xxd | head -n 1
1566 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1568 * 5 bytes 8 bytes n bytes
1569 * <lzma_params><uncompressed_size><data...>
1571 * lzma_params is a 5-byte blob that has to be decoded to extract
1572 * parameters of this LZMA stream. The uncompressed_size field is an
1573 * uint64_t value that contains information about the size of the
1574 * uncompressed file, or UINT64_MAX if this value is unknown.
1575 * The <data...> part is the actual lzma-compressed data stream.
1577 * Now here's the structure of the stream inside the ZIPX file:
1579 * $ cat stream_inside_zipx | xxd | head -n 1
1580 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1582 * 2byte 2byte 5 bytes n bytes
1583 * <magic1><magic2><lzma_params><data...>
1585 * This means that the ZIPX file contains an additional magic1 and
1586 * magic2 headers, the lzma_params field contains the same parameter
1587 * set as in the "lzma alone" format, and the <data...> field is the
1588 * same as in the "lzma alone" format as well. Note that also the zipx
1589 * format is missing the uncompressed_size field.
1591 * So, in order to use the "lzma alone" decoder for the zipx lzma
1592 * stream, we simply need to shuffle around some fields, prepare a new
1593 * lzma alone header, feed it into lzma alone decoder so it will
1594 * initialize itself properly, and then we can start feeding normal
1595 * zipx lzma stream into the decoder.
1598 /* Read magic1,magic2,lzma_params from the ZIPX stream. */
1599 if((p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1600 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1601 "Truncated lzma data");
1602 return (ARCHIVE_FATAL);
1605 if(p[2] != 0x05 || p[3] != 0x00) {
1606 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1607 "Invalid lzma data");
1608 return (ARCHIVE_FATAL);
1611 /* Prepare an lzma alone header: copy the lzma_params blob into
1612 * a proper place into the lzma alone header. */
1613 memcpy(&alone_header.bytes[0], p + 4, 5);
1615 /* Initialize the 'uncompressed size' field to unknown; we'll manually
1616 * monitor how many bytes there are still to be uncompressed. */
1617 alone_header.uncompressed_size = UINT64_MAX;
1619 if(!zip->uncompressed_buffer) {
1620 zip->uncompressed_buffer_size = 256 * 1024;
1621 zip->uncompressed_buffer =
1622 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1624 if (zip->uncompressed_buffer == NULL) {
1625 archive_set_error(&a->archive, ENOMEM,
1626 "No memory for lzma decompression");
1627 return (ARCHIVE_FATAL);
1631 zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1632 zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1633 zip->zipx_lzma_stream.total_in = 0;
1634 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1635 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1636 zip->zipx_lzma_stream.total_out = 0;
1638 /* Feed only the header into the lzma alone decoder. This will
1639 * effectively initialize the decoder, and will not produce any
1640 * output bytes yet. */
1641 r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1643 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1644 "lzma stream initialization error");
1645 return ARCHIVE_FATAL;
1648 /* We've already consumed some bytes, so take this into account. */
1649 __archive_read_consume(a, 9);
1650 zip->entry_bytes_remaining -= 9;
1651 zip->entry_compressed_bytes_read += 9;
1653 zip->decompress_init = 1;
1654 return (ARCHIVE_OK);
1658 zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1659 size_t *size, int64_t *offset)
1661 struct zip* zip = (struct zip *)(a->format->data);
1664 const void* compressed_buf;
1665 ssize_t bytes_avail, in_bytes, to_consume = 0;
1667 (void) offset; /* UNUSED */
1669 /* Initialize decompressor if not yet initialized. */
1670 if (!zip->decompress_init) {
1671 ret = zipx_xz_init(a, zip);
1672 if (ret != ARCHIVE_OK)
1676 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1677 if (bytes_avail < 0) {
1678 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1679 "Truncated xz file body");
1680 return (ARCHIVE_FATAL);
1683 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1684 zip->zipx_lzma_stream.next_in = compressed_buf;
1685 zip->zipx_lzma_stream.avail_in = in_bytes;
1686 zip->zipx_lzma_stream.total_in = 0;
1687 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1688 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1689 zip->zipx_lzma_stream.total_out = 0;
1691 /* Perform the decompression. */
1692 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1694 case LZMA_DATA_ERROR:
1695 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1696 "xz data error (error %d)", (int) lz_ret);
1697 return (ARCHIVE_FATAL);
1704 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1705 "xz unknown error %d", (int) lz_ret);
1706 return (ARCHIVE_FATAL);
1708 case LZMA_STREAM_END:
1709 lzma_end(&zip->zipx_lzma_stream);
1710 zip->zipx_lzma_valid = 0;
1712 if((int64_t) zip->zipx_lzma_stream.total_in !=
1713 zip->entry_bytes_remaining)
1715 archive_set_error(&a->archive,
1717 "xz premature end of stream");
1718 return (ARCHIVE_FATAL);
1721 zip->end_of_entry = 1;
1725 to_consume = zip->zipx_lzma_stream.total_in;
1727 __archive_read_consume(a, to_consume);
1728 zip->entry_bytes_remaining -= to_consume;
1729 zip->entry_compressed_bytes_read += to_consume;
1730 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1732 *size = zip->zipx_lzma_stream.total_out;
1733 *buff = zip->uncompressed_buffer;
1735 ret = consume_optional_marker(a, zip);
1736 if (ret != ARCHIVE_OK)
1739 return (ARCHIVE_OK);
1743 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1744 size_t *size, int64_t *offset)
1746 struct zip* zip = (struct zip *)(a->format->data);
1749 const void* compressed_buf;
1750 ssize_t bytes_avail, in_bytes, to_consume;
1752 (void) offset; /* UNUSED */
1754 /* Initialize decompressor if not yet initialized. */
1755 if (!zip->decompress_init) {
1756 ret = zipx_lzma_alone_init(a, zip);
1757 if (ret != ARCHIVE_OK)
1761 /* Fetch more compressed data. The same note as in deflate handler
1762 * applies here as well:
1764 * Note: '1' here is a performance optimization. Recall that the
1765 * decompression layer returns a count of available bytes; asking for
1766 * more than that forces the decompressor to combine reads by copying
1769 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1770 if (bytes_avail < 0) {
1771 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1772 "Truncated lzma file body");
1773 return (ARCHIVE_FATAL);
1776 /* Set decompressor parameters. */
1777 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1779 zip->zipx_lzma_stream.next_in = compressed_buf;
1780 zip->zipx_lzma_stream.avail_in = in_bytes;
1781 zip->zipx_lzma_stream.total_in = 0;
1782 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1783 zip->zipx_lzma_stream.avail_out =
1784 /* These lzma_alone streams lack end of stream marker, so let's
1785 * make sure the unpacker won't try to unpack more than it's
1787 zipmin((int64_t) zip->uncompressed_buffer_size,
1788 zip->entry->uncompressed_size -
1789 zip->entry_uncompressed_bytes_read);
1790 zip->zipx_lzma_stream.total_out = 0;
1792 /* Perform the decompression. */
1793 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1795 case LZMA_DATA_ERROR:
1796 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1797 "lzma data error (error %d)", (int) lz_ret);
1798 return (ARCHIVE_FATAL);
1800 /* This case is optional in lzma alone format. It can happen,
1801 * but most of the files don't have it. (GitHub #1257) */
1802 case LZMA_STREAM_END:
1803 lzma_end(&zip->zipx_lzma_stream);
1804 zip->zipx_lzma_valid = 0;
1805 if((int64_t) zip->zipx_lzma_stream.total_in !=
1806 zip->entry_bytes_remaining)
1808 archive_set_error(&a->archive,
1810 "lzma alone premature end of stream");
1811 return (ARCHIVE_FATAL);
1814 zip->end_of_entry = 1;
1821 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1822 "lzma unknown error %d", (int) lz_ret);
1823 return (ARCHIVE_FATAL);
1826 to_consume = zip->zipx_lzma_stream.total_in;
1828 /* Update pointers. */
1829 __archive_read_consume(a, to_consume);
1830 zip->entry_bytes_remaining -= to_consume;
1831 zip->entry_compressed_bytes_read += to_consume;
1832 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1834 if(zip->entry_bytes_remaining == 0) {
1835 zip->end_of_entry = 1;
1838 /* Return values. */
1839 *size = zip->zipx_lzma_stream.total_out;
1840 *buff = zip->uncompressed_buffer;
1842 /* Behave the same way as during deflate decompression. */
1843 ret = consume_optional_marker(a, zip);
1844 if (ret != ARCHIVE_OK)
1847 /* Free lzma decoder handle because we'll no longer need it. */
1848 if(zip->end_of_entry) {
1849 lzma_end(&zip->zipx_lzma_stream);
1850 zip->zipx_lzma_valid = 0;
1853 /* If we're here, then we're good! */
1854 return (ARCHIVE_OK);
1856 #endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1859 zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1865 uint32_t restore_method;
1867 /* Remove previous decompression context if it exists. */
1868 if(zip->ppmd8_valid) {
1869 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1870 zip->ppmd8_valid = 0;
1873 /* Create a new decompression context. */
1874 __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1875 zip->ppmd8_stream_failed = 0;
1877 /* Setup function pointers required by Ppmd8 decompressor. The
1878 * 'ppmd_read' function will feed new bytes to the decompressor,
1879 * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
1880 zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
1881 zip->zipx_ppmd_stream.a = a;
1882 zip->zipx_ppmd_stream.Read = &ppmd_read;
1884 /* Reset number of read bytes to 0. */
1885 zip->zipx_ppmd_read_compressed = 0;
1887 /* Read Ppmd8 header (2 bytes). */
1888 p = __archive_read_ahead(a, 2, NULL);
1890 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1891 "Truncated file data in PPMd8 stream");
1892 return (ARCHIVE_FATAL);
1894 __archive_read_consume(a, 2);
1896 /* Decode the stream's compression parameters. */
1897 val = archive_le16dec(p);
1898 order = (val & 15) + 1;
1899 mem = ((val >> 4) & 0xff) + 1;
1900 restore_method = (val >> 12);
1902 if(order < 2 || restore_method > 2) {
1903 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1904 "Invalid parameter set in PPMd8 stream (order=%d, "
1905 "restore=%d)", order, restore_method);
1906 return (ARCHIVE_FAILED);
1909 /* Allocate the memory needed to properly decompress the file. */
1910 if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
1911 archive_set_error(&a->archive, ENOMEM,
1912 "Unable to allocate memory for PPMd8 stream: %d bytes",
1914 return (ARCHIVE_FATAL);
1917 /* Signal the cleanup function to release Ppmd8 context in the
1919 zip->ppmd8_valid = 1;
1921 /* Perform further Ppmd8 initialization. */
1922 if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
1923 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1924 "PPMd8 stream range decoder initialization error");
1925 return (ARCHIVE_FATAL);
1928 __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
1931 /* Allocate the buffer that will hold uncompressed data. */
1932 free(zip->uncompressed_buffer);
1934 zip->uncompressed_buffer_size = 256 * 1024;
1935 zip->uncompressed_buffer =
1936 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1938 if(zip->uncompressed_buffer == NULL) {
1939 archive_set_error(&a->archive, ENOMEM,
1940 "No memory for PPMd8 decompression");
1941 return ARCHIVE_FATAL;
1944 /* Ppmd8 initialization is done. */
1945 zip->decompress_init = 1;
1947 /* We've already read 2 bytes in the output stream. Additionally,
1948 * Ppmd8 initialization code could read some data as well. So we
1949 * are advancing the stream by 2 bytes plus whatever number of
1950 * bytes Ppmd8 init function used. */
1951 zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
1957 zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
1958 size_t *size, int64_t *offset)
1960 struct zip* zip = (struct zip *)(a->format->data);
1962 size_t consumed_bytes = 0;
1963 ssize_t bytes_avail = 0;
1965 (void) offset; /* UNUSED */
1967 /* If we're here for the first time, initialize Ppmd8 decompression
1969 if(!zip->decompress_init) {
1970 ret = zipx_ppmd8_init(a, zip);
1971 if(ret != ARCHIVE_OK)
1975 /* Fetch for more data. We're reading 1 byte here, but libarchive
1976 * should prefetch more bytes. */
1977 (void) __archive_read_ahead(a, 1, &bytes_avail);
1978 if(bytes_avail < 0) {
1979 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1980 "Truncated PPMd8 file body");
1981 return (ARCHIVE_FATAL);
1984 /* This counter will be updated inside ppmd_read(), which at one
1985 * point will be called by Ppmd8_DecodeSymbol. */
1986 zip->zipx_ppmd_read_compressed = 0;
1988 /* Decompression loop. */
1990 int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
1993 zip->end_of_entry = 1;
1997 /* This field is set by ppmd_read() when there was no more data
1999 if(zip->ppmd8_stream_failed) {
2000 archive_set_error(&a->archive,
2001 ARCHIVE_ERRNO_FILE_FORMAT,
2002 "Truncated PPMd8 file body");
2003 return (ARCHIVE_FATAL);
2006 zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
2008 } while(consumed_bytes < zip->uncompressed_buffer_size);
2010 /* Update pointers for libarchive. */
2011 *buff = zip->uncompressed_buffer;
2012 *size = consumed_bytes;
2014 /* Update pointers so we can continue decompression in another call. */
2015 zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
2016 zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
2017 zip->entry_uncompressed_bytes_read += consumed_bytes;
2019 /* If we're at the end of stream, deinitialize Ppmd8 context. */
2020 if(zip->end_of_entry) {
2021 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2022 zip->ppmd8_valid = 0;
2025 /* Seek for optional marker, same way as in each zip entry. */
2026 ret = consume_optional_marker(a, zip);
2027 if (ret != ARCHIVE_OK)
2035 zipx_bzip2_init(struct archive_read *a, struct zip *zip)
2039 /* Deallocate already existing BZ2 decompression context if it
2041 if(zip->bzstream_valid) {
2042 BZ2_bzDecompressEnd(&zip->bzstream);
2043 zip->bzstream_valid = 0;
2046 /* Allocate a new BZ2 decompression context. */
2047 memset(&zip->bzstream, 0, sizeof(bz_stream));
2048 r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
2050 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
2051 "bzip2 initialization failed(%d)",
2054 return ARCHIVE_FAILED;
2057 /* Mark the bzstream field to be released in cleanup phase. */
2058 zip->bzstream_valid = 1;
2060 /* (Re)allocate the buffer that will contain decompressed bytes. */
2061 free(zip->uncompressed_buffer);
2063 zip->uncompressed_buffer_size = 256 * 1024;
2064 zip->uncompressed_buffer =
2065 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2066 if (zip->uncompressed_buffer == NULL) {
2067 archive_set_error(&a->archive, ENOMEM,
2068 "No memory for bzip2 decompression");
2069 return ARCHIVE_FATAL;
2072 /* Initialization done. */
2073 zip->decompress_init = 1;
2078 zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
2079 size_t *size, int64_t *offset)
2081 struct zip *zip = (struct zip *)(a->format->data);
2082 ssize_t bytes_avail = 0, in_bytes, to_consume;
2083 const void *compressed_buff;
2087 (void) offset; /* UNUSED */
2089 /* Initialize decompression context if we're here for the first time. */
2090 if(!zip->decompress_init) {
2091 r = zipx_bzip2_init(a, zip);
2096 /* Fetch more compressed bytes. */
2097 compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2098 if(bytes_avail < 0) {
2099 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2100 "Truncated bzip2 file body");
2101 return (ARCHIVE_FATAL);
2104 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2106 /* libbz2 doesn't complain when caller feeds avail_in == 0.
2107 * It will actually return success in this case, which is
2108 * undesirable. This is why we need to make this check
2111 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2112 "Truncated bzip2 file body");
2113 return (ARCHIVE_FATAL);
2116 /* Setup buffer boundaries. */
2117 zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
2118 zip->bzstream.avail_in = in_bytes;
2119 zip->bzstream.total_in_hi32 = 0;
2120 zip->bzstream.total_in_lo32 = 0;
2121 zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2122 zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2123 zip->bzstream.total_out_hi32 = 0;
2124 zip->bzstream.total_out_lo32 = 0;
2126 /* Perform the decompression. */
2127 r = BZ2_bzDecompress(&zip->bzstream);
2130 /* If we're at the end of the stream, deinitialize the
2131 * decompression context now. */
2132 switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2136 archive_set_error(&a->archive,
2138 "Failed to clean up bzip2 "
2140 return ARCHIVE_FATAL;
2143 zip->end_of_entry = 1;
2146 /* The decompressor has successfully decoded this
2147 * chunk of data, but more data is still in queue. */
2150 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2151 "bzip2 decompression failed");
2152 return ARCHIVE_FATAL;
2155 /* Update the pointers so decompressor can continue decoding. */
2156 to_consume = zip->bzstream.total_in_lo32;
2157 __archive_read_consume(a, to_consume);
2159 total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2160 zip->bzstream.total_out_lo32;
2162 zip->entry_bytes_remaining -= to_consume;
2163 zip->entry_compressed_bytes_read += to_consume;
2164 zip->entry_uncompressed_bytes_read += total_out;
2166 /* Give libarchive its due. */
2168 *buff = zip->uncompressed_buffer;
2170 /* Seek for optional marker, like in other entries. */
2171 r = consume_optional_marker(a, zip);
2182 zip_deflate_init(struct archive_read *a, struct zip *zip)
2186 /* If we haven't yet read any data, initialize the decompressor. */
2187 if (!zip->decompress_init) {
2188 if (zip->stream_valid)
2189 r = inflateReset(&zip->stream);
2191 r = inflateInit2(&zip->stream,
2192 -15 /* Don't check for zlib header */);
2194 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2195 "Can't initialize ZIP decompression.");
2196 return (ARCHIVE_FATAL);
2198 /* Stream structure has been set up. */
2199 zip->stream_valid = 1;
2200 /* We've initialized decompression for this stream. */
2201 zip->decompress_init = 1;
2203 return (ARCHIVE_OK);
2207 zip_read_data_deflate(struct archive_read *a, const void **buff,
2208 size_t *size, int64_t *offset)
2211 ssize_t bytes_avail;
2212 const void *compressed_buff, *sp;
2215 (void)offset; /* UNUSED */
2217 zip = (struct zip *)(a->format->data);
2219 /* If the buffer hasn't been allocated, allocate it now. */
2220 if (zip->uncompressed_buffer == NULL) {
2221 zip->uncompressed_buffer_size = 256 * 1024;
2222 zip->uncompressed_buffer
2223 = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2224 if (zip->uncompressed_buffer == NULL) {
2225 archive_set_error(&a->archive, ENOMEM,
2226 "No memory for ZIP decompression");
2227 return (ARCHIVE_FATAL);
2231 r = zip_deflate_init(a, zip);
2232 if (r != ARCHIVE_OK)
2236 * Note: '1' here is a performance optimization.
2237 * Recall that the decompression layer returns a count of
2238 * available bytes; asking for more than that forces the
2239 * decompressor to combine reads by copying data.
2241 compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2242 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2243 && bytes_avail > zip->entry_bytes_remaining) {
2244 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2246 if (bytes_avail < 0) {
2247 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2248 "Truncated ZIP file body");
2249 return (ARCHIVE_FATAL);
2252 if (zip->tctx_valid || zip->cctx_valid) {
2253 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2254 size_t buff_remaining =
2255 (zip->decrypted_buffer +
2256 zip->decrypted_buffer_size)
2257 - (zip->decrypted_ptr +
2258 zip->decrypted_bytes_remaining);
2260 if (buff_remaining > (size_t)bytes_avail)
2261 buff_remaining = (size_t)bytes_avail;
2263 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2264 zip->entry_bytes_remaining > 0) {
2265 if ((int64_t)(zip->decrypted_bytes_remaining
2267 > zip->entry_bytes_remaining) {
2268 if (zip->entry_bytes_remaining <
2269 (int64_t)zip->decrypted_bytes_remaining)
2273 (size_t)zip->entry_bytes_remaining
2274 - zip->decrypted_bytes_remaining;
2277 if (buff_remaining > 0) {
2278 if (zip->tctx_valid) {
2279 trad_enc_decrypt_update(&zip->tctx,
2280 compressed_buff, buff_remaining,
2282 + zip->decrypted_bytes_remaining,
2285 size_t dsize = buff_remaining;
2286 archive_decrypto_aes_ctr_update(
2288 compressed_buff, buff_remaining,
2290 + zip->decrypted_bytes_remaining,
2293 zip->decrypted_bytes_remaining +=
2297 bytes_avail = zip->decrypted_bytes_remaining;
2298 compressed_buff = (const char *)zip->decrypted_ptr;
2302 * A bug in zlib.h: stream.next_in should be marked 'const'
2303 * but isn't (the library never alters data through the
2304 * next_in pointer, only reads it). The result: this ugly
2305 * cast to remove 'const'.
2307 zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2308 zip->stream.avail_in = (uInt)bytes_avail;
2309 zip->stream.total_in = 0;
2310 zip->stream.next_out = zip->uncompressed_buffer;
2311 zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2312 zip->stream.total_out = 0;
2314 r = inflate(&zip->stream, 0);
2319 zip->end_of_entry = 1;
2322 archive_set_error(&a->archive, ENOMEM,
2323 "Out of memory for ZIP decompression");
2324 return (ARCHIVE_FATAL);
2326 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2327 "ZIP decompression failed (%d)", r);
2328 return (ARCHIVE_FATAL);
2331 /* Consume as much as the compressor actually used. */
2332 bytes_avail = zip->stream.total_in;
2333 if (zip->tctx_valid || zip->cctx_valid) {
2334 zip->decrypted_bytes_remaining -= bytes_avail;
2335 if (zip->decrypted_bytes_remaining == 0)
2336 zip->decrypted_ptr = zip->decrypted_buffer;
2338 zip->decrypted_ptr += bytes_avail;
2340 /* Calculate compressed data as much as we used.*/
2341 if (zip->hctx_valid)
2342 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2343 __archive_read_consume(a, bytes_avail);
2344 zip->entry_bytes_remaining -= bytes_avail;
2345 zip->entry_compressed_bytes_read += bytes_avail;
2347 *size = zip->stream.total_out;
2348 zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2349 *buff = zip->uncompressed_buffer;
2351 if (zip->end_of_entry && zip->hctx_valid) {
2352 r = check_authentication_code(a, NULL);
2353 if (r != ARCHIVE_OK)
2357 r = consume_optional_marker(a, zip);
2358 if (r != ARCHIVE_OK)
2361 return (ARCHIVE_OK);
2366 read_decryption_header(struct archive_read *a)
2368 struct zip *zip = (struct zip *)(a->format->data);
2370 unsigned int remaining_size;
2374 * Read an initialization vector data field.
2376 p = __archive_read_ahead(a, 2, NULL);
2380 zip->iv_size = archive_le16dec(p);
2381 __archive_read_consume(a, 2);
2382 if (ts < zip->iv_size) {
2386 p = __archive_read_ahead(a, zip->iv_size, NULL);
2389 if (zip->iv == NULL) {
2390 zip->iv = malloc(zip->iv_size);
2391 if (zip->iv == NULL)
2394 memcpy(zip->iv, p, zip->iv_size);
2395 __archive_read_consume(a, zip->iv_size);
2398 * Read a size of remaining decryption header field.
2400 p = __archive_read_ahead(a, 14, NULL);
2403 remaining_size = archive_le32dec(p);
2404 if (remaining_size < 16 || remaining_size > (1 << 18))
2407 /* Check if format version is supported. */
2408 if (archive_le16dec(p+4) != 3) {
2409 archive_set_error(&a->archive,
2410 ARCHIVE_ERRNO_FILE_FORMAT,
2411 "Unsupported encryption format version: %u",
2412 archive_le16dec(p+4));
2413 return (ARCHIVE_FAILED);
2417 * Read an encryption algorithm field.
2419 zip->alg_id = archive_le16dec(p+6);
2420 switch (zip->alg_id) {
2421 case 0x6601:/* DES */
2422 case 0x6602:/* RC2 */
2423 case 0x6603:/* 3DES 168 */
2424 case 0x6609:/* 3DES 112 */
2425 case 0x660E:/* AES 128 */
2426 case 0x660F:/* AES 192 */
2427 case 0x6610:/* AES 256 */
2428 case 0x6702:/* RC2 (version >= 5.2) */
2429 case 0x6720:/* Blowfish */
2430 case 0x6721:/* Twofish */
2431 case 0x6801:/* RC4 */
2432 /* Supported encryption algorithm. */
2435 archive_set_error(&a->archive,
2436 ARCHIVE_ERRNO_FILE_FORMAT,
2437 "Unknown encryption algorithm: %u", zip->alg_id);
2438 return (ARCHIVE_FAILED);
2442 * Read a bit length field.
2444 zip->bit_len = archive_le16dec(p+8);
2447 * Read a flags field.
2449 zip->flags = archive_le16dec(p+10);
2450 switch (zip->flags & 0xf000) {
2451 case 0x0001: /* Password is required to decrypt. */
2452 case 0x0002: /* Certificates only. */
2453 case 0x0003: /* Password or certificate required to decrypt. */
2456 archive_set_error(&a->archive,
2457 ARCHIVE_ERRNO_FILE_FORMAT,
2458 "Unknown encryption flag: %u", zip->flags);
2459 return (ARCHIVE_FAILED);
2461 if ((zip->flags & 0xf000) == 0 ||
2462 (zip->flags & 0xf000) == 0x4000) {
2463 archive_set_error(&a->archive,
2464 ARCHIVE_ERRNO_FILE_FORMAT,
2465 "Unknown encryption flag: %u", zip->flags);
2466 return (ARCHIVE_FAILED);
2470 * Read an encrypted random data field.
2473 zip->erd_size = archive_le16dec(p+12);
2474 __archive_read_consume(a, 14);
2475 if ((zip->erd_size & 0xf) != 0 ||
2476 (zip->erd_size + 16) > remaining_size ||
2477 (zip->erd_size + 16) < zip->erd_size)
2480 if (ts < zip->erd_size) {
2484 p = __archive_read_ahead(a, zip->erd_size, NULL);
2487 if (zip->erd == NULL) {
2488 zip->erd = malloc(zip->erd_size);
2489 if (zip->erd == NULL)
2492 memcpy(zip->erd, p, zip->erd_size);
2493 __archive_read_consume(a, zip->erd_size);
2496 * Read a reserved data field.
2498 p = __archive_read_ahead(a, 4, NULL);
2501 /* Reserved data size should be zero. */
2502 if (archive_le32dec(p) != 0)
2504 __archive_read_consume(a, 4);
2507 * Read a password validation data field.
2509 p = __archive_read_ahead(a, 2, NULL);
2513 zip->v_size = archive_le16dec(p);
2514 __archive_read_consume(a, 2);
2515 if ((zip->v_size & 0x0f) != 0 ||
2516 (zip->erd_size + zip->v_size + 16) > remaining_size ||
2517 (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2519 if (ts < zip->v_size) {
2523 p = __archive_read_ahead(a, zip->v_size, NULL);
2526 if (zip->v_data == NULL) {
2527 zip->v_data = malloc(zip->v_size);
2528 if (zip->v_data == NULL)
2531 memcpy(zip->v_data, p, zip->v_size);
2532 __archive_read_consume(a, zip->v_size);
2534 p = __archive_read_ahead(a, 4, NULL);
2537 zip->v_crc32 = archive_le32dec(p);
2538 __archive_read_consume(a, 4);
2540 /*return (ARCHIVE_OK);
2541 * This is not fully implemented yet.*/
2542 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2543 "Encrypted file is unsupported");
2544 return (ARCHIVE_FAILED);
2546 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2547 "Truncated ZIP file data");
2548 return (ARCHIVE_FATAL);
2550 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2551 "Corrupted ZIP file data");
2552 return (ARCHIVE_FATAL);
2554 archive_set_error(&a->archive, ENOMEM,
2555 "No memory for ZIP decryption");
2556 return (ARCHIVE_FATAL);
2560 zip_alloc_decryption_buffer(struct archive_read *a)
2562 struct zip *zip = (struct zip *)(a->format->data);
2563 size_t bs = 256 * 1024;
2565 if (zip->decrypted_buffer == NULL) {
2566 zip->decrypted_buffer_size = bs;
2567 zip->decrypted_buffer = malloc(bs);
2568 if (zip->decrypted_buffer == NULL) {
2569 archive_set_error(&a->archive, ENOMEM,
2570 "No memory for ZIP decryption");
2571 return (ARCHIVE_FATAL);
2574 zip->decrypted_ptr = zip->decrypted_buffer;
2575 return (ARCHIVE_OK);
2579 init_traditional_PKWARE_decryption(struct archive_read *a)
2581 struct zip *zip = (struct zip *)(a->format->data);
2586 if (zip->tctx_valid)
2587 return (ARCHIVE_OK);
2590 Read the 12 bytes encryption header stored at
2591 the start of the data area.
2593 #define ENC_HEADER_SIZE 12
2594 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2595 && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2596 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2597 "Truncated Zip encrypted body: only %jd bytes available",
2598 (intmax_t)zip->entry_bytes_remaining);
2599 return (ARCHIVE_FATAL);
2602 p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2604 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2605 "Truncated ZIP file data");
2606 return (ARCHIVE_FATAL);
2609 for (retry = 0;; retry++) {
2610 const char *passphrase;
2613 passphrase = __archive_read_next_passphrase(a);
2614 if (passphrase == NULL) {
2615 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2617 "Incorrect passphrase":
2618 "Passphrase required for this entry");
2619 return (ARCHIVE_FAILED);
2623 * Initialize ctx for Traditional PKWARE Decryption.
2625 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2626 p, ENC_HEADER_SIZE, &crcchk);
2627 if (r == 0 && crcchk == zip->entry->decdat)
2628 break;/* The passphrase is OK. */
2629 if (retry > 10000) {
2630 /* Avoid infinity loop. */
2631 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2632 "Too many incorrect passphrases");
2633 return (ARCHIVE_FAILED);
2637 __archive_read_consume(a, ENC_HEADER_SIZE);
2638 zip->tctx_valid = 1;
2639 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2640 zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2642 /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2643 zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2644 zip->decrypted_bytes_remaining = 0;
2646 return (zip_alloc_decryption_buffer(a));
2647 #undef ENC_HEADER_SIZE
2651 init_WinZip_AES_decryption(struct archive_read *a)
2653 struct zip *zip = (struct zip *)(a->format->data);
2656 size_t key_len, salt_len;
2657 uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2661 if (zip->cctx_valid || zip->hctx_valid)
2662 return (ARCHIVE_OK);
2664 switch (zip->entry->aes_extra.strength) {
2665 case 1: salt_len = 8; key_len = 16; break;
2666 case 2: salt_len = 12; key_len = 24; break;
2667 case 3: salt_len = 16; key_len = 32; break;
2668 default: goto corrupted;
2670 p = __archive_read_ahead(a, salt_len + 2, NULL);
2674 for (retry = 0;; retry++) {
2675 const char *passphrase;
2677 passphrase = __archive_read_next_passphrase(a);
2678 if (passphrase == NULL) {
2679 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2681 "Incorrect passphrase":
2682 "Passphrase required for this entry");
2683 return (ARCHIVE_FAILED);
2685 memset(derived_key, 0, sizeof(derived_key));
2686 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2687 p, salt_len, 1000, derived_key, key_len * 2 + 2);
2689 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2690 "Decryption is unsupported due to lack of "
2692 return (ARCHIVE_FAILED);
2695 /* Check password verification value. */
2696 pv = ((const uint8_t *)p) + salt_len;
2697 if (derived_key[key_len * 2] == pv[0] &&
2698 derived_key[key_len * 2 + 1] == pv[1])
2699 break;/* The passphrase is OK. */
2700 if (retry > 10000) {
2701 /* Avoid infinity loop. */
2702 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2703 "Too many incorrect passphrases");
2704 return (ARCHIVE_FAILED);
2708 r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2710 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2711 "Decryption is unsupported due to lack of crypto library");
2712 return (ARCHIVE_FAILED);
2714 r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2716 archive_decrypto_aes_ctr_release(&zip->cctx);
2717 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2718 "Failed to initialize HMAC-SHA1");
2719 return (ARCHIVE_FAILED);
2721 zip->cctx_valid = zip->hctx_valid = 1;
2722 __archive_read_consume(a, salt_len + 2);
2723 zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2724 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2725 && zip->entry_bytes_remaining < 0)
2727 zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2728 zip->decrypted_bytes_remaining = 0;
2730 zip->entry->compression = zip->entry->aes_extra.compression;
2731 return (zip_alloc_decryption_buffer(a));
2734 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2735 "Truncated ZIP file data");
2736 return (ARCHIVE_FATAL);
2738 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2739 "Corrupted ZIP file data");
2740 return (ARCHIVE_FATAL);
2744 archive_read_format_zip_read_data(struct archive_read *a,
2745 const void **buff, size_t *size, int64_t *offset)
2748 struct zip *zip = (struct zip *)(a->format->data);
2750 if (zip->has_encrypted_entries ==
2751 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2752 zip->has_encrypted_entries = 0;
2755 *offset = zip->entry_uncompressed_bytes_read;
2759 /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2760 if (zip->end_of_entry)
2761 return (ARCHIVE_EOF);
2763 /* Return EOF immediately if this is a non-regular file. */
2764 if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2765 return (ARCHIVE_EOF);
2767 __archive_read_consume(a, zip->unconsumed);
2768 zip->unconsumed = 0;
2770 if (zip->init_decryption) {
2771 zip->has_encrypted_entries = 1;
2772 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2773 r = read_decryption_header(a);
2774 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2775 r = init_WinZip_AES_decryption(a);
2777 r = init_traditional_PKWARE_decryption(a);
2778 if (r != ARCHIVE_OK)
2780 zip->init_decryption = 0;
2783 switch(zip->entry->compression) {
2784 case 0: /* No compression. */
2785 r = zip_read_data_none(a, buff, size, offset);
2788 case 12: /* ZIPx bzip2 compression. */
2789 r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2792 #if HAVE_LZMA_H && HAVE_LIBLZMA
2793 case 14: /* ZIPx LZMA compression. */
2794 r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
2796 case 95: /* ZIPx XZ compression. */
2797 r = zip_read_data_zipx_xz(a, buff, size, offset);
2800 /* PPMd support is built-in, so we don't need any #if guards. */
2801 case 98: /* ZIPx PPMd compression. */
2802 r = zip_read_data_zipx_ppmd(a, buff, size, offset);
2806 case 8: /* Deflate compression. */
2807 r = zip_read_data_deflate(a, buff, size, offset);
2810 default: /* Unsupported compression. */
2811 /* Return a warning. */
2812 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2813 "Unsupported ZIP compression method (%d: %s)",
2814 zip->entry->compression, compression_name(zip->entry->compression));
2815 /* We can't decompress this entry, but we will
2816 * be able to skip() it and try the next entry. */
2817 return (ARCHIVE_FAILED);
2820 if (r != ARCHIVE_OK)
2822 /* Update checksum */
2824 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
2826 /* If we hit the end, swallow any end-of-data marker. */
2827 if (zip->end_of_entry) {
2828 /* Check file size, CRC against these values. */
2829 if (zip->entry->compressed_size !=
2830 zip->entry_compressed_bytes_read) {
2831 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2832 "ZIP compressed data is wrong size "
2833 "(read %jd, expected %jd)",
2834 (intmax_t)zip->entry_compressed_bytes_read,
2835 (intmax_t)zip->entry->compressed_size);
2836 return (ARCHIVE_WARN);
2838 /* Size field only stores the lower 32 bits of the actual
2840 if ((zip->entry->uncompressed_size & UINT32_MAX)
2841 != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
2842 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2843 "ZIP uncompressed data is wrong size "
2844 "(read %jd, expected %jd)\n",
2845 (intmax_t)zip->entry_uncompressed_bytes_read,
2846 (intmax_t)zip->entry->uncompressed_size);
2847 return (ARCHIVE_WARN);
2849 /* Check computed CRC against header */
2850 if ((!zip->hctx_valid ||
2851 zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
2852 zip->entry->crc32 != zip->entry_crc32
2853 && !zip->ignore_crc32) {
2854 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2855 "ZIP bad CRC: 0x%lx should be 0x%lx",
2856 (unsigned long)zip->entry_crc32,
2857 (unsigned long)zip->entry->crc32);
2858 return (ARCHIVE_WARN);
2862 return (ARCHIVE_OK);
2866 archive_read_format_zip_cleanup(struct archive_read *a)
2869 struct zip_entry *zip_entry, *next_zip_entry;
2871 zip = (struct zip *)(a->format->data);
2874 if (zip->stream_valid)
2875 inflateEnd(&zip->stream);
2878 #if HAVE_LZMA_H && HAVE_LIBLZMA
2879 if (zip->zipx_lzma_valid) {
2880 lzma_end(&zip->zipx_lzma_stream);
2885 if (zip->bzstream_valid) {
2886 BZ2_bzDecompressEnd(&zip->bzstream);
2890 free(zip->uncompressed_buffer);
2892 if (zip->ppmd8_valid)
2893 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2895 if (zip->zip_entries) {
2896 zip_entry = zip->zip_entries;
2897 while (zip_entry != NULL) {
2898 next_zip_entry = zip_entry->next;
2899 archive_string_free(&zip_entry->rsrcname);
2901 zip_entry = next_zip_entry;
2904 free(zip->decrypted_buffer);
2905 if (zip->cctx_valid)
2906 archive_decrypto_aes_ctr_release(&zip->cctx);
2907 if (zip->hctx_valid)
2908 archive_hmac_sha1_cleanup(&zip->hctx);
2912 archive_string_free(&zip->format_name);
2914 (a->format->data) = NULL;
2915 return (ARCHIVE_OK);
2919 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
2921 if (_a && _a->format) {
2922 struct zip * zip = (struct zip *)_a->format->data;
2924 return zip->has_encrypted_entries;
2927 return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2931 archive_read_format_zip_options(struct archive_read *a,
2932 const char *key, const char *val)
2935 int ret = ARCHIVE_FAILED;
2937 zip = (struct zip *)(a->format->data);
2938 if (strcmp(key, "compat-2x") == 0) {
2939 /* Handle filenames as libarchive 2.x */
2940 zip->init_default_conversion = (val != NULL) ? 1 : 0;
2941 return (ARCHIVE_OK);
2942 } else if (strcmp(key, "hdrcharset") == 0) {
2943 if (val == NULL || val[0] == 0)
2944 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2945 "zip: hdrcharset option needs a character-set name"
2948 zip->sconv = archive_string_conversion_from_charset(
2949 &a->archive, val, 0);
2950 if (zip->sconv != NULL) {
2951 if (strcmp(val, "UTF-8") == 0)
2952 zip->sconv_utf8 = zip->sconv;
2955 ret = ARCHIVE_FATAL;
2958 } else if (strcmp(key, "ignorecrc32") == 0) {
2959 /* Mostly useful for testing. */
2960 if (val == NULL || val[0] == 0) {
2961 zip->crc32func = real_crc32;
2962 zip->ignore_crc32 = 0;
2964 zip->crc32func = fake_crc32;
2965 zip->ignore_crc32 = 1;
2967 return (ARCHIVE_OK);
2968 } else if (strcmp(key, "mac-ext") == 0) {
2969 zip->process_mac_extensions = (val != NULL && val[0] != 0);
2970 return (ARCHIVE_OK);
2973 /* Note: The "warn" return is just to inform the options
2974 * supervisor that we didn't handle it. It will generate
2975 * a suitable error if no one used this option. */
2976 return (ARCHIVE_WARN);
2980 archive_read_support_format_zip(struct archive *a)
2983 r = archive_read_support_format_zip_streamable(a);
2984 if (r != ARCHIVE_OK)
2986 return (archive_read_support_format_zip_seekable(a));
2989 /* ------------------------------------------------------------------------ */
2992 * Streaming-mode support
2997 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
2999 (void)a; /* UNUSED */
3000 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3001 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3005 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
3009 (void)best_bid; /* UNUSED */
3011 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3015 * Bid of 29 here comes from:
3016 * + 16 bits for "PK",
3017 * + next 16-bit field has 6 options so contributes
3018 * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
3020 * So we've effectively verified ~29 total bits of check data.
3022 if (p[0] == 'P' && p[1] == 'K') {
3023 if ((p[2] == '\001' && p[3] == '\002')
3024 || (p[2] == '\003' && p[3] == '\004')
3025 || (p[2] == '\005' && p[3] == '\006')
3026 || (p[2] == '\006' && p[3] == '\006')
3027 || (p[2] == '\007' && p[3] == '\010')
3028 || (p[2] == '0' && p[3] == '0'))
3032 /* TODO: It's worth looking ahead a little bit for a valid
3033 * PK signature. In particular, that would make it possible
3034 * to read some UUEncoded SFX files or SFX files coming from
3035 * a network socket. */
3041 archive_read_format_zip_streamable_read_header(struct archive_read *a,
3042 struct archive_entry *entry)
3046 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3047 if (a->archive.archive_format_name == NULL)
3048 a->archive.archive_format_name = "ZIP";
3050 zip = (struct zip *)(a->format->data);
3053 * It should be sufficient to call archive_read_next_header() for
3054 * a reader to determine if an entry is encrypted or not. If the
3055 * encryption of an entry is only detectable when calling
3056 * archive_read_data(), so be it. We'll do the same check there
3059 if (zip->has_encrypted_entries ==
3060 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3061 zip->has_encrypted_entries = 0;
3063 /* Make sure we have a zip_entry structure to use. */
3064 if (zip->zip_entries == NULL) {
3065 zip->zip_entries = malloc(sizeof(struct zip_entry));
3066 if (zip->zip_entries == NULL) {
3067 archive_set_error(&a->archive, ENOMEM,
3069 return ARCHIVE_FATAL;
3072 zip->entry = zip->zip_entries;
3073 memset(zip->entry, 0, sizeof(struct zip_entry));
3075 if (zip->cctx_valid)
3076 archive_decrypto_aes_ctr_release(&zip->cctx);
3077 if (zip->hctx_valid)
3078 archive_hmac_sha1_cleanup(&zip->hctx);
3079 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3080 __archive_read_reset_passphrase(a);
3082 /* Search ahead for the next local file header. */
3083 __archive_read_consume(a, zip->unconsumed);
3084 zip->unconsumed = 0;
3086 int64_t skipped = 0;
3087 const char *p, *end;
3090 p = __archive_read_ahead(a, 4, &bytes);
3092 return (ARCHIVE_FATAL);
3095 while (p + 4 <= end) {
3096 if (p[0] == 'P' && p[1] == 'K') {
3097 if (p[2] == '\003' && p[3] == '\004') {
3098 /* Regular file entry. */
3099 __archive_read_consume(a, skipped);
3100 return zip_read_local_file_header(a,
3105 * TODO: We cannot restore permissions
3106 * based only on the local file headers.
3107 * Consider scanning the central
3108 * directory and returning additional
3109 * entries for at least directories.
3110 * This would allow us to properly set
3111 * directory permissions.
3113 * This won't help us fix symlinks
3114 * and may not help with regular file
3115 * permissions, either. <sigh>
3117 if (p[2] == '\001' && p[3] == '\002') {
3118 return (ARCHIVE_EOF);
3121 /* End of central directory? Must be an
3123 if ((p[2] == '\005' && p[3] == '\006')
3124 || (p[2] == '\006' && p[3] == '\006'))
3125 return (ARCHIVE_EOF);
3130 __archive_read_consume(a, skipped);
3135 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3138 int64_t bytes_skipped;
3140 zip = (struct zip *)(a->format->data);
3141 bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3142 zip->unconsumed = 0;
3143 if (bytes_skipped < 0)
3144 return (ARCHIVE_FATAL);
3146 /* If we've already read to end of data, we're done. */
3147 if (zip->end_of_entry)
3148 return (ARCHIVE_OK);
3150 /* So we know we're streaming... */
3151 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3152 || zip->entry->compressed_size > 0) {
3153 /* We know the compressed length, so we can just skip. */
3154 bytes_skipped = __archive_read_consume(a,
3155 zip->entry_bytes_remaining);
3156 if (bytes_skipped < 0)
3157 return (ARCHIVE_FATAL);
3158 return (ARCHIVE_OK);
3161 if (zip->init_decryption) {
3164 zip->has_encrypted_entries = 1;
3165 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3166 r = read_decryption_header(a);
3167 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3168 r = init_WinZip_AES_decryption(a);
3170 r = init_traditional_PKWARE_decryption(a);
3171 if (r != ARCHIVE_OK)
3173 zip->init_decryption = 0;
3176 /* We're streaming and we don't know the length. */
3177 /* If the body is compressed and we know the format, we can
3178 * find an exact end-of-entry by decompressing it. */
3179 switch (zip->entry->compression) {
3181 case 8: /* Deflate compression. */
3182 while (!zip->end_of_entry) {
3184 const void *buff = NULL;
3187 r = zip_read_data_deflate(a, &buff, &size, &offset);
3188 if (r != ARCHIVE_OK)
3193 default: /* Uncompressed or unknown. */
3194 /* Scan for a PK\007\010 signature. */
3196 const char *p, *buff;
3197 ssize_t bytes_avail;
3198 buff = __archive_read_ahead(a, 16, &bytes_avail);
3199 if (bytes_avail < 16) {
3200 archive_set_error(&a->archive,
3201 ARCHIVE_ERRNO_FILE_FORMAT,
3202 "Truncated ZIP file data");
3203 return (ARCHIVE_FATAL);
3206 while (p <= buff + bytes_avail - 16) {
3207 if (p[3] == 'P') { p += 3; }
3208 else if (p[3] == 'K') { p += 2; }
3209 else if (p[3] == '\007') { p += 1; }
3210 else if (p[3] == '\010' && p[2] == '\007'
3211 && p[1] == 'K' && p[0] == 'P') {
3212 if (zip->entry->flags & LA_USED_ZIP64)
3213 __archive_read_consume(a,
3216 __archive_read_consume(a,
3221 __archive_read_consume(a, p - buff);
3227 archive_read_support_format_zip_streamable(struct archive *_a)
3229 struct archive_read *a = (struct archive_read *)_a;
3233 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3234 ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3236 zip = (struct zip *)calloc(1, sizeof(*zip));
3238 archive_set_error(&a->archive, ENOMEM,
3239 "Can't allocate zip data");
3240 return (ARCHIVE_FATAL);
3243 /* Streamable reader doesn't support mac extensions. */
3244 zip->process_mac_extensions = 0;
3247 * Until enough data has been read, we cannot tell about
3248 * any encrypted entries yet.
3250 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3251 zip->crc32func = real_crc32;
3253 r = __archive_read_register_format(a,
3256 archive_read_format_zip_streamable_bid,
3257 archive_read_format_zip_options,
3258 archive_read_format_zip_streamable_read_header,
3259 archive_read_format_zip_read_data,
3260 archive_read_format_zip_read_data_skip_streamable,
3262 archive_read_format_zip_cleanup,
3263 archive_read_support_format_zip_capabilities_streamable,
3264 archive_read_format_zip_has_encrypted_entries);
3266 if (r != ARCHIVE_OK)
3268 return (ARCHIVE_OK);
3271 /* ------------------------------------------------------------------------ */
3274 * Seeking-mode support
3278 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3280 (void)a; /* UNUSED */
3281 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3282 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3286 * TODO: This is a performance sink because it forces the read core to
3287 * drop buffered data from the start of file, which will then have to
3288 * be re-read again if this bidder loses.
3290 * We workaround this a little by passing in the best bid so far so
3291 * that later bidders can do nothing if they know they'll never
3292 * outbid. But we can certainly do better...
3295 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3297 /* Sanity-check the EOCD we've found. */
3299 /* This must be the first volume. */
3300 if (archive_le16dec(p + 4) != 0)
3302 /* Central directory must be on this volume. */
3303 if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
3305 /* All central directory entries must be on this volume. */
3306 if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3308 /* Central directory can't extend beyond start of EOCD record. */
3309 if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
3313 /* Save the central directory location for later use. */
3314 zip->central_directory_offset = archive_le32dec(p + 16);
3316 /* This is just a tiny bit higher than the maximum
3317 returned by the streaming Zip bidder. This ensures
3318 that the more accurate seeking Zip parser wins
3319 whenever seek is available. */
3324 * Examine Zip64 EOCD locator: If it's valid, store the information
3328 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3330 int64_t eocd64_offset;
3331 int64_t eocd64_size;
3333 /* Sanity-check the locator record. */
3335 /* Central dir must be on first volume. */
3336 if (archive_le32dec(p + 4) != 0)
3338 /* Must be only a single volume. */
3339 if (archive_le32dec(p + 16) != 1)
3342 /* Find the Zip64 EOCD record. */
3343 eocd64_offset = archive_le64dec(p + 8);
3344 if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3346 if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3348 /* Make sure we can read all of it. */
3349 eocd64_size = archive_le64dec(p + 4) + 12;
3350 if (eocd64_size < 56 || eocd64_size > 16384)
3352 if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3355 /* Sanity-check the EOCD64 */
3356 if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3358 if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3360 /* CD can't be split. */
3361 if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3364 /* Save the central directory offset for later use. */
3365 zip->central_directory_offset = archive_le64dec(p + 48);
3371 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3373 struct zip *zip = (struct zip *)a->format->data;
3374 int64_t file_size, current_offset;
3378 /* If someone has already bid more than 32, then avoid
3379 trashing the look-ahead buffers with a seek. */
3383 file_size = __archive_read_seek(a, 0, SEEK_END);
3387 /* Search last 16k of file for end-of-central-directory
3388 * record (which starts with PK\005\006) */
3389 tail = (int)zipmin(1024 * 16, file_size);
3390 current_offset = __archive_read_seek(a, -tail, SEEK_END);
3391 if (current_offset < 0)
3393 if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3395 /* Boyer-Moore search backwards from the end, since we want
3396 * to match the last EOCD in the file (there can be more than
3397 * one if there is an uncompressed Zip archive as a member
3398 * within this Zip archive). */
3399 for (i = tail - 22; i > 0;) {
3402 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3403 int ret = read_eocd(zip, p + i,
3404 current_offset + i);
3405 /* Zip64 EOCD locator precedes
3406 * regular EOCD if present. */
3407 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3408 int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3409 if (ret_zip64 > ret)
3416 case 'K': i -= 1; break;
3417 case 005: i -= 2; break;
3418 case 006: i -= 3; break;
3419 default: i -= 4; break;
3425 /* The red-black trees are only used in seeking mode to manage
3426 * the in-memory copy of the central directory. */
3429 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3431 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3432 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3434 if (e1->local_header_offset > e2->local_header_offset)
3436 if (e1->local_header_offset < e2->local_header_offset)
3442 cmp_key(const struct archive_rb_node *n, const void *key)
3444 /* This function won't be called */
3445 (void)n; /* UNUSED */
3446 (void)key; /* UNUSED */
3450 static const struct archive_rb_tree_ops rb_ops = {
3455 rsrc_cmp_node(const struct archive_rb_node *n1,
3456 const struct archive_rb_node *n2)
3458 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3459 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3461 return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3465 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3467 const struct zip_entry *e = (const struct zip_entry *)n;
3468 return (strcmp((const char *)key, e->rsrcname.s));
3471 static const struct archive_rb_tree_ops rb_rsrc_ops = {
3472 &rsrc_cmp_node, &rsrc_cmp_key
3476 rsrc_basename(const char *name, size_t name_length)
3482 s = memchr(s, '/', name_length - (s - name));
3491 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3493 struct archive_string str;
3494 struct zip_entry *dir;
3497 archive_string_init(&str);
3498 archive_strncpy(&str, name, name_length);
3500 s = strrchr(str.s, '/');
3504 /* Transfer the parent directory from zip->tree_rsrc RB
3505 * tree to zip->tree RB tree to expose. */
3506 dir = (struct zip_entry *)
3507 __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3510 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3511 archive_string_free(&dir->rsrcname);
3512 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
3514 archive_string_free(&str);
3518 slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
3524 ssize_t bytes_avail;
3528 * Find the start of the central directory. The end-of-CD
3529 * record has our starting point, but there are lots of
3530 * Zip archives which have had other data prepended to the
3531 * file, which makes the recorded offsets all too small.
3532 * So we search forward from the specified offset until we
3533 * find the real start of the central directory. Then we
3534 * know the correction we need to apply to account for leading
3537 if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
3538 return ARCHIVE_FATAL;
3542 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3543 return ARCHIVE_FATAL;
3544 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3546 case 'P': i += 3; break;
3547 case 'K': i += 2; break;
3548 case 001: i += 1; break;
3550 if (memcmp(p + i, "PK\001\002", 4) == 0) {
3556 case 005: i += 1; break;
3558 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3561 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3567 default: i += 4; break;
3570 __archive_read_consume(a, i);
3572 correction = archive_filter_bytes(&a->archive, 0)
3573 - zip->central_directory_offset;
3575 __archive_rb_tree_init(&zip->tree, &rb_ops);
3576 __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3578 zip->central_directory_entries_total = 0;
3580 struct zip_entry *zip_entry;
3581 size_t filename_length, extra_length, comment_length;
3582 uint32_t external_attributes;
3583 const char *name, *r;
3585 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3586 return ARCHIVE_FATAL;
3587 if (memcmp(p, "PK\006\006", 4) == 0
3588 || memcmp(p, "PK\005\006", 4) == 0) {
3590 } else if (memcmp(p, "PK\001\002", 4) != 0) {
3591 archive_set_error(&a->archive,
3592 -1, "Invalid central directory signature");
3593 return ARCHIVE_FATAL;
3595 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3596 return ARCHIVE_FATAL;
3598 zip_entry = calloc(1, sizeof(struct zip_entry));
3599 if (zip_entry == NULL) {
3600 archive_set_error(&a->archive, ENOMEM,
3601 "Can't allocate zip entry");
3602 return ARCHIVE_FATAL;
3604 zip_entry->next = zip->zip_entries;
3605 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3606 zip->zip_entries = zip_entry;
3607 zip->central_directory_entries_total++;
3609 /* version = p[4]; */
3610 zip_entry->system = p[5];
3611 /* version_required = archive_le16dec(p + 6); */
3612 zip_entry->zip_flags = archive_le16dec(p + 8);
3613 if (zip_entry->zip_flags
3614 & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3615 zip->has_encrypted_entries = 1;
3617 zip_entry->compression = (char)archive_le16dec(p + 10);
3618 zip_entry->mtime = zip_time(p + 12);
3619 zip_entry->crc32 = archive_le32dec(p + 16);
3620 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3621 zip_entry->decdat = p[13];
3623 zip_entry->decdat = p[19];
3624 zip_entry->compressed_size = archive_le32dec(p + 20);
3625 zip_entry->uncompressed_size = archive_le32dec(p + 24);
3626 filename_length = archive_le16dec(p + 28);
3627 extra_length = archive_le16dec(p + 30);
3628 comment_length = archive_le16dec(p + 32);
3629 /* disk_start = archive_le16dec(p + 34);
3631 * internal_attributes = archive_le16dec(p + 36);
3633 external_attributes = archive_le32dec(p + 38);
3634 zip_entry->local_header_offset =
3635 archive_le32dec(p + 42) + correction;
3637 /* If we can't guess the mode, leave it zero here;
3638 when we read the local file header we might get
3639 more information. */
3640 if (zip_entry->system == 3) {
3641 zip_entry->mode = external_attributes >> 16;
3642 } else if (zip_entry->system == 0) {
3643 // Interpret MSDOS directory bit
3644 if (0x10 == (external_attributes & 0x10)) {
3645 zip_entry->mode = AE_IFDIR | 0775;
3647 zip_entry->mode = AE_IFREG | 0664;
3649 if (0x01 == (external_attributes & 0x01)) {
3650 // Read-only bit; strip write permissions
3651 zip_entry->mode &= 0555;
3654 zip_entry->mode = 0;
3657 /* We're done with the regular data; get the filename and
3659 __archive_read_consume(a, 46);
3660 p = __archive_read_ahead(a, filename_length + extra_length,
3663 archive_set_error(&a->archive,
3664 ARCHIVE_ERRNO_FILE_FORMAT,
3665 "Truncated ZIP file header");
3666 return ARCHIVE_FATAL;
3668 if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
3669 extra_length, zip_entry)) {
3670 return ARCHIVE_FATAL;
3674 * Mac resource fork files are stored under the
3675 * "__MACOSX/" directory, so we should check if
3678 if (!zip->process_mac_extensions) {
3679 /* Treat every entry as a regular entry. */
3680 __archive_rb_tree_insert_node(&zip->tree,
3684 r = rsrc_basename(name, filename_length);
3685 if (filename_length >= 9 &&
3686 strncmp("__MACOSX/", name, 9) == 0) {
3687 /* If this file is not a resource fork nor
3688 * a directory. We should treat it as a non
3689 * resource fork file to expose it. */
3690 if (name[filename_length-1] != '/' &&
3691 (r - name < 3 || r[0] != '.' ||
3693 __archive_rb_tree_insert_node(
3694 &zip->tree, &zip_entry->node);
3695 /* Expose its parent directories. */
3696 expose_parent_dirs(zip, name,
3699 /* This file is a resource fork file or
3701 archive_strncpy(&(zip_entry->rsrcname),
3702 name, filename_length);
3703 __archive_rb_tree_insert_node(
3704 &zip->tree_rsrc, &zip_entry->node);
3707 /* Generate resource fork name to find its
3708 * resource file at zip->tree_rsrc. */
3709 archive_strcpy(&(zip_entry->rsrcname),
3711 archive_strncat(&(zip_entry->rsrcname),
3713 archive_strcat(&(zip_entry->rsrcname), "._");
3714 archive_strncat(&(zip_entry->rsrcname),
3716 filename_length - (r - name));
3717 /* Register an entry to RB tree to sort it by
3719 __archive_rb_tree_insert_node(&zip->tree,
3724 /* Skip the comment too ... */
3725 __archive_read_consume(a,
3726 filename_length + extra_length + comment_length);
3733 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3736 ssize_t filename_length, extra_length;
3738 if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3739 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3740 "Truncated ZIP file header");
3741 return (ARCHIVE_WARN);
3745 if (memcmp(p, "PK\003\004", 4) != 0) {
3746 archive_set_error(&a->archive, -1, "Damaged Zip archive");
3747 return ARCHIVE_WARN;
3749 filename_length = archive_le16dec(p + 26);
3750 extra_length = archive_le16dec(p + 28);
3752 return (30 + filename_length + extra_length);
3756 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3757 struct zip_entry *rsrc)
3759 struct zip *zip = (struct zip *)a->format->data;
3760 unsigned char *metadata, *mp;
3761 int64_t offset = archive_filter_bytes(&a->archive, 0);
3762 size_t remaining_bytes, metadata_bytes;
3764 int ret = ARCHIVE_OK, eof;
3766 switch(rsrc->compression) {
3767 case 0: /* No compression. */
3768 if (rsrc->uncompressed_size != rsrc->compressed_size) {
3769 archive_set_error(&a->archive,
3770 ARCHIVE_ERRNO_FILE_FORMAT,
3771 "Malformed OS X metadata entry: "
3772 "inconsistent size");
3773 return (ARCHIVE_FATAL);
3776 case 8: /* Deflate compression. */
3779 default: /* Unsupported compression. */
3780 /* Return a warning. */
3781 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3782 "Unsupported ZIP compression method (%s)",
3783 compression_name(rsrc->compression));
3784 /* We can't decompress this entry, but we will
3785 * be able to skip() it and try the next entry. */
3786 return (ARCHIVE_WARN);
3789 if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
3790 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3791 "Mac metadata is too large: %jd > 4M bytes",
3792 (intmax_t)rsrc->uncompressed_size);
3793 return (ARCHIVE_WARN);
3795 if (rsrc->compressed_size > (4 * 1024 * 1024)) {
3796 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3797 "Mac metadata is too large: %jd > 4M bytes",
3798 (intmax_t)rsrc->compressed_size);
3799 return (ARCHIVE_WARN);
3802 metadata = malloc((size_t)rsrc->uncompressed_size);
3803 if (metadata == NULL) {
3804 archive_set_error(&a->archive, ENOMEM,
3805 "Can't allocate memory for Mac metadata");
3806 return (ARCHIVE_FATAL);
3809 if (offset < rsrc->local_header_offset)
3810 __archive_read_consume(a, rsrc->local_header_offset - offset);
3811 else if (offset != rsrc->local_header_offset) {
3812 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
3815 hsize = zip_get_local_file_header_size(a, 0);
3816 __archive_read_consume(a, hsize);
3818 remaining_bytes = (size_t)rsrc->compressed_size;
3819 metadata_bytes = (size_t)rsrc->uncompressed_size;
3822 while (!eof && remaining_bytes) {
3823 const unsigned char *p;
3824 ssize_t bytes_avail;
3827 p = __archive_read_ahead(a, 1, &bytes_avail);
3829 archive_set_error(&a->archive,
3830 ARCHIVE_ERRNO_FILE_FORMAT,
3831 "Truncated ZIP file header");
3833 goto exit_mac_metadata;
3835 if ((size_t)bytes_avail > remaining_bytes)
3836 bytes_avail = remaining_bytes;
3837 switch(rsrc->compression) {
3838 case 0: /* No compression. */
3839 if ((size_t)bytes_avail > metadata_bytes)
3840 bytes_avail = metadata_bytes;
3841 memcpy(mp, p, bytes_avail);
3842 bytes_used = (size_t)bytes_avail;
3843 metadata_bytes -= bytes_used;
3845 if (metadata_bytes == 0)
3849 case 8: /* Deflate compression. */
3853 ret = zip_deflate_init(a, zip);
3854 if (ret != ARCHIVE_OK)
3855 goto exit_mac_metadata;
3856 zip->stream.next_in =
3857 (Bytef *)(uintptr_t)(const void *)p;
3858 zip->stream.avail_in = (uInt)bytes_avail;
3859 zip->stream.total_in = 0;
3860 zip->stream.next_out = mp;
3861 zip->stream.avail_out = (uInt)metadata_bytes;
3862 zip->stream.total_out = 0;
3864 r = inflate(&zip->stream, 0);
3872 archive_set_error(&a->archive, ENOMEM,
3873 "Out of memory for ZIP decompression");
3874 ret = ARCHIVE_FATAL;
3875 goto exit_mac_metadata;
3877 archive_set_error(&a->archive,
3879 "ZIP decompression failed (%d)", r);
3880 ret = ARCHIVE_FATAL;
3881 goto exit_mac_metadata;
3883 bytes_used = zip->stream.total_in;
3884 metadata_bytes -= zip->stream.total_out;
3885 mp += zip->stream.total_out;
3893 __archive_read_consume(a, bytes_used);
3894 remaining_bytes -= bytes_used;
3896 archive_entry_copy_mac_metadata(entry, metadata,
3897 (size_t)rsrc->uncompressed_size - metadata_bytes);
3900 __archive_read_seek(a, offset, SEEK_SET);
3901 zip->decompress_init = 0;
3907 archive_read_format_zip_seekable_read_header(struct archive_read *a,
3908 struct archive_entry *entry)
3910 struct zip *zip = (struct zip *)a->format->data;
3911 struct zip_entry *rsrc;
3913 int r, ret = ARCHIVE_OK;
3916 * It should be sufficient to call archive_read_next_header() for
3917 * a reader to determine if an entry is encrypted or not. If the
3918 * encryption of an entry is only detectable when calling
3919 * archive_read_data(), so be it. We'll do the same check there
3922 if (zip->has_encrypted_entries ==
3923 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3924 zip->has_encrypted_entries = 0;
3926 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3927 if (a->archive.archive_format_name == NULL)
3928 a->archive.archive_format_name = "ZIP";
3930 if (zip->zip_entries == NULL) {
3931 r = slurp_central_directory(a, entry, zip);
3932 if (r != ARCHIVE_OK)
3934 /* Get first entry whose local header offset is lower than
3935 * other entries in the archive file. */
3937 (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
3938 } else if (zip->entry != NULL) {
3939 /* Get next entry in local header offset order. */
3940 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
3941 &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
3944 if (zip->entry == NULL)
3947 if (zip->entry->rsrcname.s)
3948 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
3949 &zip->tree_rsrc, zip->entry->rsrcname.s);
3953 if (zip->cctx_valid)
3954 archive_decrypto_aes_ctr_release(&zip->cctx);
3955 if (zip->hctx_valid)
3956 archive_hmac_sha1_cleanup(&zip->hctx);
3957 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3958 __archive_read_reset_passphrase(a);
3960 /* File entries are sorted by the header offset, we should mostly
3961 * use __archive_read_consume to advance a read point to avoid
3962 * redundant data reading. */
3963 offset = archive_filter_bytes(&a->archive, 0);
3964 if (offset < zip->entry->local_header_offset)
3965 __archive_read_consume(a,
3966 zip->entry->local_header_offset - offset);
3967 else if (offset != zip->entry->local_header_offset) {
3968 __archive_read_seek(a, zip->entry->local_header_offset,
3971 zip->unconsumed = 0;
3972 r = zip_read_local_file_header(a, entry, zip);
3973 if (r != ARCHIVE_OK)
3976 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
3984 * We're going to seek for the next header anyway, so we don't
3985 * need to bother doing anything here.
3988 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
3991 zip = (struct zip *)(a->format->data);
3993 zip->unconsumed = 0;
3994 return (ARCHIVE_OK);
3998 archive_read_support_format_zip_seekable(struct archive *_a)
4000 struct archive_read *a = (struct archive_read *)_a;
4004 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
4005 ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
4007 zip = (struct zip *)calloc(1, sizeof(*zip));
4009 archive_set_error(&a->archive, ENOMEM,
4010 "Can't allocate zip data");
4011 return (ARCHIVE_FATAL);
4014 #ifdef HAVE_COPYFILE_H
4015 /* Set this by default on Mac OS. */
4016 zip->process_mac_extensions = 1;
4020 * Until enough data has been read, we cannot tell about
4021 * any encrypted entries yet.
4023 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4024 zip->crc32func = real_crc32;
4026 r = __archive_read_register_format(a,
4029 archive_read_format_zip_seekable_bid,
4030 archive_read_format_zip_options,
4031 archive_read_format_zip_seekable_read_header,
4032 archive_read_format_zip_read_data,
4033 archive_read_format_zip_read_data_skip_seekable,
4035 archive_read_format_zip_cleanup,
4036 archive_read_support_format_zip_capabilities_seekable,
4037 archive_read_format_zip_has_encrypted_entries);
4039 if (r != ARCHIVE_OK)
4041 return (ARCHIVE_OK);