2 * Copyright (c) 2004-2013 Tim Kientzle
3 * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
4 * Copyright (c) 2013 Konrad Kleine
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD$");
32 * The definitive documentation of the Zip file format is:
33 * http://www.pkware.com/documents/casestudies/APPNOTE.TXT
35 * The Info-Zip project has pioneered various extensions to better
36 * support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
37 * "Ux", and 0x7875 "ux" extensions for time and ownership
40 * History of this code: The streaming Zip reader was first added to
41 * libarchive in January 2005. Support for seekable input sources was
42 * added in Nov 2011. Zip64 support (including a significant code
43 * refactoring) was added in 2014.
63 #include "archive_digest_private.h"
64 #include "archive_cryptor_private.h"
65 #include "archive_endian.h"
66 #include "archive_entry.h"
67 #include "archive_entry_locale.h"
68 #include "archive_hmac_private.h"
69 #include "archive_private.h"
70 #include "archive_rb.h"
71 #include "archive_read_private.h"
72 #include "archive_ppmd8_private.h"
75 #include "archive_crc32.h"
79 struct archive_rb_node node;
80 struct zip_entry *next;
81 int64_t local_header_offset;
82 int64_t compressed_size;
83 int64_t uncompressed_size;
86 struct archive_string rsrcname;
92 uint16_t zip_flags; /* From GP Flags Field */
93 unsigned char compression;
94 unsigned char system; /* From "version written by" */
95 unsigned char flags; /* Our extra markers. */
96 unsigned char decdat;/* Used for Decryption check */
98 /* WinZip AES encryption extra field should be available
99 * when compression is 99. */
101 /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
103 #define AES_VENDOR_AE_1 0x0001
104 #define AES_VENDOR_AE_2 0x0002
105 /* AES encryption strength:
106 * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
108 /* Actual compression method. */
109 unsigned char compression;
113 struct trad_enc_ctx {
117 /* Bits used in zip_flags. */
118 #define ZIP_ENCRYPTED (1 << 0)
119 #define ZIP_LENGTH_AT_END (1 << 3)
120 #define ZIP_STRONG_ENCRYPTED (1 << 6)
121 #define ZIP_UTF8_NAME (1 << 11)
122 /* See "7.2 Single Password Symmetric Encryption Method"
123 in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
124 #define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
126 /* Bits used in flags. */
127 #define LA_USED_ZIP64 (1 << 0)
128 #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
131 * See "WinZip - AES Encryption Information"
132 * http://www.winzip.com/aes_info.htm
134 /* Value used in compression method. */
135 #define WINZIP_AES_ENCRYPTION 99
136 /* Authentication code size. */
137 #define AUTH_CODE_SIZE 10
139 #define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
142 /* Structural information about the archive. */
143 struct archive_string format_name;
144 int64_t central_directory_offset;
145 size_t central_directory_entries_total;
146 size_t central_directory_entries_on_this_disk;
147 int has_encrypted_entries;
149 /* List of entries (seekable Zip only) */
150 struct zip_entry *zip_entries;
151 struct archive_rb_tree tree;
152 struct archive_rb_tree tree_rsrc;
154 /* Bytes read but not yet consumed via __archive_read_consume() */
157 /* Information about entry we're currently reading. */
158 struct zip_entry *entry;
159 int64_t entry_bytes_remaining;
161 /* These count the number of bytes actually read for the entry. */
162 int64_t entry_compressed_bytes_read;
163 int64_t entry_uncompressed_bytes_read;
165 /* Running CRC32 of the decompressed data */
166 unsigned long entry_crc32;
167 unsigned long (*crc32func)(unsigned long, const void *,
171 /* Flags to mark progress of decompression. */
172 char decompress_init;
175 unsigned char *uncompressed_buffer;
176 size_t uncompressed_buffer_size;
183 #if HAVE_LZMA_H && HAVE_LIBLZMA
184 lzma_stream zipx_lzma_stream;
185 char zipx_lzma_valid;
193 IByteIn zipx_ppmd_stream;
194 ssize_t zipx_ppmd_read_compressed;
197 char ppmd8_stream_failed;
199 struct archive_string_conv *sconv;
200 struct archive_string_conv *sconv_default;
201 struct archive_string_conv *sconv_utf8;
202 int init_default_conversion;
203 int process_mac_extensions;
205 char init_decryption;
207 /* Decryption buffer. */
209 * The decrypted data starts at decrypted_ptr and
210 * extends for decrypted_bytes_remaining. Decryption
211 * adds new data to the end of this block, data is returned
212 * to clients from the beginning. When the block hits the
213 * end of decrypted_buffer, it has to be shuffled back to
214 * the beginning of the buffer.
216 unsigned char *decrypted_buffer;
217 unsigned char *decrypted_ptr;
218 size_t decrypted_buffer_size;
219 size_t decrypted_bytes_remaining;
220 size_t decrypted_unconsumed_bytes;
222 /* Traditional PKWARE decryption. */
223 struct trad_enc_ctx tctx;
226 /* WinZip AES decryption. */
227 /* Contexts used for AES decryption. */
228 archive_crypto_ctx cctx;
230 archive_hmac_sha1_ctx hctx;
233 /* Strong encryption's decryption header information. */
246 /* Many systems define min or MIN, but not all. */
247 #define zipmin(a,b) ((a) < (b) ? (a) : (b))
249 /* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8
250 * streams inside ZIP files. It has 2 purposes: one is to fetch the next
251 * compressed byte from the stream, second one is to increase the counter how
252 * many compressed bytes were read. */
255 /* Get the handle to current decompression context. */
256 struct archive_read *a = ((IByteIn*)p)->a;
257 struct zip *zip = (struct zip*) a->format->data;
258 ssize_t bytes_avail = 0;
260 /* Fetch next byte. */
261 const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail);
262 if(bytes_avail < 1) {
263 zip->ppmd8_stream_failed = 1;
267 __archive_read_consume(a, 1);
269 /* Increment the counter. */
270 ++zip->zipx_ppmd_read_compressed;
272 /* Return the next compressed byte. */
276 /* ------------------------------------------------------------------------ */
279 Traditional PKWARE Decryption functions.
283 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
286 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
288 ctx->keys[0] = CRC32(ctx->keys[0], c);
289 ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
290 t = (ctx->keys[1] >> 24) & 0xff;
291 ctx->keys[2] = CRC32(ctx->keys[2], t);
296 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
298 unsigned temp = ctx->keys[2] | 2;
299 return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
303 trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
304 size_t in_len, uint8_t *out, size_t out_len)
308 max = (unsigned)((in_len < out_len)? in_len: out_len);
310 for (i = 0; i < max; i++) {
311 uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
313 trad_enc_update_keys(ctx, t);
318 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
319 const uint8_t *key, size_t key_len, uint8_t *crcchk)
328 ctx->keys[0] = 305419896L;
329 ctx->keys[1] = 591751049L;
330 ctx->keys[2] = 878082192L;
332 for (;pw_len; --pw_len)
333 trad_enc_update_keys(ctx, *pw++);
335 trad_enc_decrypt_update(ctx, key, 12, header, 12);
336 /* Return the last byte for CRC check. */
337 *crcchk = header[11];
343 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
347 archive_sha1_ctx ctx;
348 unsigned char md1[MD_SIZE];
349 unsigned char md2[MD_SIZE * 2];
350 unsigned char mkb[64];
353 archive_sha1_init(&ctx);
354 archive_sha1_update(&ctx, p, size);
355 archive_sha1_final(&ctx, md1);
357 memset(mkb, 0x36, sizeof(mkb));
358 for (i = 0; i < MD_SIZE; i++)
360 archive_sha1_init(&ctx);
361 archive_sha1_update(&ctx, mkb, sizeof(mkb));
362 archive_sha1_final(&ctx, md2);
364 memset(mkb, 0x5C, sizeof(mkb));
365 for (i = 0; i < MD_SIZE; i++)
367 archive_sha1_init(&ctx);
368 archive_sha1_update(&ctx, mkb, sizeof(mkb));
369 archive_sha1_final(&ctx, md2 + MD_SIZE);
373 memcpy(key, md2, key_size);
379 * Common code for streaming or seeking modes.
381 * Includes code to read local file headers, decompress data
382 * from entry bodies, and common API.
386 real_crc32(unsigned long crc, const void *buff, size_t len)
388 return crc32(crc, buff, (unsigned int)len);
391 /* Used by "ignorecrc32" option to speed up tests. */
393 fake_crc32(unsigned long crc, const void *buff, size_t len)
395 (void)crc; /* UNUSED */
396 (void)buff; /* UNUSED */
397 (void)len; /* UNUSED */
401 static const struct {
404 } compression_methods[] = {
405 {0, "uncompressed"}, /* The file is stored (no compression) */
406 {1, "shrinking"}, /* The file is Shrunk */
407 {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
408 {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
409 {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
410 {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
411 {6, "imploded"}, /* The file is Imploded */
412 {7, "reserved"}, /* Reserved for Tokenizing compression algorithm */
413 {8, "deflation"}, /* The file is Deflated */
414 {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
415 {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
417 {11, "reserved"}, /* Reserved by PKWARE */
418 {12, "bzip"}, /* File is compressed using BZIP2 algorithm */
419 {13, "reserved"}, /* Reserved by PKWARE */
420 {14, "lzma"}, /* LZMA (EFS) */
421 {15, "reserved"}, /* Reserved by PKWARE */
422 {16, "reserved"}, /* Reserved by PKWARE */
423 {17, "reserved"}, /* Reserved by PKWARE */
424 {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
425 {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
426 {95, "xz"}, /* XZ compressed data */
427 {96, "jpeg"}, /* JPEG compressed data */
428 {97, "wav-pack"}, /* WavPack compressed data */
429 {98, "ppmd-1"}, /* PPMd version I, Rev 1 */
430 {99, "aes"} /* WinZip AES encryption */
434 compression_name(const int compression)
436 static const int num_compression_methods =
437 sizeof(compression_methods)/sizeof(compression_methods[0]);
440 while(compression >= 0 && i < num_compression_methods) {
441 if (compression_methods[i].id == compression)
442 return compression_methods[i].name;
448 /* Convert an MSDOS-style date/time into Unix-style time. */
450 zip_time(const char *p)
455 msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
456 msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
458 memset(&ts, 0, sizeof(ts));
459 ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
460 ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
461 ts.tm_mday = msDate & 0x1f; /* Day of month. */
462 ts.tm_hour = (msTime >> 11) & 0x1f;
463 ts.tm_min = (msTime >> 5) & 0x3f;
464 ts.tm_sec = (msTime << 1) & 0x3e;
470 * The extra data is stored as a list of
471 * id1+size1+data1 + id2+size2+data2 ...
472 * triplets. id and size are 2 bytes each.
475 process_extra(struct archive_read *a, struct archive_entry *entry,
476 const char *p, size_t extra_length, struct zip_entry* zip_entry)
479 struct zip *zip = (struct zip *)(a->format->data);
481 if (extra_length == 0) {
485 if (extra_length < 4) {
487 /* Some ZIP files may have trailing 0 bytes. Let's check they
488 * are all 0 and ignore them instead of returning an error.
490 * This is not technically correct, but some ZIP files look
491 * like this and other tools support those files - so let's
494 for (; i < extra_length; i++) {
496 archive_set_error(&a->archive,
497 ARCHIVE_ERRNO_FILE_FORMAT,
498 "Too-small extra data: "
499 "Need at least 4 bytes, "
500 "but only found %d bytes",
502 return ARCHIVE_FAILED;
509 while (offset <= extra_length - 4) {
510 unsigned short headerid = archive_le16dec(p + offset);
511 unsigned short datasize = archive_le16dec(p + offset + 2);
514 if (offset + datasize > extra_length) {
515 archive_set_error(&a->archive,
516 ARCHIVE_ERRNO_FILE_FORMAT, "Extra data overflow: "
517 "Need %d bytes but only found %d bytes",
518 (int)datasize, (int)(extra_length - offset));
519 return ARCHIVE_FAILED;
522 fprintf(stderr, "Header id 0x%04x, length %d\n",
527 /* Zip64 extended information extra field. */
528 zip_entry->flags |= LA_USED_ZIP64;
529 if (zip_entry->uncompressed_size == 0xffffffff) {
532 || (t = archive_le64dec(p + offset)) >
534 archive_set_error(&a->archive,
535 ARCHIVE_ERRNO_FILE_FORMAT,
537 "uncompressed size");
538 return ARCHIVE_FAILED;
540 zip_entry->uncompressed_size = t;
544 if (zip_entry->compressed_size == 0xffffffff) {
547 || (t = archive_le64dec(p + offset)) >
549 archive_set_error(&a->archive,
550 ARCHIVE_ERRNO_FILE_FORMAT,
553 return ARCHIVE_FAILED;
555 zip_entry->compressed_size = t;
559 if (zip_entry->local_header_offset == 0xffffffff) {
562 || (t = archive_le64dec(p + offset)) >
564 archive_set_error(&a->archive,
565 ARCHIVE_ERRNO_FILE_FORMAT,
567 "local header offset");
568 return ARCHIVE_FAILED;
570 zip_entry->local_header_offset = t;
574 /* archive_le32dec(p + offset) gives disk
575 * on which file starts, but we don't handle
576 * multi-volume Zip files. */
581 /* Strong encryption field. */
582 if (archive_le16dec(p + offset) == 2) {
584 archive_le16dec(p + offset + 2);
586 archive_le16dec(p + offset + 4);
588 archive_le16dec(p + offset + 6);
589 fprintf(stderr, "algId=0x%04x, bitLen=%u, "
590 "flgas=%d\n", algId, bitLen,flags);
597 /* Extended time field "UT". */
600 archive_set_error(&a->archive,
601 ARCHIVE_ERRNO_FILE_FORMAT,
602 "Incomplete extended time field");
603 return ARCHIVE_FAILED;
608 /* Flag bits indicate which dates are present. */
612 fprintf(stderr, "mtime: %lld -> %d\n",
613 (long long)zip_entry->mtime,
614 archive_le32dec(p + offset));
618 zip_entry->mtime = archive_le32dec(p + offset);
626 zip_entry->atime = archive_le32dec(p + offset);
634 zip_entry->ctime = archive_le32dec(p + offset);
642 /* Info-ZIP Unix Extra Field (old version) "UX". */
644 zip_entry->atime = archive_le32dec(p + offset);
646 archive_le32dec(p + offset + 4);
648 if (datasize >= 12) {
650 archive_le16dec(p + offset + 8);
652 archive_le16dec(p + offset + 10);
658 /* Experimental 'xl' field */
660 * Introduced Dec 2013 to provide a way to
661 * include external file attributes (and other
662 * fields that ordinarily appear only in
663 * central directory) in local file header.
664 * This provides file type and permission
665 * information necessary to support full
666 * streaming extraction. Currently being
667 * discussed with other Zip developers
668 * ... subject to change.
671 * The field starts with a bitmap that specifies
672 * which additional fields are included. The
673 * bitmap is variable length and can be extended in
676 * n bytes - feature bitmap: first byte has low-order
677 * 7 bits. If high-order bit is set, a subsequent
678 * byte holds the next 7 bits, etc.
680 * if bitmap & 1, 2 byte "version made by"
681 * if bitmap & 2, 2 byte "internal file attributes"
682 * if bitmap & 4, 4 byte "external file attributes"
683 * if bitmap & 8, 2 byte comment length + n byte
686 int bitmap, bitmap_last;
690 bitmap_last = bitmap = 0xff & p[offset];
694 /* We only support first 7 bits of bitmap; skip rest. */
695 while ((bitmap_last & 0x80) != 0
697 bitmap_last = p[offset];
703 /* 2 byte "version made by" */
707 = archive_le16dec(p + offset) >> 8;
712 /* 2 byte "internal file attributes" */
713 uint32_t internal_attributes;
717 = archive_le16dec(p + offset);
718 /* Not used by libarchive at present. */
719 (void)internal_attributes; /* UNUSED */
724 /* 4 byte "external file attributes" */
725 uint32_t external_attributes;
729 = archive_le32dec(p + offset);
730 if (zip_entry->system == 3) {
732 = external_attributes >> 16;
733 } else if (zip_entry->system == 0) {
734 // Interpret MSDOS directory bit
735 if (0x10 == (external_attributes &
743 if (0x01 == (external_attributes &
746 * strip write permissions */
747 zip_entry->mode &= 0555;
756 /* 2 byte comment length + comment */
757 uint32_t comment_length;
761 = archive_le16dec(p + offset);
765 if (datasize < comment_length)
767 /* Comment is not supported by libarchive */
768 offset += comment_length;
769 datasize -= comment_length;
775 /* Info-ZIP Unicode Path Extra Field. */
776 if (datasize < 5 || entry == NULL)
781 /* The path name in this field is always encoded
783 if (zip->sconv_utf8 == NULL) {
785 archive_string_conversion_from_charset(
786 &a->archive, "UTF-8", 1);
787 /* If the converter from UTF-8 is not
788 * available, then the path name from the main
789 * field will more likely be correct. */
790 if (zip->sconv_utf8 == NULL)
794 /* Make sure the CRC32 of the filename matches. */
795 if (!zip->ignore_crc32) {
796 const char *cp = archive_entry_pathname(entry);
798 unsigned long file_crc =
799 zip->crc32func(0, cp, strlen(cp));
800 unsigned long utf_crc =
801 archive_le32dec(p + offset - 4);
802 if (file_crc != utf_crc) {
805 "CRC filename mismatch; "
806 "CDE is %lx, but UTF8 "
807 "is outdated with %lx\n",
815 if (archive_entry_copy_pathname_l(entry,
816 p + offset, datasize, zip->sconv_utf8) != 0) {
817 /* Ignore the error, and fallback to the path
818 * name from the main field. */
820 fprintf(stderr, "Failed to read the ZIP "
821 "0x7075 extra field path.\n");
827 /* Info-ZIP Unix Extra Field (type 2) "Ux". */
829 fprintf(stderr, "uid %d gid %d\n",
830 archive_le16dec(p + offset),
831 archive_le16dec(p + offset + 2));
834 zip_entry->uid = archive_le16dec(p + offset);
837 archive_le16dec(p + offset + 2);
841 /* Info-Zip Unix Extra Field (type 3) "ux". */
842 int uidsize = 0, gidsize = 0;
844 /* TODO: support arbitrary uidsize/gidsize. */
845 if (datasize >= 1 && p[offset] == 1) {/* version=1 */
847 /* get a uid size. */
848 uidsize = 0xff & (int)p[offset+1];
853 else if (uidsize == 4 && datasize >= 6)
858 if (datasize >= (2 + uidsize + 3)) {
859 /* get a gid size. */
861 (int)p[offset+2+uidsize];
865 p+offset+2+uidsize+1);
866 else if (gidsize == 4 &&
867 datasize >= (2 + uidsize + 5))
870 p+offset+2+uidsize+1);
876 /* WinZip AES extra data field. */
878 archive_set_error(&a->archive,
879 ARCHIVE_ERRNO_FILE_FORMAT,
880 "Incomplete AES field");
881 return ARCHIVE_FAILED;
883 if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
884 /* Vendor version. */
885 zip_entry->aes_extra.vendor =
886 archive_le16dec(p + offset);
887 /* AES encryption strength. */
888 zip_entry->aes_extra.strength = p[offset + 4];
889 /* Actual compression method. */
890 zip_entry->aes_extra.compression =
902 #if HAVE_LZMA_H && HAVE_LIBLZMA
904 * Auxiliary function to uncompress data chunk from zipx archive
905 * (zip with lzma compression).
908 zipx_lzma_uncompress_buffer(const char *compressed_buffer,
909 size_t compressed_buffer_size,
910 char *uncompressed_buffer,
911 size_t uncompressed_buffer_size)
913 int status = ARCHIVE_FATAL;
914 // length of 'lzma properties data' in lzma compressed
915 // data segment (stream) inside zip archive
916 const size_t lzma_params_length = 5;
917 // offset of 'lzma properties data' from the beginning of lzma stream
918 const size_t lzma_params_offset = 4;
919 // end position of 'lzma properties data' in lzma stream
920 const size_t lzma_params_end = lzma_params_offset + lzma_params_length;
921 if (compressed_buffer == NULL ||
922 compressed_buffer_size < lzma_params_end ||
923 uncompressed_buffer == NULL)
926 // prepare header for lzma_alone_decoder to replace zipx header
927 // (see comments in 'zipx_lzma_alone_init' for justification)
932 uint8_t bytes[5]; // lzma_params_length
933 uint64_t uncompressed_size;
936 // copy 'lzma properties data' blob
937 memcpy(&alone_header.bytes[0], compressed_buffer + lzma_params_offset,
939 alone_header.uncompressed_size = UINT64_MAX;
941 // prepare new compressed buffer, see 'zipx_lzma_alone_init' for details
942 const size_t lzma_alone_buffer_size =
943 compressed_buffer_size - lzma_params_end + sizeof(alone_header);
944 unsigned char *lzma_alone_compressed_buffer =
945 (unsigned char*) malloc(lzma_alone_buffer_size);
946 if (lzma_alone_compressed_buffer == NULL)
948 // copy lzma_alone header into new buffer
949 memcpy(lzma_alone_compressed_buffer, (void*) &alone_header,
950 sizeof(alone_header));
951 // copy compressed data into new buffer
952 memcpy(lzma_alone_compressed_buffer + sizeof(alone_header),
953 compressed_buffer + lzma_params_end,
954 compressed_buffer_size - lzma_params_end);
956 // create and fill in lzma_alone_decoder stream
957 lzma_stream stream = LZMA_STREAM_INIT;
958 lzma_ret ret = lzma_alone_decoder(&stream, UINT64_MAX);
961 stream.next_in = lzma_alone_compressed_buffer;
962 stream.avail_in = lzma_alone_buffer_size;
964 stream.next_out = (unsigned char*)uncompressed_buffer;
965 stream.avail_out = uncompressed_buffer_size;
966 stream.total_out = 0;
967 ret = lzma_code(&stream, LZMA_RUN);
968 if (ret == LZMA_OK || ret == LZMA_STREAM_END)
972 free(lzma_alone_compressed_buffer);
978 * Assumes file pointer is at beginning of local file header.
981 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
988 size_t len, filename_length, extra_length;
989 struct archive_string_conv *sconv;
990 struct zip_entry *zip_entry = zip->entry;
991 struct zip_entry zip_entry_central_dir;
992 int ret = ARCHIVE_OK;
995 /* Save a copy of the original for consistency checks. */
996 zip_entry_central_dir = *zip_entry;
998 zip->decompress_init = 0;
999 zip->end_of_entry = 0;
1000 zip->entry_uncompressed_bytes_read = 0;
1001 zip->entry_compressed_bytes_read = 0;
1002 zip->entry_crc32 = zip->crc32func(0, NULL, 0);
1004 /* Setup default conversion. */
1005 if (zip->sconv == NULL && !zip->init_default_conversion) {
1006 zip->sconv_default =
1007 archive_string_default_conversion_for_read(&(a->archive));
1008 zip->init_default_conversion = 1;
1011 if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
1012 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1013 "Truncated ZIP file header");
1014 return (ARCHIVE_FATAL);
1017 if (memcmp(p, "PK\003\004", 4) != 0) {
1018 archive_set_error(&a->archive, -1, "Damaged Zip archive");
1019 return ARCHIVE_FATAL;
1022 zip_entry->system = p[5];
1023 zip_entry->zip_flags = archive_le16dec(p + 6);
1024 if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
1025 zip->has_encrypted_entries = 1;
1026 archive_entry_set_is_data_encrypted(entry, 1);
1027 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
1028 zip_entry->zip_flags & ZIP_ENCRYPTED &&
1029 zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
1030 archive_entry_set_is_metadata_encrypted(entry, 1);
1031 return ARCHIVE_FATAL;
1034 zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
1035 zip_entry->compression = (char)archive_le16dec(p + 8);
1036 zip_entry->mtime = zip_time(p + 10);
1037 zip_entry->crc32 = archive_le32dec(p + 14);
1038 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1039 zip_entry->decdat = p[11];
1041 zip_entry->decdat = p[17];
1042 zip_entry->compressed_size = archive_le32dec(p + 18);
1043 zip_entry->uncompressed_size = archive_le32dec(p + 22);
1044 filename_length = archive_le16dec(p + 26);
1045 extra_length = archive_le16dec(p + 28);
1047 __archive_read_consume(a, 30);
1049 /* Read the filename. */
1050 if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
1051 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1052 "Truncated ZIP file header");
1053 return (ARCHIVE_FATAL);
1055 if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
1056 /* The filename is stored to be UTF-8. */
1057 if (zip->sconv_utf8 == NULL) {
1059 archive_string_conversion_from_charset(
1060 &a->archive, "UTF-8", 1);
1061 if (zip->sconv_utf8 == NULL)
1062 return (ARCHIVE_FATAL);
1064 sconv = zip->sconv_utf8;
1065 } else if (zip->sconv != NULL)
1068 sconv = zip->sconv_default;
1070 if (archive_entry_copy_pathname_l(entry,
1071 h, filename_length, sconv) != 0) {
1072 if (errno == ENOMEM) {
1073 archive_set_error(&a->archive, ENOMEM,
1074 "Can't allocate memory for Pathname");
1075 return (ARCHIVE_FATAL);
1077 archive_set_error(&a->archive,
1078 ARCHIVE_ERRNO_FILE_FORMAT,
1079 "Pathname cannot be converted "
1080 "from %s to current locale.",
1081 archive_string_conversion_charset_name(sconv));
1084 __archive_read_consume(a, filename_length);
1086 /* Read the extra data. */
1087 if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
1088 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1089 "Truncated ZIP file header");
1090 return (ARCHIVE_FATAL);
1093 if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
1095 return ARCHIVE_FATAL;
1097 __archive_read_consume(a, extra_length);
1099 /* Work around a bug in Info-Zip: When reading from a pipe, it
1100 * stats the pipe instead of synthesizing a file entry. */
1101 if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
1102 zip_entry->mode &= ~ AE_IFMT;
1103 zip_entry->mode |= AE_IFREG;
1106 /* If the mode is totally empty, set some sane default. */
1107 if (zip_entry->mode == 0) {
1108 zip_entry->mode |= 0664;
1111 /* Windows archivers sometimes use backslash as the directory
1112 * separator. Normalize to slash. */
1113 if (zip_entry->system == 0 &&
1114 (wp = archive_entry_pathname_w(entry)) != NULL) {
1115 if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
1117 struct archive_wstring s;
1118 archive_string_init(&s);
1119 archive_wstrcpy(&s, wp);
1120 for (i = 0; i < archive_strlen(&s); i++) {
1124 archive_entry_copy_pathname_w(entry, s.s);
1125 archive_wstring_free(&s);
1129 /* Make sure that entries with a trailing '/' are marked as directories
1130 * even if the External File Attributes contains bogus values. If this
1131 * is not a directory and there is no type, assume a regular file. */
1132 if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
1135 wp = archive_entry_pathname_w(entry);
1138 has_slash = len > 0 && wp[len - 1] == L'/';
1140 cp = archive_entry_pathname(entry);
1141 len = (cp != NULL)?strlen(cp):0;
1142 has_slash = len > 0 && cp[len - 1] == '/';
1144 /* Correct file type as needed. */
1146 zip_entry->mode &= ~AE_IFMT;
1147 zip_entry->mode |= AE_IFDIR;
1148 zip_entry->mode |= 0111;
1149 } else if ((zip_entry->mode & AE_IFMT) == 0) {
1150 zip_entry->mode |= AE_IFREG;
1154 /* Make sure directories end in '/' */
1155 if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
1156 wp = archive_entry_pathname_w(entry);
1159 if (len > 0 && wp[len - 1] != L'/') {
1160 struct archive_wstring s;
1161 archive_string_init(&s);
1162 archive_wstrcat(&s, wp);
1163 archive_wstrappend_wchar(&s, L'/');
1164 archive_entry_copy_pathname_w(entry, s.s);
1165 archive_wstring_free(&s);
1168 cp = archive_entry_pathname(entry);
1169 len = (cp != NULL)?strlen(cp):0;
1170 if (len > 0 && cp[len - 1] != '/') {
1171 struct archive_string s;
1172 archive_string_init(&s);
1173 archive_strcat(&s, cp);
1174 archive_strappend_char(&s, '/');
1175 archive_entry_set_pathname(entry, s.s);
1176 archive_string_free(&s);
1181 if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1182 /* If this came from the central dir, its size info
1183 * is definitive, so ignore the length-at-end flag. */
1184 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1185 /* If local header is missing a value, use the one from
1186 the central directory. If both have it, warn about
1188 if (zip_entry->crc32 == 0) {
1189 zip_entry->crc32 = zip_entry_central_dir.crc32;
1190 } else if (!zip->ignore_crc32
1191 && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1192 archive_set_error(&a->archive,
1193 ARCHIVE_ERRNO_FILE_FORMAT,
1194 "Inconsistent CRC32 values");
1197 if (zip_entry->compressed_size == 0) {
1198 zip_entry->compressed_size
1199 = zip_entry_central_dir.compressed_size;
1200 } else if (zip_entry->compressed_size
1201 != zip_entry_central_dir.compressed_size) {
1202 archive_set_error(&a->archive,
1203 ARCHIVE_ERRNO_FILE_FORMAT,
1204 "Inconsistent compressed size: "
1205 "%jd in central directory, %jd in local header",
1206 (intmax_t)zip_entry_central_dir.compressed_size,
1207 (intmax_t)zip_entry->compressed_size);
1210 if (zip_entry->uncompressed_size == 0) {
1211 zip_entry->uncompressed_size
1212 = zip_entry_central_dir.uncompressed_size;
1213 } else if (zip_entry->uncompressed_size
1214 != zip_entry_central_dir.uncompressed_size) {
1215 archive_set_error(&a->archive,
1216 ARCHIVE_ERRNO_FILE_FORMAT,
1217 "Inconsistent uncompressed size: "
1218 "%jd in central directory, %jd in local header",
1219 (intmax_t)zip_entry_central_dir.uncompressed_size,
1220 (intmax_t)zip_entry->uncompressed_size);
1225 /* Populate some additional entry fields: */
1226 archive_entry_set_mode(entry, zip_entry->mode);
1227 archive_entry_set_uid(entry, zip_entry->uid);
1228 archive_entry_set_gid(entry, zip_entry->gid);
1229 archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1230 archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1231 archive_entry_set_atime(entry, zip_entry->atime, 0);
1233 if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1234 size_t linkname_length;
1236 if (zip_entry->compressed_size > 64 * 1024) {
1237 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1238 "Zip file with oversized link entry");
1239 return ARCHIVE_FATAL;
1242 linkname_length = (size_t)zip_entry->compressed_size;
1244 archive_entry_set_size(entry, 0);
1245 p = __archive_read_ahead(a, linkname_length, NULL);
1247 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1248 "Truncated Zip file");
1249 return ARCHIVE_FATAL;
1251 // take into account link compression if any
1252 size_t linkname_full_length = linkname_length;
1253 if (zip->entry->compression != 0)
1255 // symlink target string appeared to be compressed
1256 int status = ARCHIVE_FATAL;
1257 char *uncompressed_buffer =
1258 (char*) malloc(zip_entry->uncompressed_size);
1259 if (uncompressed_buffer == NULL)
1261 archive_set_error(&a->archive, ENOMEM,
1262 "No memory for lzma decompression");
1266 switch (zip->entry->compression)
1268 #if HAVE_LZMA_H && HAVE_LIBLZMA
1269 case 14: /* ZIPx LZMA compression. */
1270 /*(see zip file format specification, section 4.4.5)*/
1271 status = zipx_lzma_uncompress_buffer(p,
1273 uncompressed_buffer,
1274 (size_t)zip_entry->uncompressed_size);
1277 default: /* Unsupported compression. */
1280 if (status == ARCHIVE_OK)
1282 p = uncompressed_buffer;
1283 linkname_full_length =
1284 (size_t)zip_entry->uncompressed_size;
1288 archive_set_error(&a->archive,
1289 ARCHIVE_ERRNO_FILE_FORMAT,
1290 "Unsupported ZIP compression method "
1291 "during decompression of link entry (%d: %s)",
1292 zip->entry->compression,
1293 compression_name(zip->entry->compression));
1294 return ARCHIVE_FAILED;
1299 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1300 sconv = zip->sconv_utf8;
1302 sconv = zip->sconv_default;
1303 if (archive_entry_copy_symlink_l(entry, p, linkname_full_length,
1305 if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1306 (zip->entry->zip_flags & ZIP_UTF8_NAME))
1307 archive_entry_copy_symlink_l(entry, p,
1308 linkname_full_length, NULL);
1309 if (errno == ENOMEM) {
1310 archive_set_error(&a->archive, ENOMEM,
1311 "Can't allocate memory for Symlink");
1312 return (ARCHIVE_FATAL);
1315 * Since there is no character-set regulation for
1316 * symlink name, do not report the conversion error
1317 * in an automatic conversion.
1319 if (sconv != zip->sconv_utf8 ||
1320 (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1321 archive_set_error(&a->archive,
1322 ARCHIVE_ERRNO_FILE_FORMAT,
1323 "Symlink cannot be converted "
1324 "from %s to current locale.",
1325 archive_string_conversion_charset_name(
1330 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1332 if (__archive_read_consume(a, linkname_length) < 0) {
1333 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1334 "Read error skipping symlink target name");
1335 return ARCHIVE_FATAL;
1337 } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1338 || zip_entry->uncompressed_size > 0) {
1339 /* Set the size only if it's meaningful. */
1340 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1342 zip->entry_bytes_remaining = zip_entry->compressed_size;
1344 /* If there's no body, force read_data() to return EOF immediately. */
1345 if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1346 && zip->entry_bytes_remaining < 1)
1347 zip->end_of_entry = 1;
1349 /* Set up a more descriptive format name. */
1350 archive_string_empty(&zip->format_name);
1351 archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1352 version / 10, version % 10,
1353 compression_name(zip->entry->compression));
1354 a->archive.archive_format_name = zip->format_name.s;
1360 check_authentication_code(struct archive_read *a, const void *_p)
1362 struct zip *zip = (struct zip *)(a->format->data);
1364 /* Check authentication code. */
1365 if (zip->hctx_valid) {
1368 size_t hmac_len = 20;
1371 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1373 /* Read authentication code. */
1374 p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1376 archive_set_error(&a->archive,
1377 ARCHIVE_ERRNO_FILE_FORMAT,
1378 "Truncated ZIP file data");
1379 return (ARCHIVE_FATAL);
1384 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1385 __archive_read_consume(a, AUTH_CODE_SIZE);
1387 archive_set_error(&a->archive,
1389 "ZIP bad Authentication code");
1390 return (ARCHIVE_WARN);
1393 return (ARCHIVE_OK);
1397 * Read "uncompressed" data. There are three cases:
1398 * 1) We know the size of the data. This is always true for the
1399 * seeking reader (we've examined the Central Directory already).
1400 * 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1401 * Info-ZIP seems to do this; we know the size but have to grab
1402 * the CRC from the data descriptor afterwards.
1403 * 3) We're streaming and ZIP_LENGTH_AT_END was specified and
1404 * we have no size information. In this case, we can do pretty
1405 * well by watching for the data descriptor record. The data
1406 * descriptor is 16 bytes and includes a computed CRC that should
1407 * provide a strong check.
1409 * TODO: Technically, the PK\007\010 signature is optional.
1410 * In the original spec, the data descriptor contained CRC
1411 * and size fields but had no leading signature. In practice,
1412 * newer writers seem to provide the signature pretty consistently.
1414 * For uncompressed data, the PK\007\010 marker seems essential
1415 * to be sure we've actually seen the end of the entry.
1417 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1418 * zip->end_of_entry if it consumes all of the data.
1421 zip_read_data_none(struct archive_read *a, const void **_buff,
1422 size_t *size, int64_t *offset)
1426 ssize_t bytes_avail;
1429 (void)offset; /* UNUSED */
1431 zip = (struct zip *)(a->format->data);
1433 if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1435 ssize_t grabbing_bytes = 24;
1437 if (zip->hctx_valid)
1438 grabbing_bytes += AUTH_CODE_SIZE;
1439 /* Grab at least 24 bytes. */
1440 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1441 if (bytes_avail < grabbing_bytes) {
1442 /* Zip archives have end-of-archive markers
1443 that are longer than this, so a failure to get at
1444 least 24 bytes really does indicate a truncated
1446 archive_set_error(&a->archive,
1447 ARCHIVE_ERRNO_FILE_FORMAT,
1448 "Truncated ZIP file data");
1449 return (ARCHIVE_FATAL);
1451 /* Check for a complete PK\007\010 signature, followed
1452 * by the correct 4-byte CRC. */
1454 if (zip->hctx_valid)
1455 p += AUTH_CODE_SIZE;
1456 if (p[0] == 'P' && p[1] == 'K'
1457 && p[2] == '\007' && p[3] == '\010'
1458 && (archive_le32dec(p + 4) == zip->entry_crc32
1459 || zip->ignore_crc32
1461 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1462 if (zip->entry->flags & LA_USED_ZIP64) {
1463 uint64_t compressed, uncompressed;
1464 zip->entry->crc32 = archive_le32dec(p + 4);
1465 compressed = archive_le64dec(p + 8);
1466 uncompressed = archive_le64dec(p + 16);
1467 if (compressed > INT64_MAX || uncompressed >
1469 archive_set_error(&a->archive,
1470 ARCHIVE_ERRNO_FILE_FORMAT,
1471 "Overflow of 64-bit file sizes");
1472 return ARCHIVE_FAILED;
1474 zip->entry->compressed_size = compressed;
1475 zip->entry->uncompressed_size = uncompressed;
1476 zip->unconsumed = 24;
1478 zip->entry->crc32 = archive_le32dec(p + 4);
1479 zip->entry->compressed_size =
1480 archive_le32dec(p + 8);
1481 zip->entry->uncompressed_size =
1482 archive_le32dec(p + 12);
1483 zip->unconsumed = 16;
1485 if (zip->hctx_valid) {
1486 r = check_authentication_code(a, buff);
1487 if (r != ARCHIVE_OK)
1490 zip->end_of_entry = 1;
1491 return (ARCHIVE_OK);
1493 /* If not at EOF, ensure we consume at least one byte. */
1496 /* Scan forward until we see where a PK\007\010 signature
1498 /* Return bytes up until that point. On the next call,
1499 * the code above will verify the data descriptor. */
1500 while (p < buff + bytes_avail - 4) {
1501 if (p[3] == 'P') { p += 3; }
1502 else if (p[3] == 'K') { p += 2; }
1503 else if (p[3] == '\007') { p += 1; }
1504 else if (p[3] == '\010' && p[2] == '\007'
1505 && p[1] == 'K' && p[0] == 'P') {
1506 if (zip->hctx_valid)
1507 p -= AUTH_CODE_SIZE;
1511 bytes_avail = p - buff;
1513 if (zip->entry_bytes_remaining == 0) {
1514 zip->end_of_entry = 1;
1515 if (zip->hctx_valid) {
1516 r = check_authentication_code(a, NULL);
1517 if (r != ARCHIVE_OK)
1520 return (ARCHIVE_OK);
1522 /* Grab a bunch of bytes. */
1523 buff = __archive_read_ahead(a, 1, &bytes_avail);
1524 if (bytes_avail <= 0) {
1525 archive_set_error(&a->archive,
1526 ARCHIVE_ERRNO_FILE_FORMAT,
1527 "Truncated ZIP file data");
1528 return (ARCHIVE_FATAL);
1530 if (bytes_avail > zip->entry_bytes_remaining)
1531 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1533 if (zip->tctx_valid || zip->cctx_valid) {
1534 size_t dec_size = bytes_avail;
1536 if (dec_size > zip->decrypted_buffer_size)
1537 dec_size = zip->decrypted_buffer_size;
1538 if (zip->tctx_valid) {
1539 trad_enc_decrypt_update(&zip->tctx,
1540 (const uint8_t *)buff, dec_size,
1541 zip->decrypted_buffer, dec_size);
1543 size_t dsize = dec_size;
1544 archive_hmac_sha1_update(&zip->hctx,
1545 (const uint8_t *)buff, dec_size);
1546 archive_decrypto_aes_ctr_update(&zip->cctx,
1547 (const uint8_t *)buff, dec_size,
1548 zip->decrypted_buffer, &dsize);
1550 bytes_avail = dec_size;
1551 buff = (const char *)zip->decrypted_buffer;
1553 *size = bytes_avail;
1554 zip->entry_bytes_remaining -= bytes_avail;
1555 zip->entry_uncompressed_bytes_read += bytes_avail;
1556 zip->entry_compressed_bytes_read += bytes_avail;
1557 zip->unconsumed += bytes_avail;
1559 return (ARCHIVE_OK);
1563 consume_optional_marker(struct archive_read *a, struct zip *zip)
1565 if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1568 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1569 archive_set_error(&a->archive,
1570 ARCHIVE_ERRNO_FILE_FORMAT,
1571 "Truncated ZIP end-of-file record");
1572 return (ARCHIVE_FATAL);
1574 /* Consume the optional PK\007\010 marker. */
1575 if (p[0] == 'P' && p[1] == 'K' &&
1576 p[2] == '\007' && p[3] == '\010') {
1578 zip->unconsumed = 4;
1580 if (zip->entry->flags & LA_USED_ZIP64) {
1581 uint64_t compressed, uncompressed;
1582 zip->entry->crc32 = archive_le32dec(p);
1583 compressed = archive_le64dec(p + 4);
1584 uncompressed = archive_le64dec(p + 12);
1585 if (compressed > INT64_MAX ||
1586 uncompressed > INT64_MAX) {
1587 archive_set_error(&a->archive,
1588 ARCHIVE_ERRNO_FILE_FORMAT,
1589 "Overflow of 64-bit file sizes");
1590 return ARCHIVE_FAILED;
1592 zip->entry->compressed_size = compressed;
1593 zip->entry->uncompressed_size = uncompressed;
1594 zip->unconsumed += 20;
1596 zip->entry->crc32 = archive_le32dec(p);
1597 zip->entry->compressed_size = archive_le32dec(p + 4);
1598 zip->entry->uncompressed_size = archive_le32dec(p + 8);
1599 zip->unconsumed += 12;
1603 return (ARCHIVE_OK);
1606 #if HAVE_LZMA_H && HAVE_LIBLZMA
1608 zipx_xz_init(struct archive_read *a, struct zip *zip)
1612 if(zip->zipx_lzma_valid) {
1613 lzma_end(&zip->zipx_lzma_stream);
1614 zip->zipx_lzma_valid = 0;
1617 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1618 r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1620 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1621 "xz initialization failed(%d)",
1624 return (ARCHIVE_FAILED);
1627 zip->zipx_lzma_valid = 1;
1629 free(zip->uncompressed_buffer);
1631 zip->uncompressed_buffer_size = 256 * 1024;
1632 zip->uncompressed_buffer =
1633 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1634 if (zip->uncompressed_buffer == NULL) {
1635 archive_set_error(&a->archive, ENOMEM,
1636 "No memory for xz decompression");
1637 return (ARCHIVE_FATAL);
1640 zip->decompress_init = 1;
1641 return (ARCHIVE_OK);
1645 zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1652 struct _alone_header {
1654 uint64_t uncompressed_size;
1658 if(zip->zipx_lzma_valid) {
1659 lzma_end(&zip->zipx_lzma_stream);
1660 zip->zipx_lzma_valid = 0;
1663 /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
1664 * that is a part of XZ Utils. The stream format stored inside ZIPX
1665 * file is a modified "lzma alone" file format, that was used by the
1666 * `lzma` utility which was later deprecated in favour of `xz` utility. * Since those formats are nearly the same, we can use a standard
1667 * "lzma alone" decoder from XZ Utils. */
1669 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1670 r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1672 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1673 "lzma initialization failed(%d)", r);
1675 return (ARCHIVE_FAILED);
1678 /* Flag the cleanup function that we want our lzma-related structures
1679 * to be freed later. */
1680 zip->zipx_lzma_valid = 1;
1682 /* The "lzma alone" file format and the stream format inside ZIPx are
1683 * almost the same. Here's an example of a structure of "lzma alone"
1686 * $ cat /bin/ls | lzma | xxd | head -n 1
1687 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1689 * 5 bytes 8 bytes n bytes
1690 * <lzma_params><uncompressed_size><data...>
1692 * lzma_params is a 5-byte blob that has to be decoded to extract
1693 * parameters of this LZMA stream. The uncompressed_size field is an
1694 * uint64_t value that contains information about the size of the
1695 * uncompressed file, or UINT64_MAX if this value is unknown.
1696 * The <data...> part is the actual lzma-compressed data stream.
1698 * Now here's the structure of the stream inside the ZIPX file:
1700 * $ cat stream_inside_zipx | xxd | head -n 1
1701 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1703 * 2byte 2byte 5 bytes n bytes
1704 * <magic1><magic2><lzma_params><data...>
1706 * This means that the ZIPX file contains an additional magic1 and
1707 * magic2 headers, the lzma_params field contains the same parameter
1708 * set as in the "lzma alone" format, and the <data...> field is the
1709 * same as in the "lzma alone" format as well. Note that also the zipx
1710 * format is missing the uncompressed_size field.
1712 * So, in order to use the "lzma alone" decoder for the zipx lzma
1713 * stream, we simply need to shuffle around some fields, prepare a new
1714 * lzma alone header, feed it into lzma alone decoder so it will
1715 * initialize itself properly, and then we can start feeding normal
1716 * zipx lzma stream into the decoder.
1719 /* Read magic1,magic2,lzma_params from the ZIPX stream. */
1720 if((p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1721 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1722 "Truncated lzma data");
1723 return (ARCHIVE_FATAL);
1726 if(p[2] != 0x05 || p[3] != 0x00) {
1727 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1728 "Invalid lzma data");
1729 return (ARCHIVE_FATAL);
1732 /* Prepare an lzma alone header: copy the lzma_params blob into
1733 * a proper place into the lzma alone header. */
1734 memcpy(&alone_header.bytes[0], p + 4, 5);
1736 /* Initialize the 'uncompressed size' field to unknown; we'll manually
1737 * monitor how many bytes there are still to be uncompressed. */
1738 alone_header.uncompressed_size = UINT64_MAX;
1740 if(!zip->uncompressed_buffer) {
1741 zip->uncompressed_buffer_size = 256 * 1024;
1742 zip->uncompressed_buffer =
1743 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1745 if (zip->uncompressed_buffer == NULL) {
1746 archive_set_error(&a->archive, ENOMEM,
1747 "No memory for lzma decompression");
1748 return (ARCHIVE_FATAL);
1752 zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1753 zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1754 zip->zipx_lzma_stream.total_in = 0;
1755 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1756 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1757 zip->zipx_lzma_stream.total_out = 0;
1759 /* Feed only the header into the lzma alone decoder. This will
1760 * effectively initialize the decoder, and will not produce any
1761 * output bytes yet. */
1762 r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1764 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1765 "lzma stream initialization error");
1766 return ARCHIVE_FATAL;
1769 /* We've already consumed some bytes, so take this into account. */
1770 __archive_read_consume(a, 9);
1771 zip->entry_bytes_remaining -= 9;
1772 zip->entry_compressed_bytes_read += 9;
1774 zip->decompress_init = 1;
1775 return (ARCHIVE_OK);
1779 zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1780 size_t *size, int64_t *offset)
1782 struct zip* zip = (struct zip *)(a->format->data);
1785 const void* compressed_buf;
1786 ssize_t bytes_avail, in_bytes, to_consume = 0;
1788 (void) offset; /* UNUSED */
1790 /* Initialize decompressor if not yet initialized. */
1791 if (!zip->decompress_init) {
1792 ret = zipx_xz_init(a, zip);
1793 if (ret != ARCHIVE_OK)
1797 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1798 if (bytes_avail < 0) {
1799 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1800 "Truncated xz file body");
1801 return (ARCHIVE_FATAL);
1804 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1805 zip->zipx_lzma_stream.next_in = compressed_buf;
1806 zip->zipx_lzma_stream.avail_in = in_bytes;
1807 zip->zipx_lzma_stream.total_in = 0;
1808 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1809 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1810 zip->zipx_lzma_stream.total_out = 0;
1812 /* Perform the decompression. */
1813 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1815 case LZMA_DATA_ERROR:
1816 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1817 "xz data error (error %d)", (int) lz_ret);
1818 return (ARCHIVE_FATAL);
1825 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1826 "xz unknown error %d", (int) lz_ret);
1827 return (ARCHIVE_FATAL);
1829 case LZMA_STREAM_END:
1830 lzma_end(&zip->zipx_lzma_stream);
1831 zip->zipx_lzma_valid = 0;
1833 if((int64_t) zip->zipx_lzma_stream.total_in !=
1834 zip->entry_bytes_remaining)
1836 archive_set_error(&a->archive,
1838 "xz premature end of stream");
1839 return (ARCHIVE_FATAL);
1842 zip->end_of_entry = 1;
1846 to_consume = zip->zipx_lzma_stream.total_in;
1848 __archive_read_consume(a, to_consume);
1849 zip->entry_bytes_remaining -= to_consume;
1850 zip->entry_compressed_bytes_read += to_consume;
1851 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1853 *size = zip->zipx_lzma_stream.total_out;
1854 *buff = zip->uncompressed_buffer;
1856 ret = consume_optional_marker(a, zip);
1857 if (ret != ARCHIVE_OK)
1860 return (ARCHIVE_OK);
1864 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1865 size_t *size, int64_t *offset)
1867 struct zip* zip = (struct zip *)(a->format->data);
1870 const void* compressed_buf;
1871 ssize_t bytes_avail, in_bytes, to_consume;
1873 (void) offset; /* UNUSED */
1875 /* Initialize decompressor if not yet initialized. */
1876 if (!zip->decompress_init) {
1877 ret = zipx_lzma_alone_init(a, zip);
1878 if (ret != ARCHIVE_OK)
1882 /* Fetch more compressed data. The same note as in deflate handler
1883 * applies here as well:
1885 * Note: '1' here is a performance optimization. Recall that the
1886 * decompression layer returns a count of available bytes; asking for
1887 * more than that forces the decompressor to combine reads by copying
1890 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1891 if (bytes_avail < 0) {
1892 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1893 "Truncated lzma file body");
1894 return (ARCHIVE_FATAL);
1897 /* Set decompressor parameters. */
1898 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1900 zip->zipx_lzma_stream.next_in = compressed_buf;
1901 zip->zipx_lzma_stream.avail_in = in_bytes;
1902 zip->zipx_lzma_stream.total_in = 0;
1903 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1904 zip->zipx_lzma_stream.avail_out =
1905 /* These lzma_alone streams lack end of stream marker, so let's
1906 * make sure the unpacker won't try to unpack more than it's
1908 zipmin((int64_t) zip->uncompressed_buffer_size,
1909 zip->entry->uncompressed_size -
1910 zip->entry_uncompressed_bytes_read);
1911 zip->zipx_lzma_stream.total_out = 0;
1913 /* Perform the decompression. */
1914 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1916 case LZMA_DATA_ERROR:
1917 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1918 "lzma data error (error %d)", (int) lz_ret);
1919 return (ARCHIVE_FATAL);
1921 /* This case is optional in lzma alone format. It can happen,
1922 * but most of the files don't have it. (GitHub #1257) */
1923 case LZMA_STREAM_END:
1924 lzma_end(&zip->zipx_lzma_stream);
1925 zip->zipx_lzma_valid = 0;
1926 if((int64_t) zip->zipx_lzma_stream.total_in !=
1927 zip->entry_bytes_remaining)
1929 archive_set_error(&a->archive,
1931 "lzma alone premature end of stream");
1932 return (ARCHIVE_FATAL);
1935 zip->end_of_entry = 1;
1942 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1943 "lzma unknown error %d", (int) lz_ret);
1944 return (ARCHIVE_FATAL);
1947 to_consume = zip->zipx_lzma_stream.total_in;
1949 /* Update pointers. */
1950 __archive_read_consume(a, to_consume);
1951 zip->entry_bytes_remaining -= to_consume;
1952 zip->entry_compressed_bytes_read += to_consume;
1953 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1955 if(zip->entry_bytes_remaining == 0) {
1956 zip->end_of_entry = 1;
1959 /* Return values. */
1960 *size = zip->zipx_lzma_stream.total_out;
1961 *buff = zip->uncompressed_buffer;
1963 /* Behave the same way as during deflate decompression. */
1964 ret = consume_optional_marker(a, zip);
1965 if (ret != ARCHIVE_OK)
1968 /* Free lzma decoder handle because we'll no longer need it. */
1969 if(zip->end_of_entry) {
1970 lzma_end(&zip->zipx_lzma_stream);
1971 zip->zipx_lzma_valid = 0;
1974 /* If we're here, then we're good! */
1975 return (ARCHIVE_OK);
1977 #endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1980 zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1986 uint32_t restore_method;
1988 /* Remove previous decompression context if it exists. */
1989 if(zip->ppmd8_valid) {
1990 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1991 zip->ppmd8_valid = 0;
1994 /* Create a new decompression context. */
1995 __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1996 zip->ppmd8_stream_failed = 0;
1998 /* Setup function pointers required by Ppmd8 decompressor. The
1999 * 'ppmd_read' function will feed new bytes to the decompressor,
2000 * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
2001 zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
2002 zip->zipx_ppmd_stream.a = a;
2003 zip->zipx_ppmd_stream.Read = &ppmd_read;
2005 /* Reset number of read bytes to 0. */
2006 zip->zipx_ppmd_read_compressed = 0;
2008 /* Read Ppmd8 header (2 bytes). */
2009 p = __archive_read_ahead(a, 2, NULL);
2011 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2012 "Truncated file data in PPMd8 stream");
2013 return (ARCHIVE_FATAL);
2015 __archive_read_consume(a, 2);
2017 /* Decode the stream's compression parameters. */
2018 val = archive_le16dec(p);
2019 order = (val & 15) + 1;
2020 mem = ((val >> 4) & 0xff) + 1;
2021 restore_method = (val >> 12);
2023 if(order < 2 || restore_method > 2) {
2024 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2025 "Invalid parameter set in PPMd8 stream (order=%" PRId32 ", "
2026 "restore=%" PRId32 ")", order, restore_method);
2027 return (ARCHIVE_FAILED);
2030 /* Allocate the memory needed to properly decompress the file. */
2031 if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
2032 archive_set_error(&a->archive, ENOMEM,
2033 "Unable to allocate memory for PPMd8 stream: %" PRId32 " bytes",
2035 return (ARCHIVE_FATAL);
2038 /* Signal the cleanup function to release Ppmd8 context in the
2040 zip->ppmd8_valid = 1;
2042 /* Perform further Ppmd8 initialization. */
2043 if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
2044 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
2045 "PPMd8 stream range decoder initialization error");
2046 return (ARCHIVE_FATAL);
2049 __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
2052 /* Allocate the buffer that will hold uncompressed data. */
2053 free(zip->uncompressed_buffer);
2055 zip->uncompressed_buffer_size = 256 * 1024;
2056 zip->uncompressed_buffer =
2057 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2059 if(zip->uncompressed_buffer == NULL) {
2060 archive_set_error(&a->archive, ENOMEM,
2061 "No memory for PPMd8 decompression");
2062 return ARCHIVE_FATAL;
2065 /* Ppmd8 initialization is done. */
2066 zip->decompress_init = 1;
2068 /* We've already read 2 bytes in the output stream. Additionally,
2069 * Ppmd8 initialization code could read some data as well. So we
2070 * are advancing the stream by 2 bytes plus whatever number of
2071 * bytes Ppmd8 init function used. */
2072 zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
2078 zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
2079 size_t *size, int64_t *offset)
2081 struct zip* zip = (struct zip *)(a->format->data);
2083 size_t consumed_bytes = 0;
2084 ssize_t bytes_avail = 0;
2086 (void) offset; /* UNUSED */
2088 /* If we're here for the first time, initialize Ppmd8 decompression
2090 if(!zip->decompress_init) {
2091 ret = zipx_ppmd8_init(a, zip);
2092 if(ret != ARCHIVE_OK)
2096 /* Fetch for more data. We're reading 1 byte here, but libarchive
2097 * should prefetch more bytes. */
2098 (void) __archive_read_ahead(a, 1, &bytes_avail);
2099 if(bytes_avail < 0) {
2100 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2101 "Truncated PPMd8 file body");
2102 return (ARCHIVE_FATAL);
2105 /* This counter will be updated inside ppmd_read(), which at one
2106 * point will be called by Ppmd8_DecodeSymbol. */
2107 zip->zipx_ppmd_read_compressed = 0;
2109 /* Decompression loop. */
2111 int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
2114 zip->end_of_entry = 1;
2118 /* This field is set by ppmd_read() when there was no more data
2120 if(zip->ppmd8_stream_failed) {
2121 archive_set_error(&a->archive,
2122 ARCHIVE_ERRNO_FILE_FORMAT,
2123 "Truncated PPMd8 file body");
2124 return (ARCHIVE_FATAL);
2127 zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
2129 } while(consumed_bytes < zip->uncompressed_buffer_size);
2131 /* Update pointers for libarchive. */
2132 *buff = zip->uncompressed_buffer;
2133 *size = consumed_bytes;
2135 /* Update pointers so we can continue decompression in another call. */
2136 zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
2137 zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
2138 zip->entry_uncompressed_bytes_read += consumed_bytes;
2140 /* If we're at the end of stream, deinitialize Ppmd8 context. */
2141 if(zip->end_of_entry) {
2142 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2143 zip->ppmd8_valid = 0;
2146 /* Seek for optional marker, same way as in each zip entry. */
2147 ret = consume_optional_marker(a, zip);
2148 if (ret != ARCHIVE_OK)
2156 zipx_bzip2_init(struct archive_read *a, struct zip *zip)
2160 /* Deallocate already existing BZ2 decompression context if it
2162 if(zip->bzstream_valid) {
2163 BZ2_bzDecompressEnd(&zip->bzstream);
2164 zip->bzstream_valid = 0;
2167 /* Allocate a new BZ2 decompression context. */
2168 memset(&zip->bzstream, 0, sizeof(bz_stream));
2169 r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
2171 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
2172 "bzip2 initialization failed(%d)",
2175 return ARCHIVE_FAILED;
2178 /* Mark the bzstream field to be released in cleanup phase. */
2179 zip->bzstream_valid = 1;
2181 /* (Re)allocate the buffer that will contain decompressed bytes. */
2182 free(zip->uncompressed_buffer);
2184 zip->uncompressed_buffer_size = 256 * 1024;
2185 zip->uncompressed_buffer =
2186 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2187 if (zip->uncompressed_buffer == NULL) {
2188 archive_set_error(&a->archive, ENOMEM,
2189 "No memory for bzip2 decompression");
2190 return ARCHIVE_FATAL;
2193 /* Initialization done. */
2194 zip->decompress_init = 1;
2199 zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
2200 size_t *size, int64_t *offset)
2202 struct zip *zip = (struct zip *)(a->format->data);
2203 ssize_t bytes_avail = 0, in_bytes, to_consume;
2204 const void *compressed_buff;
2208 (void) offset; /* UNUSED */
2210 /* Initialize decompression context if we're here for the first time. */
2211 if(!zip->decompress_init) {
2212 r = zipx_bzip2_init(a, zip);
2217 /* Fetch more compressed bytes. */
2218 compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2219 if(bytes_avail < 0) {
2220 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2221 "Truncated bzip2 file body");
2222 return (ARCHIVE_FATAL);
2225 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2227 /* libbz2 doesn't complain when caller feeds avail_in == 0.
2228 * It will actually return success in this case, which is
2229 * undesirable. This is why we need to make this check
2232 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2233 "Truncated bzip2 file body");
2234 return (ARCHIVE_FATAL);
2237 /* Setup buffer boundaries. */
2238 zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
2239 zip->bzstream.avail_in = in_bytes;
2240 zip->bzstream.total_in_hi32 = 0;
2241 zip->bzstream.total_in_lo32 = 0;
2242 zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2243 zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2244 zip->bzstream.total_out_hi32 = 0;
2245 zip->bzstream.total_out_lo32 = 0;
2247 /* Perform the decompression. */
2248 r = BZ2_bzDecompress(&zip->bzstream);
2251 /* If we're at the end of the stream, deinitialize the
2252 * decompression context now. */
2253 switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2257 archive_set_error(&a->archive,
2259 "Failed to clean up bzip2 "
2261 return ARCHIVE_FATAL;
2264 zip->end_of_entry = 1;
2267 /* The decompressor has successfully decoded this
2268 * chunk of data, but more data is still in queue. */
2271 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2272 "bzip2 decompression failed");
2273 return ARCHIVE_FATAL;
2276 /* Update the pointers so decompressor can continue decoding. */
2277 to_consume = zip->bzstream.total_in_lo32;
2278 __archive_read_consume(a, to_consume);
2280 total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2281 zip->bzstream.total_out_lo32;
2283 zip->entry_bytes_remaining -= to_consume;
2284 zip->entry_compressed_bytes_read += to_consume;
2285 zip->entry_uncompressed_bytes_read += total_out;
2287 /* Give libarchive its due. */
2289 *buff = zip->uncompressed_buffer;
2291 /* Seek for optional marker, like in other entries. */
2292 r = consume_optional_marker(a, zip);
2303 zip_deflate_init(struct archive_read *a, struct zip *zip)
2307 /* If we haven't yet read any data, initialize the decompressor. */
2308 if (!zip->decompress_init) {
2309 if (zip->stream_valid)
2310 r = inflateReset(&zip->stream);
2312 r = inflateInit2(&zip->stream,
2313 -15 /* Don't check for zlib header */);
2315 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2316 "Can't initialize ZIP decompression.");
2317 return (ARCHIVE_FATAL);
2319 /* Stream structure has been set up. */
2320 zip->stream_valid = 1;
2321 /* We've initialized decompression for this stream. */
2322 zip->decompress_init = 1;
2324 return (ARCHIVE_OK);
2328 zip_read_data_deflate(struct archive_read *a, const void **buff,
2329 size_t *size, int64_t *offset)
2332 ssize_t bytes_avail;
2333 const void *compressed_buff, *sp;
2336 (void)offset; /* UNUSED */
2338 zip = (struct zip *)(a->format->data);
2340 /* If the buffer hasn't been allocated, allocate it now. */
2341 if (zip->uncompressed_buffer == NULL) {
2342 zip->uncompressed_buffer_size = 256 * 1024;
2343 zip->uncompressed_buffer
2344 = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2345 if (zip->uncompressed_buffer == NULL) {
2346 archive_set_error(&a->archive, ENOMEM,
2347 "No memory for ZIP decompression");
2348 return (ARCHIVE_FATAL);
2352 r = zip_deflate_init(a, zip);
2353 if (r != ARCHIVE_OK)
2357 * Note: '1' here is a performance optimization.
2358 * Recall that the decompression layer returns a count of
2359 * available bytes; asking for more than that forces the
2360 * decompressor to combine reads by copying data.
2362 compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2363 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2364 && bytes_avail > zip->entry_bytes_remaining) {
2365 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2367 if (bytes_avail < 0) {
2368 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2369 "Truncated ZIP file body");
2370 return (ARCHIVE_FATAL);
2373 if (zip->tctx_valid || zip->cctx_valid) {
2374 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2375 size_t buff_remaining =
2376 (zip->decrypted_buffer +
2377 zip->decrypted_buffer_size)
2378 - (zip->decrypted_ptr +
2379 zip->decrypted_bytes_remaining);
2381 if (buff_remaining > (size_t)bytes_avail)
2382 buff_remaining = (size_t)bytes_avail;
2384 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2385 zip->entry_bytes_remaining > 0) {
2386 if ((int64_t)(zip->decrypted_bytes_remaining
2388 > zip->entry_bytes_remaining) {
2389 if (zip->entry_bytes_remaining <
2390 (int64_t)zip->decrypted_bytes_remaining)
2394 (size_t)zip->entry_bytes_remaining
2395 - zip->decrypted_bytes_remaining;
2398 if (buff_remaining > 0) {
2399 if (zip->tctx_valid) {
2400 trad_enc_decrypt_update(&zip->tctx,
2401 compressed_buff, buff_remaining,
2403 + zip->decrypted_bytes_remaining,
2406 size_t dsize = buff_remaining;
2407 archive_decrypto_aes_ctr_update(
2409 compressed_buff, buff_remaining,
2411 + zip->decrypted_bytes_remaining,
2414 zip->decrypted_bytes_remaining +=
2418 bytes_avail = zip->decrypted_bytes_remaining;
2419 compressed_buff = (const char *)zip->decrypted_ptr;
2423 * A bug in zlib.h: stream.next_in should be marked 'const'
2424 * but isn't (the library never alters data through the
2425 * next_in pointer, only reads it). The result: this ugly
2426 * cast to remove 'const'.
2428 zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2429 zip->stream.avail_in = (uInt)bytes_avail;
2430 zip->stream.total_in = 0;
2431 zip->stream.next_out = zip->uncompressed_buffer;
2432 zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2433 zip->stream.total_out = 0;
2435 r = inflate(&zip->stream, 0);
2440 zip->end_of_entry = 1;
2443 archive_set_error(&a->archive, ENOMEM,
2444 "Out of memory for ZIP decompression");
2445 return (ARCHIVE_FATAL);
2447 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2448 "ZIP decompression failed (%d)", r);
2449 return (ARCHIVE_FATAL);
2452 /* Consume as much as the compressor actually used. */
2453 bytes_avail = zip->stream.total_in;
2454 if (zip->tctx_valid || zip->cctx_valid) {
2455 zip->decrypted_bytes_remaining -= bytes_avail;
2456 if (zip->decrypted_bytes_remaining == 0)
2457 zip->decrypted_ptr = zip->decrypted_buffer;
2459 zip->decrypted_ptr += bytes_avail;
2461 /* Calculate compressed data as much as we used.*/
2462 if (zip->hctx_valid)
2463 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2464 __archive_read_consume(a, bytes_avail);
2465 zip->entry_bytes_remaining -= bytes_avail;
2466 zip->entry_compressed_bytes_read += bytes_avail;
2468 *size = zip->stream.total_out;
2469 zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2470 *buff = zip->uncompressed_buffer;
2472 if (zip->end_of_entry && zip->hctx_valid) {
2473 r = check_authentication_code(a, NULL);
2474 if (r != ARCHIVE_OK)
2478 r = consume_optional_marker(a, zip);
2479 if (r != ARCHIVE_OK)
2482 return (ARCHIVE_OK);
2487 read_decryption_header(struct archive_read *a)
2489 struct zip *zip = (struct zip *)(a->format->data);
2491 unsigned int remaining_size;
2495 * Read an initialization vector data field.
2497 p = __archive_read_ahead(a, 2, NULL);
2501 zip->iv_size = archive_le16dec(p);
2502 __archive_read_consume(a, 2);
2503 if (ts < zip->iv_size) {
2507 p = __archive_read_ahead(a, zip->iv_size, NULL);
2510 if (zip->iv == NULL) {
2511 zip->iv = malloc(zip->iv_size);
2512 if (zip->iv == NULL)
2515 memcpy(zip->iv, p, zip->iv_size);
2516 __archive_read_consume(a, zip->iv_size);
2519 * Read a size of remaining decryption header field.
2521 p = __archive_read_ahead(a, 14, NULL);
2524 remaining_size = archive_le32dec(p);
2525 if (remaining_size < 16 || remaining_size > (1 << 18))
2528 /* Check if format version is supported. */
2529 if (archive_le16dec(p+4) != 3) {
2530 archive_set_error(&a->archive,
2531 ARCHIVE_ERRNO_FILE_FORMAT,
2532 "Unsupported encryption format version: %u",
2533 archive_le16dec(p+4));
2534 return (ARCHIVE_FAILED);
2538 * Read an encryption algorithm field.
2540 zip->alg_id = archive_le16dec(p+6);
2541 switch (zip->alg_id) {
2542 case 0x6601:/* DES */
2543 case 0x6602:/* RC2 */
2544 case 0x6603:/* 3DES 168 */
2545 case 0x6609:/* 3DES 112 */
2546 case 0x660E:/* AES 128 */
2547 case 0x660F:/* AES 192 */
2548 case 0x6610:/* AES 256 */
2549 case 0x6702:/* RC2 (version >= 5.2) */
2550 case 0x6720:/* Blowfish */
2551 case 0x6721:/* Twofish */
2552 case 0x6801:/* RC4 */
2553 /* Supported encryption algorithm. */
2556 archive_set_error(&a->archive,
2557 ARCHIVE_ERRNO_FILE_FORMAT,
2558 "Unknown encryption algorithm: %u", zip->alg_id);
2559 return (ARCHIVE_FAILED);
2563 * Read a bit length field.
2565 zip->bit_len = archive_le16dec(p+8);
2568 * Read a flags field.
2570 zip->flags = archive_le16dec(p+10);
2571 switch (zip->flags & 0xf000) {
2572 case 0x0001: /* Password is required to decrypt. */
2573 case 0x0002: /* Certificates only. */
2574 case 0x0003: /* Password or certificate required to decrypt. */
2577 archive_set_error(&a->archive,
2578 ARCHIVE_ERRNO_FILE_FORMAT,
2579 "Unknown encryption flag: %u", zip->flags);
2580 return (ARCHIVE_FAILED);
2582 if ((zip->flags & 0xf000) == 0 ||
2583 (zip->flags & 0xf000) == 0x4000) {
2584 archive_set_error(&a->archive,
2585 ARCHIVE_ERRNO_FILE_FORMAT,
2586 "Unknown encryption flag: %u", zip->flags);
2587 return (ARCHIVE_FAILED);
2591 * Read an encrypted random data field.
2594 zip->erd_size = archive_le16dec(p+12);
2595 __archive_read_consume(a, 14);
2596 if ((zip->erd_size & 0xf) != 0 ||
2597 (zip->erd_size + 16) > remaining_size ||
2598 (zip->erd_size + 16) < zip->erd_size)
2601 if (ts < zip->erd_size) {
2605 p = __archive_read_ahead(a, zip->erd_size, NULL);
2608 if (zip->erd == NULL) {
2609 zip->erd = malloc(zip->erd_size);
2610 if (zip->erd == NULL)
2613 memcpy(zip->erd, p, zip->erd_size);
2614 __archive_read_consume(a, zip->erd_size);
2617 * Read a reserved data field.
2619 p = __archive_read_ahead(a, 4, NULL);
2622 /* Reserved data size should be zero. */
2623 if (archive_le32dec(p) != 0)
2625 __archive_read_consume(a, 4);
2628 * Read a password validation data field.
2630 p = __archive_read_ahead(a, 2, NULL);
2634 zip->v_size = archive_le16dec(p);
2635 __archive_read_consume(a, 2);
2636 if ((zip->v_size & 0x0f) != 0 ||
2637 (zip->erd_size + zip->v_size + 16) > remaining_size ||
2638 (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2640 if (ts < zip->v_size) {
2644 p = __archive_read_ahead(a, zip->v_size, NULL);
2647 if (zip->v_data == NULL) {
2648 zip->v_data = malloc(zip->v_size);
2649 if (zip->v_data == NULL)
2652 memcpy(zip->v_data, p, zip->v_size);
2653 __archive_read_consume(a, zip->v_size);
2655 p = __archive_read_ahead(a, 4, NULL);
2658 zip->v_crc32 = archive_le32dec(p);
2659 __archive_read_consume(a, 4);
2661 /*return (ARCHIVE_OK);
2662 * This is not fully implemented yet.*/
2663 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2664 "Encrypted file is unsupported");
2665 return (ARCHIVE_FAILED);
2667 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2668 "Truncated ZIP file data");
2669 return (ARCHIVE_FATAL);
2671 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2672 "Corrupted ZIP file data");
2673 return (ARCHIVE_FATAL);
2675 archive_set_error(&a->archive, ENOMEM,
2676 "No memory for ZIP decryption");
2677 return (ARCHIVE_FATAL);
2681 zip_alloc_decryption_buffer(struct archive_read *a)
2683 struct zip *zip = (struct zip *)(a->format->data);
2684 size_t bs = 256 * 1024;
2686 if (zip->decrypted_buffer == NULL) {
2687 zip->decrypted_buffer_size = bs;
2688 zip->decrypted_buffer = malloc(bs);
2689 if (zip->decrypted_buffer == NULL) {
2690 archive_set_error(&a->archive, ENOMEM,
2691 "No memory for ZIP decryption");
2692 return (ARCHIVE_FATAL);
2695 zip->decrypted_ptr = zip->decrypted_buffer;
2696 return (ARCHIVE_OK);
2700 init_traditional_PKWARE_decryption(struct archive_read *a)
2702 struct zip *zip = (struct zip *)(a->format->data);
2707 if (zip->tctx_valid)
2708 return (ARCHIVE_OK);
2711 Read the 12 bytes encryption header stored at
2712 the start of the data area.
2714 #define ENC_HEADER_SIZE 12
2715 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2716 && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2717 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2718 "Truncated Zip encrypted body: only %jd bytes available",
2719 (intmax_t)zip->entry_bytes_remaining);
2720 return (ARCHIVE_FATAL);
2723 p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2725 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2726 "Truncated ZIP file data");
2727 return (ARCHIVE_FATAL);
2730 for (retry = 0;; retry++) {
2731 const char *passphrase;
2734 passphrase = __archive_read_next_passphrase(a);
2735 if (passphrase == NULL) {
2736 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2738 "Incorrect passphrase":
2739 "Passphrase required for this entry");
2740 return (ARCHIVE_FAILED);
2744 * Initialize ctx for Traditional PKWARE Decryption.
2746 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2747 p, ENC_HEADER_SIZE, &crcchk);
2748 if (r == 0 && crcchk == zip->entry->decdat)
2749 break;/* The passphrase is OK. */
2750 if (retry > 10000) {
2751 /* Avoid infinity loop. */
2752 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2753 "Too many incorrect passphrases");
2754 return (ARCHIVE_FAILED);
2758 __archive_read_consume(a, ENC_HEADER_SIZE);
2759 zip->tctx_valid = 1;
2760 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2761 zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2763 /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2764 zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2765 zip->decrypted_bytes_remaining = 0;
2767 return (zip_alloc_decryption_buffer(a));
2768 #undef ENC_HEADER_SIZE
2772 init_WinZip_AES_decryption(struct archive_read *a)
2774 struct zip *zip = (struct zip *)(a->format->data);
2777 size_t key_len, salt_len;
2778 uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2782 if (zip->cctx_valid || zip->hctx_valid)
2783 return (ARCHIVE_OK);
2785 switch (zip->entry->aes_extra.strength) {
2786 case 1: salt_len = 8; key_len = 16; break;
2787 case 2: salt_len = 12; key_len = 24; break;
2788 case 3: salt_len = 16; key_len = 32; break;
2789 default: goto corrupted;
2791 p = __archive_read_ahead(a, salt_len + 2, NULL);
2795 for (retry = 0;; retry++) {
2796 const char *passphrase;
2798 passphrase = __archive_read_next_passphrase(a);
2799 if (passphrase == NULL) {
2800 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2802 "Incorrect passphrase":
2803 "Passphrase required for this entry");
2804 return (ARCHIVE_FAILED);
2806 memset(derived_key, 0, sizeof(derived_key));
2807 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2808 p, salt_len, 1000, derived_key, key_len * 2 + 2);
2810 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2811 "Decryption is unsupported due to lack of "
2813 return (ARCHIVE_FAILED);
2816 /* Check password verification value. */
2817 pv = ((const uint8_t *)p) + salt_len;
2818 if (derived_key[key_len * 2] == pv[0] &&
2819 derived_key[key_len * 2 + 1] == pv[1])
2820 break;/* The passphrase is OK. */
2821 if (retry > 10000) {
2822 /* Avoid infinity loop. */
2823 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2824 "Too many incorrect passphrases");
2825 return (ARCHIVE_FAILED);
2829 r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2831 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2832 "Decryption is unsupported due to lack of crypto library");
2833 return (ARCHIVE_FAILED);
2835 r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2837 archive_decrypto_aes_ctr_release(&zip->cctx);
2838 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2839 "Failed to initialize HMAC-SHA1");
2840 return (ARCHIVE_FAILED);
2842 zip->cctx_valid = zip->hctx_valid = 1;
2843 __archive_read_consume(a, salt_len + 2);
2844 zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2845 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2846 && zip->entry_bytes_remaining < 0)
2848 zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2849 zip->decrypted_bytes_remaining = 0;
2851 zip->entry->compression = zip->entry->aes_extra.compression;
2852 return (zip_alloc_decryption_buffer(a));
2855 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2856 "Truncated ZIP file data");
2857 return (ARCHIVE_FATAL);
2859 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2860 "Corrupted ZIP file data");
2861 return (ARCHIVE_FATAL);
2865 archive_read_format_zip_read_data(struct archive_read *a,
2866 const void **buff, size_t *size, int64_t *offset)
2869 struct zip *zip = (struct zip *)(a->format->data);
2871 if (zip->has_encrypted_entries ==
2872 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2873 zip->has_encrypted_entries = 0;
2876 *offset = zip->entry_uncompressed_bytes_read;
2880 /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2881 if (zip->end_of_entry)
2882 return (ARCHIVE_EOF);
2884 /* Return EOF immediately if this is a non-regular file. */
2885 if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2886 return (ARCHIVE_EOF);
2888 __archive_read_consume(a, zip->unconsumed);
2889 zip->unconsumed = 0;
2891 if (zip->init_decryption) {
2892 zip->has_encrypted_entries = 1;
2893 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2894 r = read_decryption_header(a);
2895 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2896 r = init_WinZip_AES_decryption(a);
2898 r = init_traditional_PKWARE_decryption(a);
2899 if (r != ARCHIVE_OK)
2901 zip->init_decryption = 0;
2904 switch(zip->entry->compression) {
2905 case 0: /* No compression. */
2906 r = zip_read_data_none(a, buff, size, offset);
2909 case 12: /* ZIPx bzip2 compression. */
2910 r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2913 #if HAVE_LZMA_H && HAVE_LIBLZMA
2914 case 14: /* ZIPx LZMA compression. */
2915 r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
2917 case 95: /* ZIPx XZ compression. */
2918 r = zip_read_data_zipx_xz(a, buff, size, offset);
2921 /* PPMd support is built-in, so we don't need any #if guards. */
2922 case 98: /* ZIPx PPMd compression. */
2923 r = zip_read_data_zipx_ppmd(a, buff, size, offset);
2927 case 8: /* Deflate compression. */
2928 r = zip_read_data_deflate(a, buff, size, offset);
2931 default: /* Unsupported compression. */
2932 /* Return a warning. */
2933 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2934 "Unsupported ZIP compression method (%d: %s)",
2935 zip->entry->compression, compression_name(zip->entry->compression));
2936 /* We can't decompress this entry, but we will
2937 * be able to skip() it and try the next entry. */
2938 return (ARCHIVE_FAILED);
2941 if (r != ARCHIVE_OK)
2943 /* Update checksum */
2945 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
2947 /* If we hit the end, swallow any end-of-data marker. */
2948 if (zip->end_of_entry) {
2949 /* Check file size, CRC against these values. */
2950 if (zip->entry->compressed_size !=
2951 zip->entry_compressed_bytes_read) {
2952 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2953 "ZIP compressed data is wrong size "
2954 "(read %jd, expected %jd)",
2955 (intmax_t)zip->entry_compressed_bytes_read,
2956 (intmax_t)zip->entry->compressed_size);
2957 return (ARCHIVE_WARN);
2959 /* Size field only stores the lower 32 bits of the actual
2961 if ((zip->entry->uncompressed_size & UINT32_MAX)
2962 != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
2963 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2964 "ZIP uncompressed data is wrong size "
2965 "(read %jd, expected %jd)\n",
2966 (intmax_t)zip->entry_uncompressed_bytes_read,
2967 (intmax_t)zip->entry->uncompressed_size);
2968 return (ARCHIVE_WARN);
2970 /* Check computed CRC against header */
2971 if ((!zip->hctx_valid ||
2972 zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
2973 zip->entry->crc32 != zip->entry_crc32
2974 && !zip->ignore_crc32) {
2975 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2976 "ZIP bad CRC: 0x%lx should be 0x%lx",
2977 (unsigned long)zip->entry_crc32,
2978 (unsigned long)zip->entry->crc32);
2979 return (ARCHIVE_WARN);
2983 return (ARCHIVE_OK);
2987 archive_read_format_zip_cleanup(struct archive_read *a)
2990 struct zip_entry *zip_entry, *next_zip_entry;
2992 zip = (struct zip *)(a->format->data);
2995 if (zip->stream_valid)
2996 inflateEnd(&zip->stream);
2999 #if HAVE_LZMA_H && HAVE_LIBLZMA
3000 if (zip->zipx_lzma_valid) {
3001 lzma_end(&zip->zipx_lzma_stream);
3006 if (zip->bzstream_valid) {
3007 BZ2_bzDecompressEnd(&zip->bzstream);
3011 free(zip->uncompressed_buffer);
3013 if (zip->ppmd8_valid)
3014 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
3016 if (zip->zip_entries) {
3017 zip_entry = zip->zip_entries;
3018 while (zip_entry != NULL) {
3019 next_zip_entry = zip_entry->next;
3020 archive_string_free(&zip_entry->rsrcname);
3022 zip_entry = next_zip_entry;
3025 free(zip->decrypted_buffer);
3026 if (zip->cctx_valid)
3027 archive_decrypto_aes_ctr_release(&zip->cctx);
3028 if (zip->hctx_valid)
3029 archive_hmac_sha1_cleanup(&zip->hctx);
3033 archive_string_free(&zip->format_name);
3035 (a->format->data) = NULL;
3036 return (ARCHIVE_OK);
3040 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
3042 if (_a && _a->format) {
3043 struct zip * zip = (struct zip *)_a->format->data;
3045 return zip->has_encrypted_entries;
3048 return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3052 archive_read_format_zip_options(struct archive_read *a,
3053 const char *key, const char *val)
3056 int ret = ARCHIVE_FAILED;
3058 zip = (struct zip *)(a->format->data);
3059 if (strcmp(key, "compat-2x") == 0) {
3060 /* Handle filenames as libarchive 2.x */
3061 zip->init_default_conversion = (val != NULL) ? 1 : 0;
3062 return (ARCHIVE_OK);
3063 } else if (strcmp(key, "hdrcharset") == 0) {
3064 if (val == NULL || val[0] == 0)
3065 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3066 "zip: hdrcharset option needs a character-set name"
3069 zip->sconv = archive_string_conversion_from_charset(
3070 &a->archive, val, 0);
3071 if (zip->sconv != NULL) {
3072 if (strcmp(val, "UTF-8") == 0)
3073 zip->sconv_utf8 = zip->sconv;
3076 ret = ARCHIVE_FATAL;
3079 } else if (strcmp(key, "ignorecrc32") == 0) {
3080 /* Mostly useful for testing. */
3081 if (val == NULL || val[0] == 0) {
3082 zip->crc32func = real_crc32;
3083 zip->ignore_crc32 = 0;
3085 zip->crc32func = fake_crc32;
3086 zip->ignore_crc32 = 1;
3088 return (ARCHIVE_OK);
3089 } else if (strcmp(key, "mac-ext") == 0) {
3090 zip->process_mac_extensions = (val != NULL && val[0] != 0);
3091 return (ARCHIVE_OK);
3094 /* Note: The "warn" return is just to inform the options
3095 * supervisor that we didn't handle it. It will generate
3096 * a suitable error if no one used this option. */
3097 return (ARCHIVE_WARN);
3101 archive_read_support_format_zip(struct archive *a)
3104 r = archive_read_support_format_zip_streamable(a);
3105 if (r != ARCHIVE_OK)
3107 return (archive_read_support_format_zip_seekable(a));
3110 /* ------------------------------------------------------------------------ */
3113 * Streaming-mode support
3118 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
3120 (void)a; /* UNUSED */
3121 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3122 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3126 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
3130 (void)best_bid; /* UNUSED */
3132 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3136 * Bid of 29 here comes from:
3137 * + 16 bits for "PK",
3138 * + next 16-bit field has 6 options so contributes
3139 * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
3141 * So we've effectively verified ~29 total bits of check data.
3143 if (p[0] == 'P' && p[1] == 'K') {
3144 if ((p[2] == '\001' && p[3] == '\002')
3145 || (p[2] == '\003' && p[3] == '\004')
3146 || (p[2] == '\005' && p[3] == '\006')
3147 || (p[2] == '\006' && p[3] == '\006')
3148 || (p[2] == '\007' && p[3] == '\010')
3149 || (p[2] == '0' && p[3] == '0'))
3153 /* TODO: It's worth looking ahead a little bit for a valid
3154 * PK signature. In particular, that would make it possible
3155 * to read some UUEncoded SFX files or SFX files coming from
3156 * a network socket. */
3162 archive_read_format_zip_streamable_read_header(struct archive_read *a,
3163 struct archive_entry *entry)
3167 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3168 if (a->archive.archive_format_name == NULL)
3169 a->archive.archive_format_name = "ZIP";
3171 zip = (struct zip *)(a->format->data);
3174 * It should be sufficient to call archive_read_next_header() for
3175 * a reader to determine if an entry is encrypted or not. If the
3176 * encryption of an entry is only detectable when calling
3177 * archive_read_data(), so be it. We'll do the same check there
3180 if (zip->has_encrypted_entries ==
3181 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3182 zip->has_encrypted_entries = 0;
3184 /* Make sure we have a zip_entry structure to use. */
3185 if (zip->zip_entries == NULL) {
3186 zip->zip_entries = malloc(sizeof(struct zip_entry));
3187 if (zip->zip_entries == NULL) {
3188 archive_set_error(&a->archive, ENOMEM,
3190 return ARCHIVE_FATAL;
3193 zip->entry = zip->zip_entries;
3194 memset(zip->entry, 0, sizeof(struct zip_entry));
3196 if (zip->cctx_valid)
3197 archive_decrypto_aes_ctr_release(&zip->cctx);
3198 if (zip->hctx_valid)
3199 archive_hmac_sha1_cleanup(&zip->hctx);
3200 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3201 __archive_read_reset_passphrase(a);
3203 /* Search ahead for the next local file header. */
3204 __archive_read_consume(a, zip->unconsumed);
3205 zip->unconsumed = 0;
3207 int64_t skipped = 0;
3208 const char *p, *end;
3211 p = __archive_read_ahead(a, 4, &bytes);
3213 return (ARCHIVE_FATAL);
3216 while (p + 4 <= end) {
3217 if (p[0] == 'P' && p[1] == 'K') {
3218 if (p[2] == '\003' && p[3] == '\004') {
3219 /* Regular file entry. */
3220 __archive_read_consume(a, skipped);
3221 return zip_read_local_file_header(a,
3226 * TODO: We cannot restore permissions
3227 * based only on the local file headers.
3228 * Consider scanning the central
3229 * directory and returning additional
3230 * entries for at least directories.
3231 * This would allow us to properly set
3232 * directory permissions.
3234 * This won't help us fix symlinks
3235 * and may not help with regular file
3236 * permissions, either. <sigh>
3238 if (p[2] == '\001' && p[3] == '\002') {
3239 return (ARCHIVE_EOF);
3242 /* End of central directory? Must be an
3244 if ((p[2] == '\005' && p[3] == '\006')
3245 || (p[2] == '\006' && p[3] == '\006'))
3246 return (ARCHIVE_EOF);
3251 __archive_read_consume(a, skipped);
3256 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3259 int64_t bytes_skipped;
3261 zip = (struct zip *)(a->format->data);
3262 bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3263 zip->unconsumed = 0;
3264 if (bytes_skipped < 0)
3265 return (ARCHIVE_FATAL);
3267 /* If we've already read to end of data, we're done. */
3268 if (zip->end_of_entry)
3269 return (ARCHIVE_OK);
3271 /* So we know we're streaming... */
3272 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3273 || zip->entry->compressed_size > 0) {
3274 /* We know the compressed length, so we can just skip. */
3275 bytes_skipped = __archive_read_consume(a,
3276 zip->entry_bytes_remaining);
3277 if (bytes_skipped < 0)
3278 return (ARCHIVE_FATAL);
3279 return (ARCHIVE_OK);
3282 if (zip->init_decryption) {
3285 zip->has_encrypted_entries = 1;
3286 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3287 r = read_decryption_header(a);
3288 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3289 r = init_WinZip_AES_decryption(a);
3291 r = init_traditional_PKWARE_decryption(a);
3292 if (r != ARCHIVE_OK)
3294 zip->init_decryption = 0;
3297 /* We're streaming and we don't know the length. */
3298 /* If the body is compressed and we know the format, we can
3299 * find an exact end-of-entry by decompressing it. */
3300 switch (zip->entry->compression) {
3302 case 8: /* Deflate compression. */
3303 while (!zip->end_of_entry) {
3305 const void *buff = NULL;
3308 r = zip_read_data_deflate(a, &buff, &size, &offset);
3309 if (r != ARCHIVE_OK)
3314 default: /* Uncompressed or unknown. */
3315 /* Scan for a PK\007\010 signature. */
3317 const char *p, *buff;
3318 ssize_t bytes_avail;
3319 buff = __archive_read_ahead(a, 16, &bytes_avail);
3320 if (bytes_avail < 16) {
3321 archive_set_error(&a->archive,
3322 ARCHIVE_ERRNO_FILE_FORMAT,
3323 "Truncated ZIP file data");
3324 return (ARCHIVE_FATAL);
3327 while (p <= buff + bytes_avail - 16) {
3328 if (p[3] == 'P') { p += 3; }
3329 else if (p[3] == 'K') { p += 2; }
3330 else if (p[3] == '\007') { p += 1; }
3331 else if (p[3] == '\010' && p[2] == '\007'
3332 && p[1] == 'K' && p[0] == 'P') {
3333 if (zip->entry->flags & LA_USED_ZIP64)
3334 __archive_read_consume(a,
3337 __archive_read_consume(a,
3342 __archive_read_consume(a, p - buff);
3348 archive_read_support_format_zip_streamable(struct archive *_a)
3350 struct archive_read *a = (struct archive_read *)_a;
3354 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3355 ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3357 zip = (struct zip *)calloc(1, sizeof(*zip));
3359 archive_set_error(&a->archive, ENOMEM,
3360 "Can't allocate zip data");
3361 return (ARCHIVE_FATAL);
3364 /* Streamable reader doesn't support mac extensions. */
3365 zip->process_mac_extensions = 0;
3368 * Until enough data has been read, we cannot tell about
3369 * any encrypted entries yet.
3371 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3372 zip->crc32func = real_crc32;
3374 r = __archive_read_register_format(a,
3377 archive_read_format_zip_streamable_bid,
3378 archive_read_format_zip_options,
3379 archive_read_format_zip_streamable_read_header,
3380 archive_read_format_zip_read_data,
3381 archive_read_format_zip_read_data_skip_streamable,
3383 archive_read_format_zip_cleanup,
3384 archive_read_support_format_zip_capabilities_streamable,
3385 archive_read_format_zip_has_encrypted_entries);
3387 if (r != ARCHIVE_OK)
3389 return (ARCHIVE_OK);
3392 /* ------------------------------------------------------------------------ */
3395 * Seeking-mode support
3399 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3401 (void)a; /* UNUSED */
3402 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3403 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3407 * TODO: This is a performance sink because it forces the read core to
3408 * drop buffered data from the start of file, which will then have to
3409 * be re-read again if this bidder loses.
3411 * We workaround this a little by passing in the best bid so far so
3412 * that later bidders can do nothing if they know they'll never
3413 * outbid. But we can certainly do better...
3416 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3418 /* Sanity-check the EOCD we've found. */
3420 /* This must be the first volume. */
3421 if (archive_le16dec(p + 4) != 0)
3423 /* Central directory must be on this volume. */
3424 if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
3426 /* All central directory entries must be on this volume. */
3427 if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3429 /* Central directory can't extend beyond start of EOCD record. */
3430 if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
3434 /* Save the central directory location for later use. */
3435 zip->central_directory_offset = archive_le32dec(p + 16);
3437 /* This is just a tiny bit higher than the maximum
3438 returned by the streaming Zip bidder. This ensures
3439 that the more accurate seeking Zip parser wins
3440 whenever seek is available. */
3445 * Examine Zip64 EOCD locator: If it's valid, store the information
3449 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3451 int64_t eocd64_offset;
3452 int64_t eocd64_size;
3454 /* Sanity-check the locator record. */
3456 /* Central dir must be on first volume. */
3457 if (archive_le32dec(p + 4) != 0)
3459 /* Must be only a single volume. */
3460 if (archive_le32dec(p + 16) != 1)
3463 /* Find the Zip64 EOCD record. */
3464 eocd64_offset = archive_le64dec(p + 8);
3465 if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3467 if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3469 /* Make sure we can read all of it. */
3470 eocd64_size = archive_le64dec(p + 4) + 12;
3471 if (eocd64_size < 56 || eocd64_size > 16384)
3473 if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3476 /* Sanity-check the EOCD64 */
3477 if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3479 if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3481 /* CD can't be split. */
3482 if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3485 /* Save the central directory offset for later use. */
3486 zip->central_directory_offset = archive_le64dec(p + 48);
3492 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3494 struct zip *zip = (struct zip *)a->format->data;
3495 int64_t file_size, current_offset;
3499 /* If someone has already bid more than 32, then avoid
3500 trashing the look-ahead buffers with a seek. */
3504 file_size = __archive_read_seek(a, 0, SEEK_END);
3508 /* Search last 16k of file for end-of-central-directory
3509 * record (which starts with PK\005\006) */
3510 tail = (int)zipmin(1024 * 16, file_size);
3511 current_offset = __archive_read_seek(a, -tail, SEEK_END);
3512 if (current_offset < 0)
3514 if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3516 /* Boyer-Moore search backwards from the end, since we want
3517 * to match the last EOCD in the file (there can be more than
3518 * one if there is an uncompressed Zip archive as a member
3519 * within this Zip archive). */
3520 for (i = tail - 22; i > 0;) {
3523 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3524 int ret = read_eocd(zip, p + i,
3525 current_offset + i);
3526 /* Zip64 EOCD locator precedes
3527 * regular EOCD if present. */
3528 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3529 int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3530 if (ret_zip64 > ret)
3537 case 'K': i -= 1; break;
3538 case 005: i -= 2; break;
3539 case 006: i -= 3; break;
3540 default: i -= 4; break;
3546 /* The red-black trees are only used in seeking mode to manage
3547 * the in-memory copy of the central directory. */
3550 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3552 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3553 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3555 if (e1->local_header_offset > e2->local_header_offset)
3557 if (e1->local_header_offset < e2->local_header_offset)
3563 cmp_key(const struct archive_rb_node *n, const void *key)
3565 /* This function won't be called */
3566 (void)n; /* UNUSED */
3567 (void)key; /* UNUSED */
3571 static const struct archive_rb_tree_ops rb_ops = {
3576 rsrc_cmp_node(const struct archive_rb_node *n1,
3577 const struct archive_rb_node *n2)
3579 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3580 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3582 return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3586 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3588 const struct zip_entry *e = (const struct zip_entry *)n;
3589 return (strcmp((const char *)key, e->rsrcname.s));
3592 static const struct archive_rb_tree_ops rb_rsrc_ops = {
3593 &rsrc_cmp_node, &rsrc_cmp_key
3597 rsrc_basename(const char *name, size_t name_length)
3603 s = memchr(s, '/', name_length - (s - name));
3612 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3614 struct archive_string str;
3615 struct zip_entry *dir;
3618 archive_string_init(&str);
3619 archive_strncpy(&str, name, name_length);
3621 s = strrchr(str.s, '/');
3625 /* Transfer the parent directory from zip->tree_rsrc RB
3626 * tree to zip->tree RB tree to expose. */
3627 dir = (struct zip_entry *)
3628 __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3631 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3632 archive_string_free(&dir->rsrcname);
3633 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
3635 archive_string_free(&str);
3639 slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
3645 ssize_t bytes_avail;
3649 * Find the start of the central directory. The end-of-CD
3650 * record has our starting point, but there are lots of
3651 * Zip archives which have had other data prepended to the
3652 * file, which makes the recorded offsets all too small.
3653 * So we search forward from the specified offset until we
3654 * find the real start of the central directory. Then we
3655 * know the correction we need to apply to account for leading
3658 if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
3659 return ARCHIVE_FATAL;
3663 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3664 return ARCHIVE_FATAL;
3665 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3667 case 'P': i += 3; break;
3668 case 'K': i += 2; break;
3669 case 001: i += 1; break;
3671 if (memcmp(p + i, "PK\001\002", 4) == 0) {
3677 case 005: i += 1; break;
3679 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3682 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3688 default: i += 4; break;
3691 __archive_read_consume(a, i);
3693 correction = archive_filter_bytes(&a->archive, 0)
3694 - zip->central_directory_offset;
3696 __archive_rb_tree_init(&zip->tree, &rb_ops);
3697 __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3699 zip->central_directory_entries_total = 0;
3701 struct zip_entry *zip_entry;
3702 size_t filename_length, extra_length, comment_length;
3703 uint32_t external_attributes;
3704 const char *name, *r;
3706 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3707 return ARCHIVE_FATAL;
3708 if (memcmp(p, "PK\006\006", 4) == 0
3709 || memcmp(p, "PK\005\006", 4) == 0) {
3711 } else if (memcmp(p, "PK\001\002", 4) != 0) {
3712 archive_set_error(&a->archive,
3713 -1, "Invalid central directory signature");
3714 return ARCHIVE_FATAL;
3716 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3717 return ARCHIVE_FATAL;
3719 zip_entry = calloc(1, sizeof(struct zip_entry));
3720 if (zip_entry == NULL) {
3721 archive_set_error(&a->archive, ENOMEM,
3722 "Can't allocate zip entry");
3723 return ARCHIVE_FATAL;
3725 zip_entry->next = zip->zip_entries;
3726 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3727 zip->zip_entries = zip_entry;
3728 zip->central_directory_entries_total++;
3730 /* version = p[4]; */
3731 zip_entry->system = p[5];
3732 /* version_required = archive_le16dec(p + 6); */
3733 zip_entry->zip_flags = archive_le16dec(p + 8);
3734 if (zip_entry->zip_flags
3735 & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3736 zip->has_encrypted_entries = 1;
3738 zip_entry->compression = (char)archive_le16dec(p + 10);
3739 zip_entry->mtime = zip_time(p + 12);
3740 zip_entry->crc32 = archive_le32dec(p + 16);
3741 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3742 zip_entry->decdat = p[13];
3744 zip_entry->decdat = p[19];
3745 zip_entry->compressed_size = archive_le32dec(p + 20);
3746 zip_entry->uncompressed_size = archive_le32dec(p + 24);
3747 filename_length = archive_le16dec(p + 28);
3748 extra_length = archive_le16dec(p + 30);
3749 comment_length = archive_le16dec(p + 32);
3750 /* disk_start = archive_le16dec(p + 34);
3752 * internal_attributes = archive_le16dec(p + 36);
3754 external_attributes = archive_le32dec(p + 38);
3755 zip_entry->local_header_offset =
3756 archive_le32dec(p + 42) + correction;
3758 /* If we can't guess the mode, leave it zero here;
3759 when we read the local file header we might get
3760 more information. */
3761 if (zip_entry->system == 3) {
3762 zip_entry->mode = external_attributes >> 16;
3763 } else if (zip_entry->system == 0) {
3764 // Interpret MSDOS directory bit
3765 if (0x10 == (external_attributes & 0x10)) {
3766 zip_entry->mode = AE_IFDIR | 0775;
3768 zip_entry->mode = AE_IFREG | 0664;
3770 if (0x01 == (external_attributes & 0x01)) {
3771 // Read-only bit; strip write permissions
3772 zip_entry->mode &= 0555;
3775 zip_entry->mode = 0;
3778 /* We're done with the regular data; get the filename and
3780 __archive_read_consume(a, 46);
3781 p = __archive_read_ahead(a, filename_length + extra_length,
3784 archive_set_error(&a->archive,
3785 ARCHIVE_ERRNO_FILE_FORMAT,
3786 "Truncated ZIP file header");
3787 return ARCHIVE_FATAL;
3789 if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
3790 extra_length, zip_entry)) {
3791 return ARCHIVE_FATAL;
3795 * Mac resource fork files are stored under the
3796 * "__MACOSX/" directory, so we should check if
3799 if (!zip->process_mac_extensions) {
3800 /* Treat every entry as a regular entry. */
3801 __archive_rb_tree_insert_node(&zip->tree,
3805 r = rsrc_basename(name, filename_length);
3806 if (filename_length >= 9 &&
3807 strncmp("__MACOSX/", name, 9) == 0) {
3808 /* If this file is not a resource fork nor
3809 * a directory. We should treat it as a non
3810 * resource fork file to expose it. */
3811 if (name[filename_length-1] != '/' &&
3812 (r - name < 3 || r[0] != '.' ||
3814 __archive_rb_tree_insert_node(
3815 &zip->tree, &zip_entry->node);
3816 /* Expose its parent directories. */
3817 expose_parent_dirs(zip, name,
3820 /* This file is a resource fork file or
3822 archive_strncpy(&(zip_entry->rsrcname),
3823 name, filename_length);
3824 __archive_rb_tree_insert_node(
3825 &zip->tree_rsrc, &zip_entry->node);
3828 /* Generate resource fork name to find its
3829 * resource file at zip->tree_rsrc. */
3830 archive_strcpy(&(zip_entry->rsrcname),
3832 archive_strncat(&(zip_entry->rsrcname),
3834 archive_strcat(&(zip_entry->rsrcname), "._");
3835 archive_strncat(&(zip_entry->rsrcname),
3837 filename_length - (r - name));
3838 /* Register an entry to RB tree to sort it by
3840 __archive_rb_tree_insert_node(&zip->tree,
3845 /* Skip the comment too ... */
3846 __archive_read_consume(a,
3847 filename_length + extra_length + comment_length);
3854 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3857 ssize_t filename_length, extra_length;
3859 if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3860 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3861 "Truncated ZIP file header");
3862 return (ARCHIVE_WARN);
3866 if (memcmp(p, "PK\003\004", 4) != 0) {
3867 archive_set_error(&a->archive, -1, "Damaged Zip archive");
3868 return ARCHIVE_WARN;
3870 filename_length = archive_le16dec(p + 26);
3871 extra_length = archive_le16dec(p + 28);
3873 return (30 + filename_length + extra_length);
3877 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3878 struct zip_entry *rsrc)
3880 struct zip *zip = (struct zip *)a->format->data;
3881 unsigned char *metadata, *mp;
3882 int64_t offset = archive_filter_bytes(&a->archive, 0);
3883 size_t remaining_bytes, metadata_bytes;
3885 int ret = ARCHIVE_OK, eof;
3887 switch(rsrc->compression) {
3888 case 0: /* No compression. */
3889 if (rsrc->uncompressed_size != rsrc->compressed_size) {
3890 archive_set_error(&a->archive,
3891 ARCHIVE_ERRNO_FILE_FORMAT,
3892 "Malformed OS X metadata entry: "
3893 "inconsistent size");
3894 return (ARCHIVE_FATAL);
3897 case 8: /* Deflate compression. */
3900 default: /* Unsupported compression. */
3901 /* Return a warning. */
3902 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3903 "Unsupported ZIP compression method (%s)",
3904 compression_name(rsrc->compression));
3905 /* We can't decompress this entry, but we will
3906 * be able to skip() it and try the next entry. */
3907 return (ARCHIVE_WARN);
3910 if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
3911 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3912 "Mac metadata is too large: %jd > 4M bytes",
3913 (intmax_t)rsrc->uncompressed_size);
3914 return (ARCHIVE_WARN);
3916 if (rsrc->compressed_size > (4 * 1024 * 1024)) {
3917 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3918 "Mac metadata is too large: %jd > 4M bytes",
3919 (intmax_t)rsrc->compressed_size);
3920 return (ARCHIVE_WARN);
3923 metadata = malloc((size_t)rsrc->uncompressed_size);
3924 if (metadata == NULL) {
3925 archive_set_error(&a->archive, ENOMEM,
3926 "Can't allocate memory for Mac metadata");
3927 return (ARCHIVE_FATAL);
3930 if (offset < rsrc->local_header_offset)
3931 __archive_read_consume(a, rsrc->local_header_offset - offset);
3932 else if (offset != rsrc->local_header_offset) {
3933 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
3936 hsize = zip_get_local_file_header_size(a, 0);
3937 __archive_read_consume(a, hsize);
3939 remaining_bytes = (size_t)rsrc->compressed_size;
3940 metadata_bytes = (size_t)rsrc->uncompressed_size;
3943 while (!eof && remaining_bytes) {
3944 const unsigned char *p;
3945 ssize_t bytes_avail;
3948 p = __archive_read_ahead(a, 1, &bytes_avail);
3950 archive_set_error(&a->archive,
3951 ARCHIVE_ERRNO_FILE_FORMAT,
3952 "Truncated ZIP file header");
3954 goto exit_mac_metadata;
3956 if ((size_t)bytes_avail > remaining_bytes)
3957 bytes_avail = remaining_bytes;
3958 switch(rsrc->compression) {
3959 case 0: /* No compression. */
3960 if ((size_t)bytes_avail > metadata_bytes)
3961 bytes_avail = metadata_bytes;
3962 memcpy(mp, p, bytes_avail);
3963 bytes_used = (size_t)bytes_avail;
3964 metadata_bytes -= bytes_used;
3966 if (metadata_bytes == 0)
3970 case 8: /* Deflate compression. */
3974 ret = zip_deflate_init(a, zip);
3975 if (ret != ARCHIVE_OK)
3976 goto exit_mac_metadata;
3977 zip->stream.next_in =
3978 (Bytef *)(uintptr_t)(const void *)p;
3979 zip->stream.avail_in = (uInt)bytes_avail;
3980 zip->stream.total_in = 0;
3981 zip->stream.next_out = mp;
3982 zip->stream.avail_out = (uInt)metadata_bytes;
3983 zip->stream.total_out = 0;
3985 r = inflate(&zip->stream, 0);
3993 archive_set_error(&a->archive, ENOMEM,
3994 "Out of memory for ZIP decompression");
3995 ret = ARCHIVE_FATAL;
3996 goto exit_mac_metadata;
3998 archive_set_error(&a->archive,
4000 "ZIP decompression failed (%d)", r);
4001 ret = ARCHIVE_FATAL;
4002 goto exit_mac_metadata;
4004 bytes_used = zip->stream.total_in;
4005 metadata_bytes -= zip->stream.total_out;
4006 mp += zip->stream.total_out;
4014 __archive_read_consume(a, bytes_used);
4015 remaining_bytes -= bytes_used;
4017 archive_entry_copy_mac_metadata(entry, metadata,
4018 (size_t)rsrc->uncompressed_size - metadata_bytes);
4021 __archive_read_seek(a, offset, SEEK_SET);
4022 zip->decompress_init = 0;
4028 archive_read_format_zip_seekable_read_header(struct archive_read *a,
4029 struct archive_entry *entry)
4031 struct zip *zip = (struct zip *)a->format->data;
4032 struct zip_entry *rsrc;
4034 int r, ret = ARCHIVE_OK;
4037 * It should be sufficient to call archive_read_next_header() for
4038 * a reader to determine if an entry is encrypted or not. If the
4039 * encryption of an entry is only detectable when calling
4040 * archive_read_data(), so be it. We'll do the same check there
4043 if (zip->has_encrypted_entries ==
4044 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
4045 zip->has_encrypted_entries = 0;
4047 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
4048 if (a->archive.archive_format_name == NULL)
4049 a->archive.archive_format_name = "ZIP";
4051 if (zip->zip_entries == NULL) {
4052 r = slurp_central_directory(a, entry, zip);
4053 if (r != ARCHIVE_OK)
4055 /* Get first entry whose local header offset is lower than
4056 * other entries in the archive file. */
4058 (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
4059 } else if (zip->entry != NULL) {
4060 /* Get next entry in local header offset order. */
4061 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
4062 &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
4065 if (zip->entry == NULL)
4068 if (zip->entry->rsrcname.s)
4069 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
4070 &zip->tree_rsrc, zip->entry->rsrcname.s);
4074 if (zip->cctx_valid)
4075 archive_decrypto_aes_ctr_release(&zip->cctx);
4076 if (zip->hctx_valid)
4077 archive_hmac_sha1_cleanup(&zip->hctx);
4078 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
4079 __archive_read_reset_passphrase(a);
4081 /* File entries are sorted by the header offset, we should mostly
4082 * use __archive_read_consume to advance a read point to avoid
4083 * redundant data reading. */
4084 offset = archive_filter_bytes(&a->archive, 0);
4085 if (offset < zip->entry->local_header_offset)
4086 __archive_read_consume(a,
4087 zip->entry->local_header_offset - offset);
4088 else if (offset != zip->entry->local_header_offset) {
4089 __archive_read_seek(a, zip->entry->local_header_offset,
4092 zip->unconsumed = 0;
4093 r = zip_read_local_file_header(a, entry, zip);
4094 if (r != ARCHIVE_OK)
4097 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
4105 * We're going to seek for the next header anyway, so we don't
4106 * need to bother doing anything here.
4109 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
4112 zip = (struct zip *)(a->format->data);
4114 zip->unconsumed = 0;
4115 return (ARCHIVE_OK);
4119 archive_read_support_format_zip_seekable(struct archive *_a)
4121 struct archive_read *a = (struct archive_read *)_a;
4125 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
4126 ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
4128 zip = (struct zip *)calloc(1, sizeof(*zip));
4130 archive_set_error(&a->archive, ENOMEM,
4131 "Can't allocate zip data");
4132 return (ARCHIVE_FATAL);
4135 #ifdef HAVE_COPYFILE_H
4136 /* Set this by default on Mac OS. */
4137 zip->process_mac_extensions = 1;
4141 * Until enough data has been read, we cannot tell about
4142 * any encrypted entries yet.
4144 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4145 zip->crc32func = real_crc32;
4147 r = __archive_read_register_format(a,
4150 archive_read_format_zip_seekable_bid,
4151 archive_read_format_zip_options,
4152 archive_read_format_zip_seekable_read_header,
4153 archive_read_format_zip_read_data,
4154 archive_read_format_zip_read_data_skip_seekable,
4156 archive_read_format_zip_cleanup,
4157 archive_read_support_format_zip_capabilities_seekable,
4158 archive_read_format_zip_has_encrypted_entries);
4160 if (r != ARCHIVE_OK)
4162 return (ARCHIVE_OK);