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 =
903 * Auxiliary function to uncompress data chunk from zipx archive
904 * (zip with lzma compression).
907 zipx_lzma_uncompress_buffer(const char *compressed_buffer,
908 size_t compressed_buffer_size,
909 char *uncompressed_buffer,
910 size_t uncompressed_buffer_size)
912 int status = ARCHIVE_FATAL;
913 // length of 'lzma properties data' in lzma compressed
914 // data segment (stream) inside zip archive
915 const size_t lzma_params_length = 5;
916 // offset of 'lzma properties data' from the beginning of lzma stream
917 const size_t lzma_params_offset = 4;
918 // end position of 'lzma properties data' in lzma stream
919 const size_t lzma_params_end = lzma_params_offset + lzma_params_length;
920 if (compressed_buffer == NULL ||
921 compressed_buffer_size < lzma_params_end ||
922 uncompressed_buffer == NULL)
925 // prepare header for lzma_alone_decoder to replace zipx header
926 // (see comments in 'zipx_lzma_alone_init' for justification)
931 uint8_t bytes[5]; // lzma_params_length
932 uint64_t uncompressed_size;
935 // copy 'lzma properties data' blob
936 memcpy(&alone_header.bytes[0], compressed_buffer + lzma_params_offset,
938 alone_header.uncompressed_size = UINT64_MAX;
940 // prepare new compressed buffer, see 'zipx_lzma_alone_init' for details
941 const size_t lzma_alone_buffer_size =
942 compressed_buffer_size - lzma_params_end + sizeof(alone_header);
943 unsigned char *lzma_alone_compressed_buffer =
944 (unsigned char*) malloc(lzma_alone_buffer_size);
945 if (lzma_alone_compressed_buffer == NULL)
947 // copy lzma_alone header into new buffer
948 memcpy(lzma_alone_compressed_buffer, (void*) &alone_header,
949 sizeof(alone_header));
950 // copy compressed data into new buffer
951 memcpy(lzma_alone_compressed_buffer + sizeof(alone_header),
952 compressed_buffer + lzma_params_end,
953 compressed_buffer_size - lzma_params_end);
955 // create and fill in lzma_alone_decoder stream
956 lzma_stream stream = LZMA_STREAM_INIT;
957 lzma_ret ret = lzma_alone_decoder(&stream, UINT64_MAX);
960 stream.next_in = lzma_alone_compressed_buffer;
961 stream.avail_in = lzma_alone_buffer_size;
963 stream.next_out = (unsigned char*)uncompressed_buffer;
964 stream.avail_out = uncompressed_buffer_size;
965 stream.total_out = 0;
966 ret = lzma_code(&stream, LZMA_RUN);
967 if (ret == LZMA_OK || ret == LZMA_STREAM_END)
971 free(lzma_alone_compressed_buffer);
976 * Assumes file pointer is at beginning of local file header.
979 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
986 size_t len, filename_length, extra_length;
987 struct archive_string_conv *sconv;
988 struct zip_entry *zip_entry = zip->entry;
989 struct zip_entry zip_entry_central_dir;
990 int ret = ARCHIVE_OK;
993 /* Save a copy of the original for consistency checks. */
994 zip_entry_central_dir = *zip_entry;
996 zip->decompress_init = 0;
997 zip->end_of_entry = 0;
998 zip->entry_uncompressed_bytes_read = 0;
999 zip->entry_compressed_bytes_read = 0;
1000 zip->entry_crc32 = zip->crc32func(0, NULL, 0);
1002 /* Setup default conversion. */
1003 if (zip->sconv == NULL && !zip->init_default_conversion) {
1004 zip->sconv_default =
1005 archive_string_default_conversion_for_read(&(a->archive));
1006 zip->init_default_conversion = 1;
1009 if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
1010 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1011 "Truncated ZIP file header");
1012 return (ARCHIVE_FATAL);
1015 if (memcmp(p, "PK\003\004", 4) != 0) {
1016 archive_set_error(&a->archive, -1, "Damaged Zip archive");
1017 return ARCHIVE_FATAL;
1020 zip_entry->system = p[5];
1021 zip_entry->zip_flags = archive_le16dec(p + 6);
1022 if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
1023 zip->has_encrypted_entries = 1;
1024 archive_entry_set_is_data_encrypted(entry, 1);
1025 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
1026 zip_entry->zip_flags & ZIP_ENCRYPTED &&
1027 zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
1028 archive_entry_set_is_metadata_encrypted(entry, 1);
1029 return ARCHIVE_FATAL;
1032 zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
1033 zip_entry->compression = (char)archive_le16dec(p + 8);
1034 zip_entry->mtime = zip_time(p + 10);
1035 zip_entry->crc32 = archive_le32dec(p + 14);
1036 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1037 zip_entry->decdat = p[11];
1039 zip_entry->decdat = p[17];
1040 zip_entry->compressed_size = archive_le32dec(p + 18);
1041 zip_entry->uncompressed_size = archive_le32dec(p + 22);
1042 filename_length = archive_le16dec(p + 26);
1043 extra_length = archive_le16dec(p + 28);
1045 __archive_read_consume(a, 30);
1047 /* Read the filename. */
1048 if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
1049 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1050 "Truncated ZIP file header");
1051 return (ARCHIVE_FATAL);
1053 if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
1054 /* The filename is stored to be UTF-8. */
1055 if (zip->sconv_utf8 == NULL) {
1057 archive_string_conversion_from_charset(
1058 &a->archive, "UTF-8", 1);
1059 if (zip->sconv_utf8 == NULL)
1060 return (ARCHIVE_FATAL);
1062 sconv = zip->sconv_utf8;
1063 } else if (zip->sconv != NULL)
1066 sconv = zip->sconv_default;
1068 if (archive_entry_copy_pathname_l(entry,
1069 h, filename_length, sconv) != 0) {
1070 if (errno == ENOMEM) {
1071 archive_set_error(&a->archive, ENOMEM,
1072 "Can't allocate memory for Pathname");
1073 return (ARCHIVE_FATAL);
1075 archive_set_error(&a->archive,
1076 ARCHIVE_ERRNO_FILE_FORMAT,
1077 "Pathname cannot be converted "
1078 "from %s to current locale.",
1079 archive_string_conversion_charset_name(sconv));
1082 __archive_read_consume(a, filename_length);
1084 /* Read the extra data. */
1085 if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
1086 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1087 "Truncated ZIP file header");
1088 return (ARCHIVE_FATAL);
1091 if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
1093 return ARCHIVE_FATAL;
1095 __archive_read_consume(a, extra_length);
1097 /* Work around a bug in Info-Zip: When reading from a pipe, it
1098 * stats the pipe instead of synthesizing a file entry. */
1099 if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
1100 zip_entry->mode &= ~ AE_IFMT;
1101 zip_entry->mode |= AE_IFREG;
1104 /* If the mode is totally empty, set some sane default. */
1105 if (zip_entry->mode == 0) {
1106 zip_entry->mode |= 0664;
1109 /* Windows archivers sometimes use backslash as the directory
1110 * separator. Normalize to slash. */
1111 if (zip_entry->system == 0 &&
1112 (wp = archive_entry_pathname_w(entry)) != NULL) {
1113 if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
1115 struct archive_wstring s;
1116 archive_string_init(&s);
1117 archive_wstrcpy(&s, wp);
1118 for (i = 0; i < archive_strlen(&s); i++) {
1122 archive_entry_copy_pathname_w(entry, s.s);
1123 archive_wstring_free(&s);
1127 /* Make sure that entries with a trailing '/' are marked as directories
1128 * even if the External File Attributes contains bogus values. If this
1129 * is not a directory and there is no type, assume a regular file. */
1130 if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
1133 wp = archive_entry_pathname_w(entry);
1136 has_slash = len > 0 && wp[len - 1] == L'/';
1138 cp = archive_entry_pathname(entry);
1139 len = (cp != NULL)?strlen(cp):0;
1140 has_slash = len > 0 && cp[len - 1] == '/';
1142 /* Correct file type as needed. */
1144 zip_entry->mode &= ~AE_IFMT;
1145 zip_entry->mode |= AE_IFDIR;
1146 zip_entry->mode |= 0111;
1147 } else if ((zip_entry->mode & AE_IFMT) == 0) {
1148 zip_entry->mode |= AE_IFREG;
1152 /* Make sure directories end in '/' */
1153 if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
1154 wp = archive_entry_pathname_w(entry);
1157 if (len > 0 && wp[len - 1] != L'/') {
1158 struct archive_wstring s;
1159 archive_string_init(&s);
1160 archive_wstrcat(&s, wp);
1161 archive_wstrappend_wchar(&s, L'/');
1162 archive_entry_copy_pathname_w(entry, s.s);
1163 archive_wstring_free(&s);
1166 cp = archive_entry_pathname(entry);
1167 len = (cp != NULL)?strlen(cp):0;
1168 if (len > 0 && cp[len - 1] != '/') {
1169 struct archive_string s;
1170 archive_string_init(&s);
1171 archive_strcat(&s, cp);
1172 archive_strappend_char(&s, '/');
1173 archive_entry_set_pathname(entry, s.s);
1174 archive_string_free(&s);
1179 if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1180 /* If this came from the central dir, its size info
1181 * is definitive, so ignore the length-at-end flag. */
1182 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1183 /* If local header is missing a value, use the one from
1184 the central directory. If both have it, warn about
1186 if (zip_entry->crc32 == 0) {
1187 zip_entry->crc32 = zip_entry_central_dir.crc32;
1188 } else if (!zip->ignore_crc32
1189 && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1190 archive_set_error(&a->archive,
1191 ARCHIVE_ERRNO_FILE_FORMAT,
1192 "Inconsistent CRC32 values");
1195 if (zip_entry->compressed_size == 0) {
1196 zip_entry->compressed_size
1197 = zip_entry_central_dir.compressed_size;
1198 } else if (zip_entry->compressed_size
1199 != zip_entry_central_dir.compressed_size) {
1200 archive_set_error(&a->archive,
1201 ARCHIVE_ERRNO_FILE_FORMAT,
1202 "Inconsistent compressed size: "
1203 "%jd in central directory, %jd in local header",
1204 (intmax_t)zip_entry_central_dir.compressed_size,
1205 (intmax_t)zip_entry->compressed_size);
1208 if (zip_entry->uncompressed_size == 0) {
1209 zip_entry->uncompressed_size
1210 = zip_entry_central_dir.uncompressed_size;
1211 } else if (zip_entry->uncompressed_size
1212 != zip_entry_central_dir.uncompressed_size) {
1213 archive_set_error(&a->archive,
1214 ARCHIVE_ERRNO_FILE_FORMAT,
1215 "Inconsistent uncompressed size: "
1216 "%jd in central directory, %jd in local header",
1217 (intmax_t)zip_entry_central_dir.uncompressed_size,
1218 (intmax_t)zip_entry->uncompressed_size);
1223 /* Populate some additional entry fields: */
1224 archive_entry_set_mode(entry, zip_entry->mode);
1225 archive_entry_set_uid(entry, zip_entry->uid);
1226 archive_entry_set_gid(entry, zip_entry->gid);
1227 archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1228 archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1229 archive_entry_set_atime(entry, zip_entry->atime, 0);
1231 if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1232 size_t linkname_length;
1234 if (zip_entry->compressed_size > 64 * 1024) {
1235 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1236 "Zip file with oversized link entry");
1237 return ARCHIVE_FATAL;
1240 linkname_length = (size_t)zip_entry->compressed_size;
1242 archive_entry_set_size(entry, 0);
1243 p = __archive_read_ahead(a, linkname_length, NULL);
1245 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1246 "Truncated Zip file");
1247 return ARCHIVE_FATAL;
1249 // take into account link compression if any
1250 size_t linkname_full_length = linkname_length;
1251 if (zip->entry->compression != 0)
1253 // symlink target string appeared to be compressed
1254 int status = ARCHIVE_FATAL;
1255 char *uncompressed_buffer =
1256 (char*) malloc(zip_entry->uncompressed_size);
1257 if (uncompressed_buffer == NULL)
1259 archive_set_error(&a->archive, ENOMEM,
1260 "No memory for lzma decompression");
1264 switch (zip->entry->compression)
1266 #if HAVE_LZMA_H && HAVE_LIBLZMA
1267 case 14: /* ZIPx LZMA compression. */
1268 /*(see zip file format specification, section 4.4.5)*/
1269 status = zipx_lzma_uncompress_buffer(p,
1271 uncompressed_buffer,
1272 (size_t)zip_entry->uncompressed_size);
1275 default: /* Unsupported compression. */
1278 if (status == ARCHIVE_OK)
1280 p = uncompressed_buffer;
1281 linkname_full_length =
1282 (size_t)zip_entry->uncompressed_size;
1286 archive_set_error(&a->archive,
1287 ARCHIVE_ERRNO_FILE_FORMAT,
1288 "Unsupported ZIP compression method "
1289 "during decompression of link entry (%d: %s)",
1290 zip->entry->compression,
1291 compression_name(zip->entry->compression));
1292 return ARCHIVE_FAILED;
1297 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1298 sconv = zip->sconv_utf8;
1300 sconv = zip->sconv_default;
1301 if (archive_entry_copy_symlink_l(entry, p, linkname_full_length,
1303 if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1304 (zip->entry->zip_flags & ZIP_UTF8_NAME))
1305 archive_entry_copy_symlink_l(entry, p,
1306 linkname_full_length, NULL);
1307 if (errno == ENOMEM) {
1308 archive_set_error(&a->archive, ENOMEM,
1309 "Can't allocate memory for Symlink");
1310 return (ARCHIVE_FATAL);
1313 * Since there is no character-set regulation for
1314 * symlink name, do not report the conversion error
1315 * in an automatic conversion.
1317 if (sconv != zip->sconv_utf8 ||
1318 (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1319 archive_set_error(&a->archive,
1320 ARCHIVE_ERRNO_FILE_FORMAT,
1321 "Symlink cannot be converted "
1322 "from %s to current locale.",
1323 archive_string_conversion_charset_name(
1328 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1330 if (__archive_read_consume(a, linkname_length) < 0) {
1331 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1332 "Read error skipping symlink target name");
1333 return ARCHIVE_FATAL;
1335 } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1336 || zip_entry->uncompressed_size > 0) {
1337 /* Set the size only if it's meaningful. */
1338 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1340 zip->entry_bytes_remaining = zip_entry->compressed_size;
1342 /* If there's no body, force read_data() to return EOF immediately. */
1343 if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1344 && zip->entry_bytes_remaining < 1)
1345 zip->end_of_entry = 1;
1347 /* Set up a more descriptive format name. */
1348 archive_string_empty(&zip->format_name);
1349 archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1350 version / 10, version % 10,
1351 compression_name(zip->entry->compression));
1352 a->archive.archive_format_name = zip->format_name.s;
1358 check_authentication_code(struct archive_read *a, const void *_p)
1360 struct zip *zip = (struct zip *)(a->format->data);
1362 /* Check authentication code. */
1363 if (zip->hctx_valid) {
1366 size_t hmac_len = 20;
1369 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1371 /* Read authentication code. */
1372 p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1374 archive_set_error(&a->archive,
1375 ARCHIVE_ERRNO_FILE_FORMAT,
1376 "Truncated ZIP file data");
1377 return (ARCHIVE_FATAL);
1382 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1383 __archive_read_consume(a, AUTH_CODE_SIZE);
1385 archive_set_error(&a->archive,
1387 "ZIP bad Authentication code");
1388 return (ARCHIVE_WARN);
1391 return (ARCHIVE_OK);
1395 * Read "uncompressed" data. There are three cases:
1396 * 1) We know the size of the data. This is always true for the
1397 * seeking reader (we've examined the Central Directory already).
1398 * 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1399 * Info-ZIP seems to do this; we know the size but have to grab
1400 * the CRC from the data descriptor afterwards.
1401 * 3) We're streaming and ZIP_LENGTH_AT_END was specified and
1402 * we have no size information. In this case, we can do pretty
1403 * well by watching for the data descriptor record. The data
1404 * descriptor is 16 bytes and includes a computed CRC that should
1405 * provide a strong check.
1407 * TODO: Technically, the PK\007\010 signature is optional.
1408 * In the original spec, the data descriptor contained CRC
1409 * and size fields but had no leading signature. In practice,
1410 * newer writers seem to provide the signature pretty consistently.
1412 * For uncompressed data, the PK\007\010 marker seems essential
1413 * to be sure we've actually seen the end of the entry.
1415 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1416 * zip->end_of_entry if it consumes all of the data.
1419 zip_read_data_none(struct archive_read *a, const void **_buff,
1420 size_t *size, int64_t *offset)
1424 ssize_t bytes_avail;
1427 (void)offset; /* UNUSED */
1429 zip = (struct zip *)(a->format->data);
1431 if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1433 ssize_t grabbing_bytes = 24;
1435 if (zip->hctx_valid)
1436 grabbing_bytes += AUTH_CODE_SIZE;
1437 /* Grab at least 24 bytes. */
1438 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1439 if (bytes_avail < grabbing_bytes) {
1440 /* Zip archives have end-of-archive markers
1441 that are longer than this, so a failure to get at
1442 least 24 bytes really does indicate a truncated
1444 archive_set_error(&a->archive,
1445 ARCHIVE_ERRNO_FILE_FORMAT,
1446 "Truncated ZIP file data");
1447 return (ARCHIVE_FATAL);
1449 /* Check for a complete PK\007\010 signature, followed
1450 * by the correct 4-byte CRC. */
1452 if (zip->hctx_valid)
1453 p += AUTH_CODE_SIZE;
1454 if (p[0] == 'P' && p[1] == 'K'
1455 && p[2] == '\007' && p[3] == '\010'
1456 && (archive_le32dec(p + 4) == zip->entry_crc32
1457 || zip->ignore_crc32
1459 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1460 if (zip->entry->flags & LA_USED_ZIP64) {
1461 uint64_t compressed, uncompressed;
1462 zip->entry->crc32 = archive_le32dec(p + 4);
1463 compressed = archive_le64dec(p + 8);
1464 uncompressed = archive_le64dec(p + 16);
1465 if (compressed > INT64_MAX || uncompressed >
1467 archive_set_error(&a->archive,
1468 ARCHIVE_ERRNO_FILE_FORMAT,
1469 "Overflow of 64-bit file sizes");
1470 return ARCHIVE_FAILED;
1472 zip->entry->compressed_size = compressed;
1473 zip->entry->uncompressed_size = uncompressed;
1474 zip->unconsumed = 24;
1476 zip->entry->crc32 = archive_le32dec(p + 4);
1477 zip->entry->compressed_size =
1478 archive_le32dec(p + 8);
1479 zip->entry->uncompressed_size =
1480 archive_le32dec(p + 12);
1481 zip->unconsumed = 16;
1483 if (zip->hctx_valid) {
1484 r = check_authentication_code(a, buff);
1485 if (r != ARCHIVE_OK)
1488 zip->end_of_entry = 1;
1489 return (ARCHIVE_OK);
1491 /* If not at EOF, ensure we consume at least one byte. */
1494 /* Scan forward until we see where a PK\007\010 signature
1496 /* Return bytes up until that point. On the next call,
1497 * the code above will verify the data descriptor. */
1498 while (p < buff + bytes_avail - 4) {
1499 if (p[3] == 'P') { p += 3; }
1500 else if (p[3] == 'K') { p += 2; }
1501 else if (p[3] == '\007') { p += 1; }
1502 else if (p[3] == '\010' && p[2] == '\007'
1503 && p[1] == 'K' && p[0] == 'P') {
1504 if (zip->hctx_valid)
1505 p -= AUTH_CODE_SIZE;
1509 bytes_avail = p - buff;
1511 if (zip->entry_bytes_remaining == 0) {
1512 zip->end_of_entry = 1;
1513 if (zip->hctx_valid) {
1514 r = check_authentication_code(a, NULL);
1515 if (r != ARCHIVE_OK)
1518 return (ARCHIVE_OK);
1520 /* Grab a bunch of bytes. */
1521 buff = __archive_read_ahead(a, 1, &bytes_avail);
1522 if (bytes_avail <= 0) {
1523 archive_set_error(&a->archive,
1524 ARCHIVE_ERRNO_FILE_FORMAT,
1525 "Truncated ZIP file data");
1526 return (ARCHIVE_FATAL);
1528 if (bytes_avail > zip->entry_bytes_remaining)
1529 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1531 if (zip->tctx_valid || zip->cctx_valid) {
1532 size_t dec_size = bytes_avail;
1534 if (dec_size > zip->decrypted_buffer_size)
1535 dec_size = zip->decrypted_buffer_size;
1536 if (zip->tctx_valid) {
1537 trad_enc_decrypt_update(&zip->tctx,
1538 (const uint8_t *)buff, dec_size,
1539 zip->decrypted_buffer, dec_size);
1541 size_t dsize = dec_size;
1542 archive_hmac_sha1_update(&zip->hctx,
1543 (const uint8_t *)buff, dec_size);
1544 archive_decrypto_aes_ctr_update(&zip->cctx,
1545 (const uint8_t *)buff, dec_size,
1546 zip->decrypted_buffer, &dsize);
1548 bytes_avail = dec_size;
1549 buff = (const char *)zip->decrypted_buffer;
1551 *size = bytes_avail;
1552 zip->entry_bytes_remaining -= bytes_avail;
1553 zip->entry_uncompressed_bytes_read += bytes_avail;
1554 zip->entry_compressed_bytes_read += bytes_avail;
1555 zip->unconsumed += bytes_avail;
1557 return (ARCHIVE_OK);
1561 consume_optional_marker(struct archive_read *a, struct zip *zip)
1563 if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1566 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1567 archive_set_error(&a->archive,
1568 ARCHIVE_ERRNO_FILE_FORMAT,
1569 "Truncated ZIP end-of-file record");
1570 return (ARCHIVE_FATAL);
1572 /* Consume the optional PK\007\010 marker. */
1573 if (p[0] == 'P' && p[1] == 'K' &&
1574 p[2] == '\007' && p[3] == '\010') {
1576 zip->unconsumed = 4;
1578 if (zip->entry->flags & LA_USED_ZIP64) {
1579 uint64_t compressed, uncompressed;
1580 zip->entry->crc32 = archive_le32dec(p);
1581 compressed = archive_le64dec(p + 4);
1582 uncompressed = archive_le64dec(p + 12);
1583 if (compressed > INT64_MAX ||
1584 uncompressed > INT64_MAX) {
1585 archive_set_error(&a->archive,
1586 ARCHIVE_ERRNO_FILE_FORMAT,
1587 "Overflow of 64-bit file sizes");
1588 return ARCHIVE_FAILED;
1590 zip->entry->compressed_size = compressed;
1591 zip->entry->uncompressed_size = uncompressed;
1592 zip->unconsumed += 20;
1594 zip->entry->crc32 = archive_le32dec(p);
1595 zip->entry->compressed_size = archive_le32dec(p + 4);
1596 zip->entry->uncompressed_size = archive_le32dec(p + 8);
1597 zip->unconsumed += 12;
1601 return (ARCHIVE_OK);
1604 #if HAVE_LZMA_H && HAVE_LIBLZMA
1606 zipx_xz_init(struct archive_read *a, struct zip *zip)
1610 if(zip->zipx_lzma_valid) {
1611 lzma_end(&zip->zipx_lzma_stream);
1612 zip->zipx_lzma_valid = 0;
1615 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1616 r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1618 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1619 "xz initialization failed(%d)",
1622 return (ARCHIVE_FAILED);
1625 zip->zipx_lzma_valid = 1;
1627 free(zip->uncompressed_buffer);
1629 zip->uncompressed_buffer_size = 256 * 1024;
1630 zip->uncompressed_buffer =
1631 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1632 if (zip->uncompressed_buffer == NULL) {
1633 archive_set_error(&a->archive, ENOMEM,
1634 "No memory for xz decompression");
1635 return (ARCHIVE_FATAL);
1638 zip->decompress_init = 1;
1639 return (ARCHIVE_OK);
1643 zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1650 struct _alone_header {
1652 uint64_t uncompressed_size;
1656 if(zip->zipx_lzma_valid) {
1657 lzma_end(&zip->zipx_lzma_stream);
1658 zip->zipx_lzma_valid = 0;
1661 /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
1662 * that is a part of XZ Utils. The stream format stored inside ZIPX
1663 * file is a modified "lzma alone" file format, that was used by the
1664 * `lzma` utility which was later deprecated in favour of `xz` utility. * Since those formats are nearly the same, we can use a standard
1665 * "lzma alone" decoder from XZ Utils. */
1667 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1668 r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1670 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1671 "lzma initialization failed(%d)", r);
1673 return (ARCHIVE_FAILED);
1676 /* Flag the cleanup function that we want our lzma-related structures
1677 * to be freed later. */
1678 zip->zipx_lzma_valid = 1;
1680 /* The "lzma alone" file format and the stream format inside ZIPx are
1681 * almost the same. Here's an example of a structure of "lzma alone"
1684 * $ cat /bin/ls | lzma | xxd | head -n 1
1685 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1687 * 5 bytes 8 bytes n bytes
1688 * <lzma_params><uncompressed_size><data...>
1690 * lzma_params is a 5-byte blob that has to be decoded to extract
1691 * parameters of this LZMA stream. The uncompressed_size field is an
1692 * uint64_t value that contains information about the size of the
1693 * uncompressed file, or UINT64_MAX if this value is unknown.
1694 * The <data...> part is the actual lzma-compressed data stream.
1696 * Now here's the structure of the stream inside the ZIPX file:
1698 * $ cat stream_inside_zipx | xxd | head -n 1
1699 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1701 * 2byte 2byte 5 bytes n bytes
1702 * <magic1><magic2><lzma_params><data...>
1704 * This means that the ZIPX file contains an additional magic1 and
1705 * magic2 headers, the lzma_params field contains the same parameter
1706 * set as in the "lzma alone" format, and the <data...> field is the
1707 * same as in the "lzma alone" format as well. Note that also the zipx
1708 * format is missing the uncompressed_size field.
1710 * So, in order to use the "lzma alone" decoder for the zipx lzma
1711 * stream, we simply need to shuffle around some fields, prepare a new
1712 * lzma alone header, feed it into lzma alone decoder so it will
1713 * initialize itself properly, and then we can start feeding normal
1714 * zipx lzma stream into the decoder.
1717 /* Read magic1,magic2,lzma_params from the ZIPX stream. */
1718 if((p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1719 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1720 "Truncated lzma data");
1721 return (ARCHIVE_FATAL);
1724 if(p[2] != 0x05 || p[3] != 0x00) {
1725 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1726 "Invalid lzma data");
1727 return (ARCHIVE_FATAL);
1730 /* Prepare an lzma alone header: copy the lzma_params blob into
1731 * a proper place into the lzma alone header. */
1732 memcpy(&alone_header.bytes[0], p + 4, 5);
1734 /* Initialize the 'uncompressed size' field to unknown; we'll manually
1735 * monitor how many bytes there are still to be uncompressed. */
1736 alone_header.uncompressed_size = UINT64_MAX;
1738 if(!zip->uncompressed_buffer) {
1739 zip->uncompressed_buffer_size = 256 * 1024;
1740 zip->uncompressed_buffer =
1741 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1743 if (zip->uncompressed_buffer == NULL) {
1744 archive_set_error(&a->archive, ENOMEM,
1745 "No memory for lzma decompression");
1746 return (ARCHIVE_FATAL);
1750 zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1751 zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1752 zip->zipx_lzma_stream.total_in = 0;
1753 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1754 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1755 zip->zipx_lzma_stream.total_out = 0;
1757 /* Feed only the header into the lzma alone decoder. This will
1758 * effectively initialize the decoder, and will not produce any
1759 * output bytes yet. */
1760 r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1762 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1763 "lzma stream initialization error");
1764 return ARCHIVE_FATAL;
1767 /* We've already consumed some bytes, so take this into account. */
1768 __archive_read_consume(a, 9);
1769 zip->entry_bytes_remaining -= 9;
1770 zip->entry_compressed_bytes_read += 9;
1772 zip->decompress_init = 1;
1773 return (ARCHIVE_OK);
1777 zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1778 size_t *size, int64_t *offset)
1780 struct zip* zip = (struct zip *)(a->format->data);
1783 const void* compressed_buf;
1784 ssize_t bytes_avail, in_bytes, to_consume = 0;
1786 (void) offset; /* UNUSED */
1788 /* Initialize decompressor if not yet initialized. */
1789 if (!zip->decompress_init) {
1790 ret = zipx_xz_init(a, zip);
1791 if (ret != ARCHIVE_OK)
1795 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1796 if (bytes_avail < 0) {
1797 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1798 "Truncated xz file body");
1799 return (ARCHIVE_FATAL);
1802 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1803 zip->zipx_lzma_stream.next_in = compressed_buf;
1804 zip->zipx_lzma_stream.avail_in = in_bytes;
1805 zip->zipx_lzma_stream.total_in = 0;
1806 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1807 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1808 zip->zipx_lzma_stream.total_out = 0;
1810 /* Perform the decompression. */
1811 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1813 case LZMA_DATA_ERROR:
1814 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1815 "xz data error (error %d)", (int) lz_ret);
1816 return (ARCHIVE_FATAL);
1823 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1824 "xz unknown error %d", (int) lz_ret);
1825 return (ARCHIVE_FATAL);
1827 case LZMA_STREAM_END:
1828 lzma_end(&zip->zipx_lzma_stream);
1829 zip->zipx_lzma_valid = 0;
1831 if((int64_t) zip->zipx_lzma_stream.total_in !=
1832 zip->entry_bytes_remaining)
1834 archive_set_error(&a->archive,
1836 "xz premature end of stream");
1837 return (ARCHIVE_FATAL);
1840 zip->end_of_entry = 1;
1844 to_consume = zip->zipx_lzma_stream.total_in;
1846 __archive_read_consume(a, to_consume);
1847 zip->entry_bytes_remaining -= to_consume;
1848 zip->entry_compressed_bytes_read += to_consume;
1849 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1851 *size = zip->zipx_lzma_stream.total_out;
1852 *buff = zip->uncompressed_buffer;
1854 ret = consume_optional_marker(a, zip);
1855 if (ret != ARCHIVE_OK)
1858 return (ARCHIVE_OK);
1862 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1863 size_t *size, int64_t *offset)
1865 struct zip* zip = (struct zip *)(a->format->data);
1868 const void* compressed_buf;
1869 ssize_t bytes_avail, in_bytes, to_consume;
1871 (void) offset; /* UNUSED */
1873 /* Initialize decompressor if not yet initialized. */
1874 if (!zip->decompress_init) {
1875 ret = zipx_lzma_alone_init(a, zip);
1876 if (ret != ARCHIVE_OK)
1880 /* Fetch more compressed data. The same note as in deflate handler
1881 * applies here as well:
1883 * Note: '1' here is a performance optimization. Recall that the
1884 * decompression layer returns a count of available bytes; asking for
1885 * more than that forces the decompressor to combine reads by copying
1888 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1889 if (bytes_avail < 0) {
1890 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1891 "Truncated lzma file body");
1892 return (ARCHIVE_FATAL);
1895 /* Set decompressor parameters. */
1896 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1898 zip->zipx_lzma_stream.next_in = compressed_buf;
1899 zip->zipx_lzma_stream.avail_in = in_bytes;
1900 zip->zipx_lzma_stream.total_in = 0;
1901 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1902 zip->zipx_lzma_stream.avail_out =
1903 /* These lzma_alone streams lack end of stream marker, so let's
1904 * make sure the unpacker won't try to unpack more than it's
1906 zipmin((int64_t) zip->uncompressed_buffer_size,
1907 zip->entry->uncompressed_size -
1908 zip->entry_uncompressed_bytes_read);
1909 zip->zipx_lzma_stream.total_out = 0;
1911 /* Perform the decompression. */
1912 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1914 case LZMA_DATA_ERROR:
1915 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1916 "lzma data error (error %d)", (int) lz_ret);
1917 return (ARCHIVE_FATAL);
1919 /* This case is optional in lzma alone format. It can happen,
1920 * but most of the files don't have it. (GitHub #1257) */
1921 case LZMA_STREAM_END:
1922 lzma_end(&zip->zipx_lzma_stream);
1923 zip->zipx_lzma_valid = 0;
1924 if((int64_t) zip->zipx_lzma_stream.total_in !=
1925 zip->entry_bytes_remaining)
1927 archive_set_error(&a->archive,
1929 "lzma alone premature end of stream");
1930 return (ARCHIVE_FATAL);
1933 zip->end_of_entry = 1;
1940 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1941 "lzma unknown error %d", (int) lz_ret);
1942 return (ARCHIVE_FATAL);
1945 to_consume = zip->zipx_lzma_stream.total_in;
1947 /* Update pointers. */
1948 __archive_read_consume(a, to_consume);
1949 zip->entry_bytes_remaining -= to_consume;
1950 zip->entry_compressed_bytes_read += to_consume;
1951 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1953 if(zip->entry_bytes_remaining == 0) {
1954 zip->end_of_entry = 1;
1957 /* Return values. */
1958 *size = zip->zipx_lzma_stream.total_out;
1959 *buff = zip->uncompressed_buffer;
1961 /* Behave the same way as during deflate decompression. */
1962 ret = consume_optional_marker(a, zip);
1963 if (ret != ARCHIVE_OK)
1966 /* Free lzma decoder handle because we'll no longer need it. */
1967 if(zip->end_of_entry) {
1968 lzma_end(&zip->zipx_lzma_stream);
1969 zip->zipx_lzma_valid = 0;
1972 /* If we're here, then we're good! */
1973 return (ARCHIVE_OK);
1975 #endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1978 zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1984 uint32_t restore_method;
1986 /* Remove previous decompression context if it exists. */
1987 if(zip->ppmd8_valid) {
1988 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1989 zip->ppmd8_valid = 0;
1992 /* Create a new decompression context. */
1993 __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1994 zip->ppmd8_stream_failed = 0;
1996 /* Setup function pointers required by Ppmd8 decompressor. The
1997 * 'ppmd_read' function will feed new bytes to the decompressor,
1998 * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
1999 zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
2000 zip->zipx_ppmd_stream.a = a;
2001 zip->zipx_ppmd_stream.Read = &ppmd_read;
2003 /* Reset number of read bytes to 0. */
2004 zip->zipx_ppmd_read_compressed = 0;
2006 /* Read Ppmd8 header (2 bytes). */
2007 p = __archive_read_ahead(a, 2, NULL);
2009 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2010 "Truncated file data in PPMd8 stream");
2011 return (ARCHIVE_FATAL);
2013 __archive_read_consume(a, 2);
2015 /* Decode the stream's compression parameters. */
2016 val = archive_le16dec(p);
2017 order = (val & 15) + 1;
2018 mem = ((val >> 4) & 0xff) + 1;
2019 restore_method = (val >> 12);
2021 if(order < 2 || restore_method > 2) {
2022 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2023 "Invalid parameter set in PPMd8 stream (order=%" PRId32 ", "
2024 "restore=%" PRId32 ")", order, restore_method);
2025 return (ARCHIVE_FAILED);
2028 /* Allocate the memory needed to properly decompress the file. */
2029 if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
2030 archive_set_error(&a->archive, ENOMEM,
2031 "Unable to allocate memory for PPMd8 stream: %" PRId32 " bytes",
2033 return (ARCHIVE_FATAL);
2036 /* Signal the cleanup function to release Ppmd8 context in the
2038 zip->ppmd8_valid = 1;
2040 /* Perform further Ppmd8 initialization. */
2041 if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
2042 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
2043 "PPMd8 stream range decoder initialization error");
2044 return (ARCHIVE_FATAL);
2047 __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
2050 /* Allocate the buffer that will hold uncompressed data. */
2051 free(zip->uncompressed_buffer);
2053 zip->uncompressed_buffer_size = 256 * 1024;
2054 zip->uncompressed_buffer =
2055 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2057 if(zip->uncompressed_buffer == NULL) {
2058 archive_set_error(&a->archive, ENOMEM,
2059 "No memory for PPMd8 decompression");
2060 return ARCHIVE_FATAL;
2063 /* Ppmd8 initialization is done. */
2064 zip->decompress_init = 1;
2066 /* We've already read 2 bytes in the output stream. Additionally,
2067 * Ppmd8 initialization code could read some data as well. So we
2068 * are advancing the stream by 2 bytes plus whatever number of
2069 * bytes Ppmd8 init function used. */
2070 zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
2076 zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
2077 size_t *size, int64_t *offset)
2079 struct zip* zip = (struct zip *)(a->format->data);
2081 size_t consumed_bytes = 0;
2082 ssize_t bytes_avail = 0;
2084 (void) offset; /* UNUSED */
2086 /* If we're here for the first time, initialize Ppmd8 decompression
2088 if(!zip->decompress_init) {
2089 ret = zipx_ppmd8_init(a, zip);
2090 if(ret != ARCHIVE_OK)
2094 /* Fetch for more data. We're reading 1 byte here, but libarchive
2095 * should prefetch more bytes. */
2096 (void) __archive_read_ahead(a, 1, &bytes_avail);
2097 if(bytes_avail < 0) {
2098 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2099 "Truncated PPMd8 file body");
2100 return (ARCHIVE_FATAL);
2103 /* This counter will be updated inside ppmd_read(), which at one
2104 * point will be called by Ppmd8_DecodeSymbol. */
2105 zip->zipx_ppmd_read_compressed = 0;
2107 /* Decompression loop. */
2109 int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
2112 zip->end_of_entry = 1;
2116 /* This field is set by ppmd_read() when there was no more data
2118 if(zip->ppmd8_stream_failed) {
2119 archive_set_error(&a->archive,
2120 ARCHIVE_ERRNO_FILE_FORMAT,
2121 "Truncated PPMd8 file body");
2122 return (ARCHIVE_FATAL);
2125 zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
2127 } while(consumed_bytes < zip->uncompressed_buffer_size);
2129 /* Update pointers for libarchive. */
2130 *buff = zip->uncompressed_buffer;
2131 *size = consumed_bytes;
2133 /* Update pointers so we can continue decompression in another call. */
2134 zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
2135 zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
2136 zip->entry_uncompressed_bytes_read += consumed_bytes;
2138 /* If we're at the end of stream, deinitialize Ppmd8 context. */
2139 if(zip->end_of_entry) {
2140 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2141 zip->ppmd8_valid = 0;
2144 /* Seek for optional marker, same way as in each zip entry. */
2145 ret = consume_optional_marker(a, zip);
2146 if (ret != ARCHIVE_OK)
2154 zipx_bzip2_init(struct archive_read *a, struct zip *zip)
2158 /* Deallocate already existing BZ2 decompression context if it
2160 if(zip->bzstream_valid) {
2161 BZ2_bzDecompressEnd(&zip->bzstream);
2162 zip->bzstream_valid = 0;
2165 /* Allocate a new BZ2 decompression context. */
2166 memset(&zip->bzstream, 0, sizeof(bz_stream));
2167 r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
2169 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
2170 "bzip2 initialization failed(%d)",
2173 return ARCHIVE_FAILED;
2176 /* Mark the bzstream field to be released in cleanup phase. */
2177 zip->bzstream_valid = 1;
2179 /* (Re)allocate the buffer that will contain decompressed bytes. */
2180 free(zip->uncompressed_buffer);
2182 zip->uncompressed_buffer_size = 256 * 1024;
2183 zip->uncompressed_buffer =
2184 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2185 if (zip->uncompressed_buffer == NULL) {
2186 archive_set_error(&a->archive, ENOMEM,
2187 "No memory for bzip2 decompression");
2188 return ARCHIVE_FATAL;
2191 /* Initialization done. */
2192 zip->decompress_init = 1;
2197 zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
2198 size_t *size, int64_t *offset)
2200 struct zip *zip = (struct zip *)(a->format->data);
2201 ssize_t bytes_avail = 0, in_bytes, to_consume;
2202 const void *compressed_buff;
2206 (void) offset; /* UNUSED */
2208 /* Initialize decompression context if we're here for the first time. */
2209 if(!zip->decompress_init) {
2210 r = zipx_bzip2_init(a, zip);
2215 /* Fetch more compressed bytes. */
2216 compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2217 if(bytes_avail < 0) {
2218 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2219 "Truncated bzip2 file body");
2220 return (ARCHIVE_FATAL);
2223 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2225 /* libbz2 doesn't complain when caller feeds avail_in == 0.
2226 * It will actually return success in this case, which is
2227 * undesirable. This is why we need to make this check
2230 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2231 "Truncated bzip2 file body");
2232 return (ARCHIVE_FATAL);
2235 /* Setup buffer boundaries. */
2236 zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
2237 zip->bzstream.avail_in = in_bytes;
2238 zip->bzstream.total_in_hi32 = 0;
2239 zip->bzstream.total_in_lo32 = 0;
2240 zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2241 zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2242 zip->bzstream.total_out_hi32 = 0;
2243 zip->bzstream.total_out_lo32 = 0;
2245 /* Perform the decompression. */
2246 r = BZ2_bzDecompress(&zip->bzstream);
2249 /* If we're at the end of the stream, deinitialize the
2250 * decompression context now. */
2251 switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2255 archive_set_error(&a->archive,
2257 "Failed to clean up bzip2 "
2259 return ARCHIVE_FATAL;
2262 zip->end_of_entry = 1;
2265 /* The decompressor has successfully decoded this
2266 * chunk of data, but more data is still in queue. */
2269 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2270 "bzip2 decompression failed");
2271 return ARCHIVE_FATAL;
2274 /* Update the pointers so decompressor can continue decoding. */
2275 to_consume = zip->bzstream.total_in_lo32;
2276 __archive_read_consume(a, to_consume);
2278 total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2279 zip->bzstream.total_out_lo32;
2281 zip->entry_bytes_remaining -= to_consume;
2282 zip->entry_compressed_bytes_read += to_consume;
2283 zip->entry_uncompressed_bytes_read += total_out;
2285 /* Give libarchive its due. */
2287 *buff = zip->uncompressed_buffer;
2289 /* Seek for optional marker, like in other entries. */
2290 r = consume_optional_marker(a, zip);
2301 zip_deflate_init(struct archive_read *a, struct zip *zip)
2305 /* If we haven't yet read any data, initialize the decompressor. */
2306 if (!zip->decompress_init) {
2307 if (zip->stream_valid)
2308 r = inflateReset(&zip->stream);
2310 r = inflateInit2(&zip->stream,
2311 -15 /* Don't check for zlib header */);
2313 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2314 "Can't initialize ZIP decompression.");
2315 return (ARCHIVE_FATAL);
2317 /* Stream structure has been set up. */
2318 zip->stream_valid = 1;
2319 /* We've initialized decompression for this stream. */
2320 zip->decompress_init = 1;
2322 return (ARCHIVE_OK);
2326 zip_read_data_deflate(struct archive_read *a, const void **buff,
2327 size_t *size, int64_t *offset)
2330 ssize_t bytes_avail;
2331 const void *compressed_buff, *sp;
2334 (void)offset; /* UNUSED */
2336 zip = (struct zip *)(a->format->data);
2338 /* If the buffer hasn't been allocated, allocate it now. */
2339 if (zip->uncompressed_buffer == NULL) {
2340 zip->uncompressed_buffer_size = 256 * 1024;
2341 zip->uncompressed_buffer
2342 = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2343 if (zip->uncompressed_buffer == NULL) {
2344 archive_set_error(&a->archive, ENOMEM,
2345 "No memory for ZIP decompression");
2346 return (ARCHIVE_FATAL);
2350 r = zip_deflate_init(a, zip);
2351 if (r != ARCHIVE_OK)
2355 * Note: '1' here is a performance optimization.
2356 * Recall that the decompression layer returns a count of
2357 * available bytes; asking for more than that forces the
2358 * decompressor to combine reads by copying data.
2360 compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2361 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2362 && bytes_avail > zip->entry_bytes_remaining) {
2363 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2365 if (bytes_avail < 0) {
2366 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2367 "Truncated ZIP file body");
2368 return (ARCHIVE_FATAL);
2371 if (zip->tctx_valid || zip->cctx_valid) {
2372 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2373 size_t buff_remaining =
2374 (zip->decrypted_buffer +
2375 zip->decrypted_buffer_size)
2376 - (zip->decrypted_ptr +
2377 zip->decrypted_bytes_remaining);
2379 if (buff_remaining > (size_t)bytes_avail)
2380 buff_remaining = (size_t)bytes_avail;
2382 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2383 zip->entry_bytes_remaining > 0) {
2384 if ((int64_t)(zip->decrypted_bytes_remaining
2386 > zip->entry_bytes_remaining) {
2387 if (zip->entry_bytes_remaining <
2388 (int64_t)zip->decrypted_bytes_remaining)
2392 (size_t)zip->entry_bytes_remaining
2393 - zip->decrypted_bytes_remaining;
2396 if (buff_remaining > 0) {
2397 if (zip->tctx_valid) {
2398 trad_enc_decrypt_update(&zip->tctx,
2399 compressed_buff, buff_remaining,
2401 + zip->decrypted_bytes_remaining,
2404 size_t dsize = buff_remaining;
2405 archive_decrypto_aes_ctr_update(
2407 compressed_buff, buff_remaining,
2409 + zip->decrypted_bytes_remaining,
2412 zip->decrypted_bytes_remaining +=
2416 bytes_avail = zip->decrypted_bytes_remaining;
2417 compressed_buff = (const char *)zip->decrypted_ptr;
2421 * A bug in zlib.h: stream.next_in should be marked 'const'
2422 * but isn't (the library never alters data through the
2423 * next_in pointer, only reads it). The result: this ugly
2424 * cast to remove 'const'.
2426 zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2427 zip->stream.avail_in = (uInt)bytes_avail;
2428 zip->stream.total_in = 0;
2429 zip->stream.next_out = zip->uncompressed_buffer;
2430 zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2431 zip->stream.total_out = 0;
2433 r = inflate(&zip->stream, 0);
2438 zip->end_of_entry = 1;
2441 archive_set_error(&a->archive, ENOMEM,
2442 "Out of memory for ZIP decompression");
2443 return (ARCHIVE_FATAL);
2445 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2446 "ZIP decompression failed (%d)", r);
2447 return (ARCHIVE_FATAL);
2450 /* Consume as much as the compressor actually used. */
2451 bytes_avail = zip->stream.total_in;
2452 if (zip->tctx_valid || zip->cctx_valid) {
2453 zip->decrypted_bytes_remaining -= bytes_avail;
2454 if (zip->decrypted_bytes_remaining == 0)
2455 zip->decrypted_ptr = zip->decrypted_buffer;
2457 zip->decrypted_ptr += bytes_avail;
2459 /* Calculate compressed data as much as we used.*/
2460 if (zip->hctx_valid)
2461 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2462 __archive_read_consume(a, bytes_avail);
2463 zip->entry_bytes_remaining -= bytes_avail;
2464 zip->entry_compressed_bytes_read += bytes_avail;
2466 *size = zip->stream.total_out;
2467 zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2468 *buff = zip->uncompressed_buffer;
2470 if (zip->end_of_entry && zip->hctx_valid) {
2471 r = check_authentication_code(a, NULL);
2472 if (r != ARCHIVE_OK)
2476 r = consume_optional_marker(a, zip);
2477 if (r != ARCHIVE_OK)
2480 return (ARCHIVE_OK);
2485 read_decryption_header(struct archive_read *a)
2487 struct zip *zip = (struct zip *)(a->format->data);
2489 unsigned int remaining_size;
2493 * Read an initialization vector data field.
2495 p = __archive_read_ahead(a, 2, NULL);
2499 zip->iv_size = archive_le16dec(p);
2500 __archive_read_consume(a, 2);
2501 if (ts < zip->iv_size) {
2505 p = __archive_read_ahead(a, zip->iv_size, NULL);
2508 if (zip->iv == NULL) {
2509 zip->iv = malloc(zip->iv_size);
2510 if (zip->iv == NULL)
2513 memcpy(zip->iv, p, zip->iv_size);
2514 __archive_read_consume(a, zip->iv_size);
2517 * Read a size of remaining decryption header field.
2519 p = __archive_read_ahead(a, 14, NULL);
2522 remaining_size = archive_le32dec(p);
2523 if (remaining_size < 16 || remaining_size > (1 << 18))
2526 /* Check if format version is supported. */
2527 if (archive_le16dec(p+4) != 3) {
2528 archive_set_error(&a->archive,
2529 ARCHIVE_ERRNO_FILE_FORMAT,
2530 "Unsupported encryption format version: %u",
2531 archive_le16dec(p+4));
2532 return (ARCHIVE_FAILED);
2536 * Read an encryption algorithm field.
2538 zip->alg_id = archive_le16dec(p+6);
2539 switch (zip->alg_id) {
2540 case 0x6601:/* DES */
2541 case 0x6602:/* RC2 */
2542 case 0x6603:/* 3DES 168 */
2543 case 0x6609:/* 3DES 112 */
2544 case 0x660E:/* AES 128 */
2545 case 0x660F:/* AES 192 */
2546 case 0x6610:/* AES 256 */
2547 case 0x6702:/* RC2 (version >= 5.2) */
2548 case 0x6720:/* Blowfish */
2549 case 0x6721:/* Twofish */
2550 case 0x6801:/* RC4 */
2551 /* Supported encryption algorithm. */
2554 archive_set_error(&a->archive,
2555 ARCHIVE_ERRNO_FILE_FORMAT,
2556 "Unknown encryption algorithm: %u", zip->alg_id);
2557 return (ARCHIVE_FAILED);
2561 * Read a bit length field.
2563 zip->bit_len = archive_le16dec(p+8);
2566 * Read a flags field.
2568 zip->flags = archive_le16dec(p+10);
2569 switch (zip->flags & 0xf000) {
2570 case 0x0001: /* Password is required to decrypt. */
2571 case 0x0002: /* Certificates only. */
2572 case 0x0003: /* Password or certificate required to decrypt. */
2575 archive_set_error(&a->archive,
2576 ARCHIVE_ERRNO_FILE_FORMAT,
2577 "Unknown encryption flag: %u", zip->flags);
2578 return (ARCHIVE_FAILED);
2580 if ((zip->flags & 0xf000) == 0 ||
2581 (zip->flags & 0xf000) == 0x4000) {
2582 archive_set_error(&a->archive,
2583 ARCHIVE_ERRNO_FILE_FORMAT,
2584 "Unknown encryption flag: %u", zip->flags);
2585 return (ARCHIVE_FAILED);
2589 * Read an encrypted random data field.
2592 zip->erd_size = archive_le16dec(p+12);
2593 __archive_read_consume(a, 14);
2594 if ((zip->erd_size & 0xf) != 0 ||
2595 (zip->erd_size + 16) > remaining_size ||
2596 (zip->erd_size + 16) < zip->erd_size)
2599 if (ts < zip->erd_size) {
2603 p = __archive_read_ahead(a, zip->erd_size, NULL);
2606 if (zip->erd == NULL) {
2607 zip->erd = malloc(zip->erd_size);
2608 if (zip->erd == NULL)
2611 memcpy(zip->erd, p, zip->erd_size);
2612 __archive_read_consume(a, zip->erd_size);
2615 * Read a reserved data field.
2617 p = __archive_read_ahead(a, 4, NULL);
2620 /* Reserved data size should be zero. */
2621 if (archive_le32dec(p) != 0)
2623 __archive_read_consume(a, 4);
2626 * Read a password validation data field.
2628 p = __archive_read_ahead(a, 2, NULL);
2632 zip->v_size = archive_le16dec(p);
2633 __archive_read_consume(a, 2);
2634 if ((zip->v_size & 0x0f) != 0 ||
2635 (zip->erd_size + zip->v_size + 16) > remaining_size ||
2636 (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2638 if (ts < zip->v_size) {
2642 p = __archive_read_ahead(a, zip->v_size, NULL);
2645 if (zip->v_data == NULL) {
2646 zip->v_data = malloc(zip->v_size);
2647 if (zip->v_data == NULL)
2650 memcpy(zip->v_data, p, zip->v_size);
2651 __archive_read_consume(a, zip->v_size);
2653 p = __archive_read_ahead(a, 4, NULL);
2656 zip->v_crc32 = archive_le32dec(p);
2657 __archive_read_consume(a, 4);
2659 /*return (ARCHIVE_OK);
2660 * This is not fully implemented yet.*/
2661 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2662 "Encrypted file is unsupported");
2663 return (ARCHIVE_FAILED);
2665 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2666 "Truncated ZIP file data");
2667 return (ARCHIVE_FATAL);
2669 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2670 "Corrupted ZIP file data");
2671 return (ARCHIVE_FATAL);
2673 archive_set_error(&a->archive, ENOMEM,
2674 "No memory for ZIP decryption");
2675 return (ARCHIVE_FATAL);
2679 zip_alloc_decryption_buffer(struct archive_read *a)
2681 struct zip *zip = (struct zip *)(a->format->data);
2682 size_t bs = 256 * 1024;
2684 if (zip->decrypted_buffer == NULL) {
2685 zip->decrypted_buffer_size = bs;
2686 zip->decrypted_buffer = malloc(bs);
2687 if (zip->decrypted_buffer == NULL) {
2688 archive_set_error(&a->archive, ENOMEM,
2689 "No memory for ZIP decryption");
2690 return (ARCHIVE_FATAL);
2693 zip->decrypted_ptr = zip->decrypted_buffer;
2694 return (ARCHIVE_OK);
2698 init_traditional_PKWARE_decryption(struct archive_read *a)
2700 struct zip *zip = (struct zip *)(a->format->data);
2705 if (zip->tctx_valid)
2706 return (ARCHIVE_OK);
2709 Read the 12 bytes encryption header stored at
2710 the start of the data area.
2712 #define ENC_HEADER_SIZE 12
2713 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2714 && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2715 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2716 "Truncated Zip encrypted body: only %jd bytes available",
2717 (intmax_t)zip->entry_bytes_remaining);
2718 return (ARCHIVE_FATAL);
2721 p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2723 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2724 "Truncated ZIP file data");
2725 return (ARCHIVE_FATAL);
2728 for (retry = 0;; retry++) {
2729 const char *passphrase;
2732 passphrase = __archive_read_next_passphrase(a);
2733 if (passphrase == NULL) {
2734 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2736 "Incorrect passphrase":
2737 "Passphrase required for this entry");
2738 return (ARCHIVE_FAILED);
2742 * Initialize ctx for Traditional PKWARE Decryption.
2744 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2745 p, ENC_HEADER_SIZE, &crcchk);
2746 if (r == 0 && crcchk == zip->entry->decdat)
2747 break;/* The passphrase is OK. */
2748 if (retry > 10000) {
2749 /* Avoid infinity loop. */
2750 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2751 "Too many incorrect passphrases");
2752 return (ARCHIVE_FAILED);
2756 __archive_read_consume(a, ENC_HEADER_SIZE);
2757 zip->tctx_valid = 1;
2758 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2759 zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2761 /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2762 zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2763 zip->decrypted_bytes_remaining = 0;
2765 return (zip_alloc_decryption_buffer(a));
2766 #undef ENC_HEADER_SIZE
2770 init_WinZip_AES_decryption(struct archive_read *a)
2772 struct zip *zip = (struct zip *)(a->format->data);
2775 size_t key_len, salt_len;
2776 uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2780 if (zip->cctx_valid || zip->hctx_valid)
2781 return (ARCHIVE_OK);
2783 switch (zip->entry->aes_extra.strength) {
2784 case 1: salt_len = 8; key_len = 16; break;
2785 case 2: salt_len = 12; key_len = 24; break;
2786 case 3: salt_len = 16; key_len = 32; break;
2787 default: goto corrupted;
2789 p = __archive_read_ahead(a, salt_len + 2, NULL);
2793 for (retry = 0;; retry++) {
2794 const char *passphrase;
2796 passphrase = __archive_read_next_passphrase(a);
2797 if (passphrase == NULL) {
2798 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2800 "Incorrect passphrase":
2801 "Passphrase required for this entry");
2802 return (ARCHIVE_FAILED);
2804 memset(derived_key, 0, sizeof(derived_key));
2805 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2806 p, salt_len, 1000, derived_key, key_len * 2 + 2);
2808 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2809 "Decryption is unsupported due to lack of "
2811 return (ARCHIVE_FAILED);
2814 /* Check password verification value. */
2815 pv = ((const uint8_t *)p) + salt_len;
2816 if (derived_key[key_len * 2] == pv[0] &&
2817 derived_key[key_len * 2 + 1] == pv[1])
2818 break;/* The passphrase is OK. */
2819 if (retry > 10000) {
2820 /* Avoid infinity loop. */
2821 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2822 "Too many incorrect passphrases");
2823 return (ARCHIVE_FAILED);
2827 r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2829 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2830 "Decryption is unsupported due to lack of crypto library");
2831 return (ARCHIVE_FAILED);
2833 r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2835 archive_decrypto_aes_ctr_release(&zip->cctx);
2836 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2837 "Failed to initialize HMAC-SHA1");
2838 return (ARCHIVE_FAILED);
2840 zip->cctx_valid = zip->hctx_valid = 1;
2841 __archive_read_consume(a, salt_len + 2);
2842 zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2843 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2844 && zip->entry_bytes_remaining < 0)
2846 zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2847 zip->decrypted_bytes_remaining = 0;
2849 zip->entry->compression = zip->entry->aes_extra.compression;
2850 return (zip_alloc_decryption_buffer(a));
2853 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2854 "Truncated ZIP file data");
2855 return (ARCHIVE_FATAL);
2857 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2858 "Corrupted ZIP file data");
2859 return (ARCHIVE_FATAL);
2863 archive_read_format_zip_read_data(struct archive_read *a,
2864 const void **buff, size_t *size, int64_t *offset)
2867 struct zip *zip = (struct zip *)(a->format->data);
2869 if (zip->has_encrypted_entries ==
2870 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2871 zip->has_encrypted_entries = 0;
2874 *offset = zip->entry_uncompressed_bytes_read;
2878 /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2879 if (zip->end_of_entry)
2880 return (ARCHIVE_EOF);
2882 /* Return EOF immediately if this is a non-regular file. */
2883 if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2884 return (ARCHIVE_EOF);
2886 __archive_read_consume(a, zip->unconsumed);
2887 zip->unconsumed = 0;
2889 if (zip->init_decryption) {
2890 zip->has_encrypted_entries = 1;
2891 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2892 r = read_decryption_header(a);
2893 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2894 r = init_WinZip_AES_decryption(a);
2896 r = init_traditional_PKWARE_decryption(a);
2897 if (r != ARCHIVE_OK)
2899 zip->init_decryption = 0;
2902 switch(zip->entry->compression) {
2903 case 0: /* No compression. */
2904 r = zip_read_data_none(a, buff, size, offset);
2907 case 12: /* ZIPx bzip2 compression. */
2908 r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2911 #if HAVE_LZMA_H && HAVE_LIBLZMA
2912 case 14: /* ZIPx LZMA compression. */
2913 r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
2915 case 95: /* ZIPx XZ compression. */
2916 r = zip_read_data_zipx_xz(a, buff, size, offset);
2919 /* PPMd support is built-in, so we don't need any #if guards. */
2920 case 98: /* ZIPx PPMd compression. */
2921 r = zip_read_data_zipx_ppmd(a, buff, size, offset);
2925 case 8: /* Deflate compression. */
2926 r = zip_read_data_deflate(a, buff, size, offset);
2929 default: /* Unsupported compression. */
2930 /* Return a warning. */
2931 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2932 "Unsupported ZIP compression method (%d: %s)",
2933 zip->entry->compression, compression_name(zip->entry->compression));
2934 /* We can't decompress this entry, but we will
2935 * be able to skip() it and try the next entry. */
2936 return (ARCHIVE_FAILED);
2939 if (r != ARCHIVE_OK)
2941 /* Update checksum */
2943 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
2945 /* If we hit the end, swallow any end-of-data marker. */
2946 if (zip->end_of_entry) {
2947 /* Check file size, CRC against these values. */
2948 if (zip->entry->compressed_size !=
2949 zip->entry_compressed_bytes_read) {
2950 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2951 "ZIP compressed data is wrong size "
2952 "(read %jd, expected %jd)",
2953 (intmax_t)zip->entry_compressed_bytes_read,
2954 (intmax_t)zip->entry->compressed_size);
2955 return (ARCHIVE_WARN);
2957 /* Size field only stores the lower 32 bits of the actual
2959 if ((zip->entry->uncompressed_size & UINT32_MAX)
2960 != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
2961 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2962 "ZIP uncompressed data is wrong size "
2963 "(read %jd, expected %jd)\n",
2964 (intmax_t)zip->entry_uncompressed_bytes_read,
2965 (intmax_t)zip->entry->uncompressed_size);
2966 return (ARCHIVE_WARN);
2968 /* Check computed CRC against header */
2969 if ((!zip->hctx_valid ||
2970 zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
2971 zip->entry->crc32 != zip->entry_crc32
2972 && !zip->ignore_crc32) {
2973 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2974 "ZIP bad CRC: 0x%lx should be 0x%lx",
2975 (unsigned long)zip->entry_crc32,
2976 (unsigned long)zip->entry->crc32);
2977 return (ARCHIVE_WARN);
2981 return (ARCHIVE_OK);
2985 archive_read_format_zip_cleanup(struct archive_read *a)
2988 struct zip_entry *zip_entry, *next_zip_entry;
2990 zip = (struct zip *)(a->format->data);
2993 if (zip->stream_valid)
2994 inflateEnd(&zip->stream);
2997 #if HAVE_LZMA_H && HAVE_LIBLZMA
2998 if (zip->zipx_lzma_valid) {
2999 lzma_end(&zip->zipx_lzma_stream);
3004 if (zip->bzstream_valid) {
3005 BZ2_bzDecompressEnd(&zip->bzstream);
3009 free(zip->uncompressed_buffer);
3011 if (zip->ppmd8_valid)
3012 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
3014 if (zip->zip_entries) {
3015 zip_entry = zip->zip_entries;
3016 while (zip_entry != NULL) {
3017 next_zip_entry = zip_entry->next;
3018 archive_string_free(&zip_entry->rsrcname);
3020 zip_entry = next_zip_entry;
3023 free(zip->decrypted_buffer);
3024 if (zip->cctx_valid)
3025 archive_decrypto_aes_ctr_release(&zip->cctx);
3026 if (zip->hctx_valid)
3027 archive_hmac_sha1_cleanup(&zip->hctx);
3031 archive_string_free(&zip->format_name);
3033 (a->format->data) = NULL;
3034 return (ARCHIVE_OK);
3038 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
3040 if (_a && _a->format) {
3041 struct zip * zip = (struct zip *)_a->format->data;
3043 return zip->has_encrypted_entries;
3046 return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3050 archive_read_format_zip_options(struct archive_read *a,
3051 const char *key, const char *val)
3054 int ret = ARCHIVE_FAILED;
3056 zip = (struct zip *)(a->format->data);
3057 if (strcmp(key, "compat-2x") == 0) {
3058 /* Handle filenames as libarchive 2.x */
3059 zip->init_default_conversion = (val != NULL) ? 1 : 0;
3060 return (ARCHIVE_OK);
3061 } else if (strcmp(key, "hdrcharset") == 0) {
3062 if (val == NULL || val[0] == 0)
3063 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3064 "zip: hdrcharset option needs a character-set name"
3067 zip->sconv = archive_string_conversion_from_charset(
3068 &a->archive, val, 0);
3069 if (zip->sconv != NULL) {
3070 if (strcmp(val, "UTF-8") == 0)
3071 zip->sconv_utf8 = zip->sconv;
3074 ret = ARCHIVE_FATAL;
3077 } else if (strcmp(key, "ignorecrc32") == 0) {
3078 /* Mostly useful for testing. */
3079 if (val == NULL || val[0] == 0) {
3080 zip->crc32func = real_crc32;
3081 zip->ignore_crc32 = 0;
3083 zip->crc32func = fake_crc32;
3084 zip->ignore_crc32 = 1;
3086 return (ARCHIVE_OK);
3087 } else if (strcmp(key, "mac-ext") == 0) {
3088 zip->process_mac_extensions = (val != NULL && val[0] != 0);
3089 return (ARCHIVE_OK);
3092 /* Note: The "warn" return is just to inform the options
3093 * supervisor that we didn't handle it. It will generate
3094 * a suitable error if no one used this option. */
3095 return (ARCHIVE_WARN);
3099 archive_read_support_format_zip(struct archive *a)
3102 r = archive_read_support_format_zip_streamable(a);
3103 if (r != ARCHIVE_OK)
3105 return (archive_read_support_format_zip_seekable(a));
3108 /* ------------------------------------------------------------------------ */
3111 * Streaming-mode support
3116 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
3118 (void)a; /* UNUSED */
3119 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3120 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3124 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
3128 (void)best_bid; /* UNUSED */
3130 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3134 * Bid of 29 here comes from:
3135 * + 16 bits for "PK",
3136 * + next 16-bit field has 6 options so contributes
3137 * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
3139 * So we've effectively verified ~29 total bits of check data.
3141 if (p[0] == 'P' && p[1] == 'K') {
3142 if ((p[2] == '\001' && p[3] == '\002')
3143 || (p[2] == '\003' && p[3] == '\004')
3144 || (p[2] == '\005' && p[3] == '\006')
3145 || (p[2] == '\006' && p[3] == '\006')
3146 || (p[2] == '\007' && p[3] == '\010')
3147 || (p[2] == '0' && p[3] == '0'))
3151 /* TODO: It's worth looking ahead a little bit for a valid
3152 * PK signature. In particular, that would make it possible
3153 * to read some UUEncoded SFX files or SFX files coming from
3154 * a network socket. */
3160 archive_read_format_zip_streamable_read_header(struct archive_read *a,
3161 struct archive_entry *entry)
3165 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3166 if (a->archive.archive_format_name == NULL)
3167 a->archive.archive_format_name = "ZIP";
3169 zip = (struct zip *)(a->format->data);
3172 * It should be sufficient to call archive_read_next_header() for
3173 * a reader to determine if an entry is encrypted or not. If the
3174 * encryption of an entry is only detectable when calling
3175 * archive_read_data(), so be it. We'll do the same check there
3178 if (zip->has_encrypted_entries ==
3179 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3180 zip->has_encrypted_entries = 0;
3182 /* Make sure we have a zip_entry structure to use. */
3183 if (zip->zip_entries == NULL) {
3184 zip->zip_entries = malloc(sizeof(struct zip_entry));
3185 if (zip->zip_entries == NULL) {
3186 archive_set_error(&a->archive, ENOMEM,
3188 return ARCHIVE_FATAL;
3191 zip->entry = zip->zip_entries;
3192 memset(zip->entry, 0, sizeof(struct zip_entry));
3194 if (zip->cctx_valid)
3195 archive_decrypto_aes_ctr_release(&zip->cctx);
3196 if (zip->hctx_valid)
3197 archive_hmac_sha1_cleanup(&zip->hctx);
3198 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3199 __archive_read_reset_passphrase(a);
3201 /* Search ahead for the next local file header. */
3202 __archive_read_consume(a, zip->unconsumed);
3203 zip->unconsumed = 0;
3205 int64_t skipped = 0;
3206 const char *p, *end;
3209 p = __archive_read_ahead(a, 4, &bytes);
3211 return (ARCHIVE_FATAL);
3214 while (p + 4 <= end) {
3215 if (p[0] == 'P' && p[1] == 'K') {
3216 if (p[2] == '\003' && p[3] == '\004') {
3217 /* Regular file entry. */
3218 __archive_read_consume(a, skipped);
3219 return zip_read_local_file_header(a,
3224 * TODO: We cannot restore permissions
3225 * based only on the local file headers.
3226 * Consider scanning the central
3227 * directory and returning additional
3228 * entries for at least directories.
3229 * This would allow us to properly set
3230 * directory permissions.
3232 * This won't help us fix symlinks
3233 * and may not help with regular file
3234 * permissions, either. <sigh>
3236 if (p[2] == '\001' && p[3] == '\002') {
3237 return (ARCHIVE_EOF);
3240 /* End of central directory? Must be an
3242 if ((p[2] == '\005' && p[3] == '\006')
3243 || (p[2] == '\006' && p[3] == '\006'))
3244 return (ARCHIVE_EOF);
3249 __archive_read_consume(a, skipped);
3254 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3257 int64_t bytes_skipped;
3259 zip = (struct zip *)(a->format->data);
3260 bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3261 zip->unconsumed = 0;
3262 if (bytes_skipped < 0)
3263 return (ARCHIVE_FATAL);
3265 /* If we've already read to end of data, we're done. */
3266 if (zip->end_of_entry)
3267 return (ARCHIVE_OK);
3269 /* So we know we're streaming... */
3270 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3271 || zip->entry->compressed_size > 0) {
3272 /* We know the compressed length, so we can just skip. */
3273 bytes_skipped = __archive_read_consume(a,
3274 zip->entry_bytes_remaining);
3275 if (bytes_skipped < 0)
3276 return (ARCHIVE_FATAL);
3277 return (ARCHIVE_OK);
3280 if (zip->init_decryption) {
3283 zip->has_encrypted_entries = 1;
3284 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3285 r = read_decryption_header(a);
3286 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3287 r = init_WinZip_AES_decryption(a);
3289 r = init_traditional_PKWARE_decryption(a);
3290 if (r != ARCHIVE_OK)
3292 zip->init_decryption = 0;
3295 /* We're streaming and we don't know the length. */
3296 /* If the body is compressed and we know the format, we can
3297 * find an exact end-of-entry by decompressing it. */
3298 switch (zip->entry->compression) {
3300 case 8: /* Deflate compression. */
3301 while (!zip->end_of_entry) {
3303 const void *buff = NULL;
3306 r = zip_read_data_deflate(a, &buff, &size, &offset);
3307 if (r != ARCHIVE_OK)
3312 default: /* Uncompressed or unknown. */
3313 /* Scan for a PK\007\010 signature. */
3315 const char *p, *buff;
3316 ssize_t bytes_avail;
3317 buff = __archive_read_ahead(a, 16, &bytes_avail);
3318 if (bytes_avail < 16) {
3319 archive_set_error(&a->archive,
3320 ARCHIVE_ERRNO_FILE_FORMAT,
3321 "Truncated ZIP file data");
3322 return (ARCHIVE_FATAL);
3325 while (p <= buff + bytes_avail - 16) {
3326 if (p[3] == 'P') { p += 3; }
3327 else if (p[3] == 'K') { p += 2; }
3328 else if (p[3] == '\007') { p += 1; }
3329 else if (p[3] == '\010' && p[2] == '\007'
3330 && p[1] == 'K' && p[0] == 'P') {
3331 if (zip->entry->flags & LA_USED_ZIP64)
3332 __archive_read_consume(a,
3335 __archive_read_consume(a,
3340 __archive_read_consume(a, p - buff);
3346 archive_read_support_format_zip_streamable(struct archive *_a)
3348 struct archive_read *a = (struct archive_read *)_a;
3352 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3353 ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3355 zip = (struct zip *)calloc(1, sizeof(*zip));
3357 archive_set_error(&a->archive, ENOMEM,
3358 "Can't allocate zip data");
3359 return (ARCHIVE_FATAL);
3362 /* Streamable reader doesn't support mac extensions. */
3363 zip->process_mac_extensions = 0;
3366 * Until enough data has been read, we cannot tell about
3367 * any encrypted entries yet.
3369 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3370 zip->crc32func = real_crc32;
3372 r = __archive_read_register_format(a,
3375 archive_read_format_zip_streamable_bid,
3376 archive_read_format_zip_options,
3377 archive_read_format_zip_streamable_read_header,
3378 archive_read_format_zip_read_data,
3379 archive_read_format_zip_read_data_skip_streamable,
3381 archive_read_format_zip_cleanup,
3382 archive_read_support_format_zip_capabilities_streamable,
3383 archive_read_format_zip_has_encrypted_entries);
3385 if (r != ARCHIVE_OK)
3387 return (ARCHIVE_OK);
3390 /* ------------------------------------------------------------------------ */
3393 * Seeking-mode support
3397 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3399 (void)a; /* UNUSED */
3400 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3401 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3405 * TODO: This is a performance sink because it forces the read core to
3406 * drop buffered data from the start of file, which will then have to
3407 * be re-read again if this bidder loses.
3409 * We workaround this a little by passing in the best bid so far so
3410 * that later bidders can do nothing if they know they'll never
3411 * outbid. But we can certainly do better...
3414 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3416 /* Sanity-check the EOCD we've found. */
3418 /* This must be the first volume. */
3419 if (archive_le16dec(p + 4) != 0)
3421 /* Central directory must be on this volume. */
3422 if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
3424 /* All central directory entries must be on this volume. */
3425 if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3427 /* Central directory can't extend beyond start of EOCD record. */
3428 if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
3432 /* Save the central directory location for later use. */
3433 zip->central_directory_offset = archive_le32dec(p + 16);
3435 /* This is just a tiny bit higher than the maximum
3436 returned by the streaming Zip bidder. This ensures
3437 that the more accurate seeking Zip parser wins
3438 whenever seek is available. */
3443 * Examine Zip64 EOCD locator: If it's valid, store the information
3447 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3449 int64_t eocd64_offset;
3450 int64_t eocd64_size;
3452 /* Sanity-check the locator record. */
3454 /* Central dir must be on first volume. */
3455 if (archive_le32dec(p + 4) != 0)
3457 /* Must be only a single volume. */
3458 if (archive_le32dec(p + 16) != 1)
3461 /* Find the Zip64 EOCD record. */
3462 eocd64_offset = archive_le64dec(p + 8);
3463 if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3465 if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3467 /* Make sure we can read all of it. */
3468 eocd64_size = archive_le64dec(p + 4) + 12;
3469 if (eocd64_size < 56 || eocd64_size > 16384)
3471 if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3474 /* Sanity-check the EOCD64 */
3475 if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3477 if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3479 /* CD can't be split. */
3480 if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3483 /* Save the central directory offset for later use. */
3484 zip->central_directory_offset = archive_le64dec(p + 48);
3490 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3492 struct zip *zip = (struct zip *)a->format->data;
3493 int64_t file_size, current_offset;
3497 /* If someone has already bid more than 32, then avoid
3498 trashing the look-ahead buffers with a seek. */
3502 file_size = __archive_read_seek(a, 0, SEEK_END);
3506 /* Search last 16k of file for end-of-central-directory
3507 * record (which starts with PK\005\006) */
3508 tail = (int)zipmin(1024 * 16, file_size);
3509 current_offset = __archive_read_seek(a, -tail, SEEK_END);
3510 if (current_offset < 0)
3512 if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3514 /* Boyer-Moore search backwards from the end, since we want
3515 * to match the last EOCD in the file (there can be more than
3516 * one if there is an uncompressed Zip archive as a member
3517 * within this Zip archive). */
3518 for (i = tail - 22; i > 0;) {
3521 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3522 int ret = read_eocd(zip, p + i,
3523 current_offset + i);
3524 /* Zip64 EOCD locator precedes
3525 * regular EOCD if present. */
3526 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3527 int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3528 if (ret_zip64 > ret)
3535 case 'K': i -= 1; break;
3536 case 005: i -= 2; break;
3537 case 006: i -= 3; break;
3538 default: i -= 4; break;
3544 /* The red-black trees are only used in seeking mode to manage
3545 * the in-memory copy of the central directory. */
3548 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3550 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3551 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3553 if (e1->local_header_offset > e2->local_header_offset)
3555 if (e1->local_header_offset < e2->local_header_offset)
3561 cmp_key(const struct archive_rb_node *n, const void *key)
3563 /* This function won't be called */
3564 (void)n; /* UNUSED */
3565 (void)key; /* UNUSED */
3569 static const struct archive_rb_tree_ops rb_ops = {
3574 rsrc_cmp_node(const struct archive_rb_node *n1,
3575 const struct archive_rb_node *n2)
3577 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3578 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3580 return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3584 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3586 const struct zip_entry *e = (const struct zip_entry *)n;
3587 return (strcmp((const char *)key, e->rsrcname.s));
3590 static const struct archive_rb_tree_ops rb_rsrc_ops = {
3591 &rsrc_cmp_node, &rsrc_cmp_key
3595 rsrc_basename(const char *name, size_t name_length)
3601 s = memchr(s, '/', name_length - (s - name));
3610 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3612 struct archive_string str;
3613 struct zip_entry *dir;
3616 archive_string_init(&str);
3617 archive_strncpy(&str, name, name_length);
3619 s = strrchr(str.s, '/');
3623 /* Transfer the parent directory from zip->tree_rsrc RB
3624 * tree to zip->tree RB tree to expose. */
3625 dir = (struct zip_entry *)
3626 __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3629 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3630 archive_string_free(&dir->rsrcname);
3631 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
3633 archive_string_free(&str);
3637 slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
3643 ssize_t bytes_avail;
3647 * Find the start of the central directory. The end-of-CD
3648 * record has our starting point, but there are lots of
3649 * Zip archives which have had other data prepended to the
3650 * file, which makes the recorded offsets all too small.
3651 * So we search forward from the specified offset until we
3652 * find the real start of the central directory. Then we
3653 * know the correction we need to apply to account for leading
3656 if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
3657 return ARCHIVE_FATAL;
3661 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3662 return ARCHIVE_FATAL;
3663 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3665 case 'P': i += 3; break;
3666 case 'K': i += 2; break;
3667 case 001: i += 1; break;
3669 if (memcmp(p + i, "PK\001\002", 4) == 0) {
3675 case 005: i += 1; break;
3677 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3680 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3686 default: i += 4; break;
3689 __archive_read_consume(a, i);
3691 correction = archive_filter_bytes(&a->archive, 0)
3692 - zip->central_directory_offset;
3694 __archive_rb_tree_init(&zip->tree, &rb_ops);
3695 __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3697 zip->central_directory_entries_total = 0;
3699 struct zip_entry *zip_entry;
3700 size_t filename_length, extra_length, comment_length;
3701 uint32_t external_attributes;
3702 const char *name, *r;
3704 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3705 return ARCHIVE_FATAL;
3706 if (memcmp(p, "PK\006\006", 4) == 0
3707 || memcmp(p, "PK\005\006", 4) == 0) {
3709 } else if (memcmp(p, "PK\001\002", 4) != 0) {
3710 archive_set_error(&a->archive,
3711 -1, "Invalid central directory signature");
3712 return ARCHIVE_FATAL;
3714 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3715 return ARCHIVE_FATAL;
3717 zip_entry = calloc(1, sizeof(struct zip_entry));
3718 if (zip_entry == NULL) {
3719 archive_set_error(&a->archive, ENOMEM,
3720 "Can't allocate zip entry");
3721 return ARCHIVE_FATAL;
3723 zip_entry->next = zip->zip_entries;
3724 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3725 zip->zip_entries = zip_entry;
3726 zip->central_directory_entries_total++;
3728 /* version = p[4]; */
3729 zip_entry->system = p[5];
3730 /* version_required = archive_le16dec(p + 6); */
3731 zip_entry->zip_flags = archive_le16dec(p + 8);
3732 if (zip_entry->zip_flags
3733 & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3734 zip->has_encrypted_entries = 1;
3736 zip_entry->compression = (char)archive_le16dec(p + 10);
3737 zip_entry->mtime = zip_time(p + 12);
3738 zip_entry->crc32 = archive_le32dec(p + 16);
3739 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3740 zip_entry->decdat = p[13];
3742 zip_entry->decdat = p[19];
3743 zip_entry->compressed_size = archive_le32dec(p + 20);
3744 zip_entry->uncompressed_size = archive_le32dec(p + 24);
3745 filename_length = archive_le16dec(p + 28);
3746 extra_length = archive_le16dec(p + 30);
3747 comment_length = archive_le16dec(p + 32);
3748 /* disk_start = archive_le16dec(p + 34);
3750 * internal_attributes = archive_le16dec(p + 36);
3752 external_attributes = archive_le32dec(p + 38);
3753 zip_entry->local_header_offset =
3754 archive_le32dec(p + 42) + correction;
3756 /* If we can't guess the mode, leave it zero here;
3757 when we read the local file header we might get
3758 more information. */
3759 if (zip_entry->system == 3) {
3760 zip_entry->mode = external_attributes >> 16;
3761 } else if (zip_entry->system == 0) {
3762 // Interpret MSDOS directory bit
3763 if (0x10 == (external_attributes & 0x10)) {
3764 zip_entry->mode = AE_IFDIR | 0775;
3766 zip_entry->mode = AE_IFREG | 0664;
3768 if (0x01 == (external_attributes & 0x01)) {
3769 // Read-only bit; strip write permissions
3770 zip_entry->mode &= 0555;
3773 zip_entry->mode = 0;
3776 /* We're done with the regular data; get the filename and
3778 __archive_read_consume(a, 46);
3779 p = __archive_read_ahead(a, filename_length + extra_length,
3782 archive_set_error(&a->archive,
3783 ARCHIVE_ERRNO_FILE_FORMAT,
3784 "Truncated ZIP file header");
3785 return ARCHIVE_FATAL;
3787 if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
3788 extra_length, zip_entry)) {
3789 return ARCHIVE_FATAL;
3793 * Mac resource fork files are stored under the
3794 * "__MACOSX/" directory, so we should check if
3797 if (!zip->process_mac_extensions) {
3798 /* Treat every entry as a regular entry. */
3799 __archive_rb_tree_insert_node(&zip->tree,
3803 r = rsrc_basename(name, filename_length);
3804 if (filename_length >= 9 &&
3805 strncmp("__MACOSX/", name, 9) == 0) {
3806 /* If this file is not a resource fork nor
3807 * a directory. We should treat it as a non
3808 * resource fork file to expose it. */
3809 if (name[filename_length-1] != '/' &&
3810 (r - name < 3 || r[0] != '.' ||
3812 __archive_rb_tree_insert_node(
3813 &zip->tree, &zip_entry->node);
3814 /* Expose its parent directories. */
3815 expose_parent_dirs(zip, name,
3818 /* This file is a resource fork file or
3820 archive_strncpy(&(zip_entry->rsrcname),
3821 name, filename_length);
3822 __archive_rb_tree_insert_node(
3823 &zip->tree_rsrc, &zip_entry->node);
3826 /* Generate resource fork name to find its
3827 * resource file at zip->tree_rsrc. */
3828 archive_strcpy(&(zip_entry->rsrcname),
3830 archive_strncat(&(zip_entry->rsrcname),
3832 archive_strcat(&(zip_entry->rsrcname), "._");
3833 archive_strncat(&(zip_entry->rsrcname),
3835 filename_length - (r - name));
3836 /* Register an entry to RB tree to sort it by
3838 __archive_rb_tree_insert_node(&zip->tree,
3843 /* Skip the comment too ... */
3844 __archive_read_consume(a,
3845 filename_length + extra_length + comment_length);
3852 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3855 ssize_t filename_length, extra_length;
3857 if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3858 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3859 "Truncated ZIP file header");
3860 return (ARCHIVE_WARN);
3864 if (memcmp(p, "PK\003\004", 4) != 0) {
3865 archive_set_error(&a->archive, -1, "Damaged Zip archive");
3866 return ARCHIVE_WARN;
3868 filename_length = archive_le16dec(p + 26);
3869 extra_length = archive_le16dec(p + 28);
3871 return (30 + filename_length + extra_length);
3875 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3876 struct zip_entry *rsrc)
3878 struct zip *zip = (struct zip *)a->format->data;
3879 unsigned char *metadata, *mp;
3880 int64_t offset = archive_filter_bytes(&a->archive, 0);
3881 size_t remaining_bytes, metadata_bytes;
3883 int ret = ARCHIVE_OK, eof;
3885 switch(rsrc->compression) {
3886 case 0: /* No compression. */
3887 if (rsrc->uncompressed_size != rsrc->compressed_size) {
3888 archive_set_error(&a->archive,
3889 ARCHIVE_ERRNO_FILE_FORMAT,
3890 "Malformed OS X metadata entry: "
3891 "inconsistent size");
3892 return (ARCHIVE_FATAL);
3895 case 8: /* Deflate compression. */
3898 default: /* Unsupported compression. */
3899 /* Return a warning. */
3900 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3901 "Unsupported ZIP compression method (%s)",
3902 compression_name(rsrc->compression));
3903 /* We can't decompress this entry, but we will
3904 * be able to skip() it and try the next entry. */
3905 return (ARCHIVE_WARN);
3908 if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
3909 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3910 "Mac metadata is too large: %jd > 4M bytes",
3911 (intmax_t)rsrc->uncompressed_size);
3912 return (ARCHIVE_WARN);
3914 if (rsrc->compressed_size > (4 * 1024 * 1024)) {
3915 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3916 "Mac metadata is too large: %jd > 4M bytes",
3917 (intmax_t)rsrc->compressed_size);
3918 return (ARCHIVE_WARN);
3921 metadata = malloc((size_t)rsrc->uncompressed_size);
3922 if (metadata == NULL) {
3923 archive_set_error(&a->archive, ENOMEM,
3924 "Can't allocate memory for Mac metadata");
3925 return (ARCHIVE_FATAL);
3928 if (offset < rsrc->local_header_offset)
3929 __archive_read_consume(a, rsrc->local_header_offset - offset);
3930 else if (offset != rsrc->local_header_offset) {
3931 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
3934 hsize = zip_get_local_file_header_size(a, 0);
3935 __archive_read_consume(a, hsize);
3937 remaining_bytes = (size_t)rsrc->compressed_size;
3938 metadata_bytes = (size_t)rsrc->uncompressed_size;
3941 while (!eof && remaining_bytes) {
3942 const unsigned char *p;
3943 ssize_t bytes_avail;
3946 p = __archive_read_ahead(a, 1, &bytes_avail);
3948 archive_set_error(&a->archive,
3949 ARCHIVE_ERRNO_FILE_FORMAT,
3950 "Truncated ZIP file header");
3952 goto exit_mac_metadata;
3954 if ((size_t)bytes_avail > remaining_bytes)
3955 bytes_avail = remaining_bytes;
3956 switch(rsrc->compression) {
3957 case 0: /* No compression. */
3958 if ((size_t)bytes_avail > metadata_bytes)
3959 bytes_avail = metadata_bytes;
3960 memcpy(mp, p, bytes_avail);
3961 bytes_used = (size_t)bytes_avail;
3962 metadata_bytes -= bytes_used;
3964 if (metadata_bytes == 0)
3968 case 8: /* Deflate compression. */
3972 ret = zip_deflate_init(a, zip);
3973 if (ret != ARCHIVE_OK)
3974 goto exit_mac_metadata;
3975 zip->stream.next_in =
3976 (Bytef *)(uintptr_t)(const void *)p;
3977 zip->stream.avail_in = (uInt)bytes_avail;
3978 zip->stream.total_in = 0;
3979 zip->stream.next_out = mp;
3980 zip->stream.avail_out = (uInt)metadata_bytes;
3981 zip->stream.total_out = 0;
3983 r = inflate(&zip->stream, 0);
3991 archive_set_error(&a->archive, ENOMEM,
3992 "Out of memory for ZIP decompression");
3993 ret = ARCHIVE_FATAL;
3994 goto exit_mac_metadata;
3996 archive_set_error(&a->archive,
3998 "ZIP decompression failed (%d)", r);
3999 ret = ARCHIVE_FATAL;
4000 goto exit_mac_metadata;
4002 bytes_used = zip->stream.total_in;
4003 metadata_bytes -= zip->stream.total_out;
4004 mp += zip->stream.total_out;
4012 __archive_read_consume(a, bytes_used);
4013 remaining_bytes -= bytes_used;
4015 archive_entry_copy_mac_metadata(entry, metadata,
4016 (size_t)rsrc->uncompressed_size - metadata_bytes);
4019 __archive_read_seek(a, offset, SEEK_SET);
4020 zip->decompress_init = 0;
4026 archive_read_format_zip_seekable_read_header(struct archive_read *a,
4027 struct archive_entry *entry)
4029 struct zip *zip = (struct zip *)a->format->data;
4030 struct zip_entry *rsrc;
4032 int r, ret = ARCHIVE_OK;
4035 * It should be sufficient to call archive_read_next_header() for
4036 * a reader to determine if an entry is encrypted or not. If the
4037 * encryption of an entry is only detectable when calling
4038 * archive_read_data(), so be it. We'll do the same check there
4041 if (zip->has_encrypted_entries ==
4042 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
4043 zip->has_encrypted_entries = 0;
4045 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
4046 if (a->archive.archive_format_name == NULL)
4047 a->archive.archive_format_name = "ZIP";
4049 if (zip->zip_entries == NULL) {
4050 r = slurp_central_directory(a, entry, zip);
4051 if (r != ARCHIVE_OK)
4053 /* Get first entry whose local header offset is lower than
4054 * other entries in the archive file. */
4056 (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
4057 } else if (zip->entry != NULL) {
4058 /* Get next entry in local header offset order. */
4059 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
4060 &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
4063 if (zip->entry == NULL)
4066 if (zip->entry->rsrcname.s)
4067 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
4068 &zip->tree_rsrc, zip->entry->rsrcname.s);
4072 if (zip->cctx_valid)
4073 archive_decrypto_aes_ctr_release(&zip->cctx);
4074 if (zip->hctx_valid)
4075 archive_hmac_sha1_cleanup(&zip->hctx);
4076 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
4077 __archive_read_reset_passphrase(a);
4079 /* File entries are sorted by the header offset, we should mostly
4080 * use __archive_read_consume to advance a read point to avoid
4081 * redundant data reading. */
4082 offset = archive_filter_bytes(&a->archive, 0);
4083 if (offset < zip->entry->local_header_offset)
4084 __archive_read_consume(a,
4085 zip->entry->local_header_offset - offset);
4086 else if (offset != zip->entry->local_header_offset) {
4087 __archive_read_seek(a, zip->entry->local_header_offset,
4090 zip->unconsumed = 0;
4091 r = zip_read_local_file_header(a, entry, zip);
4092 if (r != ARCHIVE_OK)
4095 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
4103 * We're going to seek for the next header anyway, so we don't
4104 * need to bother doing anything here.
4107 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
4110 zip = (struct zip *)(a->format->data);
4112 zip->unconsumed = 0;
4113 return (ARCHIVE_OK);
4117 archive_read_support_format_zip_seekable(struct archive *_a)
4119 struct archive_read *a = (struct archive_read *)_a;
4123 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
4124 ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
4126 zip = (struct zip *)calloc(1, sizeof(*zip));
4128 archive_set_error(&a->archive, ENOMEM,
4129 "Can't allocate zip data");
4130 return (ARCHIVE_FATAL);
4133 #ifdef HAVE_COPYFILE_H
4134 /* Set this by default on Mac OS. */
4135 zip->process_mac_extensions = 1;
4139 * Until enough data has been read, we cannot tell about
4140 * any encrypted entries yet.
4142 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4143 zip->crc32func = real_crc32;
4145 r = __archive_read_register_format(a,
4148 archive_read_format_zip_seekable_bid,
4149 archive_read_format_zip_options,
4150 archive_read_format_zip_seekable_read_header,
4151 archive_read_format_zip_read_data,
4152 archive_read_format_zip_read_data_skip_seekable,
4154 archive_read_format_zip_cleanup,
4155 archive_read_support_format_zip_capabilities_seekable,
4156 archive_read_format_zip_has_encrypted_entries);
4158 if (r != ARCHIVE_OK)
4160 return (ARCHIVE_OK);