2 * Copyright (c) 2004-2013 Tim Kientzle
3 * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
4 * Copyright (c) 2013 Konrad Kleine
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "archive_platform.h"
29 __FBSDID("$FreeBSD: head/lib/libarchive/archive_read_support_format_zip.c 201102 2009-12-28 03:11:36Z kientzle $");
32 * The definitive documentation of the Zip file format is:
33 * http://www.pkware.com/documents/casestudies/APPNOTE.TXT
35 * The Info-Zip project has pioneered various extensions to better
36 * support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
37 * "Ux", and 0x7875 "ux" extensions for time and ownership
40 * History of this code: The streaming Zip reader was first added to
41 * libarchive in January 2005. Support for seekable input sources was
42 * added in Nov 2011. Zip64 support (including a significant code
43 * refactoring) was added in 2014.
66 #include "archive_digest_private.h"
67 #include "archive_cryptor_private.h"
68 #include "archive_endian.h"
69 #include "archive_entry.h"
70 #include "archive_entry_locale.h"
71 #include "archive_hmac_private.h"
72 #include "archive_private.h"
73 #include "archive_rb.h"
74 #include "archive_read_private.h"
75 #include "archive_ppmd8_private.h"
78 #include "archive_crc32.h"
82 struct archive_rb_node node;
83 struct zip_entry *next;
84 int64_t local_header_offset;
85 int64_t compressed_size;
86 int64_t uncompressed_size;
89 struct archive_string rsrcname;
95 uint16_t zip_flags; /* From GP Flags Field */
96 unsigned char compression;
97 unsigned char system; /* From "version written by" */
98 unsigned char flags; /* Our extra markers. */
99 unsigned char decdat;/* Used for Decryption check */
101 /* WinZip AES encryption extra field should be available
102 * when compression is 99. */
104 /* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
106 #define AES_VENDOR_AE_1 0x0001
107 #define AES_VENDOR_AE_2 0x0002
108 /* AES encryption strength:
109 * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
111 /* Actual compression method. */
112 unsigned char compression;
116 struct trad_enc_ctx {
120 /* Bits used in zip_flags. */
121 #define ZIP_ENCRYPTED (1 << 0)
122 #define ZIP_LENGTH_AT_END (1 << 3)
123 #define ZIP_STRONG_ENCRYPTED (1 << 6)
124 #define ZIP_UTF8_NAME (1 << 11)
125 /* See "7.2 Single Password Symmetric Encryption Method"
126 in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
127 #define ZIP_CENTRAL_DIRECTORY_ENCRYPTED (1 << 13)
129 /* Bits used in flags. */
130 #define LA_USED_ZIP64 (1 << 0)
131 #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
134 * See "WinZip - AES Encryption Information"
135 * http://www.winzip.com/aes_info.htm
137 /* Value used in compression method. */
138 #define WINZIP_AES_ENCRYPTION 99
139 /* Authentication code size. */
140 #define AUTH_CODE_SIZE 10
142 #define MAX_DERIVED_KEY_BUF_SIZE (AES_MAX_KEY_SIZE * 2 + 2)
145 /* Structural information about the archive. */
146 struct archive_string format_name;
147 int64_t central_directory_offset;
148 int64_t central_directory_offset_adjusted;
149 size_t central_directory_entries_total;
150 size_t central_directory_entries_on_this_disk;
151 int has_encrypted_entries;
153 /* List of entries (seekable Zip only) */
154 struct zip_entry *zip_entries;
155 struct archive_rb_tree tree;
156 struct archive_rb_tree tree_rsrc;
158 /* Bytes read but not yet consumed via __archive_read_consume() */
161 /* Information about entry we're currently reading. */
162 struct zip_entry *entry;
163 int64_t entry_bytes_remaining;
165 /* These count the number of bytes actually read for the entry. */
166 int64_t entry_compressed_bytes_read;
167 int64_t entry_uncompressed_bytes_read;
169 /* Running CRC32 of the decompressed data */
170 unsigned long entry_crc32;
171 unsigned long (*crc32func)(unsigned long, const void *,
175 /* Flags to mark progress of decompression. */
176 char decompress_init;
179 unsigned char *uncompressed_buffer;
180 size_t uncompressed_buffer_size;
187 #if HAVE_LZMA_H && HAVE_LIBLZMA
188 lzma_stream zipx_lzma_stream;
189 char zipx_lzma_valid;
197 #if HAVE_ZSTD_H && HAVE_LIBZSTD
198 ZSTD_DStream *zstdstream;
199 char zstdstream_valid;
202 IByteIn zipx_ppmd_stream;
203 ssize_t zipx_ppmd_read_compressed;
206 char ppmd8_stream_failed;
208 struct archive_string_conv *sconv;
209 struct archive_string_conv *sconv_default;
210 struct archive_string_conv *sconv_utf8;
211 int init_default_conversion;
212 int process_mac_extensions;
214 char init_decryption;
216 /* Decryption buffer. */
218 * The decrypted data starts at decrypted_ptr and
219 * extends for decrypted_bytes_remaining. Decryption
220 * adds new data to the end of this block, data is returned
221 * to clients from the beginning. When the block hits the
222 * end of decrypted_buffer, it has to be shuffled back to
223 * the beginning of the buffer.
225 unsigned char *decrypted_buffer;
226 unsigned char *decrypted_ptr;
227 size_t decrypted_buffer_size;
228 size_t decrypted_bytes_remaining;
229 size_t decrypted_unconsumed_bytes;
231 /* Traditional PKWARE decryption. */
232 struct trad_enc_ctx tctx;
235 /* WinZip AES decryption. */
236 /* Contexts used for AES decryption. */
237 archive_crypto_ctx cctx;
239 archive_hmac_sha1_ctx hctx;
242 /* Strong encryption's decryption header information. */
255 /* Many systems define min or MIN, but not all. */
256 #define zipmin(a,b) ((a) < (b) ? (a) : (b))
260 zip_read_data_deflate(struct archive_read *a, const void **buff,
261 size_t *size, int64_t *offset);
263 #if HAVE_LZMA_H && HAVE_LIBLZMA
265 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
266 size_t *size, int64_t *offset);
269 /* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8
270 * streams inside ZIP files. It has 2 purposes: one is to fetch the next
271 * compressed byte from the stream, second one is to increase the counter how
272 * many compressed bytes were read. */
275 /* Get the handle to current decompression context. */
276 struct archive_read *a = ((IByteIn*)p)->a;
277 struct zip *zip = (struct zip*) a->format->data;
278 ssize_t bytes_avail = 0;
280 /* Fetch next byte. */
281 const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail);
282 if(bytes_avail < 1) {
283 zip->ppmd8_stream_failed = 1;
287 __archive_read_consume(a, 1);
289 /* Increment the counter. */
290 ++zip->zipx_ppmd_read_compressed;
292 /* Return the next compressed byte. */
296 /* ------------------------------------------------------------------------ */
299 Traditional PKWARE Decryption functions.
303 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
306 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
308 ctx->keys[0] = CRC32(ctx->keys[0], c);
309 ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
310 t = (ctx->keys[1] >> 24) & 0xff;
311 ctx->keys[2] = CRC32(ctx->keys[2], t);
316 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
318 unsigned temp = ctx->keys[2] | 2;
319 return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
323 trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
324 size_t in_len, uint8_t *out, size_t out_len)
328 max = (unsigned)((in_len < out_len)? in_len: out_len);
330 for (i = 0; i < max; i++) {
331 uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
333 trad_enc_update_keys(ctx, t);
338 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
339 const uint8_t *key, size_t key_len, uint8_t *crcchk)
348 ctx->keys[0] = 305419896L;
349 ctx->keys[1] = 591751049L;
350 ctx->keys[2] = 878082192L;
352 for (;pw_len; --pw_len)
353 trad_enc_update_keys(ctx, *pw++);
355 trad_enc_decrypt_update(ctx, key, 12, header, 12);
356 /* Return the last byte for CRC check. */
357 *crcchk = header[11];
363 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
367 archive_sha1_ctx ctx;
368 unsigned char md1[MD_SIZE];
369 unsigned char md2[MD_SIZE * 2];
370 unsigned char mkb[64];
373 archive_sha1_init(&ctx);
374 archive_sha1_update(&ctx, p, size);
375 archive_sha1_final(&ctx, md1);
377 memset(mkb, 0x36, sizeof(mkb));
378 for (i = 0; i < MD_SIZE; i++)
380 archive_sha1_init(&ctx);
381 archive_sha1_update(&ctx, mkb, sizeof(mkb));
382 archive_sha1_final(&ctx, md2);
384 memset(mkb, 0x5C, sizeof(mkb));
385 for (i = 0; i < MD_SIZE; i++)
387 archive_sha1_init(&ctx);
388 archive_sha1_update(&ctx, mkb, sizeof(mkb));
389 archive_sha1_final(&ctx, md2 + MD_SIZE);
393 memcpy(key, md2, key_size);
399 * Common code for streaming or seeking modes.
401 * Includes code to read local file headers, decompress data
402 * from entry bodies, and common API.
406 real_crc32(unsigned long crc, const void *buff, size_t len)
408 return crc32(crc, buff, (unsigned int)len);
411 /* Used by "ignorecrc32" option to speed up tests. */
413 fake_crc32(unsigned long crc, const void *buff, size_t len)
415 (void)crc; /* UNUSED */
416 (void)buff; /* UNUSED */
417 (void)len; /* UNUSED */
421 static const struct {
424 } compression_methods[] = {
425 {0, "uncompressed"}, /* The file is stored (no compression) */
426 {1, "shrinking"}, /* The file is Shrunk */
427 {2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
428 {3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
429 {4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
430 {5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
431 {6, "imploded"}, /* The file is Imploded */
432 {7, "reserved"}, /* Reserved for Tokenizing compression algorithm */
433 {8, "deflation"}, /* The file is Deflated */
434 {9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
435 {10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
437 {11, "reserved"}, /* Reserved by PKWARE */
438 {12, "bzip"}, /* File is compressed using BZIP2 algorithm */
439 {13, "reserved"}, /* Reserved by PKWARE */
440 {14, "lzma"}, /* LZMA (EFS) */
441 {15, "reserved"}, /* Reserved by PKWARE */
442 {16, "reserved"}, /* Reserved by PKWARE */
443 {17, "reserved"}, /* Reserved by PKWARE */
444 {18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
445 {19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
446 {93, "zstd"}, /* Zstandard (zstd) Compression */
447 {95, "xz"}, /* XZ compressed data */
448 {96, "jpeg"}, /* JPEG compressed data */
449 {97, "wav-pack"}, /* WavPack compressed data */
450 {98, "ppmd-1"}, /* PPMd version I, Rev 1 */
451 {99, "aes"} /* WinZip AES encryption */
455 compression_name(const int compression)
457 static const int num_compression_methods =
458 sizeof(compression_methods)/sizeof(compression_methods[0]);
461 while(compression >= 0 && i < num_compression_methods) {
462 if (compression_methods[i].id == compression)
463 return compression_methods[i].name;
469 /* Convert an MSDOS-style date/time into Unix-style time. */
471 zip_time(const char *p)
476 msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
477 msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
479 memset(&ts, 0, sizeof(ts));
480 ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
481 ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
482 ts.tm_mday = msDate & 0x1f; /* Day of month. */
483 ts.tm_hour = (msTime >> 11) & 0x1f;
484 ts.tm_min = (msTime >> 5) & 0x3f;
485 ts.tm_sec = (msTime << 1) & 0x3e;
491 * The extra data is stored as a list of
492 * id1+size1+data1 + id2+size2+data2 ...
493 * triplets. id and size are 2 bytes each.
496 process_extra(struct archive_read *a, struct archive_entry *entry,
497 const char *p, size_t extra_length, struct zip_entry* zip_entry)
500 struct zip *zip = (struct zip *)(a->format->data);
502 if (extra_length == 0) {
506 if (extra_length < 4) {
508 /* Some ZIP files may have trailing 0 bytes. Let's check they
509 * are all 0 and ignore them instead of returning an error.
511 * This is not technically correct, but some ZIP files look
512 * like this and other tools support those files - so let's
515 for (; i < extra_length; i++) {
517 archive_set_error(&a->archive,
518 ARCHIVE_ERRNO_FILE_FORMAT,
519 "Too-small extra data: "
520 "Need at least 4 bytes, "
521 "but only found %d bytes",
523 return ARCHIVE_FAILED;
530 while (offset <= extra_length - 4) {
531 unsigned short headerid = archive_le16dec(p + offset);
532 unsigned short datasize = archive_le16dec(p + offset + 2);
535 if (offset + datasize > extra_length) {
536 archive_set_error(&a->archive,
537 ARCHIVE_ERRNO_FILE_FORMAT, "Extra data overflow: "
538 "Need %d bytes but only found %d bytes",
539 (int)datasize, (int)(extra_length - offset));
540 return ARCHIVE_FAILED;
543 fprintf(stderr, "Header id 0x%04x, length %d\n",
548 /* Zip64 extended information extra field. */
549 zip_entry->flags |= LA_USED_ZIP64;
550 if (zip_entry->uncompressed_size == 0xffffffff) {
553 || (t = archive_le64dec(p + offset)) >
555 archive_set_error(&a->archive,
556 ARCHIVE_ERRNO_FILE_FORMAT,
558 "uncompressed size");
559 return ARCHIVE_FAILED;
561 zip_entry->uncompressed_size = t;
565 if (zip_entry->compressed_size == 0xffffffff) {
568 || (t = archive_le64dec(p + offset)) >
570 archive_set_error(&a->archive,
571 ARCHIVE_ERRNO_FILE_FORMAT,
574 return ARCHIVE_FAILED;
576 zip_entry->compressed_size = t;
580 if (zip_entry->local_header_offset == 0xffffffff) {
583 || (t = archive_le64dec(p + offset)) >
585 archive_set_error(&a->archive,
586 ARCHIVE_ERRNO_FILE_FORMAT,
588 "local header offset");
589 return ARCHIVE_FAILED;
591 zip_entry->local_header_offset = t;
595 /* archive_le32dec(p + offset) gives disk
596 * on which file starts, but we don't handle
597 * multi-volume Zip files. */
602 /* Strong encryption field. */
603 if (archive_le16dec(p + offset) == 2) {
605 archive_le16dec(p + offset + 2);
607 archive_le16dec(p + offset + 4);
609 archive_le16dec(p + offset + 6);
610 fprintf(stderr, "algId=0x%04x, bitLen=%u, "
611 "flgas=%d\n", algId, bitLen,flags);
618 /* Extended time field "UT". */
621 archive_set_error(&a->archive,
622 ARCHIVE_ERRNO_FILE_FORMAT,
623 "Incomplete extended time field");
624 return ARCHIVE_FAILED;
629 /* Flag bits indicate which dates are present. */
633 fprintf(stderr, "mtime: %lld -> %d\n",
634 (long long)zip_entry->mtime,
635 archive_le32dec(p + offset));
639 zip_entry->mtime = archive_le32dec(p + offset);
647 zip_entry->atime = archive_le32dec(p + offset);
655 zip_entry->ctime = archive_le32dec(p + offset);
663 /* Info-ZIP Unix Extra Field (old version) "UX". */
665 zip_entry->atime = archive_le32dec(p + offset);
667 archive_le32dec(p + offset + 4);
669 if (datasize >= 12) {
671 archive_le16dec(p + offset + 8);
673 archive_le16dec(p + offset + 10);
679 /* Experimental 'xl' field */
681 * Introduced Dec 2013 to provide a way to
682 * include external file attributes (and other
683 * fields that ordinarily appear only in
684 * central directory) in local file header.
685 * This provides file type and permission
686 * information necessary to support full
687 * streaming extraction. Currently being
688 * discussed with other Zip developers
689 * ... subject to change.
692 * The field starts with a bitmap that specifies
693 * which additional fields are included. The
694 * bitmap is variable length and can be extended in
697 * n bytes - feature bitmap: first byte has low-order
698 * 7 bits. If high-order bit is set, a subsequent
699 * byte holds the next 7 bits, etc.
701 * if bitmap & 1, 2 byte "version made by"
702 * if bitmap & 2, 2 byte "internal file attributes"
703 * if bitmap & 4, 4 byte "external file attributes"
704 * if bitmap & 8, 2 byte comment length + n byte
707 int bitmap, bitmap_last;
711 bitmap_last = bitmap = 0xff & p[offset];
715 /* We only support first 7 bits of bitmap; skip rest. */
716 while ((bitmap_last & 0x80) != 0
718 bitmap_last = p[offset];
724 /* 2 byte "version made by" */
728 = archive_le16dec(p + offset) >> 8;
733 /* 2 byte "internal file attributes" */
734 uint32_t internal_attributes;
738 = archive_le16dec(p + offset);
739 /* Not used by libarchive at present. */
740 (void)internal_attributes; /* UNUSED */
745 /* 4 byte "external file attributes" */
746 uint32_t external_attributes;
750 = archive_le32dec(p + offset);
751 if (zip_entry->system == 3) {
753 = external_attributes >> 16;
754 } else if (zip_entry->system == 0) {
755 // Interpret MSDOS directory bit
756 if (0x10 == (external_attributes &
764 if (0x01 == (external_attributes &
767 * strip write permissions */
768 zip_entry->mode &= 0555;
777 /* 2 byte comment length + comment */
778 uint32_t comment_length;
782 = archive_le16dec(p + offset);
786 if (datasize < comment_length)
788 /* Comment is not supported by libarchive */
789 offset += comment_length;
790 datasize -= comment_length;
796 /* Info-ZIP Unicode Path Extra Field. */
797 if (datasize < 5 || entry == NULL)
802 /* The path name in this field is always encoded
804 if (zip->sconv_utf8 == NULL) {
806 archive_string_conversion_from_charset(
807 &a->archive, "UTF-8", 1);
808 /* If the converter from UTF-8 is not
809 * available, then the path name from the main
810 * field will more likely be correct. */
811 if (zip->sconv_utf8 == NULL)
815 /* Make sure the CRC32 of the filename matches. */
816 if (!zip->ignore_crc32) {
817 const char *cp = archive_entry_pathname(entry);
819 unsigned long file_crc =
820 zip->crc32func(0, cp, strlen(cp));
821 unsigned long utf_crc =
822 archive_le32dec(p + offset - 4);
823 if (file_crc != utf_crc) {
826 "CRC filename mismatch; "
827 "CDE is %lx, but UTF8 "
828 "is outdated with %lx\n",
836 if (archive_entry_copy_pathname_l(entry,
837 p + offset, datasize, zip->sconv_utf8) != 0) {
838 /* Ignore the error, and fallback to the path
839 * name from the main field. */
841 fprintf(stderr, "Failed to read the ZIP "
842 "0x7075 extra field path.\n");
848 /* Info-ZIP Unix Extra Field (type 2) "Ux". */
850 fprintf(stderr, "uid %d gid %d\n",
851 archive_le16dec(p + offset),
852 archive_le16dec(p + offset + 2));
855 zip_entry->uid = archive_le16dec(p + offset);
858 archive_le16dec(p + offset + 2);
862 /* Info-Zip Unix Extra Field (type 3) "ux". */
863 int uidsize = 0, gidsize = 0;
865 /* TODO: support arbitrary uidsize/gidsize. */
866 if (datasize >= 1 && p[offset] == 1) {/* version=1 */
868 /* get a uid size. */
869 uidsize = 0xff & (int)p[offset+1];
874 else if (uidsize == 4 && datasize >= 6)
879 if (datasize >= (2 + uidsize + 3)) {
880 /* get a gid size. */
882 (int)p[offset+2+uidsize];
886 p+offset+2+uidsize+1);
887 else if (gidsize == 4 &&
888 datasize >= (2 + uidsize + 5))
891 p+offset+2+uidsize+1);
897 /* WinZip AES extra data field. */
899 archive_set_error(&a->archive,
900 ARCHIVE_ERRNO_FILE_FORMAT,
901 "Incomplete AES field");
902 return ARCHIVE_FAILED;
904 if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
905 /* Vendor version. */
906 zip_entry->aes_extra.vendor =
907 archive_le16dec(p + offset);
908 /* AES encryption strength. */
909 zip_entry->aes_extra.strength = p[offset + 4];
910 /* Actual compression method. */
911 zip_entry->aes_extra.compression =
924 * Assumes file pointer is at beginning of local file header.
927 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
934 size_t len, filename_length, extra_length;
935 struct archive_string_conv *sconv;
936 struct zip_entry *zip_entry = zip->entry;
937 struct zip_entry zip_entry_central_dir;
938 int ret = ARCHIVE_OK;
941 /* Save a copy of the original for consistency checks. */
942 zip_entry_central_dir = *zip_entry;
944 zip->decompress_init = 0;
945 zip->end_of_entry = 0;
946 zip->entry_uncompressed_bytes_read = 0;
947 zip->entry_compressed_bytes_read = 0;
948 zip->entry_crc32 = zip->crc32func(0, NULL, 0);
950 /* Setup default conversion. */
951 if (zip->sconv == NULL && !zip->init_default_conversion) {
953 archive_string_default_conversion_for_read(&(a->archive));
954 zip->init_default_conversion = 1;
957 if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
958 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
959 "Truncated ZIP file header");
960 return (ARCHIVE_FATAL);
963 if (memcmp(p, "PK\003\004", 4) != 0) {
964 archive_set_error(&a->archive, -1, "Damaged Zip archive");
965 return ARCHIVE_FATAL;
968 zip_entry->system = p[5];
969 zip_entry->zip_flags = archive_le16dec(p + 6);
970 if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
971 zip->has_encrypted_entries = 1;
972 archive_entry_set_is_data_encrypted(entry, 1);
973 if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
974 zip_entry->zip_flags & ZIP_ENCRYPTED &&
975 zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
976 archive_entry_set_is_metadata_encrypted(entry, 1);
977 return ARCHIVE_FATAL;
980 zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
981 zip_entry->compression = (char)archive_le16dec(p + 8);
982 zip_entry->mtime = zip_time(p + 10);
983 zip_entry->crc32 = archive_le32dec(p + 14);
984 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
985 zip_entry->decdat = p[11];
987 zip_entry->decdat = p[17];
988 zip_entry->compressed_size = archive_le32dec(p + 18);
989 zip_entry->uncompressed_size = archive_le32dec(p + 22);
990 filename_length = archive_le16dec(p + 26);
991 extra_length = archive_le16dec(p + 28);
993 __archive_read_consume(a, 30);
995 /* Read the filename. */
996 if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
997 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
998 "Truncated ZIP file header");
999 return (ARCHIVE_FATAL);
1001 if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
1002 /* The filename is stored to be UTF-8. */
1003 if (zip->sconv_utf8 == NULL) {
1005 archive_string_conversion_from_charset(
1006 &a->archive, "UTF-8", 1);
1007 if (zip->sconv_utf8 == NULL)
1008 return (ARCHIVE_FATAL);
1010 sconv = zip->sconv_utf8;
1011 } else if (zip->sconv != NULL)
1014 sconv = zip->sconv_default;
1016 if (archive_entry_copy_pathname_l(entry,
1017 h, filename_length, sconv) != 0) {
1018 if (errno == ENOMEM) {
1019 archive_set_error(&a->archive, ENOMEM,
1020 "Can't allocate memory for Pathname");
1021 return (ARCHIVE_FATAL);
1023 archive_set_error(&a->archive,
1024 ARCHIVE_ERRNO_FILE_FORMAT,
1025 "Pathname cannot be converted "
1026 "from %s to current locale.",
1027 archive_string_conversion_charset_name(sconv));
1030 __archive_read_consume(a, filename_length);
1032 /* Read the extra data. */
1033 if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
1034 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1035 "Truncated ZIP file header");
1036 return (ARCHIVE_FATAL);
1039 if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
1041 return ARCHIVE_FATAL;
1043 __archive_read_consume(a, extra_length);
1045 /* Work around a bug in Info-Zip: When reading from a pipe, it
1046 * stats the pipe instead of synthesizing a file entry. */
1047 if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
1048 zip_entry->mode &= ~ AE_IFMT;
1049 zip_entry->mode |= AE_IFREG;
1052 /* If the mode is totally empty, set some sane default. */
1053 if (zip_entry->mode == 0) {
1054 zip_entry->mode |= 0664;
1057 /* Windows archivers sometimes use backslash as the directory
1058 * separator. Normalize to slash. */
1059 if (zip_entry->system == 0 &&
1060 (wp = archive_entry_pathname_w(entry)) != NULL) {
1061 if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
1063 struct archive_wstring s;
1064 archive_string_init(&s);
1065 archive_wstrcpy(&s, wp);
1066 for (i = 0; i < archive_strlen(&s); i++) {
1070 archive_entry_copy_pathname_w(entry, s.s);
1071 archive_wstring_free(&s);
1075 /* Make sure that entries with a trailing '/' are marked as directories
1076 * even if the External File Attributes contains bogus values. If this
1077 * is not a directory and there is no type, assume a regular file. */
1078 if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
1081 wp = archive_entry_pathname_w(entry);
1084 has_slash = len > 0 && wp[len - 1] == L'/';
1086 cp = archive_entry_pathname(entry);
1087 len = (cp != NULL)?strlen(cp):0;
1088 has_slash = len > 0 && cp[len - 1] == '/';
1090 /* Correct file type as needed. */
1092 zip_entry->mode &= ~AE_IFMT;
1093 zip_entry->mode |= AE_IFDIR;
1094 zip_entry->mode |= 0111;
1095 } else if ((zip_entry->mode & AE_IFMT) == 0) {
1096 zip_entry->mode |= AE_IFREG;
1100 /* Make sure directories end in '/' */
1101 if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
1102 wp = archive_entry_pathname_w(entry);
1105 if (len > 0 && wp[len - 1] != L'/') {
1106 struct archive_wstring s;
1107 archive_string_init(&s);
1108 archive_wstrcat(&s, wp);
1109 archive_wstrappend_wchar(&s, L'/');
1110 archive_entry_copy_pathname_w(entry, s.s);
1111 archive_wstring_free(&s);
1114 cp = archive_entry_pathname(entry);
1115 len = (cp != NULL)?strlen(cp):0;
1116 if (len > 0 && cp[len - 1] != '/') {
1117 struct archive_string s;
1118 archive_string_init(&s);
1119 archive_strcat(&s, cp);
1120 archive_strappend_char(&s, '/');
1121 archive_entry_set_pathname(entry, s.s);
1122 archive_string_free(&s);
1127 if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1128 /* If this came from the central dir, its size info
1129 * is definitive, so ignore the length-at-end flag. */
1130 zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1131 /* If local header is missing a value, use the one from
1132 the central directory. If both have it, warn about
1134 if (zip_entry->crc32 == 0) {
1135 zip_entry->crc32 = zip_entry_central_dir.crc32;
1136 } else if (!zip->ignore_crc32
1137 && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1138 archive_set_error(&a->archive,
1139 ARCHIVE_ERRNO_FILE_FORMAT,
1140 "Inconsistent CRC32 values");
1143 if (zip_entry->compressed_size == 0) {
1144 zip_entry->compressed_size
1145 = zip_entry_central_dir.compressed_size;
1146 } else if (zip_entry->compressed_size
1147 != zip_entry_central_dir.compressed_size) {
1148 archive_set_error(&a->archive,
1149 ARCHIVE_ERRNO_FILE_FORMAT,
1150 "Inconsistent compressed size: "
1151 "%jd in central directory, %jd in local header",
1152 (intmax_t)zip_entry_central_dir.compressed_size,
1153 (intmax_t)zip_entry->compressed_size);
1156 if (zip_entry->uncompressed_size == 0 ||
1157 zip_entry->uncompressed_size == 0xffffffff) {
1158 zip_entry->uncompressed_size
1159 = zip_entry_central_dir.uncompressed_size;
1160 } else if (zip_entry->uncompressed_size
1161 != zip_entry_central_dir.uncompressed_size) {
1162 archive_set_error(&a->archive,
1163 ARCHIVE_ERRNO_FILE_FORMAT,
1164 "Inconsistent uncompressed size: "
1165 "%jd in central directory, %jd in local header",
1166 (intmax_t)zip_entry_central_dir.uncompressed_size,
1167 (intmax_t)zip_entry->uncompressed_size);
1172 /* Populate some additional entry fields: */
1173 archive_entry_set_mode(entry, zip_entry->mode);
1174 archive_entry_set_uid(entry, zip_entry->uid);
1175 archive_entry_set_gid(entry, zip_entry->gid);
1176 archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1177 archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1178 archive_entry_set_atime(entry, zip_entry->atime, 0);
1180 if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1181 size_t linkname_length;
1183 if (zip_entry->compressed_size > 64 * 1024) {
1184 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1185 "Zip file with oversized link entry");
1186 return ARCHIVE_FATAL;
1189 linkname_length = (size_t)zip_entry->compressed_size;
1191 archive_entry_set_size(entry, 0);
1193 // take into account link compression if any
1194 size_t linkname_full_length = linkname_length;
1195 if (zip->entry->compression != 0)
1197 // symlink target string appeared to be compressed
1198 int status = ARCHIVE_FATAL;
1199 const void *uncompressed_buffer = NULL;
1201 switch (zip->entry->compression)
1204 case 8: /* Deflate compression. */
1205 zip->entry_bytes_remaining = zip_entry->compressed_size;
1206 status = zip_read_data_deflate(a, &uncompressed_buffer,
1207 &linkname_full_length, NULL);
1210 #if HAVE_LZMA_H && HAVE_LIBLZMA
1211 case 14: /* ZIPx LZMA compression. */
1212 /*(see zip file format specification, section 4.4.5)*/
1213 zip->entry_bytes_remaining = zip_entry->compressed_size;
1214 status = zip_read_data_zipx_lzma_alone(a, &uncompressed_buffer,
1215 &linkname_full_length, NULL);
1218 default: /* Unsupported compression. */
1221 if (status == ARCHIVE_OK)
1223 p = uncompressed_buffer;
1227 archive_set_error(&a->archive,
1228 ARCHIVE_ERRNO_FILE_FORMAT,
1229 "Unsupported ZIP compression method "
1230 "during decompression of link entry (%d: %s)",
1231 zip->entry->compression,
1232 compression_name(zip->entry->compression));
1233 return ARCHIVE_FAILED;
1238 p = __archive_read_ahead(a, linkname_length, NULL);
1242 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1243 "Truncated Zip file");
1244 return ARCHIVE_FATAL;
1248 if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1249 sconv = zip->sconv_utf8;
1251 sconv = zip->sconv_default;
1252 if (archive_entry_copy_symlink_l(entry, p, linkname_full_length,
1254 if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1255 (zip->entry->zip_flags & ZIP_UTF8_NAME))
1256 archive_entry_copy_symlink_l(entry, p,
1257 linkname_full_length, NULL);
1258 if (errno == ENOMEM) {
1259 archive_set_error(&a->archive, ENOMEM,
1260 "Can't allocate memory for Symlink");
1261 return (ARCHIVE_FATAL);
1264 * Since there is no character-set regulation for
1265 * symlink name, do not report the conversion error
1266 * in an automatic conversion.
1268 if (sconv != zip->sconv_utf8 ||
1269 (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1270 archive_set_error(&a->archive,
1271 ARCHIVE_ERRNO_FILE_FORMAT,
1272 "Symlink cannot be converted "
1273 "from %s to current locale.",
1274 archive_string_conversion_charset_name(
1279 zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1281 if (__archive_read_consume(a, linkname_length) < 0) {
1282 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1283 "Read error skipping symlink target name");
1284 return ARCHIVE_FATAL;
1286 } else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1287 || zip_entry->uncompressed_size > 0) {
1288 /* Set the size only if it's meaningful. */
1289 archive_entry_set_size(entry, zip_entry->uncompressed_size);
1291 zip->entry_bytes_remaining = zip_entry->compressed_size;
1293 /* If there's no body, force read_data() to return EOF immediately. */
1294 if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1295 && zip->entry_bytes_remaining < 1)
1296 zip->end_of_entry = 1;
1298 /* Set up a more descriptive format name. */
1299 archive_string_empty(&zip->format_name);
1300 archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1301 version / 10, version % 10,
1302 compression_name(zip->entry->compression));
1303 a->archive.archive_format_name = zip->format_name.s;
1309 check_authentication_code(struct archive_read *a, const void *_p)
1311 struct zip *zip = (struct zip *)(a->format->data);
1313 /* Check authentication code. */
1314 if (zip->hctx_valid) {
1317 size_t hmac_len = 20;
1320 archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1322 /* Read authentication code. */
1323 p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1325 archive_set_error(&a->archive,
1326 ARCHIVE_ERRNO_FILE_FORMAT,
1327 "Truncated ZIP file data");
1328 return (ARCHIVE_FATAL);
1333 cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1334 __archive_read_consume(a, AUTH_CODE_SIZE);
1336 archive_set_error(&a->archive,
1338 "ZIP bad Authentication code");
1339 return (ARCHIVE_WARN);
1342 return (ARCHIVE_OK);
1346 * Read "uncompressed" data. There are three cases:
1347 * 1) We know the size of the data. This is always true for the
1348 * seeking reader (we've examined the Central Directory already).
1349 * 2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1350 * Info-ZIP seems to do this; we know the size but have to grab
1351 * the CRC from the data descriptor afterwards.
1352 * 3) We're streaming and ZIP_LENGTH_AT_END was specified and
1353 * we have no size information. In this case, we can do pretty
1354 * well by watching for the data descriptor record. The data
1355 * descriptor is 16 bytes and includes a computed CRC that should
1356 * provide a strong check.
1358 * TODO: Technically, the PK\007\010 signature is optional.
1359 * In the original spec, the data descriptor contained CRC
1360 * and size fields but had no leading signature. In practice,
1361 * newer writers seem to provide the signature pretty consistently.
1363 * For uncompressed data, the PK\007\010 marker seems essential
1364 * to be sure we've actually seen the end of the entry.
1366 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1367 * zip->end_of_entry if it consumes all of the data.
1370 zip_read_data_none(struct archive_read *a, const void **_buff,
1371 size_t *size, int64_t *offset)
1375 ssize_t bytes_avail;
1378 (void)offset; /* UNUSED */
1380 zip = (struct zip *)(a->format->data);
1382 if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1384 ssize_t grabbing_bytes = 24;
1386 if (zip->hctx_valid)
1387 grabbing_bytes += AUTH_CODE_SIZE;
1388 /* Grab at least 24 bytes. */
1389 buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1390 if (bytes_avail < grabbing_bytes) {
1391 /* Zip archives have end-of-archive markers
1392 that are longer than this, so a failure to get at
1393 least 24 bytes really does indicate a truncated
1395 archive_set_error(&a->archive,
1396 ARCHIVE_ERRNO_FILE_FORMAT,
1397 "Truncated ZIP file data");
1398 return (ARCHIVE_FATAL);
1400 /* Check for a complete PK\007\010 signature, followed
1401 * by the correct 4-byte CRC. */
1403 if (zip->hctx_valid)
1404 p += AUTH_CODE_SIZE;
1405 if (p[0] == 'P' && p[1] == 'K'
1406 && p[2] == '\007' && p[3] == '\010'
1407 && (archive_le32dec(p + 4) == zip->entry_crc32
1408 || zip->ignore_crc32
1410 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1411 if (zip->entry->flags & LA_USED_ZIP64) {
1412 uint64_t compressed, uncompressed;
1413 zip->entry->crc32 = archive_le32dec(p + 4);
1414 compressed = archive_le64dec(p + 8);
1415 uncompressed = archive_le64dec(p + 16);
1416 if (compressed > INT64_MAX || uncompressed >
1418 archive_set_error(&a->archive,
1419 ARCHIVE_ERRNO_FILE_FORMAT,
1420 "Overflow of 64-bit file sizes");
1421 return ARCHIVE_FAILED;
1423 zip->entry->compressed_size = compressed;
1424 zip->entry->uncompressed_size = uncompressed;
1425 zip->unconsumed = 24;
1427 zip->entry->crc32 = archive_le32dec(p + 4);
1428 zip->entry->compressed_size =
1429 archive_le32dec(p + 8);
1430 zip->entry->uncompressed_size =
1431 archive_le32dec(p + 12);
1432 zip->unconsumed = 16;
1434 if (zip->hctx_valid) {
1435 r = check_authentication_code(a, buff);
1436 if (r != ARCHIVE_OK)
1439 zip->end_of_entry = 1;
1440 return (ARCHIVE_OK);
1442 /* If not at EOF, ensure we consume at least one byte. */
1445 /* Scan forward until we see where a PK\007\010 signature
1447 /* Return bytes up until that point. On the next call,
1448 * the code above will verify the data descriptor. */
1449 while (p < buff + bytes_avail - 4) {
1450 if (p[3] == 'P') { p += 3; }
1451 else if (p[3] == 'K') { p += 2; }
1452 else if (p[3] == '\007') { p += 1; }
1453 else if (p[3] == '\010' && p[2] == '\007'
1454 && p[1] == 'K' && p[0] == 'P') {
1455 if (zip->hctx_valid)
1456 p -= AUTH_CODE_SIZE;
1460 bytes_avail = p - buff;
1462 if (zip->entry_bytes_remaining == 0) {
1463 zip->end_of_entry = 1;
1464 if (zip->hctx_valid) {
1465 r = check_authentication_code(a, NULL);
1466 if (r != ARCHIVE_OK)
1469 return (ARCHIVE_OK);
1471 /* Grab a bunch of bytes. */
1472 buff = __archive_read_ahead(a, 1, &bytes_avail);
1473 if (bytes_avail <= 0) {
1474 archive_set_error(&a->archive,
1475 ARCHIVE_ERRNO_FILE_FORMAT,
1476 "Truncated ZIP file data");
1477 return (ARCHIVE_FATAL);
1479 if (bytes_avail > zip->entry_bytes_remaining)
1480 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1482 if (zip->tctx_valid || zip->cctx_valid) {
1483 size_t dec_size = bytes_avail;
1485 if (dec_size > zip->decrypted_buffer_size)
1486 dec_size = zip->decrypted_buffer_size;
1487 if (zip->tctx_valid) {
1488 trad_enc_decrypt_update(&zip->tctx,
1489 (const uint8_t *)buff, dec_size,
1490 zip->decrypted_buffer, dec_size);
1492 size_t dsize = dec_size;
1493 archive_hmac_sha1_update(&zip->hctx,
1494 (const uint8_t *)buff, dec_size);
1495 archive_decrypto_aes_ctr_update(&zip->cctx,
1496 (const uint8_t *)buff, dec_size,
1497 zip->decrypted_buffer, &dsize);
1499 bytes_avail = dec_size;
1500 buff = (const char *)zip->decrypted_buffer;
1502 *size = bytes_avail;
1503 zip->entry_bytes_remaining -= bytes_avail;
1504 zip->entry_uncompressed_bytes_read += bytes_avail;
1505 zip->entry_compressed_bytes_read += bytes_avail;
1506 zip->unconsumed += bytes_avail;
1508 return (ARCHIVE_OK);
1512 consume_optional_marker(struct archive_read *a, struct zip *zip)
1514 if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1517 if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1518 archive_set_error(&a->archive,
1519 ARCHIVE_ERRNO_FILE_FORMAT,
1520 "Truncated ZIP end-of-file record");
1521 return (ARCHIVE_FATAL);
1523 /* Consume the optional PK\007\010 marker. */
1524 if (p[0] == 'P' && p[1] == 'K' &&
1525 p[2] == '\007' && p[3] == '\010') {
1527 zip->unconsumed = 4;
1529 if (zip->entry->flags & LA_USED_ZIP64) {
1530 uint64_t compressed, uncompressed;
1531 zip->entry->crc32 = archive_le32dec(p);
1532 compressed = archive_le64dec(p + 4);
1533 uncompressed = archive_le64dec(p + 12);
1534 if (compressed > INT64_MAX ||
1535 uncompressed > INT64_MAX) {
1536 archive_set_error(&a->archive,
1537 ARCHIVE_ERRNO_FILE_FORMAT,
1538 "Overflow of 64-bit file sizes");
1539 return ARCHIVE_FAILED;
1541 zip->entry->compressed_size = compressed;
1542 zip->entry->uncompressed_size = uncompressed;
1543 zip->unconsumed += 20;
1545 zip->entry->crc32 = archive_le32dec(p);
1546 zip->entry->compressed_size = archive_le32dec(p + 4);
1547 zip->entry->uncompressed_size = archive_le32dec(p + 8);
1548 zip->unconsumed += 12;
1552 return (ARCHIVE_OK);
1555 #if HAVE_LZMA_H && HAVE_LIBLZMA
1557 zipx_xz_init(struct archive_read *a, struct zip *zip)
1561 if(zip->zipx_lzma_valid) {
1562 lzma_end(&zip->zipx_lzma_stream);
1563 zip->zipx_lzma_valid = 0;
1566 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1567 r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1569 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1570 "xz initialization failed(%d)",
1573 return (ARCHIVE_FAILED);
1576 zip->zipx_lzma_valid = 1;
1578 free(zip->uncompressed_buffer);
1580 zip->uncompressed_buffer_size = 256 * 1024;
1581 zip->uncompressed_buffer =
1582 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1583 if (zip->uncompressed_buffer == NULL) {
1584 archive_set_error(&a->archive, ENOMEM,
1585 "No memory for xz decompression");
1586 return (ARCHIVE_FATAL);
1589 zip->decompress_init = 1;
1590 return (ARCHIVE_OK);
1594 zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1601 struct _alone_header {
1603 uint64_t uncompressed_size;
1607 if(zip->zipx_lzma_valid) {
1608 lzma_end(&zip->zipx_lzma_stream);
1609 zip->zipx_lzma_valid = 0;
1612 /* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
1613 * that is a part of XZ Utils. The stream format stored inside ZIPX
1614 * file is a modified "lzma alone" file format, that was used by the
1615 * `lzma` utility which was later deprecated in favour of `xz` utility.
1616 * Since those formats are nearly the same, we can use a standard
1617 * "lzma alone" decoder from XZ Utils. */
1619 memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1620 r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1622 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1623 "lzma initialization failed(%d)", r);
1625 return (ARCHIVE_FAILED);
1628 /* Flag the cleanup function that we want our lzma-related structures
1629 * to be freed later. */
1630 zip->zipx_lzma_valid = 1;
1632 /* The "lzma alone" file format and the stream format inside ZIPx are
1633 * almost the same. Here's an example of a structure of "lzma alone"
1636 * $ cat /bin/ls | lzma | xxd | head -n 1
1637 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1639 * 5 bytes 8 bytes n bytes
1640 * <lzma_params><uncompressed_size><data...>
1642 * lzma_params is a 5-byte blob that has to be decoded to extract
1643 * parameters of this LZMA stream. The uncompressed_size field is an
1644 * uint64_t value that contains information about the size of the
1645 * uncompressed file, or UINT64_MAX if this value is unknown.
1646 * The <data...> part is the actual lzma-compressed data stream.
1648 * Now here's the structure of the stream inside the ZIPX file:
1650 * $ cat stream_inside_zipx | xxd | head -n 1
1651 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1653 * 2byte 2byte 5 bytes n bytes
1654 * <magic1><magic2><lzma_params><data...>
1656 * This means that the ZIPX file contains an additional magic1 and
1657 * magic2 headers, the lzma_params field contains the same parameter
1658 * set as in the "lzma alone" format, and the <data...> field is the
1659 * same as in the "lzma alone" format as well. Note that also the zipx
1660 * format is missing the uncompressed_size field.
1662 * So, in order to use the "lzma alone" decoder for the zipx lzma
1663 * stream, we simply need to shuffle around some fields, prepare a new
1664 * lzma alone header, feed it into lzma alone decoder so it will
1665 * initialize itself properly, and then we can start feeding normal
1666 * zipx lzma stream into the decoder.
1669 /* Read magic1,magic2,lzma_params from the ZIPX stream. */
1670 if(zip->entry_bytes_remaining < 9 || (p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1671 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1672 "Truncated lzma data");
1673 return (ARCHIVE_FATAL);
1676 if(p[2] != 0x05 || p[3] != 0x00) {
1677 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1678 "Invalid lzma data");
1679 return (ARCHIVE_FATAL);
1682 /* Prepare an lzma alone header: copy the lzma_params blob into
1683 * a proper place into the lzma alone header. */
1684 memcpy(&alone_header.bytes[0], p + 4, 5);
1686 /* Initialize the 'uncompressed size' field to unknown; we'll manually
1687 * monitor how many bytes there are still to be uncompressed. */
1688 alone_header.uncompressed_size = UINT64_MAX;
1690 if(!zip->uncompressed_buffer) {
1691 zip->uncompressed_buffer_size = 256 * 1024;
1692 zip->uncompressed_buffer =
1693 (uint8_t*) malloc(zip->uncompressed_buffer_size);
1695 if (zip->uncompressed_buffer == NULL) {
1696 archive_set_error(&a->archive, ENOMEM,
1697 "No memory for lzma decompression");
1698 return (ARCHIVE_FATAL);
1702 zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1703 zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1704 zip->zipx_lzma_stream.total_in = 0;
1705 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1706 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1707 zip->zipx_lzma_stream.total_out = 0;
1709 /* Feed only the header into the lzma alone decoder. This will
1710 * effectively initialize the decoder, and will not produce any
1711 * output bytes yet. */
1712 r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1714 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1715 "lzma stream initialization error");
1716 return ARCHIVE_FATAL;
1719 /* We've already consumed some bytes, so take this into account. */
1720 __archive_read_consume(a, 9);
1721 zip->entry_bytes_remaining -= 9;
1722 zip->entry_compressed_bytes_read += 9;
1724 zip->decompress_init = 1;
1725 return (ARCHIVE_OK);
1729 zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1730 size_t *size, int64_t *offset)
1732 struct zip* zip = (struct zip *)(a->format->data);
1735 const void* compressed_buf;
1736 ssize_t bytes_avail, in_bytes, to_consume = 0;
1738 (void) offset; /* UNUSED */
1740 /* Initialize decompressor if not yet initialized. */
1741 if (!zip->decompress_init) {
1742 ret = zipx_xz_init(a, zip);
1743 if (ret != ARCHIVE_OK)
1747 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1748 if (bytes_avail < 0) {
1749 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1750 "Truncated xz file body");
1751 return (ARCHIVE_FATAL);
1754 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1755 zip->zipx_lzma_stream.next_in = compressed_buf;
1756 zip->zipx_lzma_stream.avail_in = in_bytes;
1757 zip->zipx_lzma_stream.total_in = 0;
1758 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1759 zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1760 zip->zipx_lzma_stream.total_out = 0;
1762 /* Perform the decompression. */
1763 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1765 case LZMA_DATA_ERROR:
1766 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1767 "xz data error (error %d)", (int) lz_ret);
1768 return (ARCHIVE_FATAL);
1775 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1776 "xz unknown error %d", (int) lz_ret);
1777 return (ARCHIVE_FATAL);
1779 case LZMA_STREAM_END:
1780 lzma_end(&zip->zipx_lzma_stream);
1781 zip->zipx_lzma_valid = 0;
1783 if((int64_t) zip->zipx_lzma_stream.total_in !=
1784 zip->entry_bytes_remaining)
1786 archive_set_error(&a->archive,
1788 "xz premature end of stream");
1789 return (ARCHIVE_FATAL);
1792 zip->end_of_entry = 1;
1796 to_consume = zip->zipx_lzma_stream.total_in;
1798 __archive_read_consume(a, to_consume);
1799 zip->entry_bytes_remaining -= to_consume;
1800 zip->entry_compressed_bytes_read += to_consume;
1801 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1803 *size = zip->zipx_lzma_stream.total_out;
1804 *buff = zip->uncompressed_buffer;
1806 ret = consume_optional_marker(a, zip);
1807 if (ret != ARCHIVE_OK)
1810 return (ARCHIVE_OK);
1814 zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1815 size_t *size, int64_t *offset)
1817 struct zip* zip = (struct zip *)(a->format->data);
1820 const void* compressed_buf;
1821 ssize_t bytes_avail, in_bytes, to_consume;
1823 (void) offset; /* UNUSED */
1825 /* Initialize decompressor if not yet initialized. */
1826 if (!zip->decompress_init) {
1827 ret = zipx_lzma_alone_init(a, zip);
1828 if (ret != ARCHIVE_OK)
1832 /* Fetch more compressed data. The same note as in deflate handler
1833 * applies here as well:
1835 * Note: '1' here is a performance optimization. Recall that the
1836 * decompression layer returns a count of available bytes; asking for
1837 * more than that forces the decompressor to combine reads by copying
1840 compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1841 if (bytes_avail < 0) {
1842 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1843 "Truncated lzma file body");
1844 return (ARCHIVE_FATAL);
1847 /* Set decompressor parameters. */
1848 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1850 zip->zipx_lzma_stream.next_in = compressed_buf;
1851 zip->zipx_lzma_stream.avail_in = in_bytes;
1852 zip->zipx_lzma_stream.total_in = 0;
1853 zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1854 zip->zipx_lzma_stream.avail_out =
1855 /* These lzma_alone streams lack end of stream marker, so let's
1856 * make sure the unpacker won't try to unpack more than it's
1858 zipmin((int64_t) zip->uncompressed_buffer_size,
1859 zip->entry->uncompressed_size -
1860 zip->entry_uncompressed_bytes_read);
1861 zip->zipx_lzma_stream.total_out = 0;
1863 /* Perform the decompression. */
1864 lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1866 case LZMA_DATA_ERROR:
1867 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1868 "lzma data error (error %d)", (int) lz_ret);
1869 return (ARCHIVE_FATAL);
1871 /* This case is optional in lzma alone format. It can happen,
1872 * but most of the files don't have it. (GitHub #1257) */
1873 case LZMA_STREAM_END:
1874 lzma_end(&zip->zipx_lzma_stream);
1875 zip->zipx_lzma_valid = 0;
1876 if((int64_t) zip->zipx_lzma_stream.total_in !=
1877 zip->entry_bytes_remaining)
1879 archive_set_error(&a->archive,
1881 "lzma alone premature end of stream");
1882 return (ARCHIVE_FATAL);
1885 zip->end_of_entry = 1;
1892 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1893 "lzma unknown error %d", (int) lz_ret);
1894 return (ARCHIVE_FATAL);
1897 to_consume = zip->zipx_lzma_stream.total_in;
1899 /* Update pointers. */
1900 __archive_read_consume(a, to_consume);
1901 zip->entry_bytes_remaining -= to_consume;
1902 zip->entry_compressed_bytes_read += to_consume;
1903 zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1905 if(zip->entry_bytes_remaining == 0) {
1906 zip->end_of_entry = 1;
1909 /* Return values. */
1910 *size = zip->zipx_lzma_stream.total_out;
1911 *buff = zip->uncompressed_buffer;
1913 /* Behave the same way as during deflate decompression. */
1914 ret = consume_optional_marker(a, zip);
1915 if (ret != ARCHIVE_OK)
1918 /* Free lzma decoder handle because we'll no longer need it. */
1919 if(zip->end_of_entry) {
1920 lzma_end(&zip->zipx_lzma_stream);
1921 zip->zipx_lzma_valid = 0;
1924 /* If we're here, then we're good! */
1925 return (ARCHIVE_OK);
1927 #endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1930 zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1936 uint32_t restore_method;
1938 /* Remove previous decompression context if it exists. */
1939 if(zip->ppmd8_valid) {
1940 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1941 zip->ppmd8_valid = 0;
1944 /* Create a new decompression context. */
1945 __archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1946 zip->ppmd8_stream_failed = 0;
1948 /* Setup function pointers required by Ppmd8 decompressor. The
1949 * 'ppmd_read' function will feed new bytes to the decompressor,
1950 * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
1951 zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
1952 zip->zipx_ppmd_stream.a = a;
1953 zip->zipx_ppmd_stream.Read = &ppmd_read;
1955 /* Reset number of read bytes to 0. */
1956 zip->zipx_ppmd_read_compressed = 0;
1958 /* Read Ppmd8 header (2 bytes). */
1959 p = __archive_read_ahead(a, 2, NULL);
1961 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1962 "Truncated file data in PPMd8 stream");
1963 return (ARCHIVE_FATAL);
1965 __archive_read_consume(a, 2);
1967 /* Decode the stream's compression parameters. */
1968 val = archive_le16dec(p);
1969 order = (val & 15) + 1;
1970 mem = ((val >> 4) & 0xff) + 1;
1971 restore_method = (val >> 12);
1973 if(order < 2 || restore_method > 2) {
1974 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1975 "Invalid parameter set in PPMd8 stream (order=%" PRId32 ", "
1976 "restore=%" PRId32 ")", order, restore_method);
1977 return (ARCHIVE_FAILED);
1980 /* Allocate the memory needed to properly decompress the file. */
1981 if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
1982 archive_set_error(&a->archive, ENOMEM,
1983 "Unable to allocate memory for PPMd8 stream: %" PRId32 " bytes",
1985 return (ARCHIVE_FATAL);
1988 /* Signal the cleanup function to release Ppmd8 context in the
1990 zip->ppmd8_valid = 1;
1992 /* Perform further Ppmd8 initialization. */
1993 if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
1994 archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1995 "PPMd8 stream range decoder initialization error");
1996 return (ARCHIVE_FATAL);
1999 __archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
2002 /* Allocate the buffer that will hold uncompressed data. */
2003 free(zip->uncompressed_buffer);
2005 zip->uncompressed_buffer_size = 256 * 1024;
2006 zip->uncompressed_buffer =
2007 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2009 if(zip->uncompressed_buffer == NULL) {
2010 archive_set_error(&a->archive, ENOMEM,
2011 "No memory for PPMd8 decompression");
2012 return ARCHIVE_FATAL;
2015 /* Ppmd8 initialization is done. */
2016 zip->decompress_init = 1;
2018 /* We've already read 2 bytes in the output stream. Additionally,
2019 * Ppmd8 initialization code could read some data as well. So we
2020 * are advancing the stream by 2 bytes plus whatever number of
2021 * bytes Ppmd8 init function used. */
2022 zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
2028 zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
2029 size_t *size, int64_t *offset)
2031 struct zip* zip = (struct zip *)(a->format->data);
2033 size_t consumed_bytes = 0;
2034 ssize_t bytes_avail = 0;
2036 (void) offset; /* UNUSED */
2038 /* If we're here for the first time, initialize Ppmd8 decompression
2040 if(!zip->decompress_init) {
2041 ret = zipx_ppmd8_init(a, zip);
2042 if(ret != ARCHIVE_OK)
2046 /* Fetch for more data. We're reading 1 byte here, but libarchive
2047 * should prefetch more bytes. */
2048 (void) __archive_read_ahead(a, 1, &bytes_avail);
2049 if(bytes_avail < 0) {
2050 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2051 "Truncated PPMd8 file body");
2052 return (ARCHIVE_FATAL);
2055 /* This counter will be updated inside ppmd_read(), which at one
2056 * point will be called by Ppmd8_DecodeSymbol. */
2057 zip->zipx_ppmd_read_compressed = 0;
2059 /* Decompression loop. */
2061 int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
2064 zip->end_of_entry = 1;
2068 /* This field is set by ppmd_read() when there was no more data
2070 if(zip->ppmd8_stream_failed) {
2071 archive_set_error(&a->archive,
2072 ARCHIVE_ERRNO_FILE_FORMAT,
2073 "Truncated PPMd8 file body");
2074 return (ARCHIVE_FATAL);
2077 zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
2079 } while(consumed_bytes < zip->uncompressed_buffer_size);
2081 /* Update pointers for libarchive. */
2082 *buff = zip->uncompressed_buffer;
2083 *size = consumed_bytes;
2085 /* Update pointers so we can continue decompression in another call. */
2086 zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
2087 zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
2088 zip->entry_uncompressed_bytes_read += consumed_bytes;
2090 /* If we're at the end of stream, deinitialize Ppmd8 context. */
2091 if(zip->end_of_entry) {
2092 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2093 zip->ppmd8_valid = 0;
2096 /* Seek for optional marker, same way as in each zip entry. */
2097 ret = consume_optional_marker(a, zip);
2098 if (ret != ARCHIVE_OK)
2106 zipx_bzip2_init(struct archive_read *a, struct zip *zip)
2110 /* Deallocate already existing BZ2 decompression context if it
2112 if(zip->bzstream_valid) {
2113 BZ2_bzDecompressEnd(&zip->bzstream);
2114 zip->bzstream_valid = 0;
2117 /* Allocate a new BZ2 decompression context. */
2118 memset(&zip->bzstream, 0, sizeof(bz_stream));
2119 r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
2121 archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
2122 "bzip2 initialization failed(%d)",
2125 return ARCHIVE_FAILED;
2128 /* Mark the bzstream field to be released in cleanup phase. */
2129 zip->bzstream_valid = 1;
2131 /* (Re)allocate the buffer that will contain decompressed bytes. */
2132 free(zip->uncompressed_buffer);
2134 zip->uncompressed_buffer_size = 256 * 1024;
2135 zip->uncompressed_buffer =
2136 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2137 if (zip->uncompressed_buffer == NULL) {
2138 archive_set_error(&a->archive, ENOMEM,
2139 "No memory for bzip2 decompression");
2140 return ARCHIVE_FATAL;
2143 /* Initialization done. */
2144 zip->decompress_init = 1;
2149 zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
2150 size_t *size, int64_t *offset)
2152 struct zip *zip = (struct zip *)(a->format->data);
2153 ssize_t bytes_avail = 0, in_bytes, to_consume;
2154 const void *compressed_buff;
2158 (void) offset; /* UNUSED */
2160 /* Initialize decompression context if we're here for the first time. */
2161 if(!zip->decompress_init) {
2162 r = zipx_bzip2_init(a, zip);
2167 /* Fetch more compressed bytes. */
2168 compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2169 if(bytes_avail < 0) {
2170 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2171 "Truncated bzip2 file body");
2172 return (ARCHIVE_FATAL);
2175 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2177 /* libbz2 doesn't complain when caller feeds avail_in == 0.
2178 * It will actually return success in this case, which is
2179 * undesirable. This is why we need to make this check
2182 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2183 "Truncated bzip2 file body");
2184 return (ARCHIVE_FATAL);
2187 /* Setup buffer boundaries. */
2188 zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
2189 zip->bzstream.avail_in = in_bytes;
2190 zip->bzstream.total_in_hi32 = 0;
2191 zip->bzstream.total_in_lo32 = 0;
2192 zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2193 zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2194 zip->bzstream.total_out_hi32 = 0;
2195 zip->bzstream.total_out_lo32 = 0;
2197 /* Perform the decompression. */
2198 r = BZ2_bzDecompress(&zip->bzstream);
2201 /* If we're at the end of the stream, deinitialize the
2202 * decompression context now. */
2203 switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2207 archive_set_error(&a->archive,
2209 "Failed to clean up bzip2 "
2211 return ARCHIVE_FATAL;
2214 zip->end_of_entry = 1;
2217 /* The decompressor has successfully decoded this
2218 * chunk of data, but more data is still in queue. */
2221 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2222 "bzip2 decompression failed");
2223 return ARCHIVE_FATAL;
2226 /* Update the pointers so decompressor can continue decoding. */
2227 to_consume = zip->bzstream.total_in_lo32;
2228 __archive_read_consume(a, to_consume);
2230 total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2231 zip->bzstream.total_out_lo32;
2233 zip->entry_bytes_remaining -= to_consume;
2234 zip->entry_compressed_bytes_read += to_consume;
2235 zip->entry_uncompressed_bytes_read += total_out;
2237 /* Give libarchive its due. */
2239 *buff = zip->uncompressed_buffer;
2241 /* Seek for optional marker, like in other entries. */
2242 r = consume_optional_marker(a, zip);
2251 #if HAVE_ZSTD_H && HAVE_LIBZSTD
2253 zipx_zstd_init(struct archive_read *a, struct zip *zip)
2257 /* Deallocate already existing Zstd decompression context if it
2259 if(zip->zstdstream_valid) {
2260 ZSTD_freeDStream(zip->zstdstream);
2261 zip->zstdstream_valid = 0;
2264 /* Allocate a new Zstd decompression context. */
2265 zip->zstdstream = ZSTD_createDStream();
2267 r = ZSTD_initDStream(zip->zstdstream);
2268 if (ZSTD_isError(r)) {
2269 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2270 "Error initializing zstd decompressor: %s",
2271 ZSTD_getErrorName(r));
2273 return ARCHIVE_FAILED;
2276 /* Mark the zstdstream field to be released in cleanup phase. */
2277 zip->zstdstream_valid = 1;
2279 /* (Re)allocate the buffer that will contain decompressed bytes. */
2280 free(zip->uncompressed_buffer);
2282 zip->uncompressed_buffer_size = ZSTD_DStreamOutSize();
2283 zip->uncompressed_buffer =
2284 (uint8_t*) malloc(zip->uncompressed_buffer_size);
2285 if (zip->uncompressed_buffer == NULL) {
2286 archive_set_error(&a->archive, ENOMEM,
2287 "No memory for Zstd decompression");
2289 return ARCHIVE_FATAL;
2292 /* Initialization done. */
2293 zip->decompress_init = 1;
2298 zip_read_data_zipx_zstd(struct archive_read *a, const void **buff,
2299 size_t *size, int64_t *offset)
2301 struct zip *zip = (struct zip *)(a->format->data);
2302 ssize_t bytes_avail = 0, in_bytes, to_consume;
2303 const void *compressed_buff;
2310 (void) offset; /* UNUSED */
2312 /* Initialize decompression context if we're here for the first time. */
2313 if(!zip->decompress_init) {
2314 r = zipx_zstd_init(a, zip);
2319 /* Fetch more compressed bytes */
2320 compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2321 if(bytes_avail < 0) {
2322 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2323 "Truncated zstd file body");
2324 return (ARCHIVE_FATAL);
2327 in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2329 /* zstd doesn't complain when caller feeds avail_in == 0.
2330 * It will actually return success in this case, which is
2331 * undesirable. This is why we need to make this check
2333 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2334 "Truncated zstd file body");
2335 return (ARCHIVE_FATAL);
2338 /* Setup buffer boundaries */
2339 in.src = compressed_buff;
2342 out = (ZSTD_outBuffer) { zip->uncompressed_buffer, zip->uncompressed_buffer_size, 0 };
2344 /* Perform the decompression. */
2345 ret = ZSTD_decompressStream(zip->zstdstream, &out, &in);
2346 if (ZSTD_isError(ret)) {
2347 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2348 "Error during zstd decompression: %s",
2349 ZSTD_getErrorName(ret));
2350 return (ARCHIVE_FATAL);
2353 /* Check end of the stream. */
2355 if ((in.pos == in.size) && (out.pos < out.size)) {
2356 zip->end_of_entry = 1;
2357 ZSTD_freeDStream(zip->zstdstream);
2358 zip->zstdstream_valid = 0;
2362 /* Update the pointers so decompressor can continue decoding. */
2363 to_consume = in.pos;
2364 __archive_read_consume(a, to_consume);
2366 total_out = out.pos;
2368 zip->entry_bytes_remaining -= to_consume;
2369 zip->entry_compressed_bytes_read += to_consume;
2370 zip->entry_uncompressed_bytes_read += total_out;
2372 /* Give libarchive its due. */
2374 *buff = zip->uncompressed_buffer;
2376 /* Seek for optional marker, like in other entries. */
2377 r = consume_optional_marker(a, zip);
2387 zip_deflate_init(struct archive_read *a, struct zip *zip)
2391 /* If we haven't yet read any data, initialize the decompressor. */
2392 if (!zip->decompress_init) {
2393 if (zip->stream_valid)
2394 r = inflateReset(&zip->stream);
2396 r = inflateInit2(&zip->stream,
2397 -15 /* Don't check for zlib header */);
2399 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2400 "Can't initialize ZIP decompression.");
2401 return (ARCHIVE_FATAL);
2403 /* Stream structure has been set up. */
2404 zip->stream_valid = 1;
2405 /* We've initialized decompression for this stream. */
2406 zip->decompress_init = 1;
2408 return (ARCHIVE_OK);
2412 zip_read_data_deflate(struct archive_read *a, const void **buff,
2413 size_t *size, int64_t *offset)
2416 ssize_t bytes_avail;
2417 const void *compressed_buff, *sp;
2420 (void)offset; /* UNUSED */
2422 zip = (struct zip *)(a->format->data);
2424 /* If the buffer hasn't been allocated, allocate it now. */
2425 if (zip->uncompressed_buffer == NULL) {
2426 zip->uncompressed_buffer_size = 256 * 1024;
2427 zip->uncompressed_buffer
2428 = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2429 if (zip->uncompressed_buffer == NULL) {
2430 archive_set_error(&a->archive, ENOMEM,
2431 "No memory for ZIP decompression");
2432 return (ARCHIVE_FATAL);
2436 r = zip_deflate_init(a, zip);
2437 if (r != ARCHIVE_OK)
2441 * Note: '1' here is a performance optimization.
2442 * Recall that the decompression layer returns a count of
2443 * available bytes; asking for more than that forces the
2444 * decompressor to combine reads by copying data.
2446 compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2447 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2448 && bytes_avail > zip->entry_bytes_remaining) {
2449 bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2451 if (bytes_avail < 0) {
2452 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2453 "Truncated ZIP file body");
2454 return (ARCHIVE_FATAL);
2457 if (zip->tctx_valid || zip->cctx_valid) {
2458 if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2459 size_t buff_remaining =
2460 (zip->decrypted_buffer +
2461 zip->decrypted_buffer_size)
2462 - (zip->decrypted_ptr +
2463 zip->decrypted_bytes_remaining);
2465 if (buff_remaining > (size_t)bytes_avail)
2466 buff_remaining = (size_t)bytes_avail;
2468 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2469 zip->entry_bytes_remaining > 0) {
2470 if ((int64_t)(zip->decrypted_bytes_remaining
2472 > zip->entry_bytes_remaining) {
2473 if (zip->entry_bytes_remaining <
2474 (int64_t)zip->decrypted_bytes_remaining)
2478 (size_t)zip->entry_bytes_remaining
2479 - zip->decrypted_bytes_remaining;
2482 if (buff_remaining > 0) {
2483 if (zip->tctx_valid) {
2484 trad_enc_decrypt_update(&zip->tctx,
2485 compressed_buff, buff_remaining,
2487 + zip->decrypted_bytes_remaining,
2490 size_t dsize = buff_remaining;
2491 archive_decrypto_aes_ctr_update(
2493 compressed_buff, buff_remaining,
2495 + zip->decrypted_bytes_remaining,
2498 zip->decrypted_bytes_remaining +=
2502 bytes_avail = zip->decrypted_bytes_remaining;
2503 compressed_buff = (const char *)zip->decrypted_ptr;
2507 * A bug in zlib.h: stream.next_in should be marked 'const'
2508 * but isn't (the library never alters data through the
2509 * next_in pointer, only reads it). The result: this ugly
2510 * cast to remove 'const'.
2512 zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2513 zip->stream.avail_in = (uInt)bytes_avail;
2514 zip->stream.total_in = 0;
2515 zip->stream.next_out = zip->uncompressed_buffer;
2516 zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2517 zip->stream.total_out = 0;
2519 r = inflate(&zip->stream, 0);
2524 zip->end_of_entry = 1;
2527 archive_set_error(&a->archive, ENOMEM,
2528 "Out of memory for ZIP decompression");
2529 return (ARCHIVE_FATAL);
2531 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2532 "ZIP decompression failed (%d)", r);
2533 return (ARCHIVE_FATAL);
2536 /* Consume as much as the compressor actually used. */
2537 bytes_avail = zip->stream.total_in;
2538 if (zip->tctx_valid || zip->cctx_valid) {
2539 zip->decrypted_bytes_remaining -= bytes_avail;
2540 if (zip->decrypted_bytes_remaining == 0)
2541 zip->decrypted_ptr = zip->decrypted_buffer;
2543 zip->decrypted_ptr += bytes_avail;
2545 /* Calculate compressed data as much as we used.*/
2546 if (zip->hctx_valid)
2547 archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2548 __archive_read_consume(a, bytes_avail);
2549 zip->entry_bytes_remaining -= bytes_avail;
2550 zip->entry_compressed_bytes_read += bytes_avail;
2552 *size = zip->stream.total_out;
2553 zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2554 *buff = zip->uncompressed_buffer;
2556 if (zip->end_of_entry && zip->hctx_valid) {
2557 r = check_authentication_code(a, NULL);
2558 if (r != ARCHIVE_OK)
2562 r = consume_optional_marker(a, zip);
2563 if (r != ARCHIVE_OK)
2566 return (ARCHIVE_OK);
2571 read_decryption_header(struct archive_read *a)
2573 struct zip *zip = (struct zip *)(a->format->data);
2575 unsigned int remaining_size;
2579 * Read an initialization vector data field.
2581 p = __archive_read_ahead(a, 2, NULL);
2585 zip->iv_size = archive_le16dec(p);
2586 __archive_read_consume(a, 2);
2587 if (ts < zip->iv_size) {
2591 p = __archive_read_ahead(a, zip->iv_size, NULL);
2594 if (zip->iv == NULL) {
2595 zip->iv = malloc(zip->iv_size);
2596 if (zip->iv == NULL)
2599 memcpy(zip->iv, p, zip->iv_size);
2600 __archive_read_consume(a, zip->iv_size);
2603 * Read a size of remaining decryption header field.
2605 p = __archive_read_ahead(a, 14, NULL);
2608 remaining_size = archive_le32dec(p);
2609 if (remaining_size < 16 || remaining_size > (1 << 18))
2612 /* Check if format version is supported. */
2613 if (archive_le16dec(p+4) != 3) {
2614 archive_set_error(&a->archive,
2615 ARCHIVE_ERRNO_FILE_FORMAT,
2616 "Unsupported encryption format version: %u",
2617 archive_le16dec(p+4));
2618 return (ARCHIVE_FAILED);
2622 * Read an encryption algorithm field.
2624 zip->alg_id = archive_le16dec(p+6);
2625 switch (zip->alg_id) {
2626 case 0x6601:/* DES */
2627 case 0x6602:/* RC2 */
2628 case 0x6603:/* 3DES 168 */
2629 case 0x6609:/* 3DES 112 */
2630 case 0x660E:/* AES 128 */
2631 case 0x660F:/* AES 192 */
2632 case 0x6610:/* AES 256 */
2633 case 0x6702:/* RC2 (version >= 5.2) */
2634 case 0x6720:/* Blowfish */
2635 case 0x6721:/* Twofish */
2636 case 0x6801:/* RC4 */
2637 /* Supported encryption algorithm. */
2640 archive_set_error(&a->archive,
2641 ARCHIVE_ERRNO_FILE_FORMAT,
2642 "Unknown encryption algorithm: %u", zip->alg_id);
2643 return (ARCHIVE_FAILED);
2647 * Read a bit length field.
2649 zip->bit_len = archive_le16dec(p+8);
2652 * Read a flags field.
2654 zip->flags = archive_le16dec(p+10);
2655 switch (zip->flags & 0xf000) {
2656 case 0x0001: /* Password is required to decrypt. */
2657 case 0x0002: /* Certificates only. */
2658 case 0x0003: /* Password or certificate required to decrypt. */
2661 archive_set_error(&a->archive,
2662 ARCHIVE_ERRNO_FILE_FORMAT,
2663 "Unknown encryption flag: %u", zip->flags);
2664 return (ARCHIVE_FAILED);
2666 if ((zip->flags & 0xf000) == 0 ||
2667 (zip->flags & 0xf000) == 0x4000) {
2668 archive_set_error(&a->archive,
2669 ARCHIVE_ERRNO_FILE_FORMAT,
2670 "Unknown encryption flag: %u", zip->flags);
2671 return (ARCHIVE_FAILED);
2675 * Read an encrypted random data field.
2678 zip->erd_size = archive_le16dec(p+12);
2679 __archive_read_consume(a, 14);
2680 if ((zip->erd_size & 0xf) != 0 ||
2681 (zip->erd_size + 16) > remaining_size ||
2682 (zip->erd_size + 16) < zip->erd_size)
2685 if (ts < zip->erd_size) {
2689 p = __archive_read_ahead(a, zip->erd_size, NULL);
2692 if (zip->erd == NULL) {
2693 zip->erd = malloc(zip->erd_size);
2694 if (zip->erd == NULL)
2697 memcpy(zip->erd, p, zip->erd_size);
2698 __archive_read_consume(a, zip->erd_size);
2701 * Read a reserved data field.
2703 p = __archive_read_ahead(a, 4, NULL);
2706 /* Reserved data size should be zero. */
2707 if (archive_le32dec(p) != 0)
2709 __archive_read_consume(a, 4);
2712 * Read a password validation data field.
2714 p = __archive_read_ahead(a, 2, NULL);
2718 zip->v_size = archive_le16dec(p);
2719 __archive_read_consume(a, 2);
2720 if ((zip->v_size & 0x0f) != 0 ||
2721 (zip->erd_size + zip->v_size + 16) > remaining_size ||
2722 (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2724 if (ts < zip->v_size) {
2728 p = __archive_read_ahead(a, zip->v_size, NULL);
2731 if (zip->v_data == NULL) {
2732 zip->v_data = malloc(zip->v_size);
2733 if (zip->v_data == NULL)
2736 memcpy(zip->v_data, p, zip->v_size);
2737 __archive_read_consume(a, zip->v_size);
2739 p = __archive_read_ahead(a, 4, NULL);
2742 zip->v_crc32 = archive_le32dec(p);
2743 __archive_read_consume(a, 4);
2745 /*return (ARCHIVE_OK);
2746 * This is not fully implemented yet.*/
2747 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2748 "Encrypted file is unsupported");
2749 return (ARCHIVE_FAILED);
2751 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2752 "Truncated ZIP file data");
2753 return (ARCHIVE_FATAL);
2755 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2756 "Corrupted ZIP file data");
2757 return (ARCHIVE_FATAL);
2759 archive_set_error(&a->archive, ENOMEM,
2760 "No memory for ZIP decryption");
2761 return (ARCHIVE_FATAL);
2765 zip_alloc_decryption_buffer(struct archive_read *a)
2767 struct zip *zip = (struct zip *)(a->format->data);
2768 size_t bs = 256 * 1024;
2770 if (zip->decrypted_buffer == NULL) {
2771 zip->decrypted_buffer_size = bs;
2772 zip->decrypted_buffer = malloc(bs);
2773 if (zip->decrypted_buffer == NULL) {
2774 archive_set_error(&a->archive, ENOMEM,
2775 "No memory for ZIP decryption");
2776 return (ARCHIVE_FATAL);
2779 zip->decrypted_ptr = zip->decrypted_buffer;
2780 return (ARCHIVE_OK);
2784 init_traditional_PKWARE_decryption(struct archive_read *a)
2786 struct zip *zip = (struct zip *)(a->format->data);
2791 if (zip->tctx_valid)
2792 return (ARCHIVE_OK);
2795 Read the 12 bytes encryption header stored at
2796 the start of the data area.
2798 #define ENC_HEADER_SIZE 12
2799 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2800 && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2801 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2802 "Truncated Zip encrypted body: only %jd bytes available",
2803 (intmax_t)zip->entry_bytes_remaining);
2804 return (ARCHIVE_FATAL);
2807 p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2809 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2810 "Truncated ZIP file data");
2811 return (ARCHIVE_FATAL);
2814 for (retry = 0;; retry++) {
2815 const char *passphrase;
2818 passphrase = __archive_read_next_passphrase(a);
2819 if (passphrase == NULL) {
2820 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2822 "Incorrect passphrase":
2823 "Passphrase required for this entry");
2824 return (ARCHIVE_FAILED);
2828 * Initialize ctx for Traditional PKWARE Decryption.
2830 r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2831 p, ENC_HEADER_SIZE, &crcchk);
2832 if (r == 0 && crcchk == zip->entry->decdat)
2833 break;/* The passphrase is OK. */
2834 if (retry > 10000) {
2835 /* Avoid infinity loop. */
2836 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2837 "Too many incorrect passphrases");
2838 return (ARCHIVE_FAILED);
2842 __archive_read_consume(a, ENC_HEADER_SIZE);
2843 zip->tctx_valid = 1;
2844 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2845 zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2847 /*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2848 zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2849 zip->decrypted_bytes_remaining = 0;
2851 return (zip_alloc_decryption_buffer(a));
2852 #undef ENC_HEADER_SIZE
2856 init_WinZip_AES_decryption(struct archive_read *a)
2858 struct zip *zip = (struct zip *)(a->format->data);
2861 size_t key_len, salt_len;
2862 uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2866 if (zip->cctx_valid || zip->hctx_valid)
2867 return (ARCHIVE_OK);
2869 switch (zip->entry->aes_extra.strength) {
2870 case 1: salt_len = 8; key_len = 16; break;
2871 case 2: salt_len = 12; key_len = 24; break;
2872 case 3: salt_len = 16; key_len = 32; break;
2873 default: goto corrupted;
2875 p = __archive_read_ahead(a, salt_len + 2, NULL);
2879 for (retry = 0;; retry++) {
2880 const char *passphrase;
2882 passphrase = __archive_read_next_passphrase(a);
2883 if (passphrase == NULL) {
2884 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2886 "Incorrect passphrase":
2887 "Passphrase required for this entry");
2888 return (ARCHIVE_FAILED);
2890 memset(derived_key, 0, sizeof(derived_key));
2891 r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2892 p, salt_len, 1000, derived_key, key_len * 2 + 2);
2894 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2895 "Decryption is unsupported due to lack of "
2897 return (ARCHIVE_FAILED);
2900 /* Check password verification value. */
2901 pv = ((const uint8_t *)p) + salt_len;
2902 if (derived_key[key_len * 2] == pv[0] &&
2903 derived_key[key_len * 2 + 1] == pv[1])
2904 break;/* The passphrase is OK. */
2905 if (retry > 10000) {
2906 /* Avoid infinity loop. */
2907 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2908 "Too many incorrect passphrases");
2909 return (ARCHIVE_FAILED);
2913 r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2915 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2916 "Decryption is unsupported due to lack of crypto library");
2917 return (ARCHIVE_FAILED);
2919 r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2921 archive_decrypto_aes_ctr_release(&zip->cctx);
2922 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2923 "Failed to initialize HMAC-SHA1");
2924 return (ARCHIVE_FAILED);
2926 zip->cctx_valid = zip->hctx_valid = 1;
2927 __archive_read_consume(a, salt_len + 2);
2928 zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2929 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2930 && zip->entry_bytes_remaining < 0)
2932 zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2933 zip->decrypted_bytes_remaining = 0;
2935 zip->entry->compression = zip->entry->aes_extra.compression;
2936 return (zip_alloc_decryption_buffer(a));
2939 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2940 "Truncated ZIP file data");
2941 return (ARCHIVE_FATAL);
2943 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2944 "Corrupted ZIP file data");
2945 return (ARCHIVE_FATAL);
2949 archive_read_format_zip_read_data(struct archive_read *a,
2950 const void **buff, size_t *size, int64_t *offset)
2953 struct zip *zip = (struct zip *)(a->format->data);
2955 if (zip->has_encrypted_entries ==
2956 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2957 zip->has_encrypted_entries = 0;
2960 *offset = zip->entry_uncompressed_bytes_read;
2964 /* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2965 if (zip->end_of_entry)
2966 return (ARCHIVE_EOF);
2968 /* Return EOF immediately if this is a non-regular file. */
2969 if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2970 return (ARCHIVE_EOF);
2972 __archive_read_consume(a, zip->unconsumed);
2973 zip->unconsumed = 0;
2975 if (zip->init_decryption) {
2976 zip->has_encrypted_entries = 1;
2977 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2978 r = read_decryption_header(a);
2979 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2980 r = init_WinZip_AES_decryption(a);
2982 r = init_traditional_PKWARE_decryption(a);
2983 if (r != ARCHIVE_OK)
2985 zip->init_decryption = 0;
2988 switch(zip->entry->compression) {
2989 case 0: /* No compression. */
2990 r = zip_read_data_none(a, buff, size, offset);
2993 case 12: /* ZIPx bzip2 compression. */
2994 r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2997 #if HAVE_LZMA_H && HAVE_LIBLZMA
2998 case 14: /* ZIPx LZMA compression. */
2999 r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
3001 case 95: /* ZIPx XZ compression. */
3002 r = zip_read_data_zipx_xz(a, buff, size, offset);
3005 #if HAVE_ZSTD_H && HAVE_LIBZSTD
3006 case 93: /* ZIPx Zstd compression. */
3007 r = zip_read_data_zipx_zstd(a, buff, size, offset);
3010 /* PPMd support is built-in, so we don't need any #if guards. */
3011 case 98: /* ZIPx PPMd compression. */
3012 r = zip_read_data_zipx_ppmd(a, buff, size, offset);
3016 case 8: /* Deflate compression. */
3017 r = zip_read_data_deflate(a, buff, size, offset);
3020 default: /* Unsupported compression. */
3021 /* Return a warning. */
3022 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3023 "Unsupported ZIP compression method (%d: %s)",
3024 zip->entry->compression, compression_name(zip->entry->compression));
3025 /* We can't decompress this entry, but we will
3026 * be able to skip() it and try the next entry. */
3027 return (ARCHIVE_FAILED);
3030 if (r != ARCHIVE_OK)
3032 /* Update checksum */
3034 zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
3036 /* If we hit the end, swallow any end-of-data marker. */
3037 if (zip->end_of_entry) {
3038 /* Check file size, CRC against these values. */
3039 if (zip->entry->compressed_size !=
3040 zip->entry_compressed_bytes_read) {
3041 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3042 "ZIP compressed data is wrong size "
3043 "(read %jd, expected %jd)",
3044 (intmax_t)zip->entry_compressed_bytes_read,
3045 (intmax_t)zip->entry->compressed_size);
3046 return (ARCHIVE_WARN);
3048 /* Size field only stores the lower 32 bits of the actual
3050 if ((zip->entry->uncompressed_size & UINT32_MAX)
3051 != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
3052 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3053 "ZIP uncompressed data is wrong size "
3054 "(read %jd, expected %jd)\n",
3055 (intmax_t)zip->entry_uncompressed_bytes_read,
3056 (intmax_t)zip->entry->uncompressed_size);
3057 return (ARCHIVE_WARN);
3059 /* Check computed CRC against header */
3060 if ((!zip->hctx_valid ||
3061 zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
3062 zip->entry->crc32 != zip->entry_crc32
3063 && !zip->ignore_crc32) {
3064 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3065 "ZIP bad CRC: 0x%lx should be 0x%lx",
3066 (unsigned long)zip->entry_crc32,
3067 (unsigned long)zip->entry->crc32);
3068 return (ARCHIVE_WARN);
3072 return (ARCHIVE_OK);
3076 archive_read_format_zip_cleanup(struct archive_read *a)
3079 struct zip_entry *zip_entry, *next_zip_entry;
3081 zip = (struct zip *)(a->format->data);
3084 if (zip->stream_valid)
3085 inflateEnd(&zip->stream);
3088 #if HAVE_LZMA_H && HAVE_LIBLZMA
3089 if (zip->zipx_lzma_valid) {
3090 lzma_end(&zip->zipx_lzma_stream);
3095 if (zip->bzstream_valid) {
3096 BZ2_bzDecompressEnd(&zip->bzstream);
3100 #if HAVE_ZSTD_H && HAVE_LIBZSTD
3101 if (zip->zstdstream_valid) {
3102 ZSTD_freeDStream(zip->zstdstream);
3106 free(zip->uncompressed_buffer);
3108 if (zip->ppmd8_valid)
3109 __archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
3111 if (zip->zip_entries) {
3112 zip_entry = zip->zip_entries;
3113 while (zip_entry != NULL) {
3114 next_zip_entry = zip_entry->next;
3115 archive_string_free(&zip_entry->rsrcname);
3117 zip_entry = next_zip_entry;
3120 free(zip->decrypted_buffer);
3121 if (zip->cctx_valid)
3122 archive_decrypto_aes_ctr_release(&zip->cctx);
3123 if (zip->hctx_valid)
3124 archive_hmac_sha1_cleanup(&zip->hctx);
3128 archive_string_free(&zip->format_name);
3130 (a->format->data) = NULL;
3131 return (ARCHIVE_OK);
3135 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
3137 if (_a && _a->format) {
3138 struct zip * zip = (struct zip *)_a->format->data;
3140 return zip->has_encrypted_entries;
3143 return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3147 archive_read_format_zip_options(struct archive_read *a,
3148 const char *key, const char *val)
3151 int ret = ARCHIVE_FAILED;
3153 zip = (struct zip *)(a->format->data);
3154 if (strcmp(key, "compat-2x") == 0) {
3155 /* Handle filenames as libarchive 2.x */
3156 zip->init_default_conversion = (val != NULL) ? 1 : 0;
3157 return (ARCHIVE_OK);
3158 } else if (strcmp(key, "hdrcharset") == 0) {
3159 if (val == NULL || val[0] == 0)
3160 archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3161 "zip: hdrcharset option needs a character-set name"
3164 zip->sconv = archive_string_conversion_from_charset(
3165 &a->archive, val, 0);
3166 if (zip->sconv != NULL) {
3167 if (strcmp(val, "UTF-8") == 0)
3168 zip->sconv_utf8 = zip->sconv;
3171 ret = ARCHIVE_FATAL;
3174 } else if (strcmp(key, "ignorecrc32") == 0) {
3175 /* Mostly useful for testing. */
3176 if (val == NULL || val[0] == 0) {
3177 zip->crc32func = real_crc32;
3178 zip->ignore_crc32 = 0;
3180 zip->crc32func = fake_crc32;
3181 zip->ignore_crc32 = 1;
3183 return (ARCHIVE_OK);
3184 } else if (strcmp(key, "mac-ext") == 0) {
3185 zip->process_mac_extensions = (val != NULL && val[0] != 0);
3186 return (ARCHIVE_OK);
3189 /* Note: The "warn" return is just to inform the options
3190 * supervisor that we didn't handle it. It will generate
3191 * a suitable error if no one used this option. */
3192 return (ARCHIVE_WARN);
3196 archive_read_support_format_zip(struct archive *a)
3199 r = archive_read_support_format_zip_streamable(a);
3200 if (r != ARCHIVE_OK)
3202 return (archive_read_support_format_zip_seekable(a));
3205 /* ------------------------------------------------------------------------ */
3208 * Streaming-mode support
3213 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
3215 (void)a; /* UNUSED */
3216 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3217 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3221 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
3225 (void)best_bid; /* UNUSED */
3227 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3231 * Bid of 29 here comes from:
3232 * + 16 bits for "PK",
3233 * + next 16-bit field has 6 options so contributes
3234 * about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
3236 * So we've effectively verified ~29 total bits of check data.
3238 if (p[0] == 'P' && p[1] == 'K') {
3239 if ((p[2] == '\001' && p[3] == '\002')
3240 || (p[2] == '\003' && p[3] == '\004')
3241 || (p[2] == '\005' && p[3] == '\006')
3242 || (p[2] == '\006' && p[3] == '\006')
3243 || (p[2] == '\007' && p[3] == '\010')
3244 || (p[2] == '0' && p[3] == '0'))
3248 /* TODO: It's worth looking ahead a little bit for a valid
3249 * PK signature. In particular, that would make it possible
3250 * to read some UUEncoded SFX files or SFX files coming from
3251 * a network socket. */
3257 archive_read_format_zip_streamable_read_header(struct archive_read *a,
3258 struct archive_entry *entry)
3262 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3263 if (a->archive.archive_format_name == NULL)
3264 a->archive.archive_format_name = "ZIP";
3266 zip = (struct zip *)(a->format->data);
3269 * It should be sufficient to call archive_read_next_header() for
3270 * a reader to determine if an entry is encrypted or not. If the
3271 * encryption of an entry is only detectable when calling
3272 * archive_read_data(), so be it. We'll do the same check there
3275 if (zip->has_encrypted_entries ==
3276 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3277 zip->has_encrypted_entries = 0;
3279 /* Make sure we have a zip_entry structure to use. */
3280 if (zip->zip_entries == NULL) {
3281 zip->zip_entries = malloc(sizeof(struct zip_entry));
3282 if (zip->zip_entries == NULL) {
3283 archive_set_error(&a->archive, ENOMEM,
3285 return ARCHIVE_FATAL;
3288 zip->entry = zip->zip_entries;
3289 memset(zip->entry, 0, sizeof(struct zip_entry));
3291 if (zip->cctx_valid)
3292 archive_decrypto_aes_ctr_release(&zip->cctx);
3293 if (zip->hctx_valid)
3294 archive_hmac_sha1_cleanup(&zip->hctx);
3295 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3296 __archive_read_reset_passphrase(a);
3298 /* Search ahead for the next local file header. */
3299 __archive_read_consume(a, zip->unconsumed);
3300 zip->unconsumed = 0;
3302 int64_t skipped = 0;
3303 const char *p, *end;
3306 p = __archive_read_ahead(a, 4, &bytes);
3308 return (ARCHIVE_FATAL);
3311 while (p + 4 <= end) {
3312 if (p[0] == 'P' && p[1] == 'K') {
3313 if (p[2] == '\003' && p[3] == '\004') {
3314 /* Regular file entry. */
3315 __archive_read_consume(a, skipped);
3316 return zip_read_local_file_header(a,
3321 * TODO: We cannot restore permissions
3322 * based only on the local file headers.
3323 * Consider scanning the central
3324 * directory and returning additional
3325 * entries for at least directories.
3326 * This would allow us to properly set
3327 * directory permissions.
3329 * This won't help us fix symlinks
3330 * and may not help with regular file
3331 * permissions, either. <sigh>
3333 if (p[2] == '\001' && p[3] == '\002') {
3334 return (ARCHIVE_EOF);
3337 /* End of central directory? Must be an
3339 if ((p[2] == '\005' && p[3] == '\006')
3340 || (p[2] == '\006' && p[3] == '\006'))
3341 return (ARCHIVE_EOF);
3346 __archive_read_consume(a, skipped);
3351 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3354 int64_t bytes_skipped;
3356 zip = (struct zip *)(a->format->data);
3357 bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3358 zip->unconsumed = 0;
3359 if (bytes_skipped < 0)
3360 return (ARCHIVE_FATAL);
3362 /* If we've already read to end of data, we're done. */
3363 if (zip->end_of_entry)
3364 return (ARCHIVE_OK);
3366 /* So we know we're streaming... */
3367 if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3368 || zip->entry->compressed_size > 0) {
3369 /* We know the compressed length, so we can just skip. */
3370 bytes_skipped = __archive_read_consume(a,
3371 zip->entry_bytes_remaining);
3372 if (bytes_skipped < 0)
3373 return (ARCHIVE_FATAL);
3374 return (ARCHIVE_OK);
3377 if (zip->init_decryption) {
3380 zip->has_encrypted_entries = 1;
3381 if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3382 r = read_decryption_header(a);
3383 else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3384 r = init_WinZip_AES_decryption(a);
3386 r = init_traditional_PKWARE_decryption(a);
3387 if (r != ARCHIVE_OK)
3389 zip->init_decryption = 0;
3392 /* We're streaming and we don't know the length. */
3393 /* If the body is compressed and we know the format, we can
3394 * find an exact end-of-entry by decompressing it. */
3395 switch (zip->entry->compression) {
3397 case 8: /* Deflate compression. */
3398 while (!zip->end_of_entry) {
3400 const void *buff = NULL;
3403 r = zip_read_data_deflate(a, &buff, &size, &offset);
3404 if (r != ARCHIVE_OK)
3409 default: /* Uncompressed or unknown. */
3410 /* Scan for a PK\007\010 signature. */
3412 const char *p, *buff;
3413 ssize_t bytes_avail;
3414 buff = __archive_read_ahead(a, 16, &bytes_avail);
3415 if (bytes_avail < 16) {
3416 archive_set_error(&a->archive,
3417 ARCHIVE_ERRNO_FILE_FORMAT,
3418 "Truncated ZIP file data");
3419 return (ARCHIVE_FATAL);
3422 while (p <= buff + bytes_avail - 16) {
3423 if (p[3] == 'P') { p += 3; }
3424 else if (p[3] == 'K') { p += 2; }
3425 else if (p[3] == '\007') { p += 1; }
3426 else if (p[3] == '\010' && p[2] == '\007'
3427 && p[1] == 'K' && p[0] == 'P') {
3428 if (zip->entry->flags & LA_USED_ZIP64)
3429 __archive_read_consume(a,
3432 __archive_read_consume(a,
3437 __archive_read_consume(a, p - buff);
3443 archive_read_support_format_zip_streamable(struct archive *_a)
3445 struct archive_read *a = (struct archive_read *)_a;
3449 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3450 ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3452 zip = (struct zip *)calloc(1, sizeof(*zip));
3454 archive_set_error(&a->archive, ENOMEM,
3455 "Can't allocate zip data");
3456 return (ARCHIVE_FATAL);
3459 /* Streamable reader doesn't support mac extensions. */
3460 zip->process_mac_extensions = 0;
3463 * Until enough data has been read, we cannot tell about
3464 * any encrypted entries yet.
3466 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3467 zip->crc32func = real_crc32;
3469 r = __archive_read_register_format(a,
3472 archive_read_format_zip_streamable_bid,
3473 archive_read_format_zip_options,
3474 archive_read_format_zip_streamable_read_header,
3475 archive_read_format_zip_read_data,
3476 archive_read_format_zip_read_data_skip_streamable,
3478 archive_read_format_zip_cleanup,
3479 archive_read_support_format_zip_capabilities_streamable,
3480 archive_read_format_zip_has_encrypted_entries);
3482 if (r != ARCHIVE_OK)
3484 return (ARCHIVE_OK);
3487 /* ------------------------------------------------------------------------ */
3490 * Seeking-mode support
3494 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3496 (void)a; /* UNUSED */
3497 return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3498 ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3502 * TODO: This is a performance sink because it forces the read core to
3503 * drop buffered data from the start of file, which will then have to
3504 * be re-read again if this bidder loses.
3506 * We workaround this a little by passing in the best bid so far so
3507 * that later bidders can do nothing if they know they'll never
3508 * outbid. But we can certainly do better...
3511 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3514 uint32_t cd_size, cd_offset;
3516 disk_num = archive_le16dec(p + 4);
3517 cd_size = archive_le32dec(p + 12);
3518 cd_offset = archive_le32dec(p + 16);
3520 /* Sanity-check the EOCD we've found. */
3522 /* This must be the first volume. */
3525 /* Central directory must be on this volume. */
3526 if (disk_num != archive_le16dec(p + 6))
3528 /* All central directory entries must be on this volume. */
3529 if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3531 /* Central directory can't extend beyond start of EOCD record. */
3532 if (cd_offset + cd_size > current_offset)
3535 /* Save the central directory location for later use. */
3536 zip->central_directory_offset = cd_offset;
3537 zip->central_directory_offset_adjusted = current_offset - cd_size;
3539 /* This is just a tiny bit higher than the maximum
3540 returned by the streaming Zip bidder. This ensures
3541 that the more accurate seeking Zip parser wins
3542 whenever seek is available. */
3547 * Examine Zip64 EOCD locator: If it's valid, store the information
3551 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3553 int64_t eocd64_offset;
3554 int64_t eocd64_size;
3556 /* Sanity-check the locator record. */
3558 /* Central dir must be on first volume. */
3559 if (archive_le32dec(p + 4) != 0)
3561 /* Must be only a single volume. */
3562 if (archive_le32dec(p + 16) != 1)
3565 /* Find the Zip64 EOCD record. */
3566 eocd64_offset = archive_le64dec(p + 8);
3567 if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3569 if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3571 /* Make sure we can read all of it. */
3572 eocd64_size = archive_le64dec(p + 4) + 12;
3573 if (eocd64_size < 56 || eocd64_size > 16384)
3575 if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3578 /* Sanity-check the EOCD64 */
3579 if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3581 if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3583 /* CD can't be split. */
3584 if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3587 /* Save the central directory offset for later use. */
3588 zip->central_directory_offset = archive_le64dec(p + 48);
3589 /* TODO: Needs scanning backwards to find the eocd64 instead of assuming */
3590 zip->central_directory_offset_adjusted = zip->central_directory_offset;
3596 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3598 struct zip *zip = (struct zip *)a->format->data;
3599 int64_t file_size, current_offset;
3603 /* If someone has already bid more than 32, then avoid
3604 trashing the look-ahead buffers with a seek. */
3608 file_size = __archive_read_seek(a, 0, SEEK_END);
3612 /* Search last 16k of file for end-of-central-directory
3613 * record (which starts with PK\005\006) */
3614 tail = (int)zipmin(1024 * 16, file_size);
3615 current_offset = __archive_read_seek(a, -tail, SEEK_END);
3616 if (current_offset < 0)
3618 if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3620 /* Boyer-Moore search backwards from the end, since we want
3621 * to match the last EOCD in the file (there can be more than
3622 * one if there is an uncompressed Zip archive as a member
3623 * within this Zip archive). */
3624 for (i = tail - 22; i > 0;) {
3627 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3628 int ret = read_eocd(zip, p + i,
3629 current_offset + i);
3630 /* Zip64 EOCD locator precedes
3631 * regular EOCD if present. */
3632 if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3633 int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3634 if (ret_zip64 > ret)
3641 case 'K': i -= 1; break;
3642 case 005: i -= 2; break;
3643 case 006: i -= 3; break;
3644 default: i -= 4; break;
3650 /* The red-black trees are only used in seeking mode to manage
3651 * the in-memory copy of the central directory. */
3654 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3656 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3657 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3659 if (e1->local_header_offset > e2->local_header_offset)
3661 if (e1->local_header_offset < e2->local_header_offset)
3667 cmp_key(const struct archive_rb_node *n, const void *key)
3669 /* This function won't be called */
3670 (void)n; /* UNUSED */
3671 (void)key; /* UNUSED */
3675 static const struct archive_rb_tree_ops rb_ops = {
3680 rsrc_cmp_node(const struct archive_rb_node *n1,
3681 const struct archive_rb_node *n2)
3683 const struct zip_entry *e1 = (const struct zip_entry *)n1;
3684 const struct zip_entry *e2 = (const struct zip_entry *)n2;
3686 return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3690 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3692 const struct zip_entry *e = (const struct zip_entry *)n;
3693 return (strcmp((const char *)key, e->rsrcname.s));
3696 static const struct archive_rb_tree_ops rb_rsrc_ops = {
3697 &rsrc_cmp_node, &rsrc_cmp_key
3701 rsrc_basename(const char *name, size_t name_length)
3707 s = memchr(s, '/', name_length - (s - name));
3716 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3718 struct archive_string str;
3719 struct zip_entry *dir;
3722 archive_string_init(&str);
3723 archive_strncpy(&str, name, name_length);
3725 s = strrchr(str.s, '/');
3729 /* Transfer the parent directory from zip->tree_rsrc RB
3730 * tree to zip->tree RB tree to expose. */
3731 dir = (struct zip_entry *)
3732 __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3735 __archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3736 archive_string_free(&dir->rsrcname);
3737 __archive_rb_tree_insert_node(&zip->tree, &dir->node);
3739 archive_string_free(&str);
3743 slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
3749 ssize_t bytes_avail;
3753 * Find the start of the central directory. The end-of-CD
3754 * record has our starting point, but there are lots of
3755 * Zip archives which have had other data prepended to the
3756 * file, which makes the recorded offsets all too small.
3757 * So we search forward from the specified offset until we
3758 * find the real start of the central directory. Then we
3759 * know the correction we need to apply to account for leading
3762 if (__archive_read_seek(a, zip->central_directory_offset_adjusted, SEEK_SET)
3764 return ARCHIVE_FATAL;
3768 if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3769 return ARCHIVE_FATAL;
3770 for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3772 case 'P': i += 3; break;
3773 case 'K': i += 2; break;
3774 case 001: i += 1; break;
3776 if (memcmp(p + i, "PK\001\002", 4) == 0) {
3782 case 005: i += 1; break;
3784 if (memcmp(p + i, "PK\005\006", 4) == 0) {
3787 } else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3793 default: i += 4; break;
3796 __archive_read_consume(a, i);
3798 correction = archive_filter_bytes(&a->archive, 0)
3799 - zip->central_directory_offset;
3801 __archive_rb_tree_init(&zip->tree, &rb_ops);
3802 __archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3804 zip->central_directory_entries_total = 0;
3806 struct zip_entry *zip_entry;
3807 size_t filename_length, extra_length, comment_length;
3808 uint32_t external_attributes;
3809 const char *name, *r;
3811 if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3812 return ARCHIVE_FATAL;
3813 if (memcmp(p, "PK\006\006", 4) == 0
3814 || memcmp(p, "PK\005\006", 4) == 0) {
3816 } else if (memcmp(p, "PK\001\002", 4) != 0) {
3817 archive_set_error(&a->archive,
3818 -1, "Invalid central directory signature");
3819 return ARCHIVE_FATAL;
3821 if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3822 return ARCHIVE_FATAL;
3824 zip_entry = calloc(1, sizeof(struct zip_entry));
3825 if (zip_entry == NULL) {
3826 archive_set_error(&a->archive, ENOMEM,
3827 "Can't allocate zip entry");
3828 return ARCHIVE_FATAL;
3830 zip_entry->next = zip->zip_entries;
3831 zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3832 zip->zip_entries = zip_entry;
3833 zip->central_directory_entries_total++;
3835 /* version = p[4]; */
3836 zip_entry->system = p[5];
3837 /* version_required = archive_le16dec(p + 6); */
3838 zip_entry->zip_flags = archive_le16dec(p + 8);
3839 if (zip_entry->zip_flags
3840 & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3841 zip->has_encrypted_entries = 1;
3843 zip_entry->compression = (char)archive_le16dec(p + 10);
3844 zip_entry->mtime = zip_time(p + 12);
3845 zip_entry->crc32 = archive_le32dec(p + 16);
3846 if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3847 zip_entry->decdat = p[13];
3849 zip_entry->decdat = p[19];
3850 zip_entry->compressed_size = archive_le32dec(p + 20);
3851 zip_entry->uncompressed_size = archive_le32dec(p + 24);
3852 filename_length = archive_le16dec(p + 28);
3853 extra_length = archive_le16dec(p + 30);
3854 comment_length = archive_le16dec(p + 32);
3855 /* disk_start = archive_le16dec(p + 34);
3857 * internal_attributes = archive_le16dec(p + 36);
3859 external_attributes = archive_le32dec(p + 38);
3860 zip_entry->local_header_offset =
3861 archive_le32dec(p + 42) + correction;
3863 /* If we can't guess the mode, leave it zero here;
3864 when we read the local file header we might get
3865 more information. */
3866 if (zip_entry->system == 3) {
3867 zip_entry->mode = external_attributes >> 16;
3868 } else if (zip_entry->system == 0) {
3869 // Interpret MSDOS directory bit
3870 if (0x10 == (external_attributes & 0x10)) {
3871 zip_entry->mode = AE_IFDIR | 0775;
3873 zip_entry->mode = AE_IFREG | 0664;
3875 if (0x01 == (external_attributes & 0x01)) {
3876 // Read-only bit; strip write permissions
3877 zip_entry->mode &= 0555;
3880 zip_entry->mode = 0;
3883 /* We're done with the regular data; get the filename and
3885 __archive_read_consume(a, 46);
3886 p = __archive_read_ahead(a, filename_length + extra_length,
3889 archive_set_error(&a->archive,
3890 ARCHIVE_ERRNO_FILE_FORMAT,
3891 "Truncated ZIP file header");
3892 return ARCHIVE_FATAL;
3894 if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
3895 extra_length, zip_entry)) {
3896 return ARCHIVE_FATAL;
3900 * Mac resource fork files are stored under the
3901 * "__MACOSX/" directory, so we should check if
3904 if (!zip->process_mac_extensions) {
3905 /* Treat every entry as a regular entry. */
3906 __archive_rb_tree_insert_node(&zip->tree,
3910 r = rsrc_basename(name, filename_length);
3911 if (filename_length >= 9 &&
3912 strncmp("__MACOSX/", name, 9) == 0) {
3913 /* If this file is not a resource fork nor
3914 * a directory. We should treat it as a non
3915 * resource fork file to expose it. */
3916 if (name[filename_length-1] != '/' &&
3917 (r - name < 3 || r[0] != '.' ||
3919 __archive_rb_tree_insert_node(
3920 &zip->tree, &zip_entry->node);
3921 /* Expose its parent directories. */
3922 expose_parent_dirs(zip, name,
3925 /* This file is a resource fork file or
3927 archive_strncpy(&(zip_entry->rsrcname),
3928 name, filename_length);
3929 __archive_rb_tree_insert_node(
3930 &zip->tree_rsrc, &zip_entry->node);
3933 /* Generate resource fork name to find its
3934 * resource file at zip->tree_rsrc. */
3935 archive_strcpy(&(zip_entry->rsrcname),
3937 archive_strncat(&(zip_entry->rsrcname),
3939 archive_strcat(&(zip_entry->rsrcname), "._");
3940 archive_strncat(&(zip_entry->rsrcname),
3942 filename_length - (r - name));
3943 /* Register an entry to RB tree to sort it by
3945 __archive_rb_tree_insert_node(&zip->tree,
3950 /* Skip the comment too ... */
3951 __archive_read_consume(a,
3952 filename_length + extra_length + comment_length);
3959 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3962 ssize_t filename_length, extra_length;
3964 if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3965 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3966 "Truncated ZIP file header");
3967 return (ARCHIVE_WARN);
3971 if (memcmp(p, "PK\003\004", 4) != 0) {
3972 archive_set_error(&a->archive, -1, "Damaged Zip archive");
3973 return ARCHIVE_WARN;
3975 filename_length = archive_le16dec(p + 26);
3976 extra_length = archive_le16dec(p + 28);
3978 return (30 + filename_length + extra_length);
3982 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3983 struct zip_entry *rsrc)
3985 struct zip *zip = (struct zip *)a->format->data;
3986 unsigned char *metadata, *mp;
3987 int64_t offset = archive_filter_bytes(&a->archive, 0);
3988 size_t remaining_bytes, metadata_bytes;
3990 int ret = ARCHIVE_OK, eof;
3992 switch(rsrc->compression) {
3993 case 0: /* No compression. */
3994 if (rsrc->uncompressed_size != rsrc->compressed_size) {
3995 archive_set_error(&a->archive,
3996 ARCHIVE_ERRNO_FILE_FORMAT,
3997 "Malformed OS X metadata entry: "
3998 "inconsistent size");
3999 return (ARCHIVE_FATAL);
4002 case 8: /* Deflate compression. */
4005 default: /* Unsupported compression. */
4006 /* Return a warning. */
4007 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4008 "Unsupported ZIP compression method (%s)",
4009 compression_name(rsrc->compression));
4010 /* We can't decompress this entry, but we will
4011 * be able to skip() it and try the next entry. */
4012 return (ARCHIVE_WARN);
4015 if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
4016 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4017 "Mac metadata is too large: %jd > 4M bytes",
4018 (intmax_t)rsrc->uncompressed_size);
4019 return (ARCHIVE_WARN);
4021 if (rsrc->compressed_size > (4 * 1024 * 1024)) {
4022 archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
4023 "Mac metadata is too large: %jd > 4M bytes",
4024 (intmax_t)rsrc->compressed_size);
4025 return (ARCHIVE_WARN);
4028 metadata = malloc((size_t)rsrc->uncompressed_size);
4029 if (metadata == NULL) {
4030 archive_set_error(&a->archive, ENOMEM,
4031 "Can't allocate memory for Mac metadata");
4032 return (ARCHIVE_FATAL);
4035 if (offset < rsrc->local_header_offset)
4036 __archive_read_consume(a, rsrc->local_header_offset - offset);
4037 else if (offset != rsrc->local_header_offset) {
4038 __archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
4041 hsize = zip_get_local_file_header_size(a, 0);
4042 __archive_read_consume(a, hsize);
4044 remaining_bytes = (size_t)rsrc->compressed_size;
4045 metadata_bytes = (size_t)rsrc->uncompressed_size;
4048 while (!eof && remaining_bytes) {
4049 const unsigned char *p;
4050 ssize_t bytes_avail;
4053 p = __archive_read_ahead(a, 1, &bytes_avail);
4055 archive_set_error(&a->archive,
4056 ARCHIVE_ERRNO_FILE_FORMAT,
4057 "Truncated ZIP file header");
4059 goto exit_mac_metadata;
4061 if ((size_t)bytes_avail > remaining_bytes)
4062 bytes_avail = remaining_bytes;
4063 switch(rsrc->compression) {
4064 case 0: /* No compression. */
4065 if ((size_t)bytes_avail > metadata_bytes)
4066 bytes_avail = metadata_bytes;
4067 memcpy(mp, p, bytes_avail);
4068 bytes_used = (size_t)bytes_avail;
4069 metadata_bytes -= bytes_used;
4071 if (metadata_bytes == 0)
4075 case 8: /* Deflate compression. */
4079 ret = zip_deflate_init(a, zip);
4080 if (ret != ARCHIVE_OK)
4081 goto exit_mac_metadata;
4082 zip->stream.next_in =
4083 (Bytef *)(uintptr_t)(const void *)p;
4084 zip->stream.avail_in = (uInt)bytes_avail;
4085 zip->stream.total_in = 0;
4086 zip->stream.next_out = mp;
4087 zip->stream.avail_out = (uInt)metadata_bytes;
4088 zip->stream.total_out = 0;
4090 r = inflate(&zip->stream, 0);
4098 archive_set_error(&a->archive, ENOMEM,
4099 "Out of memory for ZIP decompression");
4100 ret = ARCHIVE_FATAL;
4101 goto exit_mac_metadata;
4103 archive_set_error(&a->archive,
4105 "ZIP decompression failed (%d)", r);
4106 ret = ARCHIVE_FATAL;
4107 goto exit_mac_metadata;
4109 bytes_used = zip->stream.total_in;
4110 metadata_bytes -= zip->stream.total_out;
4111 mp += zip->stream.total_out;
4119 __archive_read_consume(a, bytes_used);
4120 remaining_bytes -= bytes_used;
4122 archive_entry_copy_mac_metadata(entry, metadata,
4123 (size_t)rsrc->uncompressed_size - metadata_bytes);
4126 __archive_read_seek(a, offset, SEEK_SET);
4127 zip->decompress_init = 0;
4133 archive_read_format_zip_seekable_read_header(struct archive_read *a,
4134 struct archive_entry *entry)
4136 struct zip *zip = (struct zip *)a->format->data;
4137 struct zip_entry *rsrc;
4139 int r, ret = ARCHIVE_OK;
4142 * It should be sufficient to call archive_read_next_header() for
4143 * a reader to determine if an entry is encrypted or not. If the
4144 * encryption of an entry is only detectable when calling
4145 * archive_read_data(), so be it. We'll do the same check there
4148 if (zip->has_encrypted_entries ==
4149 ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
4150 zip->has_encrypted_entries = 0;
4152 a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
4153 if (a->archive.archive_format_name == NULL)
4154 a->archive.archive_format_name = "ZIP";
4156 if (zip->zip_entries == NULL) {
4157 r = slurp_central_directory(a, entry, zip);
4158 if (r != ARCHIVE_OK)
4160 /* Get first entry whose local header offset is lower than
4161 * other entries in the archive file. */
4163 (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
4164 } else if (zip->entry != NULL) {
4165 /* Get next entry in local header offset order. */
4166 zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
4167 &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
4170 if (zip->entry == NULL)
4173 if (zip->entry->rsrcname.s)
4174 rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
4175 &zip->tree_rsrc, zip->entry->rsrcname.s);
4179 if (zip->cctx_valid)
4180 archive_decrypto_aes_ctr_release(&zip->cctx);
4181 if (zip->hctx_valid)
4182 archive_hmac_sha1_cleanup(&zip->hctx);
4183 zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
4184 __archive_read_reset_passphrase(a);
4186 /* File entries are sorted by the header offset, we should mostly
4187 * use __archive_read_consume to advance a read point to avoid
4188 * redundant data reading. */
4189 offset = archive_filter_bytes(&a->archive, 0);
4190 if (offset < zip->entry->local_header_offset)
4191 __archive_read_consume(a,
4192 zip->entry->local_header_offset - offset);
4193 else if (offset != zip->entry->local_header_offset) {
4194 __archive_read_seek(a, zip->entry->local_header_offset,
4197 zip->unconsumed = 0;
4198 r = zip_read_local_file_header(a, entry, zip);
4199 if (r != ARCHIVE_OK)
4202 int ret2 = zip_read_mac_metadata(a, entry, rsrc);
4210 * We're going to seek for the next header anyway, so we don't
4211 * need to bother doing anything here.
4214 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
4217 zip = (struct zip *)(a->format->data);
4219 zip->unconsumed = 0;
4220 return (ARCHIVE_OK);
4224 archive_read_support_format_zip_seekable(struct archive *_a)
4226 struct archive_read *a = (struct archive_read *)_a;
4230 archive_check_magic(_a, ARCHIVE_READ_MAGIC,
4231 ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
4233 zip = (struct zip *)calloc(1, sizeof(*zip));
4235 archive_set_error(&a->archive, ENOMEM,
4236 "Can't allocate zip data");
4237 return (ARCHIVE_FATAL);
4240 #ifdef HAVE_COPYFILE_H
4241 /* Set this by default on Mac OS. */
4242 zip->process_mac_extensions = 1;
4246 * Until enough data has been read, we cannot tell about
4247 * any encrypted entries yet.
4249 zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4250 zip->crc32func = real_crc32;
4252 r = __archive_read_register_format(a,
4255 archive_read_format_zip_seekable_bid,
4256 archive_read_format_zip_options,
4257 archive_read_format_zip_seekable_read_header,
4258 archive_read_format_zip_read_data,
4259 archive_read_format_zip_read_data_skip_seekable,
4261 archive_read_format_zip_cleanup,
4262 archive_read_support_format_zip_capabilities_seekable,
4263 archive_read_format_zip_has_encrypted_entries);
4265 if (r != ARCHIVE_OK)
4267 return (ARCHIVE_OK);