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.
53 #include <cm3p/zlib.h>
56 #include <cm3p/bzlib.h>
59 #include <cm3p/lzma.h>
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 int64_t central_directory_offset_adjusted;
146 size_t central_directory_entries_total;
147 size_t central_directory_entries_on_this_disk;
148 int has_encrypted_entries;
150 /* List of entries (seekable Zip only) */
151 struct zip_entry *zip_entries;
152 struct archive_rb_tree tree;
153 struct archive_rb_tree tree_rsrc;
155 /* Bytes read but not yet consumed via __archive_read_consume() */
158 /* Information about entry we're currently reading. */
159 struct zip_entry *entry;
160 int64_t entry_bytes_remaining;
162 /* These count the number of bytes actually read for the entry. */
163 int64_t entry_compressed_bytes_read;
164 int64_t entry_uncompressed_bytes_read;
166 /* Running CRC32 of the decompressed data */
167 unsigned long entry_crc32;
168 unsigned long (*crc32func)(unsigned long, const void *,
172 /* Flags to mark progress of decompression. */
173 char decompress_init;
176 unsigned char *uncompressed_buffer;
177 size_t uncompressed_buffer_size;
184 #if HAVE_LZMA_H && HAVE_LIBLZMA
185 lzma_stream zipx_lzma_stream;
186 char zipx_lzma_valid;
194 IByteIn zipx_ppmd_stream;
195 ssize_t zipx_ppmd_read_compressed;
198 char ppmd8_stream_failed;
200 struct archive_string_conv *sconv;
201 struct archive_string_conv *sconv_default;
202 struct archive_string_conv *sconv_utf8;
203 int init_default_conversion;
204 int process_mac_extensions;
206 char init_decryption;
208 /* Decryption buffer. */
210 * The decrypted data starts at decrypted_ptr and
211 * extends for decrypted_bytes_remaining. Decryption
212 * adds new data to the end of this block, data is returned
213 * to clients from the beginning. When the block hits the
214 * end of decrypted_buffer, it has to be shuffled back to
215 * the beginning of the buffer.
217 unsigned char *decrypted_buffer;
218 unsigned char *decrypted_ptr;
219 size_t decrypted_buffer_size;
220 size_t decrypted_bytes_remaining;
221 size_t decrypted_unconsumed_bytes;
223 /* Traditional PKWARE decryption. */
224 struct trad_enc_ctx tctx;
227 /* WinZip AES decryption. */
228 /* Contexts used for AES decryption. */
229 archive_crypto_ctx cctx;
231 archive_hmac_sha1_ctx hctx;
234 /* Strong encryption's decryption header information. */
247 /* Many systems define min or MIN, but not all. */
248 #define zipmin(a,b) ((a) < (b) ? (a) : (b))
252 zip_read_data_deflate(struct archive_read *a, const void **buff,
253 size_t *size, int64_t *offset);
255 #if HAVE_LZMA_H && HAVE_LIBLZMA
257 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
258 size_t *size, int64_t *offset);
261 /* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8
262 * streams inside ZIP files. It has 2 purposes: one is to fetch the next
263 * compressed byte from the stream, second one is to increase the counter how
264 * many compressed bytes were read. */
267 /* Get the handle to current decompression context. */
268 struct archive_read *a = ((IByteIn*)p)->a;
269 struct zip *zip = (struct zip*) a->format->data;
270 ssize_t bytes_avail = 0;
272 /* Fetch next byte. */
273 const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail);
274 if(bytes_avail < 1) {
275 zip->ppmd8_stream_failed = 1;
279 __archive_read_consume(a, 1);
281 /* Increment the counter. */
282 ++zip->zipx_ppmd_read_compressed;
284 /* Return the next compressed byte. */
288 /* ------------------------------------------------------------------------ */
291 Traditional PKWARE Decryption functions.
295 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
298 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
300 ctx->keys[0] = CRC32(ctx->keys[0], c);
301 ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
302 t = (ctx->keys[1] >> 24) & 0xff;
303 ctx->keys[2] = CRC32(ctx->keys[2], t);
308 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
310 unsigned temp = ctx->keys[2] | 2;
311 return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
315 trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
316 size_t in_len, uint8_t *out, size_t out_len)
320 max = (unsigned)((in_len < out_len)? in_len: out_len);
322 for (i = 0; i < max; i++) {
323 uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
325 trad_enc_update_keys(ctx, t);
330 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
331 const uint8_t *key, size_t key_len, uint8_t *crcchk)
340 ctx->keys[0] = 305419896L;
341 ctx->keys[1] = 591751049L;
342 ctx->keys[2] = 878082192L;
344 for (;pw_len; --pw_len)
345 trad_enc_update_keys(ctx, *pw++);
347 trad_enc_decrypt_update(ctx, key, 12, header, 12);
348 /* Return the last byte for CRC check. */
349 *crcchk = header[11];
355 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
359 archive_sha1_ctx ctx;
360 unsigned char md1[MD_SIZE];
361 unsigned char md2[MD_SIZE * 2];
362 unsigned char mkb[64];
365 archive_sha1_init(&ctx);
366 archive_sha1_update(&ctx, p, size);
367 archive_sha1_final(&ctx, md1);
369 memset(mkb, 0x36, sizeof(mkb));
370 for (i = 0; i < MD_SIZE; i++)
372 archive_sha1_init(&ctx);
373 archive_sha1_update(&ctx, mkb, sizeof(mkb));
374 archive_sha1_final(&ctx, md2);
376 memset(mkb, 0x5C, sizeof(mkb));
377 for (i = 0; i < MD_SIZE; i++)
379 archive_sha1_init(&ctx);
380 archive_sha1_update(&ctx, mkb, sizeof(mkb));
381 archive_sha1_final(&ctx, md2 + MD_SIZE);
385 memcpy(key, md2, key_size);
391 * Common code for streaming or seeking modes.
393 * Includes code to read local file headers, decompress data
394 * from entry bodies, and common API.
398 real_crc32(unsigned long crc, const void *buff, size_t len)
400 return crc32(crc, buff, (unsigned int)len);
403 /* Used by "ignorecrc32" option to speed up tests. */
405 fake_crc32(unsigned long crc, const void *buff, size_t len)
407 (void)crc; /* UNUSED */
408 (void)buff; /* UNUSED */
409 (void)len; /* UNUSED */
413 static const struct {
416 } compression_methods[] = {
417 {0, "uncompressed"}, /* The file is stored (no compression) */
418 {1, "shrinking"}, /* The file is Shrunk */
419 {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
420 {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
421 {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
422 {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
423 {6, "imploded"}, /* The file is Imploded */
424 {7, "reserved"}, /* Reserved for Tokenizing compression algorithm */
425 {8, "deflation"}, /* The file is Deflated */
426 {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
427 {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
429 {11, "reserved"}, /* Reserved by PKWARE */
430 {12, "bzip"}, /* File is compressed using BZIP2 algorithm */
431 {13, "reserved"}, /* Reserved by PKWARE */
432 {14, "lzma"}, /* LZMA (EFS) */
433 {15, "reserved"}, /* Reserved by PKWARE */
434 {16, "reserved"}, /* Reserved by PKWARE */
435 {17, "reserved"}, /* Reserved by PKWARE */
436 {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
437 {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
438 {95, "xz"}, /* XZ compressed data */
439 {96, "jpeg"}, /* JPEG compressed data */
440 {97, "wav-pack"}, /* WavPack compressed data */
441 {98, "ppmd-1"}, /* PPMd version I, Rev 1 */
442 {99, "aes"} /* WinZip AES encryption */
446 compression_name(const int compression)
448 static const int num_compression_methods =
449 sizeof(compression_methods)/sizeof(compression_methods[0]);
452 while(compression >= 0 && i < num_compression_methods) {
453 if (compression_methods[i].id == compression)
454 return compression_methods[i].name;
460 /* Convert an MSDOS-style date/time into Unix-style time. */
462 zip_time(const char *p)
467 msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
468 msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
470 memset(&ts, 0, sizeof(ts));
471 ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
472 ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
473 ts.tm_mday = msDate & 0x1f; /* Day of month. */
474 ts.tm_hour = (msTime >> 11) & 0x1f;
475 ts.tm_min = (msTime >> 5) & 0x3f;
476 ts.tm_sec = (msTime << 1) & 0x3e;
482 * The extra data is stored as a list of
483 * id1+size1+data1 + id2+size2+data2 ...
484 * triplets. id and size are 2 bytes each.
487 process_extra(struct archive_read *a, struct archive_entry *entry,
488 const char *p, size_t extra_length, struct zip_entry* zip_entry)
491 struct zip *zip = (struct zip *)(a->format->data);
493 if (extra_length == 0) {
497 if (extra_length < 4) {
499 /* Some ZIP files may have trailing 0 bytes. Let's check they
500 * are all 0 and ignore them instead of returning an error.
502 * This is not technically correct, but some ZIP files look
503 * like this and other tools support those files - so let's
506 for (; i < extra_length; i++) {
508 archive_set_error(&a->archive,
509 ARCHIVE_ERRNO_FILE_FORMAT,
510 "Too-small extra data: "
511 "Need at least 4 bytes, "
512 "but only found %d bytes",
514 return ARCHIVE_FAILED;
521 while (offset <= extra_length - 4) {
522 unsigned short headerid = archive_le16dec(p + offset);
523 unsigned short datasize = archive_le16dec(p + offset + 2);
526 if (offset + datasize > extra_length) {
527 archive_set_error(&a->archive,
528 ARCHIVE_ERRNO_FILE_FORMAT, "Extra data overflow: "
529 "Need %d bytes but only found %d bytes",
530 (int)datasize, (int)(extra_length - offset));
531 return ARCHIVE_FAILED;
534 fprintf(stderr, "Header id 0x%04x, length %d\n",
539 /* Zip64 extended information extra field. */
540 zip_entry->flags |= LA_USED_ZIP64;
541 if (zip_entry->uncompressed_size == 0xffffffff) {
544 || (t = archive_le64dec(p + offset)) >
546 archive_set_error(&a->archive,
547 ARCHIVE_ERRNO_FILE_FORMAT,
549 "uncompressed size");
550 return ARCHIVE_FAILED;
552 zip_entry->uncompressed_size = t;
556 if (zip_entry->compressed_size == 0xffffffff) {
559 || (t = archive_le64dec(p + offset)) >
561 archive_set_error(&a->archive,
562 ARCHIVE_ERRNO_FILE_FORMAT,
565 return ARCHIVE_FAILED;
567 zip_entry->compressed_size = t;
571 if (zip_entry->local_header_offset == 0xffffffff) {
574 || (t = archive_le64dec(p + offset)) >
576 archive_set_error(&a->archive,
577 ARCHIVE_ERRNO_FILE_FORMAT,
579 "local header offset");
580 return ARCHIVE_FAILED;
582 zip_entry->local_header_offset = t;
586 /* archive_le32dec(p + offset) gives disk
587 * on which file starts, but we don't handle
588 * multi-volume Zip files. */
593 /* Strong encryption field. */
594 if (archive_le16dec(p + offset) == 2) {
596 archive_le16dec(p + offset + 2);
598 archive_le16dec(p + offset + 4);
600 archive_le16dec(p + offset + 6);
601 fprintf(stderr, "algId=0x%04x, bitLen=%u, "
602 "flgas=%d\n", algId, bitLen,flags);
609 /* Extended time field "UT". */
612 archive_set_error(&a->archive,
613 ARCHIVE_ERRNO_FILE_FORMAT,
614 "Incomplete extended time field");
615 return ARCHIVE_FAILED;
620 /* Flag bits indicate which dates are present. */
624 fprintf(stderr, "mtime: %lld -> %d\n",
625 (long long)zip_entry->mtime,
626 archive_le32dec(p + offset));
630 zip_entry->mtime = archive_le32dec(p + offset);
638 zip_entry->atime = archive_le32dec(p + offset);
646 zip_entry->ctime = archive_le32dec(p + offset);
654 /* Info-ZIP Unix Extra Field (old version) "UX". */
656 zip_entry->atime = archive_le32dec(p + offset);
658 archive_le32dec(p + offset + 4);
660 if (datasize >= 12) {
662 archive_le16dec(p + offset + 8);
664 archive_le16dec(p + offset + 10);
670 /* Experimental 'xl' field */
672 * Introduced Dec 2013 to provide a way to
673 * include external file attributes (and other
674 * fields that ordinarily appear only in
675 * central directory) in local file header.
676 * This provides file type and permission
677 * information necessary to support full
678 * streaming extraction. Currently being
679 * discussed with other Zip developers
680 * ... subject to change.
683 * The field starts with a bitmap that specifies
684 * which additional fields are included. The
685 * bitmap is variable length and can be extended in
688 * n bytes - feature bitmap: first byte has low-order
689 * 7 bits. If high-order bit is set, a subsequent
690 * byte holds the next 7 bits, etc.
692 * if bitmap & 1, 2 byte "version made by"
693 * if bitmap & 2, 2 byte "internal file attributes"
694 * if bitmap & 4, 4 byte "external file attributes"
695 * if bitmap & 8, 2 byte comment length + n byte
698 int bitmap, bitmap_last;
702 bitmap_last = bitmap = 0xff & p[offset];
706 /* We only support first 7 bits of bitmap; skip rest. */
707 while ((bitmap_last & 0x80) != 0
709 bitmap_last = p[offset];
715 /* 2 byte "version made by" */
719 = archive_le16dec(p + offset) >> 8;
724 /* 2 byte "internal file attributes" */
725 uint32_t internal_attributes;
729 = archive_le16dec(p + offset);
730 /* Not used by libarchive at present. */
731 (void)internal_attributes; /* UNUSED */
736 /* 4 byte "external file attributes" */
737 uint32_t external_attributes;
741 = archive_le32dec(p + offset);
742 if (zip_entry->system == 3) {
744 = external_attributes >> 16;
745 } else if (zip_entry->system == 0) {
746 // Interpret MSDOS directory bit
747 if (0x10 == (external_attributes &
755 if (0x01 == (external_attributes &
758 * strip write permissions */
759 zip_entry->mode &= 0555;
768 /* 2 byte comment length + comment */
769 uint32_t comment_length;
773 = archive_le16dec(p + offset);
777 if (datasize < comment_length)
779 /* Comment is not supported by libarchive */
780 offset += comment_length;
781 datasize -= comment_length;
787 /* Info-ZIP Unicode Path Extra Field. */
788 if (datasize < 5 || entry == NULL)
793 /* The path name in this field is always encoded
795 if (zip->sconv_utf8 == NULL) {
797 archive_string_conversion_from_charset(
798 &a->archive, "UTF-8", 1);
799 /* If the converter from UTF-8 is not
800 * available, then the path name from the main
801 * field will more likely be correct. */
802 if (zip->sconv_utf8 == NULL)
806 /* Make sure the CRC32 of the filename matches. */
807 if (!zip->ignore_crc32) {
808 const char *cp = archive_entry_pathname(entry);
810 unsigned long file_crc =
811 zip->crc32func(0, cp, strlen(cp));
812 unsigned long utf_crc =
813 archive_le32dec(p + offset - 4);
814 if (file_crc != utf_crc) {
817 "CRC filename mismatch; "
818 "CDE is %lx, but UTF8 "
819 "is outdated with %lx\n",
827 if (archive_entry_copy_pathname_l(entry,
828 p + offset, datasize, zip->sconv_utf8) != 0) {
829 /* Ignore the error, and fallback to the path
830 * name from the main field. */
832 fprintf(stderr, "Failed to read the ZIP "
833 "0x7075 extra field path.\n");
839 /* Info-ZIP Unix Extra Field (type 2) "Ux". */
841 fprintf(stderr, "uid %d gid %d\n",
842 archive_le16dec(p + offset),
843 archive_le16dec(p + offset + 2));
846 zip_entry->uid = archive_le16dec(p + offset);
849 archive_le16dec(p + offset + 2);
853 /* Info-Zip Unix Extra Field (type 3) "ux". */
854 int uidsize = 0, gidsize = 0;
856 /* TODO: support arbitrary uidsize/gidsize. */
857 if (datasize >= 1 && p[offset] == 1) {/* version=1 */
859 /* get a uid size. */
860 uidsize = 0xff & (int)p[offset+1];
865 else if (uidsize == 4 && datasize >= 6)
870 if (datasize >= (2 + uidsize + 3)) {
871 /* get a gid size. */
873 (int)p[offset+2+uidsize];
877 p+offset+2+uidsize+1);
878 else if (gidsize == 4 &&
879 datasize >= (2 + uidsize + 5))
882 p+offset+2+uidsize+1);
888 /* WinZip AES extra data field. */
890 archive_set_error(&a->archive,
891 ARCHIVE_ERRNO_FILE_FORMAT,
892 "Incomplete AES field");
893 return ARCHIVE_FAILED;
895 if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
896 /* Vendor version. */
897 zip_entry->aes_extra.vendor =
898 archive_le16dec(p + offset);
899 /* AES encryption strength. */
900 zip_entry->aes_extra.strength = p[offset + 4];
901 /* Actual compression method. */
902 zip_entry->aes_extra.compression =
915 * Assumes file pointer is at beginning of local file header.
918 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
925 size_t len, filename_length, extra_length;
926 struct archive_string_conv *sconv;
927 struct zip_entry *zip_entry = zip->entry;
928 struct zip_entry zip_entry_central_dir;
929 int ret = ARCHIVE_OK;
932 /* Save a copy of the original for consistency checks. */
933 zip_entry_central_dir = *zip_entry;
935 zip->decompress_init = 0;
936 zip->end_of_entry = 0;
937 zip->entry_uncompressed_bytes_read = 0;
938 zip->entry_compressed_bytes_read = 0;
939 zip->entry_crc32 = zip->crc32func(0, NULL, 0);
941 /* Setup default conversion. */
942 if (zip->sconv == NULL && !zip->init_default_conversion) {
944 archive_string_default_conversion_for_read(&(a->archive));
945 zip->init_default_conversion = 1;
948 if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
949 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
950 "Truncated ZIP file header");
951 return (ARCHIVE_FATAL);
954 if (memcmp(p, "PK\003\004", 4) != 0) {
955 archive_set_error(&a->archive, -1, "Damaged Zip archive");
956 return ARCHIVE_FATAL;
959 zip_entry->system = p[5];
960 zip_entry->zip_flags = archive_le16dec(p + 6);
961 if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
962 zip->has_encrypted_entries = 1;
963 archive_entry_set_is_data_encrypted(entry, 1);
964 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
965 zip_entry->zip_flags & ZIP_ENCRYPTED &&
966 zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
967 archive_entry_set_is_metadata_encrypted(entry, 1);
968 return ARCHIVE_FATAL;
971 zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
972 zip_entry->compression = (char)archive_le16dec(p + 8);
973 zip_entry->mtime = zip_time(p + 10);
974 zip_entry->crc32 = archive_le32dec(p + 14);
975 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
976 zip_entry->decdat = p[11];
978 zip_entry->decdat = p[17];
979 zip_entry->compressed_size = archive_le32dec(p + 18);
980 zip_entry->uncompressed_size = archive_le32dec(p + 22);
981 filename_length = archive_le16dec(p + 26);
982 extra_length = archive_le16dec(p + 28);
984 __archive_read_consume(a, 30);
986 /* Read the filename. */
987 if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
988 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
989 "Truncated ZIP file header");
990 return (ARCHIVE_FATAL);
992 if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
993 /* The filename is stored to be UTF-8. */
994 if (zip->sconv_utf8 == NULL) {
996 archive_string_conversion_from_charset(
997 &a->archive, "UTF-8", 1);
998 if (zip->sconv_utf8 == NULL)
999 return (ARCHIVE_FATAL);
1001 sconv = zip->sconv_utf8;
1002 } else if (zip->sconv != NULL)
1005 sconv = zip->sconv_default;
1007 if (archive_entry_copy_pathname_l(entry,
1008 h, filename_length, sconv) != 0) {
1009 if (errno == ENOMEM) {
1010 archive_set_error(&a->archive, ENOMEM,
1011 "Can't allocate memory for Pathname");
1012 return (ARCHIVE_FATAL);
1014 archive_set_error(&a->archive,
1015 ARCHIVE_ERRNO_FILE_FORMAT,
1016 "Pathname cannot be converted "
1017 "from %s to current locale.",
1018 archive_string_conversion_charset_name(sconv));
1021 __archive_read_consume(a, filename_length);
1023 /* Read the extra data. */
1024 if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
1025 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1026 "Truncated ZIP file header");
1027 return (ARCHIVE_FATAL);
1030 if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
1032 return ARCHIVE_FATAL;
1034 __archive_read_consume(a, extra_length);
1036 /* Work around a bug in Info-Zip: When reading from a pipe, it
1037 * stats the pipe instead of synthesizing a file entry. */
1038 if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
1039 zip_entry->mode &= ~ AE_IFMT;
1040 zip_entry->mode |= AE_IFREG;
1043 /* If the mode is totally empty, set some sane default. */
1044 if (zip_entry->mode == 0) {
1045 zip_entry->mode |= 0664;
1048 /* Windows archivers sometimes use backslash as the directory
1049 * separator. Normalize to slash. */
1050 if (zip_entry->system == 0 &&
1051 (wp = archive_entry_pathname_w(entry)) != NULL) {
1052 if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
1054 struct archive_wstring s;
1055 archive_string_init(&s);
1056 archive_wstrcpy(&s, wp);
1057 for (i = 0; i < archive_strlen(&s); i++) {
1061 archive_entry_copy_pathname_w(entry, s.s);
1062 archive_wstring_free(&s);
1066 /* Make sure that entries with a trailing '/' are marked as directories
1067 * even if the External File Attributes contains bogus values. If this
1068 * is not a directory and there is no type, assume a regular file. */
1069 if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
1072 wp = archive_entry_pathname_w(entry);
1075 has_slash = len > 0 && wp[len - 1] == L'/';
1077 cp = archive_entry_pathname(entry);
1078 len = (cp != NULL)?strlen(cp):0;
1079 has_slash = len > 0 && cp[len - 1] == '/';
1081 /* Correct file type as needed. */
1083 zip_entry->mode &= ~AE_IFMT;
1084 zip_entry->mode |= AE_IFDIR;
1085 zip_entry->mode |= 0111;
1086 } else if ((zip_entry->mode & AE_IFMT) == 0) {
1087 zip_entry->mode |= AE_IFREG;
1091 /* Make sure directories end in '/' */
1092 if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
1093 wp = archive_entry_pathname_w(entry);
1096 if (len > 0 && wp[len - 1] != L'/') {
1097 struct archive_wstring s;
1098 archive_string_init(&s);
1099 archive_wstrcat(&s, wp);
1100 archive_wstrappend_wchar(&s, L'/');
1101 archive_entry_copy_pathname_w(entry, s.s);
1102 archive_wstring_free(&s);
1105 cp = archive_entry_pathname(entry);
1106 len = (cp != NULL)?strlen(cp):0;
1107 if (len > 0 && cp[len - 1] != '/') {
1108 struct archive_string s;
1109 archive_string_init(&s);
1110 archive_strcat(&s, cp);
1111 archive_strappend_char(&s, '/');
1112 archive_entry_set_pathname(entry, s.s);
1113 archive_string_free(&s);
1118 if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1119 /* If this came from the central dir, its size info
1120 * is definitive, so ignore the length-at-end flag. */
1121 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1122 /* If local header is missing a value, use the one from
1123 the central directory. If both have it, warn about
1125 if (zip_entry->crc32 == 0) {
1126 zip_entry->crc32 = zip_entry_central_dir.crc32;
1127 } else if (!zip->ignore_crc32
1128 && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1129 archive_set_error(&a->archive,
1130 ARCHIVE_ERRNO_FILE_FORMAT,
1131 "Inconsistent CRC32 values");
1134 if (zip_entry->compressed_size == 0) {
1135 zip_entry->compressed_size
1136 = zip_entry_central_dir.compressed_size;
1137 } else if (zip_entry->compressed_size
1138 != zip_entry_central_dir.compressed_size) {
1139 archive_set_error(&a->archive,
1140 ARCHIVE_ERRNO_FILE_FORMAT,
1141 "Inconsistent compressed size: "
1142 "%jd in central directory, %jd in local header",
1143 (intmax_t)zip_entry_central_dir.compressed_size,
1144 (intmax_t)zip_entry->compressed_size);
1147 if (zip_entry->uncompressed_size == 0) {
1148 zip_entry->uncompressed_size
1149 = zip_entry_central_dir.uncompressed_size;
1150 } else if (zip_entry->uncompressed_size
1151 != zip_entry_central_dir.uncompressed_size) {
1152 archive_set_error(&a->archive,
1153 ARCHIVE_ERRNO_FILE_FORMAT,
1154 "Inconsistent uncompressed size: "
1155 "%jd in central directory, %jd in local header",
1156 (intmax_t)zip_entry_central_dir.uncompressed_size,
1157 (intmax_t)zip_entry->uncompressed_size);
1162 /* Populate some additional entry fields: */
1163 archive_entry_set_mode(entry, zip_entry->mode);
1164 archive_entry_set_uid(entry, zip_entry->uid);
1165 archive_entry_set_gid(entry, zip_entry->gid);
1166 archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1167 archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1168 archive_entry_set_atime(entry, zip_entry->atime, 0);
1170 if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1171 size_t linkname_length;
1173 if (zip_entry->compressed_size > 64 * 1024) {
1174 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1175 "Zip file with oversized link entry");
1176 return ARCHIVE_FATAL;
1179 linkname_length = (size_t)zip_entry->compressed_size;
1181 archive_entry_set_size(entry, 0);
1183 // take into account link compression if any
1184 size_t linkname_full_length = linkname_length;
1185 if (zip->entry->compression != 0)
1187 // symlink target string appeared to be compressed
1188 int status = ARCHIVE_FATAL;
1189 const void *uncompressed_buffer;
1191 switch (zip->entry->compression)
1194 case 8: /* Deflate compression. */
1195 zip->entry_bytes_remaining = zip_entry->compressed_size;
1196 status = zip_read_data_deflate(a, &uncompressed_buffer,
1197 &linkname_full_length, NULL);
1200 #if HAVE_LZMA_H && HAVE_LIBLZMA
1201 case 14: /* ZIPx LZMA compression. */
1202 /*(see zip file format specification, section 4.4.5)*/
1203 zip->entry_bytes_remaining = zip_entry->compressed_size;
1204 status = zip_read_data_zipx_lzma_alone(a, &uncompressed_buffer,
1205 &linkname_full_length, NULL);
1208 default: /* Unsupported compression. */
1211 if (status == ARCHIVE_OK)
1213 p = uncompressed_buffer;
1217 archive_set_error(&a->archive,
1218 ARCHIVE_ERRNO_FILE_FORMAT,
1219 "Unsupported ZIP compression method "
1220 "during decompression of link entry (%d: %s)",
1221 zip->entry->compression,
1222 compression_name(zip->entry->compression));
1223 return ARCHIVE_FAILED;
1228 p = __archive_read_ahead(a, linkname_length, NULL);
1232 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1233 "Truncated Zip file");
1234 return ARCHIVE_FATAL;
1238 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1239 sconv = zip->sconv_utf8;
1241 sconv = zip->sconv_default;
1242 if (archive_entry_copy_symlink_l(entry, p, linkname_full_length,
1244 if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1245 (zip->entry->zip_flags & ZIP_UTF8_NAME))
1246 archive_entry_copy_symlink_l(entry, p,
1247 linkname_full_length, NULL);
1248 if (errno == ENOMEM) {
1249 archive_set_error(&a->archive, ENOMEM,
1250 "Can't allocate memory for Symlink");
1251 return (ARCHIVE_FATAL);
1254 * Since there is no character-set regulation for
1255 * symlink name, do not report the conversion error
1256 * in an automatic conversion.
1258 if (sconv != zip->sconv_utf8 ||
1259 (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1260 archive_set_error(&a->archive,
1261 ARCHIVE_ERRNO_FILE_FORMAT,
1262 "Symlink cannot be converted "
1263 "from %s to current locale.",
1264 archive_string_conversion_charset_name(
1269 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1271 if (__archive_read_consume(a, linkname_length) < 0) {
1272 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1273 "Read error skipping symlink target name");
1274 return ARCHIVE_FATAL;
1276 } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1277 || zip_entry->uncompressed_size > 0) {
1278 /* Set the size only if it's meaningful. */
1279 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1281 zip->entry_bytes_remaining = zip_entry->compressed_size;
1283 /* If there's no body, force read_data() to return EOF immediately. */
1284 if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1285 && zip->entry_bytes_remaining < 1)
1286 zip->end_of_entry = 1;
1288 /* Set up a more descriptive format name. */
1289 archive_string_empty(&zip->format_name);
1290 archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1291 version / 10, version % 10,
1292 compression_name(zip->entry->compression));
1293 a->archive.archive_format_name = zip->format_name.s;
1299 check_authentication_code(struct archive_read *a, const void *_p)
1301 struct zip *zip = (struct zip *)(a->format->data);
1303 /* Check authentication code. */
1304 if (zip->hctx_valid) {
1307 size_t hmac_len = 20;
1310 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1312 /* Read authentication code. */
1313 p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1315 archive_set_error(&a->archive,
1316 ARCHIVE_ERRNO_FILE_FORMAT,
1317 "Truncated ZIP file data");
1318 return (ARCHIVE_FATAL);
1323 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1324 __archive_read_consume(a, AUTH_CODE_SIZE);
1326 archive_set_error(&a->archive,
1328 "ZIP bad Authentication code");
1329 return (ARCHIVE_WARN);
1332 return (ARCHIVE_OK);
1336 * Read "uncompressed" data. There are three cases:
1337 * 1) We know the size of the data. This is always true for the
1338 * seeking reader (we've examined the Central Directory already).
1339 * 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1340 * Info-ZIP seems to do this; we know the size but have to grab
1341 * the CRC from the data descriptor afterwards.
1342 * 3) We're streaming and ZIP_LENGTH_AT_END was specified and
1343 * we have no size information. In this case, we can do pretty
1344 * well by watching for the data descriptor record. The data
1345 * descriptor is 16 bytes and includes a computed CRC that should
1346 * provide a strong check.
1348 * TODO: Technically, the PK\007\010 signature is optional.
1349 * In the original spec, the data descriptor contained CRC
1350 * and size fields but had no leading signature. In practice,
1351 * newer writers seem to provide the signature pretty consistently.
1353 * For uncompressed data, the PK\007\010 marker seems essential
1354 * to be sure we've actually seen the end of the entry.
1356 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1357 * zip->end_of_entry if it consumes all of the data.
1360 zip_read_data_none(struct archive_read *a, const void **_buff,
1361 size_t *size, int64_t *offset)
1365 ssize_t bytes_avail;
1368 (void)offset; /* UNUSED */
1370 zip = (struct zip *)(a->format->data);
1372 if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1374 ssize_t grabbing_bytes = 24;
1376 if (zip->hctx_valid)
1377 grabbing_bytes += AUTH_CODE_SIZE;
1378 /* Grab at least 24 bytes. */
1379 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1380 if (bytes_avail < grabbing_bytes) {
1381 /* Zip archives have end-of-archive markers
1382 that are longer than this, so a failure to get at
1383 least 24 bytes really does indicate a truncated
1385 archive_set_error(&a->archive,
1386 ARCHIVE_ERRNO_FILE_FORMAT,
1387 "Truncated ZIP file data");
1388 return (ARCHIVE_FATAL);
1390 /* Check for a complete PK\007\010 signature, followed
1391 * by the correct 4-byte CRC. */
1393 if (zip->hctx_valid)
1394 p += AUTH_CODE_SIZE;
1395 if (p[0] == 'P' && p[1] == 'K'
1396 && p[2] == '\007' && p[3] == '\010'
1397 && (archive_le32dec(p + 4) == zip->entry_crc32
1398 || zip->ignore_crc32
1400 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1401 if (zip->entry->flags & LA_USED_ZIP64) {
1402 uint64_t compressed, uncompressed;
1403 zip->entry->crc32 = archive_le32dec(p + 4);
1404 compressed = archive_le64dec(p + 8);
1405 uncompressed = archive_le64dec(p + 16);
1406 if (compressed > INT64_MAX || uncompressed >
1408 archive_set_error(&a->archive,
1409 ARCHIVE_ERRNO_FILE_FORMAT,
1410 "Overflow of 64-bit file sizes");
1411 return ARCHIVE_FAILED;
1413 zip->entry->compressed_size = compressed;
1414 zip->entry->uncompressed_size = uncompressed;
1415 zip->unconsumed = 24;
1417 zip->entry->crc32 = archive_le32dec(p + 4);
1418 zip->entry->compressed_size =
1419 archive_le32dec(p + 8);
1420 zip->entry->uncompressed_size =
1421 archive_le32dec(p + 12);
1422 zip->unconsumed = 16;
1424 if (zip->hctx_valid) {
1425 r = check_authentication_code(a, buff);
1426 if (r != ARCHIVE_OK)
1429 zip->end_of_entry = 1;
1430 return (ARCHIVE_OK);
1432 /* If not at EOF, ensure we consume at least one byte. */
1435 /* Scan forward until we see where a PK\007\010 signature
1437 /* Return bytes up until that point. On the next call,
1438 * the code above will verify the data descriptor. */
1439 while (p < buff + bytes_avail - 4) {
1440 if (p[3] == 'P') { p += 3; }
1441 else if (p[3] == 'K') { p += 2; }
1442 else if (p[3] == '\007') { p += 1; }
1443 else if (p[3] == '\010' && p[2] == '\007'
1444 && p[1] == 'K' && p[0] == 'P') {
1445 if (zip->hctx_valid)
1446 p -= AUTH_CODE_SIZE;
1450 bytes_avail = p - buff;
1452 if (zip->entry_bytes_remaining == 0) {
1453 zip->end_of_entry = 1;
1454 if (zip->hctx_valid) {
1455 r = check_authentication_code(a, NULL);
1456 if (r != ARCHIVE_OK)
1459 return (ARCHIVE_OK);
1461 /* Grab a bunch of bytes. */
1462 buff = __archive_read_ahead(a, 1, &bytes_avail);
1463 if (bytes_avail <= 0) {
1464 archive_set_error(&a->archive,
1465 ARCHIVE_ERRNO_FILE_FORMAT,
1466 "Truncated ZIP file data");
1467 return (ARCHIVE_FATAL);
1469 if (bytes_avail > zip->entry_bytes_remaining)
1470 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1472 if (zip->tctx_valid || zip->cctx_valid) {
1473 size_t dec_size = bytes_avail;
1475 if (dec_size > zip->decrypted_buffer_size)
1476 dec_size = zip->decrypted_buffer_size;
1477 if (zip->tctx_valid) {
1478 trad_enc_decrypt_update(&zip->tctx,
1479 (const uint8_t *)buff, dec_size,
1480 zip->decrypted_buffer, dec_size);
1482 size_t dsize = dec_size;
1483 archive_hmac_sha1_update(&zip->hctx,
1484 (const uint8_t *)buff, dec_size);
1485 archive_decrypto_aes_ctr_update(&zip->cctx,
1486 (const uint8_t *)buff, dec_size,
1487 zip->decrypted_buffer, &dsize);
1489 bytes_avail = dec_size;
1490 buff = (const char *)zip->decrypted_buffer;
1492 *size = bytes_avail;
1493 zip->entry_bytes_remaining -= bytes_avail;
1494 zip->entry_uncompressed_bytes_read += bytes_avail;
1495 zip->entry_compressed_bytes_read += bytes_avail;
1496 zip->unconsumed += bytes_avail;
1498 return (ARCHIVE_OK);
1502 consume_optional_marker(struct archive_read *a, struct zip *zip)
1504 if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1507 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1508 archive_set_error(&a->archive,
1509 ARCHIVE_ERRNO_FILE_FORMAT,
1510 "Truncated ZIP end-of-file record");
1511 return (ARCHIVE_FATAL);
1513 /* Consume the optional PK\007\010 marker. */
1514 if (p[0] == 'P' && p[1] == 'K' &&
1515 p[2] == '\007' && p[3] == '\010') {
1517 zip->unconsumed = 4;
1519 if (zip->entry->flags & LA_USED_ZIP64) {
1520 uint64_t compressed, uncompressed;
1521 zip->entry->crc32 = archive_le32dec(p);
1522 compressed = archive_le64dec(p + 4);
1523 uncompressed = archive_le64dec(p + 12);
1524 if (compressed > INT64_MAX ||
1525 uncompressed > INT64_MAX) {
1526 archive_set_error(&a->archive,
1527 ARCHIVE_ERRNO_FILE_FORMAT,
1528 "Overflow of 64-bit file sizes");
1529 return ARCHIVE_FAILED;
1531 zip->entry->compressed_size = compressed;
1532 zip->entry->uncompressed_size = uncompressed;
1533 zip->unconsumed += 20;
1535 zip->entry->crc32 = archive_le32dec(p);
1536 zip->entry->compressed_size = archive_le32dec(p + 4);
1537 zip->entry->uncompressed_size = archive_le32dec(p + 8);
1538 zip->unconsumed += 12;
1542 return (ARCHIVE_OK);
1545 #if HAVE_LZMA_H && HAVE_LIBLZMA
1547 zipx_xz_init(struct archive_read *a, struct zip *zip)
1551 if(zip->zipx_lzma_valid) {
1552 lzma_end(&zip->zipx_lzma_stream);
1553 zip->zipx_lzma_valid = 0;
1556 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1557 r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1559 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1560 "xz initialization failed(%d)",
1563 return (ARCHIVE_FAILED);
1566 zip->zipx_lzma_valid = 1;
1568 free(zip->uncompressed_buffer);
1570 zip->uncompressed_buffer_size = 256 * 1024;
1571 zip->uncompressed_buffer =
1572 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1573 if (zip->uncompressed_buffer == NULL) {
1574 archive_set_error(&a->archive, ENOMEM,
1575 "No memory for xz decompression");
1576 return (ARCHIVE_FATAL);
1579 zip->decompress_init = 1;
1580 return (ARCHIVE_OK);
1584 zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1591 struct _alone_header {
1593 uint64_t uncompressed_size;
1597 if(zip->zipx_lzma_valid) {
1598 lzma_end(&zip->zipx_lzma_stream);
1599 zip->zipx_lzma_valid = 0;
1602 /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
1603 * that is a part of XZ Utils. The stream format stored inside ZIPX
1604 * file is a modified "lzma alone" file format, that was used by the
1605 * `lzma` utility which was later deprecated in favour of `xz` utility.
1606 * Since those formats are nearly the same, we can use a standard
1607 * "lzma alone" decoder from XZ Utils. */
1609 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1610 r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1612 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1613 "lzma initialization failed(%d)", r);
1615 return (ARCHIVE_FAILED);
1618 /* Flag the cleanup function that we want our lzma-related structures
1619 * to be freed later. */
1620 zip->zipx_lzma_valid = 1;
1622 /* The "lzma alone" file format and the stream format inside ZIPx are
1623 * almost the same. Here's an example of a structure of "lzma alone"
1626 * $ cat /bin/ls | lzma | xxd | head -n 1
1627 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1629 * 5 bytes 8 bytes n bytes
1630 * <lzma_params><uncompressed_size><data...>
1632 * lzma_params is a 5-byte blob that has to be decoded to extract
1633 * parameters of this LZMA stream. The uncompressed_size field is an
1634 * uint64_t value that contains information about the size of the
1635 * uncompressed file, or UINT64_MAX if this value is unknown.
1636 * The <data...> part is the actual lzma-compressed data stream.
1638 * Now here's the structure of the stream inside the ZIPX file:
1640 * $ cat stream_inside_zipx | xxd | head -n 1
1641 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1643 * 2byte 2byte 5 bytes n bytes
1644 * <magic1><magic2><lzma_params><data...>
1646 * This means that the ZIPX file contains an additional magic1 and
1647 * magic2 headers, the lzma_params field contains the same parameter
1648 * set as in the "lzma alone" format, and the <data...> field is the
1649 * same as in the "lzma alone" format as well. Note that also the zipx
1650 * format is missing the uncompressed_size field.
1652 * So, in order to use the "lzma alone" decoder for the zipx lzma
1653 * stream, we simply need to shuffle around some fields, prepare a new
1654 * lzma alone header, feed it into lzma alone decoder so it will
1655 * initialize itself properly, and then we can start feeding normal
1656 * zipx lzma stream into the decoder.
1659 /* Read magic1,magic2,lzma_params from the ZIPX stream. */
1660 if((p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1661 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1662 "Truncated lzma data");
1663 return (ARCHIVE_FATAL);
1666 if(p[2] != 0x05 || p[3] != 0x00) {
1667 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1668 "Invalid lzma data");
1669 return (ARCHIVE_FATAL);
1672 /* Prepare an lzma alone header: copy the lzma_params blob into
1673 * a proper place into the lzma alone header. */
1674 memcpy(&alone_header.bytes[0], p + 4, 5);
1676 /* Initialize the 'uncompressed size' field to unknown; we'll manually
1677 * monitor how many bytes there are still to be uncompressed. */
1678 alone_header.uncompressed_size = UINT64_MAX;
1680 if(!zip->uncompressed_buffer) {
1681 zip->uncompressed_buffer_size = 256 * 1024;
1682 zip->uncompressed_buffer =
1683 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1685 if (zip->uncompressed_buffer == NULL) {
1686 archive_set_error(&a->archive, ENOMEM,
1687 "No memory for lzma decompression");
1688 return (ARCHIVE_FATAL);
1692 zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1693 zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1694 zip->zipx_lzma_stream.total_in = 0;
1695 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1696 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1697 zip->zipx_lzma_stream.total_out = 0;
1699 /* Feed only the header into the lzma alone decoder. This will
1700 * effectively initialize the decoder, and will not produce any
1701 * output bytes yet. */
1702 r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1704 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1705 "lzma stream initialization error");
1706 return ARCHIVE_FATAL;
1709 /* We've already consumed some bytes, so take this into account. */
1710 __archive_read_consume(a, 9);
1711 zip->entry_bytes_remaining -= 9;
1712 zip->entry_compressed_bytes_read += 9;
1714 zip->decompress_init = 1;
1715 return (ARCHIVE_OK);
1719 zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1720 size_t *size, int64_t *offset)
1722 struct zip* zip = (struct zip *)(a->format->data);
1725 const void* compressed_buf;
1726 ssize_t bytes_avail, in_bytes, to_consume = 0;
1728 (void) offset; /* UNUSED */
1730 /* Initialize decompressor if not yet initialized. */
1731 if (!zip->decompress_init) {
1732 ret = zipx_xz_init(a, zip);
1733 if (ret != ARCHIVE_OK)
1737 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1738 if (bytes_avail < 0) {
1739 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1740 "Truncated xz file body");
1741 return (ARCHIVE_FATAL);
1744 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1745 zip->zipx_lzma_stream.next_in = compressed_buf;
1746 zip->zipx_lzma_stream.avail_in = in_bytes;
1747 zip->zipx_lzma_stream.total_in = 0;
1748 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1749 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1750 zip->zipx_lzma_stream.total_out = 0;
1752 /* Perform the decompression. */
1753 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1755 case LZMA_DATA_ERROR:
1756 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1757 "xz data error (error %d)", (int) lz_ret);
1758 return (ARCHIVE_FATAL);
1765 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1766 "xz unknown error %d", (int) lz_ret);
1767 return (ARCHIVE_FATAL);
1769 case LZMA_STREAM_END:
1770 lzma_end(&zip->zipx_lzma_stream);
1771 zip->zipx_lzma_valid = 0;
1773 if((int64_t) zip->zipx_lzma_stream.total_in !=
1774 zip->entry_bytes_remaining)
1776 archive_set_error(&a->archive,
1778 "xz premature end of stream");
1779 return (ARCHIVE_FATAL);
1782 zip->end_of_entry = 1;
1786 to_consume = zip->zipx_lzma_stream.total_in;
1788 __archive_read_consume(a, to_consume);
1789 zip->entry_bytes_remaining -= to_consume;
1790 zip->entry_compressed_bytes_read += to_consume;
1791 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1793 *size = zip->zipx_lzma_stream.total_out;
1794 *buff = zip->uncompressed_buffer;
1796 ret = consume_optional_marker(a, zip);
1797 if (ret != ARCHIVE_OK)
1800 return (ARCHIVE_OK);
1804 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1805 size_t *size, int64_t *offset)
1807 struct zip* zip = (struct zip *)(a->format->data);
1810 const void* compressed_buf;
1811 ssize_t bytes_avail, in_bytes, to_consume;
1813 (void) offset; /* UNUSED */
1815 /* Initialize decompressor if not yet initialized. */
1816 if (!zip->decompress_init) {
1817 ret = zipx_lzma_alone_init(a, zip);
1818 if (ret != ARCHIVE_OK)
1822 /* Fetch more compressed data. The same note as in deflate handler
1823 * applies here as well:
1825 * Note: '1' here is a performance optimization. Recall that the
1826 * decompression layer returns a count of available bytes; asking for
1827 * more than that forces the decompressor to combine reads by copying
1830 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1831 if (bytes_avail < 0) {
1832 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1833 "Truncated lzma file body");
1834 return (ARCHIVE_FATAL);
1837 /* Set decompressor parameters. */
1838 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1840 zip->zipx_lzma_stream.next_in = compressed_buf;
1841 zip->zipx_lzma_stream.avail_in = in_bytes;
1842 zip->zipx_lzma_stream.total_in = 0;
1843 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1844 zip->zipx_lzma_stream.avail_out =
1845 /* These lzma_alone streams lack end of stream marker, so let's
1846 * make sure the unpacker won't try to unpack more than it's
1848 zipmin((int64_t) zip->uncompressed_buffer_size,
1849 zip->entry->uncompressed_size -
1850 zip->entry_uncompressed_bytes_read);
1851 zip->zipx_lzma_stream.total_out = 0;
1853 /* Perform the decompression. */
1854 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1856 case LZMA_DATA_ERROR:
1857 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1858 "lzma data error (error %d)", (int) lz_ret);
1859 return (ARCHIVE_FATAL);
1861 /* This case is optional in lzma alone format. It can happen,
1862 * but most of the files don't have it. (GitHub #1257) */
1863 case LZMA_STREAM_END:
1864 lzma_end(&zip->zipx_lzma_stream);
1865 zip->zipx_lzma_valid = 0;
1866 if((int64_t) zip->zipx_lzma_stream.total_in !=
1867 zip->entry_bytes_remaining)
1869 archive_set_error(&a->archive,
1871 "lzma alone premature end of stream");
1872 return (ARCHIVE_FATAL);
1875 zip->end_of_entry = 1;
1882 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1883 "lzma unknown error %d", (int) lz_ret);
1884 return (ARCHIVE_FATAL);
1887 to_consume = zip->zipx_lzma_stream.total_in;
1889 /* Update pointers. */
1890 __archive_read_consume(a, to_consume);
1891 zip->entry_bytes_remaining -= to_consume;
1892 zip->entry_compressed_bytes_read += to_consume;
1893 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1895 if(zip->entry_bytes_remaining == 0) {
1896 zip->end_of_entry = 1;
1899 /* Return values. */
1900 *size = zip->zipx_lzma_stream.total_out;
1901 *buff = zip->uncompressed_buffer;
1903 /* Behave the same way as during deflate decompression. */
1904 ret = consume_optional_marker(a, zip);
1905 if (ret != ARCHIVE_OK)
1908 /* Free lzma decoder handle because we'll no longer need it. */
1909 if(zip->end_of_entry) {
1910 lzma_end(&zip->zipx_lzma_stream);
1911 zip->zipx_lzma_valid = 0;
1914 /* If we're here, then we're good! */
1915 return (ARCHIVE_OK);
1917 #endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1920 zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1926 uint32_t restore_method;
1928 /* Remove previous decompression context if it exists. */
1929 if(zip->ppmd8_valid) {
1930 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1931 zip->ppmd8_valid = 0;
1934 /* Create a new decompression context. */
1935 __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1936 zip->ppmd8_stream_failed = 0;
1938 /* Setup function pointers required by Ppmd8 decompressor. The
1939 * 'ppmd_read' function will feed new bytes to the decompressor,
1940 * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
1941 zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
1942 zip->zipx_ppmd_stream.a = a;
1943 zip->zipx_ppmd_stream.Read = &ppmd_read;
1945 /* Reset number of read bytes to 0. */
1946 zip->zipx_ppmd_read_compressed = 0;
1948 /* Read Ppmd8 header (2 bytes). */
1949 p = __archive_read_ahead(a, 2, NULL);
1951 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1952 "Truncated file data in PPMd8 stream");
1953 return (ARCHIVE_FATAL);
1955 __archive_read_consume(a, 2);
1957 /* Decode the stream's compression parameters. */
1958 val = archive_le16dec(p);
1959 order = (val & 15) + 1;
1960 mem = ((val >> 4) & 0xff) + 1;
1961 restore_method = (val >> 12);
1963 if(order < 2 || restore_method > 2) {
1964 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1965 "Invalid parameter set in PPMd8 stream (order=%" PRId32 ", "
1966 "restore=%" PRId32 ")", order, restore_method);
1967 return (ARCHIVE_FAILED);
1970 /* Allocate the memory needed to properly decompress the file. */
1971 if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
1972 archive_set_error(&a->archive, ENOMEM,
1973 "Unable to allocate memory for PPMd8 stream: %" PRId32 " bytes",
1975 return (ARCHIVE_FATAL);
1978 /* Signal the cleanup function to release Ppmd8 context in the
1980 zip->ppmd8_valid = 1;
1982 /* Perform further Ppmd8 initialization. */
1983 if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
1984 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1985 "PPMd8 stream range decoder initialization error");
1986 return (ARCHIVE_FATAL);
1989 __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
1992 /* Allocate the buffer that will hold uncompressed data. */
1993 free(zip->uncompressed_buffer);
1995 zip->uncompressed_buffer_size = 256 * 1024;
1996 zip->uncompressed_buffer =
1997 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1999 if(zip->uncompressed_buffer == NULL) {
2000 archive_set_error(&a->archive, ENOMEM,
2001 "No memory for PPMd8 decompression");
2002 return ARCHIVE_FATAL;
2005 /* Ppmd8 initialization is done. */
2006 zip->decompress_init = 1;
2008 /* We've already read 2 bytes in the output stream. Additionally,
2009 * Ppmd8 initialization code could read some data as well. So we
2010 * are advancing the stream by 2 bytes plus whatever number of
2011 * bytes Ppmd8 init function used. */
2012 zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
2018 zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
2019 size_t *size, int64_t *offset)
2021 struct zip* zip = (struct zip *)(a->format->data);
2023 size_t consumed_bytes = 0;
2024 ssize_t bytes_avail = 0;
2026 (void) offset; /* UNUSED */
2028 /* If we're here for the first time, initialize Ppmd8 decompression
2030 if(!zip->decompress_init) {
2031 ret = zipx_ppmd8_init(a, zip);
2032 if(ret != ARCHIVE_OK)
2036 /* Fetch for more data. We're reading 1 byte here, but libarchive
2037 * should prefetch more bytes. */
2038 (void) __archive_read_ahead(a, 1, &bytes_avail);
2039 if(bytes_avail < 0) {
2040 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2041 "Truncated PPMd8 file body");
2042 return (ARCHIVE_FATAL);
2045 /* This counter will be updated inside ppmd_read(), which at one
2046 * point will be called by Ppmd8_DecodeSymbol. */
2047 zip->zipx_ppmd_read_compressed = 0;
2049 /* Decompression loop. */
2051 int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
2054 zip->end_of_entry = 1;
2058 /* This field is set by ppmd_read() when there was no more data
2060 if(zip->ppmd8_stream_failed) {
2061 archive_set_error(&a->archive,
2062 ARCHIVE_ERRNO_FILE_FORMAT,
2063 "Truncated PPMd8 file body");
2064 return (ARCHIVE_FATAL);
2067 zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
2069 } while(consumed_bytes < zip->uncompressed_buffer_size);
2071 /* Update pointers for libarchive. */
2072 *buff = zip->uncompressed_buffer;
2073 *size = consumed_bytes;
2075 /* Update pointers so we can continue decompression in another call. */
2076 zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
2077 zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
2078 zip->entry_uncompressed_bytes_read += consumed_bytes;
2080 /* If we're at the end of stream, deinitialize Ppmd8 context. */
2081 if(zip->end_of_entry) {
2082 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2083 zip->ppmd8_valid = 0;
2086 /* Seek for optional marker, same way as in each zip entry. */
2087 ret = consume_optional_marker(a, zip);
2088 if (ret != ARCHIVE_OK)
2096 zipx_bzip2_init(struct archive_read *a, struct zip *zip)
2100 /* Deallocate already existing BZ2 decompression context if it
2102 if(zip->bzstream_valid) {
2103 BZ2_bzDecompressEnd(&zip->bzstream);
2104 zip->bzstream_valid = 0;
2107 /* Allocate a new BZ2 decompression context. */
2108 memset(&zip->bzstream, 0, sizeof(bz_stream));
2109 r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
2111 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
2112 "bzip2 initialization failed(%d)",
2115 return ARCHIVE_FAILED;
2118 /* Mark the bzstream field to be released in cleanup phase. */
2119 zip->bzstream_valid = 1;
2121 /* (Re)allocate the buffer that will contain decompressed bytes. */
2122 free(zip->uncompressed_buffer);
2124 zip->uncompressed_buffer_size = 256 * 1024;
2125 zip->uncompressed_buffer =
2126 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2127 if (zip->uncompressed_buffer == NULL) {
2128 archive_set_error(&a->archive, ENOMEM,
2129 "No memory for bzip2 decompression");
2130 return ARCHIVE_FATAL;
2133 /* Initialization done. */
2134 zip->decompress_init = 1;
2139 zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
2140 size_t *size, int64_t *offset)
2142 struct zip *zip = (struct zip *)(a->format->data);
2143 ssize_t bytes_avail = 0, in_bytes, to_consume;
2144 const void *compressed_buff;
2148 (void) offset; /* UNUSED */
2150 /* Initialize decompression context if we're here for the first time. */
2151 if(!zip->decompress_init) {
2152 r = zipx_bzip2_init(a, zip);
2157 /* Fetch more compressed bytes. */
2158 compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2159 if(bytes_avail < 0) {
2160 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2161 "Truncated bzip2 file body");
2162 return (ARCHIVE_FATAL);
2165 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2167 /* libbz2 doesn't complain when caller feeds avail_in == 0.
2168 * It will actually return success in this case, which is
2169 * undesirable. This is why we need to make this check
2172 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2173 "Truncated bzip2 file body");
2174 return (ARCHIVE_FATAL);
2177 /* Setup buffer boundaries. */
2178 zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
2179 zip->bzstream.avail_in = in_bytes;
2180 zip->bzstream.total_in_hi32 = 0;
2181 zip->bzstream.total_in_lo32 = 0;
2182 zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2183 zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2184 zip->bzstream.total_out_hi32 = 0;
2185 zip->bzstream.total_out_lo32 = 0;
2187 /* Perform the decompression. */
2188 r = BZ2_bzDecompress(&zip->bzstream);
2191 /* If we're at the end of the stream, deinitialize the
2192 * decompression context now. */
2193 switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2197 archive_set_error(&a->archive,
2199 "Failed to clean up bzip2 "
2201 return ARCHIVE_FATAL;
2204 zip->end_of_entry = 1;
2207 /* The decompressor has successfully decoded this
2208 * chunk of data, but more data is still in queue. */
2211 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2212 "bzip2 decompression failed");
2213 return ARCHIVE_FATAL;
2216 /* Update the pointers so decompressor can continue decoding. */
2217 to_consume = zip->bzstream.total_in_lo32;
2218 __archive_read_consume(a, to_consume);
2220 total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2221 zip->bzstream.total_out_lo32;
2223 zip->entry_bytes_remaining -= to_consume;
2224 zip->entry_compressed_bytes_read += to_consume;
2225 zip->entry_uncompressed_bytes_read += total_out;
2227 /* Give libarchive its due. */
2229 *buff = zip->uncompressed_buffer;
2231 /* Seek for optional marker, like in other entries. */
2232 r = consume_optional_marker(a, zip);
2243 zip_deflate_init(struct archive_read *a, struct zip *zip)
2247 /* If we haven't yet read any data, initialize the decompressor. */
2248 if (!zip->decompress_init) {
2249 if (zip->stream_valid)
2250 r = inflateReset(&zip->stream);
2252 r = inflateInit2(&zip->stream,
2253 -15 /* Don't check for zlib header */);
2255 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2256 "Can't initialize ZIP decompression.");
2257 return (ARCHIVE_FATAL);
2259 /* Stream structure has been set up. */
2260 zip->stream_valid = 1;
2261 /* We've initialized decompression for this stream. */
2262 zip->decompress_init = 1;
2264 return (ARCHIVE_OK);
2268 zip_read_data_deflate(struct archive_read *a, const void **buff,
2269 size_t *size, int64_t *offset)
2272 ssize_t bytes_avail;
2273 const void *compressed_buff, *sp;
2276 (void)offset; /* UNUSED */
2278 zip = (struct zip *)(a->format->data);
2280 /* If the buffer hasn't been allocated, allocate it now. */
2281 if (zip->uncompressed_buffer == NULL) {
2282 zip->uncompressed_buffer_size = 256 * 1024;
2283 zip->uncompressed_buffer
2284 = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2285 if (zip->uncompressed_buffer == NULL) {
2286 archive_set_error(&a->archive, ENOMEM,
2287 "No memory for ZIP decompression");
2288 return (ARCHIVE_FATAL);
2292 r = zip_deflate_init(a, zip);
2293 if (r != ARCHIVE_OK)
2297 * Note: '1' here is a performance optimization.
2298 * Recall that the decompression layer returns a count of
2299 * available bytes; asking for more than that forces the
2300 * decompressor to combine reads by copying data.
2302 compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2303 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2304 && bytes_avail > zip->entry_bytes_remaining) {
2305 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2307 if (bytes_avail < 0) {
2308 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2309 "Truncated ZIP file body");
2310 return (ARCHIVE_FATAL);
2313 if (zip->tctx_valid || zip->cctx_valid) {
2314 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2315 size_t buff_remaining =
2316 (zip->decrypted_buffer +
2317 zip->decrypted_buffer_size)
2318 - (zip->decrypted_ptr +
2319 zip->decrypted_bytes_remaining);
2321 if (buff_remaining > (size_t)bytes_avail)
2322 buff_remaining = (size_t)bytes_avail;
2324 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2325 zip->entry_bytes_remaining > 0) {
2326 if ((int64_t)(zip->decrypted_bytes_remaining
2328 > zip->entry_bytes_remaining) {
2329 if (zip->entry_bytes_remaining <
2330 (int64_t)zip->decrypted_bytes_remaining)
2334 (size_t)zip->entry_bytes_remaining
2335 - zip->decrypted_bytes_remaining;
2338 if (buff_remaining > 0) {
2339 if (zip->tctx_valid) {
2340 trad_enc_decrypt_update(&zip->tctx,
2341 compressed_buff, buff_remaining,
2343 + zip->decrypted_bytes_remaining,
2346 size_t dsize = buff_remaining;
2347 archive_decrypto_aes_ctr_update(
2349 compressed_buff, buff_remaining,
2351 + zip->decrypted_bytes_remaining,
2354 zip->decrypted_bytes_remaining +=
2358 bytes_avail = zip->decrypted_bytes_remaining;
2359 compressed_buff = (const char *)zip->decrypted_ptr;
2363 * A bug in zlib.h: stream.next_in should be marked 'const'
2364 * but isn't (the library never alters data through the
2365 * next_in pointer, only reads it). The result: this ugly
2366 * cast to remove 'const'.
2368 zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2369 zip->stream.avail_in = (uInt)bytes_avail;
2370 zip->stream.total_in = 0;
2371 zip->stream.next_out = zip->uncompressed_buffer;
2372 zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2373 zip->stream.total_out = 0;
2375 r = inflate(&zip->stream, 0);
2380 zip->end_of_entry = 1;
2383 archive_set_error(&a->archive, ENOMEM,
2384 "Out of memory for ZIP decompression");
2385 return (ARCHIVE_FATAL);
2387 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2388 "ZIP decompression failed (%d)", r);
2389 return (ARCHIVE_FATAL);
2392 /* Consume as much as the compressor actually used. */
2393 bytes_avail = zip->stream.total_in;
2394 if (zip->tctx_valid || zip->cctx_valid) {
2395 zip->decrypted_bytes_remaining -= bytes_avail;
2396 if (zip->decrypted_bytes_remaining == 0)
2397 zip->decrypted_ptr = zip->decrypted_buffer;
2399 zip->decrypted_ptr += bytes_avail;
2401 /* Calculate compressed data as much as we used.*/
2402 if (zip->hctx_valid)
2403 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2404 __archive_read_consume(a, bytes_avail);
2405 zip->entry_bytes_remaining -= bytes_avail;
2406 zip->entry_compressed_bytes_read += bytes_avail;
2408 *size = zip->stream.total_out;
2409 zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2410 *buff = zip->uncompressed_buffer;
2412 if (zip->end_of_entry && zip->hctx_valid) {
2413 r = check_authentication_code(a, NULL);
2414 if (r != ARCHIVE_OK)
2418 r = consume_optional_marker(a, zip);
2419 if (r != ARCHIVE_OK)
2422 return (ARCHIVE_OK);
2427 read_decryption_header(struct archive_read *a)
2429 struct zip *zip = (struct zip *)(a->format->data);
2431 unsigned int remaining_size;
2435 * Read an initialization vector data field.
2437 p = __archive_read_ahead(a, 2, NULL);
2441 zip->iv_size = archive_le16dec(p);
2442 __archive_read_consume(a, 2);
2443 if (ts < zip->iv_size) {
2447 p = __archive_read_ahead(a, zip->iv_size, NULL);
2450 if (zip->iv == NULL) {
2451 zip->iv = malloc(zip->iv_size);
2452 if (zip->iv == NULL)
2455 memcpy(zip->iv, p, zip->iv_size);
2456 __archive_read_consume(a, zip->iv_size);
2459 * Read a size of remaining decryption header field.
2461 p = __archive_read_ahead(a, 14, NULL);
2464 remaining_size = archive_le32dec(p);
2465 if (remaining_size < 16 || remaining_size > (1 << 18))
2468 /* Check if format version is supported. */
2469 if (archive_le16dec(p+4) != 3) {
2470 archive_set_error(&a->archive,
2471 ARCHIVE_ERRNO_FILE_FORMAT,
2472 "Unsupported encryption format version: %u",
2473 archive_le16dec(p+4));
2474 return (ARCHIVE_FAILED);
2478 * Read an encryption algorithm field.
2480 zip->alg_id = archive_le16dec(p+6);
2481 switch (zip->alg_id) {
2482 case 0x6601:/* DES */
2483 case 0x6602:/* RC2 */
2484 case 0x6603:/* 3DES 168 */
2485 case 0x6609:/* 3DES 112 */
2486 case 0x660E:/* AES 128 */
2487 case 0x660F:/* AES 192 */
2488 case 0x6610:/* AES 256 */
2489 case 0x6702:/* RC2 (version >= 5.2) */
2490 case 0x6720:/* Blowfish */
2491 case 0x6721:/* Twofish */
2492 case 0x6801:/* RC4 */
2493 /* Supported encryption algorithm. */
2496 archive_set_error(&a->archive,
2497 ARCHIVE_ERRNO_FILE_FORMAT,
2498 "Unknown encryption algorithm: %u", zip->alg_id);
2499 return (ARCHIVE_FAILED);
2503 * Read a bit length field.
2505 zip->bit_len = archive_le16dec(p+8);
2508 * Read a flags field.
2510 zip->flags = archive_le16dec(p+10);
2511 switch (zip->flags & 0xf000) {
2512 case 0x0001: /* Password is required to decrypt. */
2513 case 0x0002: /* Certificates only. */
2514 case 0x0003: /* Password or certificate required to decrypt. */
2517 archive_set_error(&a->archive,
2518 ARCHIVE_ERRNO_FILE_FORMAT,
2519 "Unknown encryption flag: %u", zip->flags);
2520 return (ARCHIVE_FAILED);
2522 if ((zip->flags & 0xf000) == 0 ||
2523 (zip->flags & 0xf000) == 0x4000) {
2524 archive_set_error(&a->archive,
2525 ARCHIVE_ERRNO_FILE_FORMAT,
2526 "Unknown encryption flag: %u", zip->flags);
2527 return (ARCHIVE_FAILED);
2531 * Read an encrypted random data field.
2534 zip->erd_size = archive_le16dec(p+12);
2535 __archive_read_consume(a, 14);
2536 if ((zip->erd_size & 0xf) != 0 ||
2537 (zip->erd_size + 16) > remaining_size ||
2538 (zip->erd_size + 16) < zip->erd_size)
2541 if (ts < zip->erd_size) {
2545 p = __archive_read_ahead(a, zip->erd_size, NULL);
2548 if (zip->erd == NULL) {
2549 zip->erd = malloc(zip->erd_size);
2550 if (zip->erd == NULL)
2553 memcpy(zip->erd, p, zip->erd_size);
2554 __archive_read_consume(a, zip->erd_size);
2557 * Read a reserved data field.
2559 p = __archive_read_ahead(a, 4, NULL);
2562 /* Reserved data size should be zero. */
2563 if (archive_le32dec(p) != 0)
2565 __archive_read_consume(a, 4);
2568 * Read a password validation data field.
2570 p = __archive_read_ahead(a, 2, NULL);
2574 zip->v_size = archive_le16dec(p);
2575 __archive_read_consume(a, 2);
2576 if ((zip->v_size & 0x0f) != 0 ||
2577 (zip->erd_size + zip->v_size + 16) > remaining_size ||
2578 (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2580 if (ts < zip->v_size) {
2584 p = __archive_read_ahead(a, zip->v_size, NULL);
2587 if (zip->v_data == NULL) {
2588 zip->v_data = malloc(zip->v_size);
2589 if (zip->v_data == NULL)
2592 memcpy(zip->v_data, p, zip->v_size);
2593 __archive_read_consume(a, zip->v_size);
2595 p = __archive_read_ahead(a, 4, NULL);
2598 zip->v_crc32 = archive_le32dec(p);
2599 __archive_read_consume(a, 4);
2601 /*return (ARCHIVE_OK);
2602 * This is not fully implemented yet.*/
2603 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2604 "Encrypted file is unsupported");
2605 return (ARCHIVE_FAILED);
2607 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2608 "Truncated ZIP file data");
2609 return (ARCHIVE_FATAL);
2611 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2612 "Corrupted ZIP file data");
2613 return (ARCHIVE_FATAL);
2615 archive_set_error(&a->archive, ENOMEM,
2616 "No memory for ZIP decryption");
2617 return (ARCHIVE_FATAL);
2621 zip_alloc_decryption_buffer(struct archive_read *a)
2623 struct zip *zip = (struct zip *)(a->format->data);
2624 size_t bs = 256 * 1024;
2626 if (zip->decrypted_buffer == NULL) {
2627 zip->decrypted_buffer_size = bs;
2628 zip->decrypted_buffer = malloc(bs);
2629 if (zip->decrypted_buffer == NULL) {
2630 archive_set_error(&a->archive, ENOMEM,
2631 "No memory for ZIP decryption");
2632 return (ARCHIVE_FATAL);
2635 zip->decrypted_ptr = zip->decrypted_buffer;
2636 return (ARCHIVE_OK);
2640 init_traditional_PKWARE_decryption(struct archive_read *a)
2642 struct zip *zip = (struct zip *)(a->format->data);
2647 if (zip->tctx_valid)
2648 return (ARCHIVE_OK);
2651 Read the 12 bytes encryption header stored at
2652 the start of the data area.
2654 #define ENC_HEADER_SIZE 12
2655 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2656 && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2657 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2658 "Truncated Zip encrypted body: only %jd bytes available",
2659 (intmax_t)zip->entry_bytes_remaining);
2660 return (ARCHIVE_FATAL);
2663 p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2665 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2666 "Truncated ZIP file data");
2667 return (ARCHIVE_FATAL);
2670 for (retry = 0;; retry++) {
2671 const char *passphrase;
2674 passphrase = __archive_read_next_passphrase(a);
2675 if (passphrase == NULL) {
2676 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2678 "Incorrect passphrase":
2679 "Passphrase required for this entry");
2680 return (ARCHIVE_FAILED);
2684 * Initialize ctx for Traditional PKWARE Decryption.
2686 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2687 p, ENC_HEADER_SIZE, &crcchk);
2688 if (r == 0 && crcchk == zip->entry->decdat)
2689 break;/* The passphrase is OK. */
2690 if (retry > 10000) {
2691 /* Avoid infinity loop. */
2692 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2693 "Too many incorrect passphrases");
2694 return (ARCHIVE_FAILED);
2698 __archive_read_consume(a, ENC_HEADER_SIZE);
2699 zip->tctx_valid = 1;
2700 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2701 zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2703 /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2704 zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2705 zip->decrypted_bytes_remaining = 0;
2707 return (zip_alloc_decryption_buffer(a));
2708 #undef ENC_HEADER_SIZE
2712 init_WinZip_AES_decryption(struct archive_read *a)
2714 struct zip *zip = (struct zip *)(a->format->data);
2717 size_t key_len, salt_len;
2718 uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2722 if (zip->cctx_valid || zip->hctx_valid)
2723 return (ARCHIVE_OK);
2725 switch (zip->entry->aes_extra.strength) {
2726 case 1: salt_len = 8; key_len = 16; break;
2727 case 2: salt_len = 12; key_len = 24; break;
2728 case 3: salt_len = 16; key_len = 32; break;
2729 default: goto corrupted;
2731 p = __archive_read_ahead(a, salt_len + 2, NULL);
2735 for (retry = 0;; retry++) {
2736 const char *passphrase;
2738 passphrase = __archive_read_next_passphrase(a);
2739 if (passphrase == NULL) {
2740 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2742 "Incorrect passphrase":
2743 "Passphrase required for this entry");
2744 return (ARCHIVE_FAILED);
2746 memset(derived_key, 0, sizeof(derived_key));
2747 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2748 p, salt_len, 1000, derived_key, key_len * 2 + 2);
2750 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2751 "Decryption is unsupported due to lack of "
2753 return (ARCHIVE_FAILED);
2756 /* Check password verification value. */
2757 pv = ((const uint8_t *)p) + salt_len;
2758 if (derived_key[key_len * 2] == pv[0] &&
2759 derived_key[key_len * 2 + 1] == pv[1])
2760 break;/* The passphrase is OK. */
2761 if (retry > 10000) {
2762 /* Avoid infinity loop. */
2763 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2764 "Too many incorrect passphrases");
2765 return (ARCHIVE_FAILED);
2769 r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2771 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2772 "Decryption is unsupported due to lack of crypto library");
2773 return (ARCHIVE_FAILED);
2775 r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2777 archive_decrypto_aes_ctr_release(&zip->cctx);
2778 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2779 "Failed to initialize HMAC-SHA1");
2780 return (ARCHIVE_FAILED);
2782 zip->cctx_valid = zip->hctx_valid = 1;
2783 __archive_read_consume(a, salt_len + 2);
2784 zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2785 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2786 && zip->entry_bytes_remaining < 0)
2788 zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2789 zip->decrypted_bytes_remaining = 0;
2791 zip->entry->compression = zip->entry->aes_extra.compression;
2792 return (zip_alloc_decryption_buffer(a));
2795 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2796 "Truncated ZIP file data");
2797 return (ARCHIVE_FATAL);
2799 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2800 "Corrupted ZIP file data");
2801 return (ARCHIVE_FATAL);
2805 archive_read_format_zip_read_data(struct archive_read *a,
2806 const void **buff, size_t *size, int64_t *offset)
2809 struct zip *zip = (struct zip *)(a->format->data);
2811 if (zip->has_encrypted_entries ==
2812 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2813 zip->has_encrypted_entries = 0;
2816 *offset = zip->entry_uncompressed_bytes_read;
2820 /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2821 if (zip->end_of_entry)
2822 return (ARCHIVE_EOF);
2824 /* Return EOF immediately if this is a non-regular file. */
2825 if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2826 return (ARCHIVE_EOF);
2828 __archive_read_consume(a, zip->unconsumed);
2829 zip->unconsumed = 0;
2831 if (zip->init_decryption) {
2832 zip->has_encrypted_entries = 1;
2833 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2834 r = read_decryption_header(a);
2835 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2836 r = init_WinZip_AES_decryption(a);
2838 r = init_traditional_PKWARE_decryption(a);
2839 if (r != ARCHIVE_OK)
2841 zip->init_decryption = 0;
2844 switch(zip->entry->compression) {
2845 case 0: /* No compression. */
2846 r = zip_read_data_none(a, buff, size, offset);
2849 case 12: /* ZIPx bzip2 compression. */
2850 r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2853 #if HAVE_LZMA_H && HAVE_LIBLZMA
2854 case 14: /* ZIPx LZMA compression. */
2855 r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
2857 case 95: /* ZIPx XZ compression. */
2858 r = zip_read_data_zipx_xz(a, buff, size, offset);
2861 /* PPMd support is built-in, so we don't need any #if guards. */
2862 case 98: /* ZIPx PPMd compression. */
2863 r = zip_read_data_zipx_ppmd(a, buff, size, offset);
2867 case 8: /* Deflate compression. */
2868 r = zip_read_data_deflate(a, buff, size, offset);
2871 default: /* Unsupported compression. */
2872 /* Return a warning. */
2873 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2874 "Unsupported ZIP compression method (%d: %s)",
2875 zip->entry->compression, compression_name(zip->entry->compression));
2876 /* We can't decompress this entry, but we will
2877 * be able to skip() it and try the next entry. */
2878 return (ARCHIVE_FAILED);
2881 if (r != ARCHIVE_OK)
2883 /* Update checksum */
2885 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
2887 /* If we hit the end, swallow any end-of-data marker. */
2888 if (zip->end_of_entry) {
2889 /* Check file size, CRC against these values. */
2890 if (zip->entry->compressed_size !=
2891 zip->entry_compressed_bytes_read) {
2892 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2893 "ZIP compressed data is wrong size "
2894 "(read %jd, expected %jd)",
2895 (intmax_t)zip->entry_compressed_bytes_read,
2896 (intmax_t)zip->entry->compressed_size);
2897 return (ARCHIVE_WARN);
2899 /* Size field only stores the lower 32 bits of the actual
2901 if ((zip->entry->uncompressed_size & UINT32_MAX)
2902 != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
2903 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2904 "ZIP uncompressed data is wrong size "
2905 "(read %jd, expected %jd)\n",
2906 (intmax_t)zip->entry_uncompressed_bytes_read,
2907 (intmax_t)zip->entry->uncompressed_size);
2908 return (ARCHIVE_WARN);
2910 /* Check computed CRC against header */
2911 if ((!zip->hctx_valid ||
2912 zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
2913 zip->entry->crc32 != zip->entry_crc32
2914 && !zip->ignore_crc32) {
2915 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2916 "ZIP bad CRC: 0x%lx should be 0x%lx",
2917 (unsigned long)zip->entry_crc32,
2918 (unsigned long)zip->entry->crc32);
2919 return (ARCHIVE_WARN);
2923 return (ARCHIVE_OK);
2927 archive_read_format_zip_cleanup(struct archive_read *a)
2930 struct zip_entry *zip_entry, *next_zip_entry;
2932 zip = (struct zip *)(a->format->data);
2935 if (zip->stream_valid)
2936 inflateEnd(&zip->stream);
2939 #if HAVE_LZMA_H && HAVE_LIBLZMA
2940 if (zip->zipx_lzma_valid) {
2941 lzma_end(&zip->zipx_lzma_stream);
2946 if (zip->bzstream_valid) {
2947 BZ2_bzDecompressEnd(&zip->bzstream);
2951 free(zip->uncompressed_buffer);
2953 if (zip->ppmd8_valid)
2954 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2956 if (zip->zip_entries) {
2957 zip_entry = zip->zip_entries;
2958 while (zip_entry != NULL) {
2959 next_zip_entry = zip_entry->next;
2960 archive_string_free(&zip_entry->rsrcname);
2962 zip_entry = next_zip_entry;
2965 free(zip->decrypted_buffer);
2966 if (zip->cctx_valid)
2967 archive_decrypto_aes_ctr_release(&zip->cctx);
2968 if (zip->hctx_valid)
2969 archive_hmac_sha1_cleanup(&zip->hctx);
2973 archive_string_free(&zip->format_name);
2975 (a->format->data) = NULL;
2976 return (ARCHIVE_OK);
2980 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
2982 if (_a && _a->format) {
2983 struct zip * zip = (struct zip *)_a->format->data;
2985 return zip->has_encrypted_entries;
2988 return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2992 archive_read_format_zip_options(struct archive_read *a,
2993 const char *key, const char *val)
2996 int ret = ARCHIVE_FAILED;
2998 zip = (struct zip *)(a->format->data);
2999 if (strcmp(key, "compat-2x") == 0) {
3000 /* Handle filenames as libarchive 2.x */
3001 zip->init_default_conversion = (val != NULL) ? 1 : 0;
3002 return (ARCHIVE_OK);
3003 } else if (strcmp(key, "hdrcharset") == 0) {
3004 if (val == NULL || val[0] == 0)
3005 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3006 "zip: hdrcharset option needs a character-set name"
3009 zip->sconv = archive_string_conversion_from_charset(
3010 &a->archive, val, 0);
3011 if (zip->sconv != NULL) {
3012 if (strcmp(val, "UTF-8") == 0)
3013 zip->sconv_utf8 = zip->sconv;
3016 ret = ARCHIVE_FATAL;
3019 } else if (strcmp(key, "ignorecrc32") == 0) {
3020 /* Mostly useful for testing. */
3021 if (val == NULL || val[0] == 0) {
3022 zip->crc32func = real_crc32;
3023 zip->ignore_crc32 = 0;
3025 zip->crc32func = fake_crc32;
3026 zip->ignore_crc32 = 1;
3028 return (ARCHIVE_OK);
3029 } else if (strcmp(key, "mac-ext") == 0) {
3030 zip->process_mac_extensions = (val != NULL && val[0] != 0);
3031 return (ARCHIVE_OK);
3034 /* Note: The "warn" return is just to inform the options
3035 * supervisor that we didn't handle it. It will generate
3036 * a suitable error if no one used this option. */
3037 return (ARCHIVE_WARN);
3041 archive_read_support_format_zip(struct archive *a)
3044 r = archive_read_support_format_zip_streamable(a);
3045 if (r != ARCHIVE_OK)
3047 return (archive_read_support_format_zip_seekable(a));
3050 /* ------------------------------------------------------------------------ */
3053 * Streaming-mode support
3058 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
3060 (void)a; /* UNUSED */
3061 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3062 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3066 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
3070 (void)best_bid; /* UNUSED */
3072 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3076 * Bid of 29 here comes from:
3077 * + 16 bits for "PK",
3078 * + next 16-bit field has 6 options so contributes
3079 * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
3081 * So we've effectively verified ~29 total bits of check data.
3083 if (p[0] == 'P' && p[1] == 'K') {
3084 if ((p[2] == '\001' && p[3] == '\002')
3085 || (p[2] == '\003' && p[3] == '\004')
3086 || (p[2] == '\005' && p[3] == '\006')
3087 || (p[2] == '\006' && p[3] == '\006')
3088 || (p[2] == '\007' && p[3] == '\010')
3089 || (p[2] == '0' && p[3] == '0'))
3093 /* TODO: It's worth looking ahead a little bit for a valid
3094 * PK signature. In particular, that would make it possible
3095 * to read some UUEncoded SFX files or SFX files coming from
3096 * a network socket. */
3102 archive_read_format_zip_streamable_read_header(struct archive_read *a,
3103 struct archive_entry *entry)
3107 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3108 if (a->archive.archive_format_name == NULL)
3109 a->archive.archive_format_name = "ZIP";
3111 zip = (struct zip *)(a->format->data);
3114 * It should be sufficient to call archive_read_next_header() for
3115 * a reader to determine if an entry is encrypted or not. If the
3116 * encryption of an entry is only detectable when calling
3117 * archive_read_data(), so be it. We'll do the same check there
3120 if (zip->has_encrypted_entries ==
3121 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3122 zip->has_encrypted_entries = 0;
3124 /* Make sure we have a zip_entry structure to use. */
3125 if (zip->zip_entries == NULL) {
3126 zip->zip_entries = malloc(sizeof(struct zip_entry));
3127 if (zip->zip_entries == NULL) {
3128 archive_set_error(&a->archive, ENOMEM,
3130 return ARCHIVE_FATAL;
3133 zip->entry = zip->zip_entries;
3134 memset(zip->entry, 0, sizeof(struct zip_entry));
3136 if (zip->cctx_valid)
3137 archive_decrypto_aes_ctr_release(&zip->cctx);
3138 if (zip->hctx_valid)
3139 archive_hmac_sha1_cleanup(&zip->hctx);
3140 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3141 __archive_read_reset_passphrase(a);
3143 /* Search ahead for the next local file header. */
3144 __archive_read_consume(a, zip->unconsumed);
3145 zip->unconsumed = 0;
3147 int64_t skipped = 0;
3148 const char *p, *end;
3151 p = __archive_read_ahead(a, 4, &bytes);
3153 return (ARCHIVE_FATAL);
3156 while (p + 4 <= end) {
3157 if (p[0] == 'P' && p[1] == 'K') {
3158 if (p[2] == '\003' && p[3] == '\004') {
3159 /* Regular file entry. */
3160 __archive_read_consume(a, skipped);
3161 return zip_read_local_file_header(a,
3166 * TODO: We cannot restore permissions
3167 * based only on the local file headers.
3168 * Consider scanning the central
3169 * directory and returning additional
3170 * entries for at least directories.
3171 * This would allow us to properly set
3172 * directory permissions.
3174 * This won't help us fix symlinks
3175 * and may not help with regular file
3176 * permissions, either. <sigh>
3178 if (p[2] == '\001' && p[3] == '\002') {
3179 return (ARCHIVE_EOF);
3182 /* End of central directory? Must be an
3184 if ((p[2] == '\005' && p[3] == '\006')
3185 || (p[2] == '\006' && p[3] == '\006'))
3186 return (ARCHIVE_EOF);
3191 __archive_read_consume(a, skipped);
3196 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3199 int64_t bytes_skipped;
3201 zip = (struct zip *)(a->format->data);
3202 bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3203 zip->unconsumed = 0;
3204 if (bytes_skipped < 0)
3205 return (ARCHIVE_FATAL);
3207 /* If we've already read to end of data, we're done. */
3208 if (zip->end_of_entry)
3209 return (ARCHIVE_OK);
3211 /* So we know we're streaming... */
3212 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3213 || zip->entry->compressed_size > 0) {
3214 /* We know the compressed length, so we can just skip. */
3215 bytes_skipped = __archive_read_consume(a,
3216 zip->entry_bytes_remaining);
3217 if (bytes_skipped < 0)
3218 return (ARCHIVE_FATAL);
3219 return (ARCHIVE_OK);
3222 if (zip->init_decryption) {
3225 zip->has_encrypted_entries = 1;
3226 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3227 r = read_decryption_header(a);
3228 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3229 r = init_WinZip_AES_decryption(a);
3231 r = init_traditional_PKWARE_decryption(a);
3232 if (r != ARCHIVE_OK)
3234 zip->init_decryption = 0;
3237 /* We're streaming and we don't know the length. */
3238 /* If the body is compressed and we know the format, we can
3239 * find an exact end-of-entry by decompressing it. */
3240 switch (zip->entry->compression) {
3242 case 8: /* Deflate compression. */
3243 while (!zip->end_of_entry) {
3245 const void *buff = NULL;
3248 r = zip_read_data_deflate(a, &buff, &size, &offset);
3249 if (r != ARCHIVE_OK)
3254 default: /* Uncompressed or unknown. */
3255 /* Scan for a PK\007\010 signature. */
3257 const char *p, *buff;
3258 ssize_t bytes_avail;
3259 buff = __archive_read_ahead(a, 16, &bytes_avail);
3260 if (bytes_avail < 16) {
3261 archive_set_error(&a->archive,
3262 ARCHIVE_ERRNO_FILE_FORMAT,
3263 "Truncated ZIP file data");
3264 return (ARCHIVE_FATAL);
3267 while (p <= buff + bytes_avail - 16) {
3268 if (p[3] == 'P') { p += 3; }
3269 else if (p[3] == 'K') { p += 2; }
3270 else if (p[3] == '\007') { p += 1; }
3271 else if (p[3] == '\010' && p[2] == '\007'
3272 && p[1] == 'K' && p[0] == 'P') {
3273 if (zip->entry->flags & LA_USED_ZIP64)
3274 __archive_read_consume(a,
3277 __archive_read_consume(a,
3282 __archive_read_consume(a, p - buff);
3288 archive_read_support_format_zip_streamable(struct archive *_a)
3290 struct archive_read *a = (struct archive_read *)_a;
3294 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3295 ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3297 zip = (struct zip *)calloc(1, sizeof(*zip));
3299 archive_set_error(&a->archive, ENOMEM,
3300 "Can't allocate zip data");
3301 return (ARCHIVE_FATAL);
3304 /* Streamable reader doesn't support mac extensions. */
3305 zip->process_mac_extensions = 0;
3308 * Until enough data has been read, we cannot tell about
3309 * any encrypted entries yet.
3311 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3312 zip->crc32func = real_crc32;
3314 r = __archive_read_register_format(a,
3317 archive_read_format_zip_streamable_bid,
3318 archive_read_format_zip_options,
3319 archive_read_format_zip_streamable_read_header,
3320 archive_read_format_zip_read_data,
3321 archive_read_format_zip_read_data_skip_streamable,
3323 archive_read_format_zip_cleanup,
3324 archive_read_support_format_zip_capabilities_streamable,
3325 archive_read_format_zip_has_encrypted_entries);
3327 if (r != ARCHIVE_OK)
3329 return (ARCHIVE_OK);
3332 /* ------------------------------------------------------------------------ */
3335 * Seeking-mode support
3339 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3341 (void)a; /* UNUSED */
3342 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3343 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3347 * TODO: This is a performance sink because it forces the read core to
3348 * drop buffered data from the start of file, which will then have to
3349 * be re-read again if this bidder loses.
3351 * We workaround this a little by passing in the best bid so far so
3352 * that later bidders can do nothing if they know they'll never
3353 * outbid. But we can certainly do better...
3356 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3359 uint32_t cd_size, cd_offset;
3361 disk_num = archive_le16dec(p + 4);
3362 cd_size = archive_le32dec(p + 12);
3363 cd_offset = archive_le32dec(p + 16);
3365 /* Sanity-check the EOCD we've found. */
3367 /* This must be the first volume. */
3370 /* Central directory must be on this volume. */
3371 if (disk_num != archive_le16dec(p + 6))
3373 /* All central directory entries must be on this volume. */
3374 if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3376 /* Central directory can't extend beyond start of EOCD record. */
3377 if (cd_offset + cd_size > current_offset)
3380 /* Save the central directory location for later use. */
3381 zip->central_directory_offset = cd_offset;
3382 zip->central_directory_offset_adjusted = current_offset - cd_size;
3384 /* This is just a tiny bit higher than the maximum
3385 returned by the streaming Zip bidder. This ensures
3386 that the more accurate seeking Zip parser wins
3387 whenever seek is available. */
3392 * Examine Zip64 EOCD locator: If it's valid, store the information
3396 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3398 int64_t eocd64_offset;
3399 int64_t eocd64_size;
3401 /* Sanity-check the locator record. */
3403 /* Central dir must be on first volume. */
3404 if (archive_le32dec(p + 4) != 0)
3406 /* Must be only a single volume. */
3407 if (archive_le32dec(p + 16) != 1)
3410 /* Find the Zip64 EOCD record. */
3411 eocd64_offset = archive_le64dec(p + 8);
3412 if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3414 if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3416 /* Make sure we can read all of it. */
3417 eocd64_size = archive_le64dec(p + 4) + 12;
3418 if (eocd64_size < 56 || eocd64_size > 16384)
3420 if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3423 /* Sanity-check the EOCD64 */
3424 if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3426 if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3428 /* CD can't be split. */
3429 if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3432 /* Save the central directory offset for later use. */
3433 zip->central_directory_offset = archive_le64dec(p + 48);
3434 /* TODO: Needs scanning backwards to find the eocd64 instead of assuming */
3435 zip->central_directory_offset_adjusted = zip->central_directory_offset;
3441 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3443 struct zip *zip = (struct zip *)a->format->data;
3444 int64_t file_size, current_offset;
3448 /* If someone has already bid more than 32, then avoid
3449 trashing the look-ahead buffers with a seek. */
3453 file_size = __archive_read_seek(a, 0, SEEK_END);
3457 /* Search last 16k of file for end-of-central-directory
3458 * record (which starts with PK\005\006) */
3459 tail = (int)zipmin(1024 * 16, file_size);
3460 current_offset = __archive_read_seek(a, -tail, SEEK_END);
3461 if (current_offset < 0)
3463 if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3465 /* Boyer-Moore search backwards from the end, since we want
3466 * to match the last EOCD in the file (there can be more than
3467 * one if there is an uncompressed Zip archive as a member
3468 * within this Zip archive). */
3469 for (i = tail - 22; i > 0;) {
3472 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3473 int ret = read_eocd(zip, p + i,
3474 current_offset + i);
3475 /* Zip64 EOCD locator precedes
3476 * regular EOCD if present. */
3477 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3478 int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3479 if (ret_zip64 > ret)
3486 case 'K': i -= 1; break;
3487 case 005: i -= 2; break;
3488 case 006: i -= 3; break;
3489 default: i -= 4; break;
3495 /* The red-black trees are only used in seeking mode to manage
3496 * the in-memory copy of the central directory. */
3499 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3501 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3502 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3504 if (e1->local_header_offset > e2->local_header_offset)
3506 if (e1->local_header_offset < e2->local_header_offset)
3512 cmp_key(const struct archive_rb_node *n, const void *key)
3514 /* This function won't be called */
3515 (void)n; /* UNUSED */
3516 (void)key; /* UNUSED */
3520 static const struct archive_rb_tree_ops rb_ops = {
3525 rsrc_cmp_node(const struct archive_rb_node *n1,
3526 const struct archive_rb_node *n2)
3528 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3529 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3531 return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3535 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3537 const struct zip_entry *e = (const struct zip_entry *)n;
3538 return (strcmp((const char *)key, e->rsrcname.s));
3541 static const struct archive_rb_tree_ops rb_rsrc_ops = {
3542 &rsrc_cmp_node, &rsrc_cmp_key
3546 rsrc_basename(const char *name, size_t name_length)
3552 s = memchr(s, '/', name_length - (s - name));
3561 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3563 struct archive_string str;
3564 struct zip_entry *dir;
3567 archive_string_init(&str);
3568 archive_strncpy(&str, name, name_length);
3570 s = strrchr(str.s, '/');
3574 /* Transfer the parent directory from zip->tree_rsrc RB
3575 * tree to zip->tree RB tree to expose. */
3576 dir = (struct zip_entry *)
3577 __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3580 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3581 archive_string_free(&dir->rsrcname);
3582 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
3584 archive_string_free(&str);
3588 slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
3594 ssize_t bytes_avail;
3598 * Find the start of the central directory. The end-of-CD
3599 * record has our starting point, but there are lots of
3600 * Zip archives which have had other data prepended to the
3601 * file, which makes the recorded offsets all too small.
3602 * So we search forward from the specified offset until we
3603 * find the real start of the central directory. Then we
3604 * know the correction we need to apply to account for leading
3607 if (__archive_read_seek(a, zip->central_directory_offset_adjusted, SEEK_SET)
3609 return ARCHIVE_FATAL;
3613 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3614 return ARCHIVE_FATAL;
3615 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3617 case 'P': i += 3; break;
3618 case 'K': i += 2; break;
3619 case 001: i += 1; break;
3621 if (memcmp(p + i, "PK\001\002", 4) == 0) {
3627 case 005: i += 1; break;
3629 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3632 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3638 default: i += 4; break;
3641 __archive_read_consume(a, i);
3643 correction = archive_filter_bytes(&a->archive, 0)
3644 - zip->central_directory_offset;
3646 __archive_rb_tree_init(&zip->tree, &rb_ops);
3647 __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3649 zip->central_directory_entries_total = 0;
3651 struct zip_entry *zip_entry;
3652 size_t filename_length, extra_length, comment_length;
3653 uint32_t external_attributes;
3654 const char *name, *r;
3656 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3657 return ARCHIVE_FATAL;
3658 if (memcmp(p, "PK\006\006", 4) == 0
3659 || memcmp(p, "PK\005\006", 4) == 0) {
3661 } else if (memcmp(p, "PK\001\002", 4) != 0) {
3662 archive_set_error(&a->archive,
3663 -1, "Invalid central directory signature");
3664 return ARCHIVE_FATAL;
3666 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3667 return ARCHIVE_FATAL;
3669 zip_entry = calloc(1, sizeof(struct zip_entry));
3670 if (zip_entry == NULL) {
3671 archive_set_error(&a->archive, ENOMEM,
3672 "Can't allocate zip entry");
3673 return ARCHIVE_FATAL;
3675 zip_entry->next = zip->zip_entries;
3676 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3677 zip->zip_entries = zip_entry;
3678 zip->central_directory_entries_total++;
3680 /* version = p[4]; */
3681 zip_entry->system = p[5];
3682 /* version_required = archive_le16dec(p + 6); */
3683 zip_entry->zip_flags = archive_le16dec(p + 8);
3684 if (zip_entry->zip_flags
3685 & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3686 zip->has_encrypted_entries = 1;
3688 zip_entry->compression = (char)archive_le16dec(p + 10);
3689 zip_entry->mtime = zip_time(p + 12);
3690 zip_entry->crc32 = archive_le32dec(p + 16);
3691 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3692 zip_entry->decdat = p[13];
3694 zip_entry->decdat = p[19];
3695 zip_entry->compressed_size = archive_le32dec(p + 20);
3696 zip_entry->uncompressed_size = archive_le32dec(p + 24);
3697 filename_length = archive_le16dec(p + 28);
3698 extra_length = archive_le16dec(p + 30);
3699 comment_length = archive_le16dec(p + 32);
3700 /* disk_start = archive_le16dec(p + 34);
3702 * internal_attributes = archive_le16dec(p + 36);
3704 external_attributes = archive_le32dec(p + 38);
3705 zip_entry->local_header_offset =
3706 archive_le32dec(p + 42) + correction;
3708 /* If we can't guess the mode, leave it zero here;
3709 when we read the local file header we might get
3710 more information. */
3711 if (zip_entry->system == 3) {
3712 zip_entry->mode = external_attributes >> 16;
3713 } else if (zip_entry->system == 0) {
3714 // Interpret MSDOS directory bit
3715 if (0x10 == (external_attributes & 0x10)) {
3716 zip_entry->mode = AE_IFDIR | 0775;
3718 zip_entry->mode = AE_IFREG | 0664;
3720 if (0x01 == (external_attributes & 0x01)) {
3721 // Read-only bit; strip write permissions
3722 zip_entry->mode &= 0555;
3725 zip_entry->mode = 0;
3728 /* We're done with the regular data; get the filename and
3730 __archive_read_consume(a, 46);
3731 p = __archive_read_ahead(a, filename_length + extra_length,
3734 archive_set_error(&a->archive,
3735 ARCHIVE_ERRNO_FILE_FORMAT,
3736 "Truncated ZIP file header");
3737 return ARCHIVE_FATAL;
3739 if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
3740 extra_length, zip_entry)) {
3741 return ARCHIVE_FATAL;
3745 * Mac resource fork files are stored under the
3746 * "__MACOSX/" directory, so we should check if
3749 if (!zip->process_mac_extensions) {
3750 /* Treat every entry as a regular entry. */
3751 __archive_rb_tree_insert_node(&zip->tree,
3755 r = rsrc_basename(name, filename_length);
3756 if (filename_length >= 9 &&
3757 strncmp("__MACOSX/", name, 9) == 0) {
3758 /* If this file is not a resource fork nor
3759 * a directory. We should treat it as a non
3760 * resource fork file to expose it. */
3761 if (name[filename_length-1] != '/' &&
3762 (r - name < 3 || r[0] != '.' ||
3764 __archive_rb_tree_insert_node(
3765 &zip->tree, &zip_entry->node);
3766 /* Expose its parent directories. */
3767 expose_parent_dirs(zip, name,
3770 /* This file is a resource fork file or
3772 archive_strncpy(&(zip_entry->rsrcname),
3773 name, filename_length);
3774 __archive_rb_tree_insert_node(
3775 &zip->tree_rsrc, &zip_entry->node);
3778 /* Generate resource fork name to find its
3779 * resource file at zip->tree_rsrc. */
3780 archive_strcpy(&(zip_entry->rsrcname),
3782 archive_strncat(&(zip_entry->rsrcname),
3784 archive_strcat(&(zip_entry->rsrcname), "._");
3785 archive_strncat(&(zip_entry->rsrcname),
3787 filename_length - (r - name));
3788 /* Register an entry to RB tree to sort it by
3790 __archive_rb_tree_insert_node(&zip->tree,
3795 /* Skip the comment too ... */
3796 __archive_read_consume(a,
3797 filename_length + extra_length + comment_length);
3804 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3807 ssize_t filename_length, extra_length;
3809 if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3810 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3811 "Truncated ZIP file header");
3812 return (ARCHIVE_WARN);
3816 if (memcmp(p, "PK\003\004", 4) != 0) {
3817 archive_set_error(&a->archive, -1, "Damaged Zip archive");
3818 return ARCHIVE_WARN;
3820 filename_length = archive_le16dec(p + 26);
3821 extra_length = archive_le16dec(p + 28);
3823 return (30 + filename_length + extra_length);
3827 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3828 struct zip_entry *rsrc)
3830 struct zip *zip = (struct zip *)a->format->data;
3831 unsigned char *metadata, *mp;
3832 int64_t offset = archive_filter_bytes(&a->archive, 0);
3833 size_t remaining_bytes, metadata_bytes;
3835 int ret = ARCHIVE_OK, eof;
3837 switch(rsrc->compression) {
3838 case 0: /* No compression. */
3839 if (rsrc->uncompressed_size != rsrc->compressed_size) {
3840 archive_set_error(&a->archive,
3841 ARCHIVE_ERRNO_FILE_FORMAT,
3842 "Malformed OS X metadata entry: "
3843 "inconsistent size");
3844 return (ARCHIVE_FATAL);
3847 case 8: /* Deflate compression. */
3850 default: /* Unsupported compression. */
3851 /* Return a warning. */
3852 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3853 "Unsupported ZIP compression method (%s)",
3854 compression_name(rsrc->compression));
3855 /* We can't decompress this entry, but we will
3856 * be able to skip() it and try the next entry. */
3857 return (ARCHIVE_WARN);
3860 if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
3861 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3862 "Mac metadata is too large: %jd > 4M bytes",
3863 (intmax_t)rsrc->uncompressed_size);
3864 return (ARCHIVE_WARN);
3866 if (rsrc->compressed_size > (4 * 1024 * 1024)) {
3867 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3868 "Mac metadata is too large: %jd > 4M bytes",
3869 (intmax_t)rsrc->compressed_size);
3870 return (ARCHIVE_WARN);
3873 metadata = malloc((size_t)rsrc->uncompressed_size);
3874 if (metadata == NULL) {
3875 archive_set_error(&a->archive, ENOMEM,
3876 "Can't allocate memory for Mac metadata");
3877 return (ARCHIVE_FATAL);
3880 if (offset < rsrc->local_header_offset)
3881 __archive_read_consume(a, rsrc->local_header_offset - offset);
3882 else if (offset != rsrc->local_header_offset) {
3883 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
3886 hsize = zip_get_local_file_header_size(a, 0);
3887 __archive_read_consume(a, hsize);
3889 remaining_bytes = (size_t)rsrc->compressed_size;
3890 metadata_bytes = (size_t)rsrc->uncompressed_size;
3893 while (!eof && remaining_bytes) {
3894 const unsigned char *p;
3895 ssize_t bytes_avail;
3898 p = __archive_read_ahead(a, 1, &bytes_avail);
3900 archive_set_error(&a->archive,
3901 ARCHIVE_ERRNO_FILE_FORMAT,
3902 "Truncated ZIP file header");
3904 goto exit_mac_metadata;
3906 if ((size_t)bytes_avail > remaining_bytes)
3907 bytes_avail = remaining_bytes;
3908 switch(rsrc->compression) {
3909 case 0: /* No compression. */
3910 if ((size_t)bytes_avail > metadata_bytes)
3911 bytes_avail = metadata_bytes;
3912 memcpy(mp, p, bytes_avail);
3913 bytes_used = (size_t)bytes_avail;
3914 metadata_bytes -= bytes_used;
3916 if (metadata_bytes == 0)
3920 case 8: /* Deflate compression. */
3924 ret = zip_deflate_init(a, zip);
3925 if (ret != ARCHIVE_OK)
3926 goto exit_mac_metadata;
3927 zip->stream.next_in =
3928 (Bytef *)(uintptr_t)(const void *)p;
3929 zip->stream.avail_in = (uInt)bytes_avail;
3930 zip->stream.total_in = 0;
3931 zip->stream.next_out = mp;
3932 zip->stream.avail_out = (uInt)metadata_bytes;
3933 zip->stream.total_out = 0;
3935 r = inflate(&zip->stream, 0);
3943 archive_set_error(&a->archive, ENOMEM,
3944 "Out of memory for ZIP decompression");
3945 ret = ARCHIVE_FATAL;
3946 goto exit_mac_metadata;
3948 archive_set_error(&a->archive,
3950 "ZIP decompression failed (%d)", r);
3951 ret = ARCHIVE_FATAL;
3952 goto exit_mac_metadata;
3954 bytes_used = zip->stream.total_in;
3955 metadata_bytes -= zip->stream.total_out;
3956 mp += zip->stream.total_out;
3964 __archive_read_consume(a, bytes_used);
3965 remaining_bytes -= bytes_used;
3967 archive_entry_copy_mac_metadata(entry, metadata,
3968 (size_t)rsrc->uncompressed_size - metadata_bytes);
3971 __archive_read_seek(a, offset, SEEK_SET);
3972 zip->decompress_init = 0;
3978 archive_read_format_zip_seekable_read_header(struct archive_read *a,
3979 struct archive_entry *entry)
3981 struct zip *zip = (struct zip *)a->format->data;
3982 struct zip_entry *rsrc;
3984 int r, ret = ARCHIVE_OK;
3987 * It should be sufficient to call archive_read_next_header() for
3988 * a reader to determine if an entry is encrypted or not. If the
3989 * encryption of an entry is only detectable when calling
3990 * archive_read_data(), so be it. We'll do the same check there
3993 if (zip->has_encrypted_entries ==
3994 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3995 zip->has_encrypted_entries = 0;
3997 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3998 if (a->archive.archive_format_name == NULL)
3999 a->archive.archive_format_name = "ZIP";
4001 if (zip->zip_entries == NULL) {
4002 r = slurp_central_directory(a, entry, zip);
4003 if (r != ARCHIVE_OK)
4005 /* Get first entry whose local header offset is lower than
4006 * other entries in the archive file. */
4008 (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
4009 } else if (zip->entry != NULL) {
4010 /* Get next entry in local header offset order. */
4011 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
4012 &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
4015 if (zip->entry == NULL)
4018 if (zip->entry->rsrcname.s)
4019 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
4020 &zip->tree_rsrc, zip->entry->rsrcname.s);
4024 if (zip->cctx_valid)
4025 archive_decrypto_aes_ctr_release(&zip->cctx);
4026 if (zip->hctx_valid)
4027 archive_hmac_sha1_cleanup(&zip->hctx);
4028 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
4029 __archive_read_reset_passphrase(a);
4031 /* File entries are sorted by the header offset, we should mostly
4032 * use __archive_read_consume to advance a read point to avoid
4033 * redundant data reading. */
4034 offset = archive_filter_bytes(&a->archive, 0);
4035 if (offset < zip->entry->local_header_offset)
4036 __archive_read_consume(a,
4037 zip->entry->local_header_offset - offset);
4038 else if (offset != zip->entry->local_header_offset) {
4039 __archive_read_seek(a, zip->entry->local_header_offset,
4042 zip->unconsumed = 0;
4043 r = zip_read_local_file_header(a, entry, zip);
4044 if (r != ARCHIVE_OK)
4047 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
4055 * We're going to seek for the next header anyway, so we don't
4056 * need to bother doing anything here.
4059 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
4062 zip = (struct zip *)(a->format->data);
4064 zip->unconsumed = 0;
4065 return (ARCHIVE_OK);
4069 archive_read_support_format_zip_seekable(struct archive *_a)
4071 struct archive_read *a = (struct archive_read *)_a;
4075 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
4076 ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
4078 zip = (struct zip *)calloc(1, sizeof(*zip));
4080 archive_set_error(&a->archive, ENOMEM,
4081 "Can't allocate zip data");
4082 return (ARCHIVE_FATAL);
4085 #ifdef HAVE_COPYFILE_H
4086 /* Set this by default on Mac OS. */
4087 zip->process_mac_extensions = 1;
4091 * Until enough data has been read, we cannot tell about
4092 * any encrypted entries yet.
4094 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4095 zip->crc32func = real_crc32;
4097 r = __archive_read_register_format(a,
4100 archive_read_format_zip_seekable_bid,
4101 archive_read_format_zip_options,
4102 archive_read_format_zip_seekable_read_header,
4103 archive_read_format_zip_read_data,
4104 archive_read_format_zip_read_data_skip_seekable,
4106 archive_read_format_zip_cleanup,
4107 archive_read_support_format_zip_capabilities_seekable,
4108 archive_read_format_zip_has_encrypted_entries);
4110 if (r != ARCHIVE_OK)
4112 return (ARCHIVE_OK);