1 /*-
2  * Copyright (c) 2004-2013 Tim Kientzle
3  * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
4  * Copyright (c) 2013 Konrad Kleine
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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.
26  */
27 
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 $");
30 
31 /*
32  * The definitive documentation of the Zip file format is:
33  *   http://www.pkware.com/documents/casestudies/APPNOTE.TXT
34  *
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
38  * information.
39  *
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.
44  */
45 
46 #ifdef HAVE_ERRNO_H
47 #include <errno.h>
48 #endif
49 #ifdef HAVE_STDLIB_H
50 #include <stdlib.h>
51 #endif
52 #ifdef HAVE_ZLIB_H
53 #include <zlib.h>
54 #endif
55 
56 #include "archive.h"
57 #include "archive_digest_private.h"
58 #include "archive_cryptor_private.h"
59 #include "archive_endian.h"
60 #include "archive_entry.h"
61 #include "archive_entry_locale.h"
62 #include "archive_hmac_private.h"
63 #include "archive_private.h"
64 #include "archive_rb.h"
65 #include "archive_read_private.h"
66 
67 #ifndef HAVE_ZLIB_H
68 #include "archive_crc32.h"
69 #endif
70 
71 struct zip_entry {
72 	struct archive_rb_node	node;
73 	struct zip_entry	*next;
74 	int64_t			local_header_offset;
75 	int64_t			compressed_size;
76 	int64_t			uncompressed_size;
77 	int64_t			gid;
78 	int64_t			uid;
79 	struct archive_string	rsrcname;
80 	time_t			mtime;
81 	time_t			atime;
82 	time_t			ctime;
83 	uint32_t		crc32;
84 	uint16_t		mode;
85 	uint16_t		zip_flags; /* From GP Flags Field */
86 	unsigned char		compression;
87 	unsigned char		system; /* From "version written by" */
88 	unsigned char		flags; /* Our extra markers. */
89 	unsigned char		decdat;/* Used for Decryption check */
90 
91 	/* WinZip AES encryption extra field should be available
92 	 * when compression is 99. */
93 	struct {
94 		/* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
95 		unsigned	vendor;
96 #define AES_VENDOR_AE_1	0x0001
97 #define AES_VENDOR_AE_2	0x0002
98 		/* AES encryption strength:
99 		 * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
100 		unsigned	strength;
101 		/* Actual compression method. */
102 		unsigned char	compression;
103 	}			aes_extra;
104 };
105 
106 struct trad_enc_ctx {
107 	uint32_t	keys[3];
108 };
109 
110 /* Bits used in zip_flags. */
111 #define ZIP_ENCRYPTED	(1 << 0)
112 #define ZIP_LENGTH_AT_END	(1 << 3)
113 #define ZIP_STRONG_ENCRYPTED	(1 << 6)
114 #define ZIP_UTF8_NAME	(1 << 11)
115 /* See "7.2 Single Password Symmetric Encryption Method"
116    in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
117 #define ZIP_CENTRAL_DIRECTORY_ENCRYPTED	(1 << 13)
118 
119 /* Bits used in flags. */
120 #define LA_USED_ZIP64	(1 << 0)
121 #define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
122 
123 /*
124  * See "WinZip - AES Encryption Information"
125  *     http://www.winzip.com/aes_info.htm
126  */
127 /* Value used in compression method. */
128 #define WINZIP_AES_ENCRYPTION	99
129 /* Authentication code size. */
130 #define AUTH_CODE_SIZE	10
131 /**/
132 #define MAX_DERIVED_KEY_BUF_SIZE	(AES_MAX_KEY_SIZE * 2 + 2)
133 
134 struct zip {
135 	/* Structural information about the archive. */
136 	struct archive_string	format_name;
137 	int64_t			central_directory_offset;
138 	size_t			central_directory_entries_total;
139 	size_t			central_directory_entries_on_this_disk;
140 	int			has_encrypted_entries;
141 
142 	/* List of entries (seekable Zip only) */
143 	struct zip_entry	*zip_entries;
144 	struct archive_rb_tree	tree;
145 	struct archive_rb_tree	tree_rsrc;
146 
147 	/* Bytes read but not yet consumed via __archive_read_consume() */
148 	size_t			unconsumed;
149 
150 	/* Information about entry we're currently reading. */
151 	struct zip_entry	*entry;
152 	int64_t			entry_bytes_remaining;
153 
154 	/* These count the number of bytes actually read for the entry. */
155 	int64_t			entry_compressed_bytes_read;
156 	int64_t			entry_uncompressed_bytes_read;
157 
158 	/* Running CRC32 of the decompressed data */
159 	unsigned long		entry_crc32;
160 	unsigned long		(*crc32func)(unsigned long, const void *,
161 				    size_t);
162 	char			ignore_crc32;
163 
164 	/* Flags to mark progress of decompression. */
165 	char			decompress_init;
166 	char			end_of_entry;
167 
168 #ifdef HAVE_ZLIB_H
169 	unsigned char 		*uncompressed_buffer;
170 	size_t 			uncompressed_buffer_size;
171 	z_stream		stream;
172 	char			stream_valid;
173 #endif
174 
175 	struct archive_string_conv *sconv;
176 	struct archive_string_conv *sconv_default;
177 	struct archive_string_conv *sconv_utf8;
178 	int			init_default_conversion;
179 	int			process_mac_extensions;
180 
181 	char			init_decryption;
182 
183 	/* Decryption buffer. */
184 	/*
185 	 * The decrypted data starts at decrypted_ptr and
186 	 * extends for decrypted_bytes_remaining.  Decryption
187 	 * adds new data to the end of this block, data is returned
188 	 * to clients from the beginning.  When the block hits the
189 	 * end of decrypted_buffer, it has to be shuffled back to
190 	 * the beginning of the buffer.
191 	 */
192 	unsigned char 		*decrypted_buffer;
193 	unsigned char 		*decrypted_ptr;
194 	size_t 			decrypted_buffer_size;
195 	size_t 			decrypted_bytes_remaining;
196 	size_t 			decrypted_unconsumed_bytes;
197 
198 	/* Traditional PKWARE decryption. */
199 	struct trad_enc_ctx	tctx;
200 	char			tctx_valid;
201 
202 	/* WinZip AES decryption. */
203 	/* Contexts used for AES decryption. */
204 	archive_crypto_ctx	cctx;
205 	char			cctx_valid;
206 	archive_hmac_sha1_ctx	hctx;
207 	char			hctx_valid;
208 
209 	/* Strong encryption's decryption header information. */
210 	unsigned		iv_size;
211 	unsigned		alg_id;
212 	unsigned		bit_len;
213 	unsigned		flags;
214 	unsigned		erd_size;
215 	unsigned		v_size;
216 	unsigned		v_crc32;
217 	uint8_t			*iv;
218 	uint8_t			*erd;
219 	uint8_t			*v_data;
220 };
221 
222 /* Many systems define min or MIN, but not all. */
223 #define	zipmin(a,b) ((a) < (b) ? (a) : (b))
224 
225 /* ------------------------------------------------------------------------ */
226 
227 /*
228   Traditional PKWARE Decryption functions.
229  */
230 
231 static void
232 trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
233 {
234 	uint8_t t;
235 #define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
236 
237 	ctx->keys[0] = CRC32(ctx->keys[0], c);
238 	ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
239 	t = (ctx->keys[1] >> 24) & 0xff;
240 	ctx->keys[2] = CRC32(ctx->keys[2], t);
241 #undef CRC32
242 }
243 
244 static uint8_t
245 trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
246 {
247 	unsigned temp = ctx->keys[2] | 2;
248 	return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
249 }
250 
251 static void
252 trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
253     size_t in_len, uint8_t *out, size_t out_len)
254 {
255 	unsigned i, max;
256 
257 	max = (unsigned)((in_len < out_len)? in_len: out_len);
258 
259 	for (i = 0; i < max; i++) {
260 		uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
261 		out[i] = t;
262 		trad_enc_update_keys(ctx, t);
263 	}
264 }
265 
266 static int
267 trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
268     const uint8_t *key, size_t key_len, uint8_t *crcchk)
269 {
270 	uint8_t header[12];
271 
272 	if (key_len < 12) {
273 		*crcchk = 0xff;
274 		return -1;
275 	}
276 
277 	ctx->keys[0] = 305419896L;
278 	ctx->keys[1] = 591751049L;
279 	ctx->keys[2] = 878082192L;
280 
281 	for (;pw_len; --pw_len)
282 		trad_enc_update_keys(ctx, *pw++);
283 
284 	trad_enc_decrypt_update(ctx, key, 12, header, 12);
285 	/* Return the last byte for CRC check. */
286 	*crcchk = header[11];
287 	return 0;
288 }
289 
290 #if 0
291 static void
292 crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
293     int key_size)
294 {
295 #define MD_SIZE 20
296 	archive_sha1_ctx ctx;
297 	unsigned char md1[MD_SIZE];
298 	unsigned char md2[MD_SIZE * 2];
299 	unsigned char mkb[64];
300 	int i;
301 
302 	archive_sha1_init(&ctx);
303 	archive_sha1_update(&ctx, p, size);
304 	archive_sha1_final(&ctx, md1);
305 
306 	memset(mkb, 0x36, sizeof(mkb));
307 	for (i = 0; i < MD_SIZE; i++)
308 		mkb[i] ^= md1[i];
309 	archive_sha1_init(&ctx);
310 	archive_sha1_update(&ctx, mkb, sizeof(mkb));
311 	archive_sha1_final(&ctx, md2);
312 
313 	memset(mkb, 0x5C, sizeof(mkb));
314 	for (i = 0; i < MD_SIZE; i++)
315 		mkb[i] ^= md1[i];
316 	archive_sha1_init(&ctx);
317 	archive_sha1_update(&ctx, mkb, sizeof(mkb));
318 	archive_sha1_final(&ctx, md2 + MD_SIZE);
319 
320 	if (key_size > 32)
321 		key_size = 32;
322 	memcpy(key, md2, key_size);
323 #undef MD_SIZE
324 }
325 #endif
326 
327 /*
328  * Common code for streaming or seeking modes.
329  *
330  * Includes code to read local file headers, decompress data
331  * from entry bodies, and common API.
332  */
333 
334 static unsigned long
335 real_crc32(unsigned long crc, const void *buff, size_t len)
336 {
337 	return crc32(crc, buff, (unsigned int)len);
338 }
339 
340 /* Used by "ignorecrc32" option to speed up tests. */
341 static unsigned long
342 fake_crc32(unsigned long crc, const void *buff, size_t len)
343 {
344 	(void)crc; /* UNUSED */
345 	(void)buff; /* UNUSED */
346 	(void)len; /* UNUSED */
347 	return 0;
348 }
349 
350 static const struct {
351 	int id;
352 	const char * name;
353 } compression_methods[] = {
354 	{0, "uncompressed"}, /* The file is stored (no compression) */
355 	{1, "shrinking"}, /* The file is Shrunk */
356 	{2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
357 	{3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
358 	{4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
359 	{5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
360 	{6, "imploded"},  /* The file is Imploded */
361 	{7, "reserved"},  /* Reserved for Tokenizing compression algorithm */
362 	{8, "deflation"}, /* The file is Deflated */
363 	{9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
364 	{10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
365 			   * (old IBM TERSE) */
366 	{11, "reserved"}, /* Reserved by PKWARE */
367 	{12, "bzip"},     /* File is compressed using BZIP2 algorithm */
368 	{13, "reserved"}, /* Reserved by PKWARE */
369 	{14, "lzma"},     /* LZMA (EFS) */
370 	{15, "reserved"}, /* Reserved by PKWARE */
371 	{16, "reserved"}, /* Reserved by PKWARE */
372 	{17, "reserved"}, /* Reserved by PKWARE */
373 	{18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
374 	{19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
375 	{97, "wav-pack"}, /* WavPack compressed data */
376 	{98, "ppmd-1"},   /* PPMd version I, Rev 1 */
377 	{99, "aes"}       /* WinZip AES encryption  */
378 };
379 
380 static const char *
381 compression_name(const int compression)
382 {
383 	static const int num_compression_methods =
384 		sizeof(compression_methods)/sizeof(compression_methods[0]);
385 	int i=0;
386 
387 	while(compression >= 0 && i < num_compression_methods) {
388 		if (compression_methods[i].id == compression)
389 			return compression_methods[i].name;
390 		i++;
391 	}
392 	return "??";
393 }
394 
395 /* Convert an MSDOS-style date/time into Unix-style time. */
396 static time_t
397 zip_time(const char *p)
398 {
399 	int msTime, msDate;
400 	struct tm ts;
401 
402 	msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
403 	msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
404 
405 	memset(&ts, 0, sizeof(ts));
406 	ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
407 	ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
408 	ts.tm_mday = msDate & 0x1f; /* Day of month. */
409 	ts.tm_hour = (msTime >> 11) & 0x1f;
410 	ts.tm_min = (msTime >> 5) & 0x3f;
411 	ts.tm_sec = (msTime << 1) & 0x3e;
412 	ts.tm_isdst = -1;
413 	return mktime(&ts);
414 }
415 
416 /*
417  * The extra data is stored as a list of
418  *	id1+size1+data1 + id2+size2+data2 ...
419  *  triplets.  id and size are 2 bytes each.
420  */
421 static int
422 process_extra(struct archive_read *a, const char *p, size_t extra_length, struct zip_entry* zip_entry)
423 {
424 	unsigned offset = 0;
425 
426 	if (extra_length == 0) {
427 		return ARCHIVE_OK;
428 	}
429 
430 	if (extra_length < 4) {
431 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
432 		    "Too-small extra data: Need at least 4 bytes, but only found %d bytes", (int)extra_length);
433 		return ARCHIVE_FAILED;
434 	}
435 	while (offset <= extra_length - 4) {
436 		unsigned short headerid = archive_le16dec(p + offset);
437 		unsigned short datasize = archive_le16dec(p + offset + 2);
438 
439 		offset += 4;
440 		if (offset + datasize > extra_length) {
441 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
442 			    "Extra data overflow: Need %d bytes but only found %d bytes",
443 			    (int)datasize, (int)(extra_length - offset));
444 			return ARCHIVE_FAILED;
445 		}
446 #ifdef DEBUG
447 		fprintf(stderr, "Header id 0x%04x, length %d\n",
448 		    headerid, datasize);
449 #endif
450 		switch (headerid) {
451 		case 0x0001:
452 			/* Zip64 extended information extra field. */
453 			zip_entry->flags |= LA_USED_ZIP64;
454 			if (zip_entry->uncompressed_size == 0xffffffff) {
455 				uint64_t t = 0;
456 				if (datasize < 8
457 				    || (t = archive_le64dec(p + offset)) > INT64_MAX) {
458 					archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
459 					    "Malformed 64-bit uncompressed size");
460 					return ARCHIVE_FAILED;
461 				}
462 				zip_entry->uncompressed_size = t;
463 				offset += 8;
464 				datasize -= 8;
465 			}
466 			if (zip_entry->compressed_size == 0xffffffff) {
467 				uint64_t t = 0;
468 				if (datasize < 8
469 				    || (t = archive_le64dec(p + offset)) > INT64_MAX) {
470 					archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
471 					    "Malformed 64-bit compressed size");
472 					return ARCHIVE_FAILED;
473 				}
474 				zip_entry->compressed_size = t;
475 				offset += 8;
476 				datasize -= 8;
477 			}
478 			if (zip_entry->local_header_offset == 0xffffffff) {
479 				uint64_t t = 0;
480 				if (datasize < 8
481 				    || (t = archive_le64dec(p + offset)) > INT64_MAX) {
482 					archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
483 					    "Malformed 64-bit local header offset");
484 					return ARCHIVE_FAILED;
485 				}
486 				zip_entry->local_header_offset = t;
487 				offset += 8;
488 				datasize -= 8;
489 			}
490 			/* archive_le32dec(p + offset) gives disk
491 			 * on which file starts, but we don't handle
492 			 * multi-volume Zip files. */
493 			break;
494 #ifdef DEBUG
495 		case 0x0017:
496 		{
497 			/* Strong encryption field. */
498 			if (archive_le16dec(p + offset) == 2) {
499 				unsigned algId =
500 					archive_le16dec(p + offset + 2);
501 				unsigned bitLen =
502 					archive_le16dec(p + offset + 4);
503 				int	 flags =
504 					archive_le16dec(p + offset + 6);
505 				fprintf(stderr, "algId=0x%04x, bitLen=%u, "
506 				    "flgas=%d\n", algId, bitLen,flags);
507 			}
508 			break;
509 		}
510 #endif
511 		case 0x5455:
512 		{
513 			/* Extended time field "UT". */
514 			int flags;
515 			if (datasize == 0) {
516 				archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
517 				    "Incomplete extended time field");
518 				return ARCHIVE_FAILED;
519 			}
520 			flags = p[offset];
521 			offset++;
522 			datasize--;
523 			/* Flag bits indicate which dates are present. */
524 			if (flags & 0x01)
525 			{
526 #ifdef DEBUG
527 				fprintf(stderr, "mtime: %lld -> %d\n",
528 				    (long long)zip_entry->mtime,
529 				    archive_le32dec(p + offset));
530 #endif
531 				if (datasize < 4)
532 					break;
533 				zip_entry->mtime = archive_le32dec(p + offset);
534 				offset += 4;
535 				datasize -= 4;
536 			}
537 			if (flags & 0x02)
538 			{
539 				if (datasize < 4)
540 					break;
541 				zip_entry->atime = archive_le32dec(p + offset);
542 				offset += 4;
543 				datasize -= 4;
544 			}
545 			if (flags & 0x04)
546 			{
547 				if (datasize < 4)
548 					break;
549 				zip_entry->ctime = archive_le32dec(p + offset);
550 				offset += 4;
551 				datasize -= 4;
552 			}
553 			break;
554 		}
555 		case 0x5855:
556 		{
557 			/* Info-ZIP Unix Extra Field (old version) "UX". */
558 			if (datasize >= 8) {
559 				zip_entry->atime = archive_le32dec(p + offset);
560 				zip_entry->mtime =
561 				    archive_le32dec(p + offset + 4);
562 			}
563 			if (datasize >= 12) {
564 				zip_entry->uid =
565 				    archive_le16dec(p + offset + 8);
566 				zip_entry->gid =
567 				    archive_le16dec(p + offset + 10);
568 			}
569 			break;
570 		}
571 		case 0x6c78:
572 		{
573 			/* Experimental 'xl' field */
574 			/*
575 			 * Introduced Dec 2013 to provide a way to
576 			 * include external file attributes (and other
577 			 * fields that ordinarily appear only in
578 			 * central directory) in local file header.
579 			 * This provides file type and permission
580 			 * information necessary to support full
581 			 * streaming extraction.  Currently being
582 			 * discussed with other Zip developers
583 			 * ... subject to change.
584 			 *
585 			 * Format:
586 			 *  The field starts with a bitmap that specifies
587 			 *  which additional fields are included.  The
588 			 *  bitmap is variable length and can be extended in
589 			 *  the future.
590 			 *
591 			 *  n bytes - feature bitmap: first byte has low-order
592 			 *    7 bits.  If high-order bit is set, a subsequent
593 			 *    byte holds the next 7 bits, etc.
594 			 *
595 			 *  if bitmap & 1, 2 byte "version made by"
596 			 *  if bitmap & 2, 2 byte "internal file attributes"
597 			 *  if bitmap & 4, 4 byte "external file attributes"
598 			 *  if bitmap & 8, 2 byte comment length + n byte comment
599 			 */
600 			int bitmap, bitmap_last;
601 
602 			if (datasize < 1)
603 				break;
604 			bitmap_last = bitmap = 0xff & p[offset];
605 			offset += 1;
606 			datasize -= 1;
607 
608 			/* We only support first 7 bits of bitmap; skip rest. */
609 			while ((bitmap_last & 0x80) != 0
610 			    && datasize >= 1) {
611 				bitmap_last = p[offset];
612 				offset += 1;
613 				datasize -= 1;
614 			}
615 
616 			if (bitmap & 1) {
617 				/* 2 byte "version made by" */
618 				if (datasize < 2)
619 					break;
620 				zip_entry->system
621 				    = archive_le16dec(p + offset) >> 8;
622 				offset += 2;
623 				datasize -= 2;
624 			}
625 			if (bitmap & 2) {
626 				/* 2 byte "internal file attributes" */
627 				uint32_t internal_attributes;
628 				if (datasize < 2)
629 					break;
630 				internal_attributes
631 				    = archive_le16dec(p + offset);
632 				/* Not used by libarchive at present. */
633 				(void)internal_attributes; /* UNUSED */
634 				offset += 2;
635 				datasize -= 2;
636 			}
637 			if (bitmap & 4) {
638 				/* 4 byte "external file attributes" */
639 				uint32_t external_attributes;
640 				if (datasize < 4)
641 					break;
642 				external_attributes
643 				    = archive_le32dec(p + offset);
644 				if (zip_entry->system == 3) {
645 					zip_entry->mode
646 					    = external_attributes >> 16;
647 				} else if (zip_entry->system == 0) {
648 					// Interpret MSDOS directory bit
649 					if (0x10 == (external_attributes & 0x10)) {
650 						zip_entry->mode = AE_IFDIR | 0775;
651 					} else {
652 						zip_entry->mode = AE_IFREG | 0664;
653 					}
654 					if (0x01 == (external_attributes & 0x01)) {
655 						// Read-only bit; strip write permissions
656 						zip_entry->mode &= 0555;
657 					}
658 				} else {
659 					zip_entry->mode = 0;
660 				}
661 				offset += 4;
662 				datasize -= 4;
663 			}
664 			if (bitmap & 8) {
665 				/* 2 byte comment length + comment */
666 				uint32_t comment_length;
667 				if (datasize < 2)
668 					break;
669 				comment_length
670 				    = archive_le16dec(p + offset);
671 				offset += 2;
672 				datasize -= 2;
673 
674 				if (datasize < comment_length)
675 					break;
676 				/* Comment is not supported by libarchive */
677 				offset += comment_length;
678 				datasize -= comment_length;
679 			}
680 			break;
681 		}
682 		case 0x7855:
683 			/* Info-ZIP Unix Extra Field (type 2) "Ux". */
684 #ifdef DEBUG
685 			fprintf(stderr, "uid %d gid %d\n",
686 			    archive_le16dec(p + offset),
687 			    archive_le16dec(p + offset + 2));
688 #endif
689 			if (datasize >= 2)
690 				zip_entry->uid = archive_le16dec(p + offset);
691 			if (datasize >= 4)
692 				zip_entry->gid =
693 				    archive_le16dec(p + offset + 2);
694 			break;
695 		case 0x7875:
696 		{
697 			/* Info-Zip Unix Extra Field (type 3) "ux". */
698 			int uidsize = 0, gidsize = 0;
699 
700 			/* TODO: support arbitrary uidsize/gidsize. */
701 			if (datasize >= 1 && p[offset] == 1) {/* version=1 */
702 				if (datasize >= 4) {
703 					/* get a uid size. */
704 					uidsize = 0xff & (int)p[offset+1];
705 					if (uidsize == 2)
706 						zip_entry->uid =
707 						    archive_le16dec(
708 						        p + offset + 2);
709 					else if (uidsize == 4 && datasize >= 6)
710 						zip_entry->uid =
711 						    archive_le32dec(
712 						        p + offset + 2);
713 				}
714 				if (datasize >= (2 + uidsize + 3)) {
715 					/* get a gid size. */
716 					gidsize = 0xff & (int)p[offset+2+uidsize];
717 					if (gidsize == 2)
718 						zip_entry->gid =
719 						    archive_le16dec(
720 						        p+offset+2+uidsize+1);
721 					else if (gidsize == 4 &&
722 					    datasize >= (2 + uidsize + 5))
723 						zip_entry->gid =
724 						    archive_le32dec(
725 						        p+offset+2+uidsize+1);
726 				}
727 			}
728 			break;
729 		}
730 		case 0x9901:
731 			/* WinZip AES extra data field. */
732 			if (datasize < 6) {
733 				archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
734 				    "Incomplete AES field");
735 				return ARCHIVE_FAILED;
736 			}
737 			if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
738 				/* Vendor version. */
739 				zip_entry->aes_extra.vendor =
740 				    archive_le16dec(p + offset);
741 				/* AES encryption strength. */
742 				zip_entry->aes_extra.strength = p[offset + 4];
743 				/* Actual compression method. */
744 				zip_entry->aes_extra.compression =
745 				    p[offset + 5];
746 			}
747 			break;
748 		default:
749 			break;
750 		}
751 		offset += datasize;
752 	}
753 	if (offset != extra_length) {
754 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
755 		    "Malformed extra data: Consumed %d bytes of %d bytes",
756 		    (int)offset, (int)extra_length);
757 		return ARCHIVE_FAILED;
758 	}
759 	return ARCHIVE_OK;
760 }
761 
762 /*
763  * Assumes file pointer is at beginning of local file header.
764  */
765 static int
766 zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
767     struct zip *zip)
768 {
769 	const char *p;
770 	const void *h;
771 	const wchar_t *wp;
772 	const char *cp;
773 	size_t len, filename_length, extra_length;
774 	struct archive_string_conv *sconv;
775 	struct zip_entry *zip_entry = zip->entry;
776 	struct zip_entry zip_entry_central_dir;
777 	int ret = ARCHIVE_OK;
778 	char version;
779 
780 	/* Save a copy of the original for consistency checks. */
781 	zip_entry_central_dir = *zip_entry;
782 
783 	zip->decompress_init = 0;
784 	zip->end_of_entry = 0;
785 	zip->entry_uncompressed_bytes_read = 0;
786 	zip->entry_compressed_bytes_read = 0;
787 	zip->entry_crc32 = zip->crc32func(0, NULL, 0);
788 
789 	/* Setup default conversion. */
790 	if (zip->sconv == NULL && !zip->init_default_conversion) {
791 		zip->sconv_default =
792 		    archive_string_default_conversion_for_read(&(a->archive));
793 		zip->init_default_conversion = 1;
794 	}
795 
796 	if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
797 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
798 		    "Truncated ZIP file header");
799 		return (ARCHIVE_FATAL);
800 	}
801 
802 	if (memcmp(p, "PK\003\004", 4) != 0) {
803 		archive_set_error(&a->archive, -1, "Damaged Zip archive");
804 		return ARCHIVE_FATAL;
805 	}
806 	version = p[4];
807 	zip_entry->system = p[5];
808 	zip_entry->zip_flags = archive_le16dec(p + 6);
809 	if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
810 		zip->has_encrypted_entries = 1;
811 		archive_entry_set_is_data_encrypted(entry, 1);
812 		if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
813 			zip_entry->zip_flags & ZIP_ENCRYPTED &&
814 			zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
815 			archive_entry_set_is_metadata_encrypted(entry, 1);
816 			return ARCHIVE_FATAL;
817 		}
818 	}
819 	zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
820 	zip_entry->compression = (char)archive_le16dec(p + 8);
821 	zip_entry->mtime = zip_time(p + 10);
822 	zip_entry->crc32 = archive_le32dec(p + 14);
823 	if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
824 		zip_entry->decdat = p[11];
825 	else
826 		zip_entry->decdat = p[17];
827 	zip_entry->compressed_size = archive_le32dec(p + 18);
828 	zip_entry->uncompressed_size = archive_le32dec(p + 22);
829 	filename_length = archive_le16dec(p + 26);
830 	extra_length = archive_le16dec(p + 28);
831 
832 	__archive_read_consume(a, 30);
833 
834 	/* Read the filename. */
835 	if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
836 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
837 		    "Truncated ZIP file header");
838 		return (ARCHIVE_FATAL);
839 	}
840 	if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
841 		/* The filename is stored to be UTF-8. */
842 		if (zip->sconv_utf8 == NULL) {
843 			zip->sconv_utf8 =
844 			    archive_string_conversion_from_charset(
845 				&a->archive, "UTF-8", 1);
846 			if (zip->sconv_utf8 == NULL)
847 				return (ARCHIVE_FATAL);
848 		}
849 		sconv = zip->sconv_utf8;
850 	} else if (zip->sconv != NULL)
851 		sconv = zip->sconv;
852 	else
853 		sconv = zip->sconv_default;
854 
855 	if (archive_entry_copy_pathname_l(entry,
856 	    h, filename_length, sconv) != 0) {
857 		if (errno == ENOMEM) {
858 			archive_set_error(&a->archive, ENOMEM,
859 			    "Can't allocate memory for Pathname");
860 			return (ARCHIVE_FATAL);
861 		}
862 		archive_set_error(&a->archive,
863 		    ARCHIVE_ERRNO_FILE_FORMAT,
864 		    "Pathname cannot be converted "
865 		    "from %s to current locale.",
866 		    archive_string_conversion_charset_name(sconv));
867 		ret = ARCHIVE_WARN;
868 	}
869 	__archive_read_consume(a, filename_length);
870 
871 	/* Read the extra data. */
872 	if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
873 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
874 		    "Truncated ZIP file header");
875 		return (ARCHIVE_FATAL);
876 	}
877 
878 	if (ARCHIVE_OK != process_extra(a, h, extra_length, zip_entry)) {
879 		return ARCHIVE_FATAL;
880 	}
881 	__archive_read_consume(a, extra_length);
882 
883 	/* Work around a bug in Info-Zip: When reading from a pipe, it
884 	 * stats the pipe instead of synthesizing a file entry. */
885 	if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
886 		zip_entry->mode &= ~ AE_IFMT;
887 		zip_entry->mode |= AE_IFREG;
888 	}
889 
890 	/* If the mode is totally empty, set some sane default. */
891 	if (zip_entry->mode == 0) {
892 		zip_entry->mode |= 0664;
893 	}
894 
895 	/* Windows archivers sometimes use backslash as the directory separator.
896 	   Normalize to slash. */
897 	if (zip_entry->system == 0 &&
898 	    (wp = archive_entry_pathname_w(entry)) != NULL) {
899 		if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
900 			size_t i;
901 			struct archive_wstring s;
902 			archive_string_init(&s);
903 			archive_wstrcpy(&s, wp);
904 			for (i = 0; i < archive_strlen(&s); i++) {
905 				if (s.s[i] == '\\')
906 					s.s[i] = '/';
907 			}
908 			archive_entry_copy_pathname_w(entry, s.s);
909 			archive_wstring_free(&s);
910 		}
911 	}
912 
913 	/* Make sure that entries with a trailing '/' are marked as directories
914 	 * even if the External File Attributes contains bogus values.  If this
915 	 * is not a directory and there is no type, assume regularfile. */
916 	if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
917 		int has_slash;
918 
919 		wp = archive_entry_pathname_w(entry);
920 		if (wp != NULL) {
921 			len = wcslen(wp);
922 			has_slash = len > 0 && wp[len - 1] == L'/';
923 		} else {
924 			cp = archive_entry_pathname(entry);
925 			len = (cp != NULL)?strlen(cp):0;
926 			has_slash = len > 0 && cp[len - 1] == '/';
927 		}
928 		/* Correct file type as needed. */
929 		if (has_slash) {
930 			zip_entry->mode &= ~AE_IFMT;
931 			zip_entry->mode |= AE_IFDIR;
932 			zip_entry->mode |= 0111;
933 		} else if ((zip_entry->mode & AE_IFMT) == 0) {
934 			zip_entry->mode |= AE_IFREG;
935 		}
936 	}
937 
938 	/* Make sure directories end in '/' */
939 	if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
940 		wp = archive_entry_pathname_w(entry);
941 		if (wp != NULL) {
942 			len = wcslen(wp);
943 			if (len > 0 && wp[len - 1] != L'/') {
944 				struct archive_wstring s;
945 				archive_string_init(&s);
946 				archive_wstrcat(&s, wp);
947 				archive_wstrappend_wchar(&s, L'/');
948 				archive_entry_copy_pathname_w(entry, s.s);
949 				archive_wstring_free(&s);
950 			}
951 		} else {
952 			cp = archive_entry_pathname(entry);
953 			len = (cp != NULL)?strlen(cp):0;
954 			if (len > 0 && cp[len - 1] != '/') {
955 				struct archive_string s;
956 				archive_string_init(&s);
957 				archive_strcat(&s, cp);
958 				archive_strappend_char(&s, '/');
959 				archive_entry_set_pathname(entry, s.s);
960 				archive_string_free(&s);
961 			}
962 		}
963 	}
964 
965 	if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
966 		/* If this came from the central dir, it's size info
967 		 * is definitive, so ignore the length-at-end flag. */
968 		zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
969 		/* If local header is missing a value, use the one from
970 		   the central directory.  If both have it, warn about
971 		   mismatches. */
972 		if (zip_entry->crc32 == 0) {
973 			zip_entry->crc32 = zip_entry_central_dir.crc32;
974 		} else if (!zip->ignore_crc32
975 		    && zip_entry->crc32 != zip_entry_central_dir.crc32) {
976 			archive_set_error(&a->archive,
977 			    ARCHIVE_ERRNO_FILE_FORMAT,
978 			    "Inconsistent CRC32 values");
979 			ret = ARCHIVE_WARN;
980 		}
981 		if (zip_entry->compressed_size == 0) {
982 			zip_entry->compressed_size
983 			    = zip_entry_central_dir.compressed_size;
984 		} else if (zip_entry->compressed_size
985 		    != zip_entry_central_dir.compressed_size) {
986 			archive_set_error(&a->archive,
987 			    ARCHIVE_ERRNO_FILE_FORMAT,
988 			    "Inconsistent compressed size: "
989 			    "%jd in central directory, %jd in local header",
990 			    (intmax_t)zip_entry_central_dir.compressed_size,
991 			    (intmax_t)zip_entry->compressed_size);
992 			ret = ARCHIVE_WARN;
993 		}
994 		if (zip_entry->uncompressed_size == 0) {
995 			zip_entry->uncompressed_size
996 			    = zip_entry_central_dir.uncompressed_size;
997 		} else if (zip_entry->uncompressed_size
998 		    != zip_entry_central_dir.uncompressed_size) {
999 			archive_set_error(&a->archive,
1000 			    ARCHIVE_ERRNO_FILE_FORMAT,
1001 			    "Inconsistent uncompressed size: "
1002 			    "%jd in central directory, %jd in local header",
1003 			    (intmax_t)zip_entry_central_dir.uncompressed_size,
1004 			    (intmax_t)zip_entry->uncompressed_size);
1005 			ret = ARCHIVE_WARN;
1006 		}
1007 	}
1008 
1009 	/* Populate some additional entry fields: */
1010 	archive_entry_set_mode(entry, zip_entry->mode);
1011 	archive_entry_set_uid(entry, zip_entry->uid);
1012 	archive_entry_set_gid(entry, zip_entry->gid);
1013 	archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1014 	archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1015 	archive_entry_set_atime(entry, zip_entry->atime, 0);
1016 
1017 	if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1018 		size_t linkname_length;
1019 
1020 		if (zip_entry->compressed_size > 64 * 1024) {
1021 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1022 			    "Zip file with oversized link entry");
1023 			return ARCHIVE_FATAL;
1024 		}
1025 
1026 		linkname_length = (size_t)zip_entry->compressed_size;
1027 
1028 		archive_entry_set_size(entry, 0);
1029 		p = __archive_read_ahead(a, linkname_length, NULL);
1030 		if (p == NULL) {
1031 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1032 			    "Truncated Zip file");
1033 			return ARCHIVE_FATAL;
1034 		}
1035 
1036 		sconv = zip->sconv;
1037 		if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1038 			sconv = zip->sconv_utf8;
1039 		if (sconv == NULL)
1040 			sconv = zip->sconv_default;
1041 		if (archive_entry_copy_symlink_l(entry, p, linkname_length,
1042 		    sconv) != 0) {
1043 			if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1044 			    (zip->entry->zip_flags & ZIP_UTF8_NAME))
1045 			    archive_entry_copy_symlink_l(entry, p,
1046 				linkname_length, NULL);
1047 			if (errno == ENOMEM) {
1048 				archive_set_error(&a->archive, ENOMEM,
1049 				    "Can't allocate memory for Symlink");
1050 				return (ARCHIVE_FATAL);
1051 			}
1052 			/*
1053 			 * Since there is no character-set regulation for
1054 			 * symlink name, do not report the conversion error
1055 			 * in an automatic conversion.
1056 			 */
1057 			if (sconv != zip->sconv_utf8 ||
1058 			    (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1059 				archive_set_error(&a->archive,
1060 				    ARCHIVE_ERRNO_FILE_FORMAT,
1061 				    "Symlink cannot be converted "
1062 				    "from %s to current locale.",
1063 				    archive_string_conversion_charset_name(
1064 					sconv));
1065 				ret = ARCHIVE_WARN;
1066 			}
1067 		}
1068 		zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1069 
1070 		if (__archive_read_consume(a, linkname_length) < 0) {
1071 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1072 			    "Read error skipping symlink target name");
1073 			return ARCHIVE_FATAL;
1074 		}
1075 	} else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1076 	    || zip_entry->uncompressed_size > 0) {
1077 		/* Set the size only if it's meaningful. */
1078 		archive_entry_set_size(entry, zip_entry->uncompressed_size);
1079 	}
1080 	zip->entry_bytes_remaining = zip_entry->compressed_size;
1081 
1082 	/* If there's no body, force read_data() to return EOF immediately. */
1083 	if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1084 	    && zip->entry_bytes_remaining < 1)
1085 		zip->end_of_entry = 1;
1086 
1087 	/* Set up a more descriptive format name. */
1088         archive_string_empty(&zip->format_name);
1089 	archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1090 	    version / 10, version % 10,
1091 	    compression_name(zip->entry->compression));
1092 	a->archive.archive_format_name = zip->format_name.s;
1093 
1094 	return (ret);
1095 }
1096 
1097 static int
1098 check_authentication_code(struct archive_read *a, const void *_p)
1099 {
1100 	struct zip *zip = (struct zip *)(a->format->data);
1101 
1102 	/* Check authentication code. */
1103 	if (zip->hctx_valid) {
1104 		const void *p;
1105 		uint8_t hmac[20];
1106 		size_t hmac_len = 20;
1107 		int cmp;
1108 
1109 		archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1110 		if (_p == NULL) {
1111 			/* Read authentication code. */
1112 			p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1113 			if (p == NULL) {
1114 				archive_set_error(&a->archive,
1115 				    ARCHIVE_ERRNO_FILE_FORMAT,
1116 				    "Truncated ZIP file data");
1117 				return (ARCHIVE_FATAL);
1118 			}
1119 		} else {
1120 			p = _p;
1121 		}
1122 		cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1123 		__archive_read_consume(a, AUTH_CODE_SIZE);
1124 		if (cmp != 0) {
1125 			archive_set_error(&a->archive,
1126 			    ARCHIVE_ERRNO_MISC,
1127 			    "ZIP bad Authentication code");
1128 			return (ARCHIVE_WARN);
1129 		}
1130 	}
1131 	return (ARCHIVE_OK);
1132 }
1133 
1134 /*
1135  * Read "uncompressed" data.  There are three cases:
1136  *  1) We know the size of the data.  This is always true for the
1137  * seeking reader (we've examined the Central Directory already).
1138  *  2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1139  * Info-ZIP seems to do this; we know the size but have to grab
1140  * the CRC from the data descriptor afterwards.
1141  *  3) We're streaming and ZIP_LENGTH_AT_END was specified and
1142  * we have no size information.  In this case, we can do pretty
1143  * well by watching for the data descriptor record.  The data
1144  * descriptor is 16 bytes and includes a computed CRC that should
1145  * provide a strong check.
1146  *
1147  * TODO: Technically, the PK\007\010 signature is optional.
1148  * In the original spec, the data descriptor contained CRC
1149  * and size fields but had no leading signature.  In practice,
1150  * newer writers seem to provide the signature pretty consistently.
1151  *
1152  * For uncompressed data, the PK\007\010 marker seems essential
1153  * to be sure we've actually seen the end of the entry.
1154  *
1155  * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1156  * zip->end_of_entry if it consumes all of the data.
1157  */
1158 static int
1159 zip_read_data_none(struct archive_read *a, const void **_buff,
1160     size_t *size, int64_t *offset)
1161 {
1162 	struct zip *zip;
1163 	const char *buff;
1164 	ssize_t bytes_avail;
1165 	int r;
1166 
1167 	(void)offset; /* UNUSED */
1168 
1169 	zip = (struct zip *)(a->format->data);
1170 
1171 	if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1172 		const char *p;
1173 		ssize_t grabbing_bytes = 24;
1174 
1175 		if (zip->hctx_valid)
1176 			grabbing_bytes += AUTH_CODE_SIZE;
1177 		/* Grab at least 24 bytes. */
1178 		buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1179 		if (bytes_avail < grabbing_bytes) {
1180 			/* Zip archives have end-of-archive markers
1181 			   that are longer than this, so a failure to get at
1182 			   least 24 bytes really does indicate a truncated
1183 			   file. */
1184 			archive_set_error(&a->archive,
1185 			    ARCHIVE_ERRNO_FILE_FORMAT,
1186 			    "Truncated ZIP file data");
1187 			return (ARCHIVE_FATAL);
1188 		}
1189 		/* Check for a complete PK\007\010 signature, followed
1190 		 * by the correct 4-byte CRC. */
1191 		p = buff;
1192 		if (zip->hctx_valid)
1193 			p += AUTH_CODE_SIZE;
1194 		if (p[0] == 'P' && p[1] == 'K'
1195 		    && p[2] == '\007' && p[3] == '\010'
1196 		    && (archive_le32dec(p + 4) == zip->entry_crc32
1197 			|| zip->ignore_crc32
1198 			|| (zip->hctx_valid
1199 			 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1200 			if (zip->entry->flags & LA_USED_ZIP64) {
1201 				uint64_t compressed, uncompressed;
1202 				zip->entry->crc32 = archive_le32dec(p + 4);
1203 				compressed = archive_le64dec(p + 8);
1204 				uncompressed = archive_le64dec(p + 16);
1205 				if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1206 					archive_set_error(&a->archive,
1207 					    ARCHIVE_ERRNO_FILE_FORMAT,
1208 					    "Overflow of 64-bit file sizes");
1209 					return ARCHIVE_FAILED;
1210 				}
1211 				zip->entry->compressed_size = compressed;
1212 				zip->entry->uncompressed_size = uncompressed;
1213 				zip->unconsumed = 24;
1214 			} else {
1215 				zip->entry->crc32 = archive_le32dec(p + 4);
1216 				zip->entry->compressed_size =
1217 					archive_le32dec(p + 8);
1218 				zip->entry->uncompressed_size =
1219 					archive_le32dec(p + 12);
1220 				zip->unconsumed = 16;
1221 			}
1222 			if (zip->hctx_valid) {
1223 				r = check_authentication_code(a, buff);
1224 				if (r != ARCHIVE_OK)
1225 					return (r);
1226 			}
1227 			zip->end_of_entry = 1;
1228 			return (ARCHIVE_OK);
1229 		}
1230 		/* If not at EOF, ensure we consume at least one byte. */
1231 		++p;
1232 
1233 		/* Scan forward until we see where a PK\007\010 signature
1234 		 * might be. */
1235 		/* Return bytes up until that point.  On the next call,
1236 		 * the code above will verify the data descriptor. */
1237 		while (p < buff + bytes_avail - 4) {
1238 			if (p[3] == 'P') { p += 3; }
1239 			else if (p[3] == 'K') { p += 2; }
1240 			else if (p[3] == '\007') { p += 1; }
1241 			else if (p[3] == '\010' && p[2] == '\007'
1242 			    && p[1] == 'K' && p[0] == 'P') {
1243 				if (zip->hctx_valid)
1244 					p -= AUTH_CODE_SIZE;
1245 				break;
1246 			} else { p += 4; }
1247 		}
1248 		bytes_avail = p - buff;
1249 	} else {
1250 		if (zip->entry_bytes_remaining == 0) {
1251 			zip->end_of_entry = 1;
1252 			if (zip->hctx_valid) {
1253 				r = check_authentication_code(a, NULL);
1254 				if (r != ARCHIVE_OK)
1255 					return (r);
1256 			}
1257 			return (ARCHIVE_OK);
1258 		}
1259 		/* Grab a bunch of bytes. */
1260 		buff = __archive_read_ahead(a, 1, &bytes_avail);
1261 		if (bytes_avail <= 0) {
1262 			archive_set_error(&a->archive,
1263 			    ARCHIVE_ERRNO_FILE_FORMAT,
1264 			    "Truncated ZIP file data");
1265 			return (ARCHIVE_FATAL);
1266 		}
1267 		if (bytes_avail > zip->entry_bytes_remaining)
1268 			bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1269 	}
1270 	if (zip->tctx_valid || zip->cctx_valid) {
1271 		size_t dec_size = bytes_avail;
1272 
1273 		if (dec_size > zip->decrypted_buffer_size)
1274 			dec_size = zip->decrypted_buffer_size;
1275 		if (zip->tctx_valid) {
1276 			trad_enc_decrypt_update(&zip->tctx,
1277 			    (const uint8_t *)buff, dec_size,
1278 			    zip->decrypted_buffer, dec_size);
1279 		} else {
1280 			size_t dsize = dec_size;
1281 			archive_hmac_sha1_update(&zip->hctx,
1282 			    (const uint8_t *)buff, dec_size);
1283 			archive_decrypto_aes_ctr_update(&zip->cctx,
1284 			    (const uint8_t *)buff, dec_size,
1285 			    zip->decrypted_buffer, &dsize);
1286 		}
1287 		bytes_avail = dec_size;
1288 		buff = (const char *)zip->decrypted_buffer;
1289 	}
1290 	*size = bytes_avail;
1291 	zip->entry_bytes_remaining -= bytes_avail;
1292 	zip->entry_uncompressed_bytes_read += bytes_avail;
1293 	zip->entry_compressed_bytes_read += bytes_avail;
1294 	zip->unconsumed += bytes_avail;
1295 	*_buff = buff;
1296 	return (ARCHIVE_OK);
1297 }
1298 
1299 #ifdef HAVE_ZLIB_H
1300 static int
1301 zip_deflate_init(struct archive_read *a, struct zip *zip)
1302 {
1303 	int r;
1304 
1305 	/* If we haven't yet read any data, initialize the decompressor. */
1306 	if (!zip->decompress_init) {
1307 		if (zip->stream_valid)
1308 			r = inflateReset(&zip->stream);
1309 		else
1310 			r = inflateInit2(&zip->stream,
1311 			    -15 /* Don't check for zlib header */);
1312 		if (r != Z_OK) {
1313 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1314 			    "Can't initialize ZIP decompression.");
1315 			return (ARCHIVE_FATAL);
1316 		}
1317 		/* Stream structure has been set up. */
1318 		zip->stream_valid = 1;
1319 		/* We've initialized decompression for this stream. */
1320 		zip->decompress_init = 1;
1321 	}
1322 	return (ARCHIVE_OK);
1323 }
1324 
1325 static int
1326 zip_read_data_deflate(struct archive_read *a, const void **buff,
1327     size_t *size, int64_t *offset)
1328 {
1329 	struct zip *zip;
1330 	ssize_t bytes_avail;
1331 	const void *compressed_buff, *sp;
1332 	int r;
1333 
1334 	(void)offset; /* UNUSED */
1335 
1336 	zip = (struct zip *)(a->format->data);
1337 
1338 	/* If the buffer hasn't been allocated, allocate it now. */
1339 	if (zip->uncompressed_buffer == NULL) {
1340 		zip->uncompressed_buffer_size = 256 * 1024;
1341 		zip->uncompressed_buffer
1342 		    = (unsigned char *)malloc(zip->uncompressed_buffer_size);
1343 		if (zip->uncompressed_buffer == NULL) {
1344 			archive_set_error(&a->archive, ENOMEM,
1345 			    "No memory for ZIP decompression");
1346 			return (ARCHIVE_FATAL);
1347 		}
1348 	}
1349 
1350 	r = zip_deflate_init(a, zip);
1351 	if (r != ARCHIVE_OK)
1352 		return (r);
1353 
1354 	/*
1355 	 * Note: '1' here is a performance optimization.
1356 	 * Recall that the decompression layer returns a count of
1357 	 * available bytes; asking for more than that forces the
1358 	 * decompressor to combine reads by copying data.
1359 	 */
1360 	compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
1361 	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1362 	    && bytes_avail > zip->entry_bytes_remaining) {
1363 		bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1364 	}
1365 	if (bytes_avail < 0) {
1366 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1367 		    "Truncated ZIP file body");
1368 		return (ARCHIVE_FATAL);
1369 	}
1370 
1371 	if (zip->tctx_valid || zip->cctx_valid) {
1372 		if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
1373 			size_t buff_remaining =
1374 			    (zip->decrypted_buffer + zip->decrypted_buffer_size)
1375 			    - (zip->decrypted_ptr + zip->decrypted_bytes_remaining);
1376 
1377 			if (buff_remaining > (size_t)bytes_avail)
1378 				buff_remaining = (size_t)bytes_avail;
1379 
1380 			if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
1381 			      zip->entry_bytes_remaining > 0) {
1382 				if ((int64_t)(zip->decrypted_bytes_remaining
1383 				    + buff_remaining)
1384 				      > zip->entry_bytes_remaining) {
1385 					if (zip->entry_bytes_remaining <
1386 					      (int64_t)zip->decrypted_bytes_remaining)
1387 						buff_remaining = 0;
1388 					else
1389 						buff_remaining =
1390 						    (size_t)zip->entry_bytes_remaining
1391 						      - zip->decrypted_bytes_remaining;
1392 				}
1393 			}
1394 			if (buff_remaining > 0) {
1395 				if (zip->tctx_valid) {
1396 					trad_enc_decrypt_update(&zip->tctx,
1397 					    compressed_buff, buff_remaining,
1398 					    zip->decrypted_ptr
1399 					      + zip->decrypted_bytes_remaining,
1400 					    buff_remaining);
1401 				} else {
1402 					size_t dsize = buff_remaining;
1403 					archive_decrypto_aes_ctr_update(
1404 					    &zip->cctx,
1405 					    compressed_buff, buff_remaining,
1406 					    zip->decrypted_ptr
1407 					      + zip->decrypted_bytes_remaining,
1408 					    &dsize);
1409 				}
1410 				zip->decrypted_bytes_remaining += buff_remaining;
1411 			}
1412 		}
1413 		bytes_avail = zip->decrypted_bytes_remaining;
1414 		compressed_buff = (const char *)zip->decrypted_ptr;
1415 	}
1416 
1417 	/*
1418 	 * A bug in zlib.h: stream.next_in should be marked 'const'
1419 	 * but isn't (the library never alters data through the
1420 	 * next_in pointer, only reads it).  The result: this ugly
1421 	 * cast to remove 'const'.
1422 	 */
1423 	zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
1424 	zip->stream.avail_in = (uInt)bytes_avail;
1425 	zip->stream.total_in = 0;
1426 	zip->stream.next_out = zip->uncompressed_buffer;
1427 	zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
1428 	zip->stream.total_out = 0;
1429 
1430 	r = inflate(&zip->stream, 0);
1431 	switch (r) {
1432 	case Z_OK:
1433 		break;
1434 	case Z_STREAM_END:
1435 		zip->end_of_entry = 1;
1436 		break;
1437 	case Z_MEM_ERROR:
1438 		archive_set_error(&a->archive, ENOMEM,
1439 		    "Out of memory for ZIP decompression");
1440 		return (ARCHIVE_FATAL);
1441 	default:
1442 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1443 		    "ZIP decompression failed (%d)", r);
1444 		return (ARCHIVE_FATAL);
1445 	}
1446 
1447 	/* Consume as much as the compressor actually used. */
1448 	bytes_avail = zip->stream.total_in;
1449 	if (zip->tctx_valid || zip->cctx_valid) {
1450 		zip->decrypted_bytes_remaining -= bytes_avail;
1451 		if (zip->decrypted_bytes_remaining == 0)
1452 			zip->decrypted_ptr = zip->decrypted_buffer;
1453 		else
1454 			zip->decrypted_ptr += bytes_avail;
1455 	}
1456 	/* Calculate compressed data as much as we used.*/
1457 	if (zip->hctx_valid)
1458 		archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
1459 	__archive_read_consume(a, bytes_avail);
1460 	zip->entry_bytes_remaining -= bytes_avail;
1461 	zip->entry_compressed_bytes_read += bytes_avail;
1462 
1463 	*size = zip->stream.total_out;
1464 	zip->entry_uncompressed_bytes_read += zip->stream.total_out;
1465 	*buff = zip->uncompressed_buffer;
1466 
1467 	if (zip->end_of_entry && zip->hctx_valid) {
1468 		r = check_authentication_code(a, NULL);
1469 		if (r != ARCHIVE_OK)
1470 			return (r);
1471 	}
1472 
1473 	if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1474 		const char *p;
1475 
1476 		if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1477 			archive_set_error(&a->archive,
1478 			    ARCHIVE_ERRNO_FILE_FORMAT,
1479 			    "Truncated ZIP end-of-file record");
1480 			return (ARCHIVE_FATAL);
1481 		}
1482 		/* Consume the optional PK\007\010 marker. */
1483 		if (p[0] == 'P' && p[1] == 'K' &&
1484 		    p[2] == '\007' && p[3] == '\010') {
1485 			p += 4;
1486 			zip->unconsumed = 4;
1487 		}
1488 		if (zip->entry->flags & LA_USED_ZIP64) {
1489 			uint64_t compressed, uncompressed;
1490 			zip->entry->crc32 = archive_le32dec(p);
1491 			compressed = archive_le64dec(p + 4);
1492 			uncompressed = archive_le64dec(p + 12);
1493 			if (compressed > INT64_MAX || uncompressed > INT64_MAX) {
1494 				archive_set_error(&a->archive,
1495 				    ARCHIVE_ERRNO_FILE_FORMAT,
1496 				    "Overflow of 64-bit file sizes");
1497 				return ARCHIVE_FAILED;
1498 			}
1499 			zip->entry->compressed_size = compressed;
1500 			zip->entry->uncompressed_size = uncompressed;
1501 			zip->unconsumed += 20;
1502 		} else {
1503 			zip->entry->crc32 = archive_le32dec(p);
1504 			zip->entry->compressed_size = archive_le32dec(p + 4);
1505 			zip->entry->uncompressed_size = archive_le32dec(p + 8);
1506 			zip->unconsumed += 12;
1507 		}
1508 	}
1509 
1510 	return (ARCHIVE_OK);
1511 }
1512 #endif
1513 
1514 static int
1515 read_decryption_header(struct archive_read *a)
1516 {
1517 	struct zip *zip = (struct zip *)(a->format->data);
1518 	const char *p;
1519 	unsigned int remaining_size;
1520 	unsigned int ts;
1521 
1522 	/*
1523 	 * Read an initialization vector data field.
1524 	 */
1525 	p = __archive_read_ahead(a, 2, NULL);
1526 	if (p == NULL)
1527 		goto truncated;
1528 	ts = zip->iv_size;
1529 	zip->iv_size = archive_le16dec(p);
1530 	__archive_read_consume(a, 2);
1531 	if (ts < zip->iv_size) {
1532 		free(zip->iv);
1533 		zip->iv = NULL;
1534 	}
1535 	p = __archive_read_ahead(a, zip->iv_size, NULL);
1536 	if (p == NULL)
1537 		goto truncated;
1538 	if (zip->iv == NULL) {
1539 		zip->iv = malloc(zip->iv_size);
1540 		if (zip->iv == NULL)
1541 			goto nomem;
1542 	}
1543 	memcpy(zip->iv, p, zip->iv_size);
1544 	__archive_read_consume(a, zip->iv_size);
1545 
1546 	/*
1547 	 * Read a size of remaining decryption header field.
1548 	 */
1549 	p = __archive_read_ahead(a, 14, NULL);
1550 	if (p == NULL)
1551 		goto truncated;
1552 	remaining_size = archive_le32dec(p);
1553 	if (remaining_size < 16 || remaining_size > (1 << 18))
1554 		goto corrupted;
1555 
1556 	/* Check if format version is supported. */
1557 	if (archive_le16dec(p+4) != 3) {
1558 		archive_set_error(&a->archive,
1559 		    ARCHIVE_ERRNO_FILE_FORMAT,
1560 		    "Unsupported encryption format version: %u",
1561 		    archive_le16dec(p+4));
1562 		return (ARCHIVE_FAILED);
1563 	}
1564 
1565 	/*
1566 	 * Read an encryption algorithm field.
1567 	 */
1568 	zip->alg_id = archive_le16dec(p+6);
1569 	switch (zip->alg_id) {
1570 	case 0x6601:/* DES */
1571 	case 0x6602:/* RC2 */
1572 	case 0x6603:/* 3DES 168 */
1573 	case 0x6609:/* 3DES 112 */
1574 	case 0x660E:/* AES 128 */
1575 	case 0x660F:/* AES 192 */
1576 	case 0x6610:/* AES 256 */
1577 	case 0x6702:/* RC2 (version >= 5.2) */
1578 	case 0x6720:/* Blowfish */
1579 	case 0x6721:/* Twofish */
1580 	case 0x6801:/* RC4 */
1581 		/* Supported encryption algorithm. */
1582 		break;
1583 	default:
1584 		archive_set_error(&a->archive,
1585 		    ARCHIVE_ERRNO_FILE_FORMAT,
1586 		    "Unknown encryption algorithm: %u", zip->alg_id);
1587 		return (ARCHIVE_FAILED);
1588 	}
1589 
1590 	/*
1591 	 * Read a bit length field.
1592 	 */
1593 	zip->bit_len = archive_le16dec(p+8);
1594 
1595 	/*
1596 	 * Read a flags field.
1597 	 */
1598 	zip->flags = archive_le16dec(p+10);
1599 	switch (zip->flags & 0xf000) {
1600 	case 0x0001: /* Password is required to decrypt. */
1601 	case 0x0002: /* Certificates only. */
1602 	case 0x0003: /* Password or certificate required to decrypt. */
1603 		break;
1604 	default:
1605 		archive_set_error(&a->archive,
1606 		    ARCHIVE_ERRNO_FILE_FORMAT,
1607 		    "Unknown encryption flag: %u", zip->flags);
1608 		return (ARCHIVE_FAILED);
1609 	}
1610 	if ((zip->flags & 0xf000) == 0 ||
1611 	    (zip->flags & 0xf000) == 0x4000) {
1612 		archive_set_error(&a->archive,
1613 		    ARCHIVE_ERRNO_FILE_FORMAT,
1614 		    "Unknown encryption flag: %u", zip->flags);
1615 		return (ARCHIVE_FAILED);
1616 	}
1617 
1618 	/*
1619 	 * Read an encrypted random data field.
1620 	 */
1621 	ts = zip->erd_size;
1622 	zip->erd_size = archive_le16dec(p+12);
1623 	__archive_read_consume(a, 14);
1624 	if ((zip->erd_size & 0xf) != 0 ||
1625 	    (zip->erd_size + 16) > remaining_size ||
1626 	    (zip->erd_size + 16) < zip->erd_size)
1627 		goto corrupted;
1628 
1629 	if (ts < zip->erd_size) {
1630 		free(zip->erd);
1631 		zip->erd = NULL;
1632 	}
1633 	p = __archive_read_ahead(a, zip->erd_size, NULL);
1634 	if (p == NULL)
1635 		goto truncated;
1636 	if (zip->erd == NULL) {
1637 		zip->erd = malloc(zip->erd_size);
1638 		if (zip->erd == NULL)
1639 			goto nomem;
1640 	}
1641 	memcpy(zip->erd, p, zip->erd_size);
1642 	__archive_read_consume(a, zip->erd_size);
1643 
1644 	/*
1645 	 * Read a reserved data field.
1646 	 */
1647 	p = __archive_read_ahead(a, 4, NULL);
1648 	if (p == NULL)
1649 		goto truncated;
1650 	/* Reserved data size should be zero. */
1651 	if (archive_le32dec(p) != 0)
1652 		goto corrupted;
1653 	__archive_read_consume(a, 4);
1654 
1655 	/*
1656 	 * Read a password validation data field.
1657 	 */
1658 	p = __archive_read_ahead(a, 2, NULL);
1659 	if (p == NULL)
1660 		goto truncated;
1661 	ts = zip->v_size;
1662 	zip->v_size = archive_le16dec(p);
1663 	__archive_read_consume(a, 2);
1664 	if ((zip->v_size & 0x0f) != 0 ||
1665 	    (zip->erd_size + zip->v_size + 16) > remaining_size ||
1666 	    (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
1667 		goto corrupted;
1668 	if (ts < zip->v_size) {
1669 		free(zip->v_data);
1670 		zip->v_data = NULL;
1671 	}
1672 	p = __archive_read_ahead(a, zip->v_size, NULL);
1673 	if (p == NULL)
1674 		goto truncated;
1675 	if (zip->v_data == NULL) {
1676 		zip->v_data = malloc(zip->v_size);
1677 		if (zip->v_data == NULL)
1678 			goto nomem;
1679 	}
1680 	memcpy(zip->v_data, p, zip->v_size);
1681 	__archive_read_consume(a, zip->v_size);
1682 
1683 	p = __archive_read_ahead(a, 4, NULL);
1684 	if (p == NULL)
1685 		goto truncated;
1686 	zip->v_crc32 = archive_le32dec(p);
1687 	__archive_read_consume(a, 4);
1688 
1689 	/*return (ARCHIVE_OK);
1690 	 * This is not fully implemented yet.*/
1691 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1692 	    "Encrypted file is unsupported");
1693 	return (ARCHIVE_FAILED);
1694 truncated:
1695 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1696 	    "Truncated ZIP file data");
1697 	return (ARCHIVE_FATAL);
1698 corrupted:
1699 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1700 	    "Corrupted ZIP file data");
1701 	return (ARCHIVE_FATAL);
1702 nomem:
1703 	archive_set_error(&a->archive, ENOMEM,
1704 	    "No memory for ZIP decryption");
1705 	return (ARCHIVE_FATAL);
1706 }
1707 
1708 static int
1709 zip_alloc_decryption_buffer(struct archive_read *a)
1710 {
1711 	struct zip *zip = (struct zip *)(a->format->data);
1712 	size_t bs = 256 * 1024;
1713 
1714 	if (zip->decrypted_buffer == NULL) {
1715 		zip->decrypted_buffer_size = bs;
1716 		zip->decrypted_buffer = malloc(bs);
1717 		if (zip->decrypted_buffer == NULL) {
1718 			archive_set_error(&a->archive, ENOMEM,
1719 			    "No memory for ZIP decryption");
1720 			return (ARCHIVE_FATAL);
1721 		}
1722 	}
1723 	zip->decrypted_ptr = zip->decrypted_buffer;
1724 	return (ARCHIVE_OK);
1725 }
1726 
1727 static int
1728 init_traditional_PKWARE_decryption(struct archive_read *a)
1729 {
1730 	struct zip *zip = (struct zip *)(a->format->data);
1731 	const void *p;
1732 	int retry;
1733 	int r;
1734 
1735 	if (zip->tctx_valid)
1736 		return (ARCHIVE_OK);
1737 
1738 	/*
1739 	   Read the 12 bytes encryption header stored at
1740 	   the start of the data area.
1741 	 */
1742 #define ENC_HEADER_SIZE	12
1743 	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1744 	    && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
1745 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1746 		    "Truncated Zip encrypted body: only %jd bytes available",
1747 		    (intmax_t)zip->entry_bytes_remaining);
1748 		return (ARCHIVE_FATAL);
1749 	}
1750 
1751 	p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
1752 	if (p == NULL) {
1753 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1754 		    "Truncated ZIP file data");
1755 		return (ARCHIVE_FATAL);
1756 	}
1757 
1758 	for (retry = 0;; retry++) {
1759 		const char *passphrase;
1760 		uint8_t crcchk;
1761 
1762 		passphrase = __archive_read_next_passphrase(a);
1763 		if (passphrase == NULL) {
1764 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1765 			    (retry > 0)?
1766 				"Incorrect passphrase":
1767 				"Passphrase required for this entry");
1768 			return (ARCHIVE_FAILED);
1769 		}
1770 
1771 		/*
1772 		 * Initialize ctx for Traditional PKWARE Decryption.
1773 		 */
1774 		r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
1775 			p, ENC_HEADER_SIZE, &crcchk);
1776 		if (r == 0 && crcchk == zip->entry->decdat)
1777 			break;/* The passphrase is OK. */
1778 		if (retry > 10000) {
1779 			/* Avoid infinity loop. */
1780 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1781 			    "Too many incorrect passphrases");
1782 			return (ARCHIVE_FAILED);
1783 		}
1784 	}
1785 
1786 	__archive_read_consume(a, ENC_HEADER_SIZE);
1787 	zip->tctx_valid = 1;
1788 	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1789 	    zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
1790 	}
1791 	/*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
1792 	zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
1793 	zip->decrypted_bytes_remaining = 0;
1794 
1795 	return (zip_alloc_decryption_buffer(a));
1796 #undef ENC_HEADER_SIZE
1797 }
1798 
1799 static int
1800 init_WinZip_AES_decryption(struct archive_read *a)
1801 {
1802 	struct zip *zip = (struct zip *)(a->format->data);
1803 	const void *p;
1804 	const uint8_t *pv;
1805 	size_t key_len, salt_len;
1806 	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
1807 	int retry;
1808 	int r;
1809 
1810 	if (zip->cctx_valid || zip->hctx_valid)
1811 		return (ARCHIVE_OK);
1812 
1813 	switch (zip->entry->aes_extra.strength) {
1814 	case 1: salt_len = 8;  key_len = 16; break;
1815 	case 2: salt_len = 12; key_len = 24; break;
1816 	case 3: salt_len = 16; key_len = 32; break;
1817 	default: goto corrupted;
1818 	}
1819 	p = __archive_read_ahead(a, salt_len + 2, NULL);
1820 	if (p == NULL)
1821 		goto truncated;
1822 
1823 	for (retry = 0;; retry++) {
1824 		const char *passphrase;
1825 
1826 		passphrase = __archive_read_next_passphrase(a);
1827 		if (passphrase == NULL) {
1828 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1829 			    (retry > 0)?
1830 				"Incorrect passphrase":
1831 				"Passphrase required for this entry");
1832 			return (ARCHIVE_FAILED);
1833 		}
1834 		memset(derived_key, 0, sizeof(derived_key));
1835 		r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
1836 		    p, salt_len, 1000, derived_key, key_len * 2 + 2);
1837 		if (r != 0) {
1838 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1839 			    "Decryption is unsupported due to lack of "
1840 			    "crypto library");
1841 			return (ARCHIVE_FAILED);
1842 		}
1843 
1844 		/* Check password verification value. */
1845 		pv = ((const uint8_t *)p) + salt_len;
1846 		if (derived_key[key_len * 2] == pv[0] &&
1847 		    derived_key[key_len * 2 + 1] == pv[1])
1848 			break;/* The passphrase is OK. */
1849 		if (retry > 10000) {
1850 			/* Avoid infinity loop. */
1851 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1852 			    "Too many incorrect passphrases");
1853 			return (ARCHIVE_FAILED);
1854 		}
1855 	}
1856 
1857 	r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
1858 	if (r != 0) {
1859 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1860 		    "Decryption is unsupported due to lack of crypto library");
1861 		return (ARCHIVE_FAILED);
1862 	}
1863 	r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
1864 	if (r != 0) {
1865 		archive_decrypto_aes_ctr_release(&zip->cctx);
1866 		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1867 		    "Failed to initialize HMAC-SHA1");
1868 		return (ARCHIVE_FAILED);
1869 	}
1870 	zip->cctx_valid = zip->hctx_valid = 1;
1871 	__archive_read_consume(a, salt_len + 2);
1872 	zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
1873 	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
1874 	    && zip->entry_bytes_remaining < 0)
1875 		goto corrupted;
1876 	zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
1877 	zip->decrypted_bytes_remaining = 0;
1878 
1879 	zip->entry->compression = zip->entry->aes_extra.compression;
1880 	return (zip_alloc_decryption_buffer(a));
1881 
1882 truncated:
1883 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1884 	    "Truncated ZIP file data");
1885 	return (ARCHIVE_FATAL);
1886 corrupted:
1887 	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1888 	    "Corrupted ZIP file data");
1889 	return (ARCHIVE_FATAL);
1890 }
1891 
1892 static int
1893 archive_read_format_zip_read_data(struct archive_read *a,
1894     const void **buff, size_t *size, int64_t *offset)
1895 {
1896 	int r;
1897 	struct zip *zip = (struct zip *)(a->format->data);
1898 
1899 	if (zip->has_encrypted_entries ==
1900 			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
1901 		zip->has_encrypted_entries = 0;
1902 	}
1903 
1904 	*offset = zip->entry_uncompressed_bytes_read;
1905 	*size = 0;
1906 	*buff = NULL;
1907 
1908 	/* If we hit end-of-entry last time, return ARCHIVE_EOF. */
1909 	if (zip->end_of_entry)
1910 		return (ARCHIVE_EOF);
1911 
1912 	/* Return EOF immediately if this is a non-regular file. */
1913 	if (AE_IFREG != (zip->entry->mode & AE_IFMT))
1914 		return (ARCHIVE_EOF);
1915 
1916 	__archive_read_consume(a, zip->unconsumed);
1917 	zip->unconsumed = 0;
1918 
1919 	if (zip->init_decryption) {
1920 		zip->has_encrypted_entries = 1;
1921 		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
1922 			r = read_decryption_header(a);
1923 		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
1924 			r = init_WinZip_AES_decryption(a);
1925 		else
1926 			r = init_traditional_PKWARE_decryption(a);
1927 		if (r != ARCHIVE_OK)
1928 			return (r);
1929 		zip->init_decryption = 0;
1930 	}
1931 
1932 	switch(zip->entry->compression) {
1933 	case 0:  /* No compression. */
1934 		r =  zip_read_data_none(a, buff, size, offset);
1935 		break;
1936 #ifdef HAVE_ZLIB_H
1937 	case 8: /* Deflate compression. */
1938 		r =  zip_read_data_deflate(a, buff, size, offset);
1939 		break;
1940 #endif
1941 	default: /* Unsupported compression. */
1942 		/* Return a warning. */
1943 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1944 		    "Unsupported ZIP compression method (%s)",
1945 		    compression_name(zip->entry->compression));
1946 		/* We can't decompress this entry, but we will
1947 		 * be able to skip() it and try the next entry. */
1948 		return (ARCHIVE_FAILED);
1949 		break;
1950 	}
1951 	if (r != ARCHIVE_OK)
1952 		return (r);
1953 	/* Update checksum */
1954 	if (*size)
1955 		zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
1956 		    (unsigned)*size);
1957 	/* If we hit the end, swallow any end-of-data marker. */
1958 	if (zip->end_of_entry) {
1959 		/* Check file size, CRC against these values. */
1960 		if (zip->entry->compressed_size !=
1961 		    zip->entry_compressed_bytes_read) {
1962 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1963 			    "ZIP compressed data is wrong size "
1964 			    "(read %jd, expected %jd)",
1965 			    (intmax_t)zip->entry_compressed_bytes_read,
1966 			    (intmax_t)zip->entry->compressed_size);
1967 			return (ARCHIVE_WARN);
1968 		}
1969 		/* Size field only stores the lower 32 bits of the actual
1970 		 * size. */
1971 		if ((zip->entry->uncompressed_size & UINT32_MAX)
1972 		    != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
1973 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1974 			    "ZIP uncompressed data is wrong size "
1975 			    "(read %jd, expected %jd)\n",
1976 			    (intmax_t)zip->entry_uncompressed_bytes_read,
1977 			    (intmax_t)zip->entry->uncompressed_size);
1978 			return (ARCHIVE_WARN);
1979 		}
1980 		/* Check computed CRC against header */
1981 		if ((!zip->hctx_valid ||
1982 		      zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
1983 		   zip->entry->crc32 != zip->entry_crc32
1984 		    && !zip->ignore_crc32) {
1985 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1986 			    "ZIP bad CRC: 0x%lx should be 0x%lx",
1987 			    (unsigned long)zip->entry_crc32,
1988 			    (unsigned long)zip->entry->crc32);
1989 			return (ARCHIVE_WARN);
1990 		}
1991 	}
1992 
1993 	return (ARCHIVE_OK);
1994 }
1995 
1996 static int
1997 archive_read_format_zip_cleanup(struct archive_read *a)
1998 {
1999 	struct zip *zip;
2000 	struct zip_entry *zip_entry, *next_zip_entry;
2001 
2002 	zip = (struct zip *)(a->format->data);
2003 #ifdef HAVE_ZLIB_H
2004 	if (zip->stream_valid)
2005 		inflateEnd(&zip->stream);
2006 	free(zip->uncompressed_buffer);
2007 #endif
2008 	if (zip->zip_entries) {
2009 		zip_entry = zip->zip_entries;
2010 		while (zip_entry != NULL) {
2011 			next_zip_entry = zip_entry->next;
2012 			archive_string_free(&zip_entry->rsrcname);
2013 			free(zip_entry);
2014 			zip_entry = next_zip_entry;
2015 		}
2016 	}
2017 	free(zip->decrypted_buffer);
2018 	if (zip->cctx_valid)
2019 		archive_decrypto_aes_ctr_release(&zip->cctx);
2020 	if (zip->hctx_valid)
2021 		archive_hmac_sha1_cleanup(&zip->hctx);
2022 	free(zip->iv);
2023 	free(zip->erd);
2024 	free(zip->v_data);
2025 	archive_string_free(&zip->format_name);
2026 	free(zip);
2027 	(a->format->data) = NULL;
2028 	return (ARCHIVE_OK);
2029 }
2030 
2031 static int
2032 archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
2033 {
2034 	if (_a && _a->format) {
2035 		struct zip * zip = (struct zip *)_a->format->data;
2036 		if (zip) {
2037 			return zip->has_encrypted_entries;
2038 		}
2039 	}
2040 	return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2041 }
2042 
2043 static int
2044 archive_read_format_zip_options(struct archive_read *a,
2045     const char *key, const char *val)
2046 {
2047 	struct zip *zip;
2048 	int ret = ARCHIVE_FAILED;
2049 
2050 	zip = (struct zip *)(a->format->data);
2051 	if (strcmp(key, "compat-2x")  == 0) {
2052 		/* Handle filenames as libarchive 2.x */
2053 		zip->init_default_conversion = (val != NULL) ? 1 : 0;
2054 		return (ARCHIVE_OK);
2055 	} else if (strcmp(key, "hdrcharset")  == 0) {
2056 		if (val == NULL || val[0] == 0)
2057 			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2058 			    "zip: hdrcharset option needs a character-set name"
2059 			);
2060 		else {
2061 			zip->sconv = archive_string_conversion_from_charset(
2062 			    &a->archive, val, 0);
2063 			if (zip->sconv != NULL) {
2064 				if (strcmp(val, "UTF-8") == 0)
2065 					zip->sconv_utf8 = zip->sconv;
2066 				ret = ARCHIVE_OK;
2067 			} else
2068 				ret = ARCHIVE_FATAL;
2069 		}
2070 		return (ret);
2071 	} else if (strcmp(key, "ignorecrc32") == 0) {
2072 		/* Mostly useful for testing. */
2073 		if (val == NULL || val[0] == 0) {
2074 			zip->crc32func = real_crc32;
2075 			zip->ignore_crc32 = 0;
2076 		} else {
2077 			zip->crc32func = fake_crc32;
2078 			zip->ignore_crc32 = 1;
2079 		}
2080 		return (ARCHIVE_OK);
2081 	} else if (strcmp(key, "mac-ext") == 0) {
2082 		zip->process_mac_extensions = (val != NULL && val[0] != 0);
2083 		return (ARCHIVE_OK);
2084 	}
2085 
2086 	/* Note: The "warn" return is just to inform the options
2087 	 * supervisor that we didn't handle it.  It will generate
2088 	 * a suitable error if no one used this option. */
2089 	return (ARCHIVE_WARN);
2090 }
2091 
2092 int
2093 archive_read_support_format_zip(struct archive *a)
2094 {
2095 	int r;
2096 	r = archive_read_support_format_zip_streamable(a);
2097 	if (r != ARCHIVE_OK)
2098 		return r;
2099 	return (archive_read_support_format_zip_seekable(a));
2100 }
2101 
2102 /* ------------------------------------------------------------------------ */
2103 
2104 /*
2105  * Streaming-mode support
2106  */
2107 
2108 
2109 static int
2110 archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
2111 {
2112 	(void)a; /* UNUSED */
2113 	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2114 		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2115 }
2116 
2117 static int
2118 archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
2119 {
2120 	const char *p;
2121 
2122 	(void)best_bid; /* UNUSED */
2123 
2124 	if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
2125 		return (-1);
2126 
2127 	/*
2128 	 * Bid of 29 here comes from:
2129 	 *  + 16 bits for "PK",
2130 	 *  + next 16-bit field has 6 options so contributes
2131 	 *    about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
2132 	 *
2133 	 * So we've effectively verified ~29 total bits of check data.
2134 	 */
2135 	if (p[0] == 'P' && p[1] == 'K') {
2136 		if ((p[2] == '\001' && p[3] == '\002')
2137 		    || (p[2] == '\003' && p[3] == '\004')
2138 		    || (p[2] == '\005' && p[3] == '\006')
2139 		    || (p[2] == '\006' && p[3] == '\006')
2140 		    || (p[2] == '\007' && p[3] == '\010')
2141 		    || (p[2] == '0' && p[3] == '0'))
2142 			return (29);
2143 	}
2144 
2145 	/* TODO: It's worth looking ahead a little bit for a valid
2146 	 * PK signature.  In particular, that would make it possible
2147 	 * to read some UUEncoded SFX files or SFX files coming from
2148 	 * a network socket. */
2149 
2150 	return (0);
2151 }
2152 
2153 static int
2154 archive_read_format_zip_streamable_read_header(struct archive_read *a,
2155     struct archive_entry *entry)
2156 {
2157 	struct zip *zip;
2158 
2159 	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
2160 	if (a->archive.archive_format_name == NULL)
2161 		a->archive.archive_format_name = "ZIP";
2162 
2163 	zip = (struct zip *)(a->format->data);
2164 
2165 	/*
2166 	 * It should be sufficient to call archive_read_next_header() for
2167 	 * a reader to determine if an entry is encrypted or not. If the
2168 	 * encryption of an entry is only detectable when calling
2169 	 * archive_read_data(), so be it. We'll do the same check there
2170 	 * as well.
2171 	 */
2172 	if (zip->has_encrypted_entries ==
2173 			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
2174 		zip->has_encrypted_entries = 0;
2175 
2176 	/* Make sure we have a zip_entry structure to use. */
2177 	if (zip->zip_entries == NULL) {
2178 		zip->zip_entries = malloc(sizeof(struct zip_entry));
2179 		if (zip->zip_entries == NULL) {
2180 			archive_set_error(&a->archive, ENOMEM,
2181 			    "Out  of memory");
2182 			return ARCHIVE_FATAL;
2183 		}
2184 	}
2185 	zip->entry = zip->zip_entries;
2186 	memset(zip->entry, 0, sizeof(struct zip_entry));
2187 
2188 	if (zip->cctx_valid)
2189 		archive_decrypto_aes_ctr_release(&zip->cctx);
2190 	if (zip->hctx_valid)
2191 		archive_hmac_sha1_cleanup(&zip->hctx);
2192 	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
2193 	__archive_read_reset_passphrase(a);
2194 
2195 	/* Search ahead for the next local file header. */
2196 	__archive_read_consume(a, zip->unconsumed);
2197 	zip->unconsumed = 0;
2198 	for (;;) {
2199 		int64_t skipped = 0;
2200 		const char *p, *end;
2201 		ssize_t bytes;
2202 
2203 		p = __archive_read_ahead(a, 4, &bytes);
2204 		if (p == NULL)
2205 			return (ARCHIVE_FATAL);
2206 		end = p + bytes;
2207 
2208 		while (p + 4 <= end) {
2209 			if (p[0] == 'P' && p[1] == 'K') {
2210 				if (p[2] == '\003' && p[3] == '\004') {
2211 					/* Regular file entry. */
2212 					__archive_read_consume(a, skipped);
2213 					return zip_read_local_file_header(a,
2214 					    entry, zip);
2215 				}
2216 
2217                               /*
2218                                * TODO: We cannot restore permissions
2219                                * based only on the local file headers.
2220                                * Consider scanning the central
2221                                * directory and returning additional
2222                                * entries for at least directories.
2223                                * This would allow us to properly set
2224                                * directory permissions.
2225 			       *
2226 			       * This won't help us fix symlinks
2227 			       * and may not help with regular file
2228 			       * permissions, either.  <sigh>
2229                                */
2230                               if (p[2] == '\001' && p[3] == '\002') {
2231                                       return (ARCHIVE_EOF);
2232                               }
2233 
2234                               /* End of central directory?  Must be an
2235                                * empty archive. */
2236                               if ((p[2] == '\005' && p[3] == '\006')
2237                                   || (p[2] == '\006' && p[3] == '\006'))
2238                                       return (ARCHIVE_EOF);
2239 			}
2240 			++p;
2241 			++skipped;
2242 		}
2243 		__archive_read_consume(a, skipped);
2244 	}
2245 }
2246 
2247 static int
2248 archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
2249 {
2250 	struct zip *zip;
2251 	int64_t bytes_skipped;
2252 
2253 	zip = (struct zip *)(a->format->data);
2254 	bytes_skipped = __archive_read_consume(a, zip->unconsumed);
2255 	zip->unconsumed = 0;
2256 	if (bytes_skipped < 0)
2257 		return (ARCHIVE_FATAL);
2258 
2259 	/* If we've already read to end of data, we're done. */
2260 	if (zip->end_of_entry)
2261 		return (ARCHIVE_OK);
2262 
2263 	/* So we know we're streaming... */
2264 	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2265 	    || zip->entry->compressed_size > 0) {
2266 		/* We know the compressed length, so we can just skip. */
2267 		bytes_skipped = __archive_read_consume(a,
2268 					zip->entry_bytes_remaining);
2269 		if (bytes_skipped < 0)
2270 			return (ARCHIVE_FATAL);
2271 		return (ARCHIVE_OK);
2272 	}
2273 
2274 	if (zip->init_decryption) {
2275 		int r;
2276 
2277 		zip->has_encrypted_entries = 1;
2278 		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2279 			r = read_decryption_header(a);
2280 		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2281 			r = init_WinZip_AES_decryption(a);
2282 		else
2283 			r = init_traditional_PKWARE_decryption(a);
2284 		if (r != ARCHIVE_OK)
2285 			return (r);
2286 		zip->init_decryption = 0;
2287 	}
2288 
2289 	/* We're streaming and we don't know the length. */
2290 	/* If the body is compressed and we know the format, we can
2291 	 * find an exact end-of-entry by decompressing it. */
2292 	switch (zip->entry->compression) {
2293 #ifdef HAVE_ZLIB_H
2294 	case 8: /* Deflate compression. */
2295 		while (!zip->end_of_entry) {
2296 			int64_t offset = 0;
2297 			const void *buff = NULL;
2298 			size_t size = 0;
2299 			int r;
2300 			r =  zip_read_data_deflate(a, &buff, &size, &offset);
2301 			if (r != ARCHIVE_OK)
2302 				return (r);
2303 		}
2304 		return ARCHIVE_OK;
2305 #endif
2306 	default: /* Uncompressed or unknown. */
2307 		/* Scan for a PK\007\010 signature. */
2308 		for (;;) {
2309 			const char *p, *buff;
2310 			ssize_t bytes_avail;
2311 			buff = __archive_read_ahead(a, 16, &bytes_avail);
2312 			if (bytes_avail < 16) {
2313 				archive_set_error(&a->archive,
2314 				    ARCHIVE_ERRNO_FILE_FORMAT,
2315 				    "Truncated ZIP file data");
2316 				return (ARCHIVE_FATAL);
2317 			}
2318 			p = buff;
2319 			while (p <= buff + bytes_avail - 16) {
2320 				if (p[3] == 'P') { p += 3; }
2321 				else if (p[3] == 'K') { p += 2; }
2322 				else if (p[3] == '\007') { p += 1; }
2323 				else if (p[3] == '\010' && p[2] == '\007'
2324 				    && p[1] == 'K' && p[0] == 'P') {
2325 					if (zip->entry->flags & LA_USED_ZIP64)
2326 						__archive_read_consume(a,
2327 						    p - buff + 24);
2328 					else
2329 						__archive_read_consume(a,
2330 						    p - buff + 16);
2331 					return ARCHIVE_OK;
2332 				} else { p += 4; }
2333 			}
2334 			__archive_read_consume(a, p - buff);
2335 		}
2336 	}
2337 }
2338 
2339 int
2340 archive_read_support_format_zip_streamable(struct archive *_a)
2341 {
2342 	struct archive_read *a = (struct archive_read *)_a;
2343 	struct zip *zip;
2344 	int r;
2345 
2346 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
2347 	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
2348 
2349 	zip = (struct zip *)calloc(1, sizeof(*zip));
2350 	if (zip == NULL) {
2351 		archive_set_error(&a->archive, ENOMEM,
2352 		    "Can't allocate zip data");
2353 		return (ARCHIVE_FATAL);
2354 	}
2355 
2356 	/* Streamable reader doesn't support mac extensions. */
2357 	zip->process_mac_extensions = 0;
2358 
2359 	/*
2360 	 * Until enough data has been read, we cannot tell about
2361 	 * any encrypted entries yet.
2362 	 */
2363 	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2364 	zip->crc32func = real_crc32;
2365 
2366 	r = __archive_read_register_format(a,
2367 	    zip,
2368 	    "zip",
2369 	    archive_read_format_zip_streamable_bid,
2370 	    archive_read_format_zip_options,
2371 	    archive_read_format_zip_streamable_read_header,
2372 	    archive_read_format_zip_read_data,
2373 	    archive_read_format_zip_read_data_skip_streamable,
2374 	    NULL,
2375 	    archive_read_format_zip_cleanup,
2376 	    archive_read_support_format_zip_capabilities_streamable,
2377 	    archive_read_format_zip_has_encrypted_entries);
2378 
2379 	if (r != ARCHIVE_OK)
2380 		free(zip);
2381 	return (ARCHIVE_OK);
2382 }
2383 
2384 /* ------------------------------------------------------------------------ */
2385 
2386 /*
2387  * Seeking-mode support
2388  */
2389 
2390 static int
2391 archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
2392 {
2393 	(void)a; /* UNUSED */
2394 	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
2395 		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
2396 }
2397 
2398 /*
2399  * TODO: This is a performance sink because it forces the read core to
2400  * drop buffered data from the start of file, which will then have to
2401  * be re-read again if this bidder loses.
2402  *
2403  * We workaround this a little by passing in the best bid so far so
2404  * that later bidders can do nothing if they know they'll never
2405  * outbid.  But we can certainly do better...
2406  */
2407 static int
2408 read_eocd(struct zip *zip, const char *p, int64_t current_offset)
2409 {
2410 	/* Sanity-check the EOCD we've found. */
2411 
2412 	/* This must be the first volume. */
2413 	if (archive_le16dec(p + 4) != 0)
2414 		return 0;
2415 	/* Central directory must be on this volume. */
2416 	if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
2417 		return 0;
2418 	/* All central directory entries must be on this volume. */
2419 	if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
2420 		return 0;
2421 	/* Central directory can't extend beyond start of EOCD record. */
2422 	if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
2423 	    > current_offset)
2424 		return 0;
2425 
2426 	/* Save the central directory location for later use. */
2427 	zip->central_directory_offset = archive_le32dec(p + 16);
2428 
2429 	/* This is just a tiny bit higher than the maximum
2430 	   returned by the streaming Zip bidder.  This ensures
2431 	   that the more accurate seeking Zip parser wins
2432 	   whenever seek is available. */
2433 	return 32;
2434 }
2435 
2436 /*
2437  * Examine Zip64 EOCD locator:  If it's valid, store the information
2438  * from it.
2439  */
2440 static int
2441 read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
2442 {
2443 	int64_t eocd64_offset;
2444 	int64_t eocd64_size;
2445 
2446 	/* Sanity-check the locator record. */
2447 
2448 	/* Central dir must be on first volume. */
2449 	if (archive_le32dec(p + 4) != 0)
2450 		return 0;
2451 	/* Must be only a single volume. */
2452 	if (archive_le32dec(p + 16) != 1)
2453 		return 0;
2454 
2455 	/* Find the Zip64 EOCD record. */
2456 	eocd64_offset = archive_le64dec(p + 8);
2457 	if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
2458 		return 0;
2459 	if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
2460 		return 0;
2461 	/* Make sure we can read all of it. */
2462 	eocd64_size = archive_le64dec(p + 4) + 12;
2463 	if (eocd64_size < 56 || eocd64_size > 16384)
2464 		return 0;
2465 	if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
2466 		return 0;
2467 
2468 	/* Sanity-check the EOCD64 */
2469 	if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
2470 		return 0;
2471 	if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
2472 		return 0;
2473 	/* CD can't be split. */
2474 	if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
2475 		return 0;
2476 
2477 	/* Save the central directory offset for later use. */
2478 	zip->central_directory_offset = archive_le64dec(p + 48);
2479 
2480 	return 32;
2481 }
2482 
2483 static int
2484 archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
2485 {
2486 	struct zip *zip = (struct zip *)a->format->data;
2487 	int64_t file_size, current_offset;
2488 	const char *p;
2489 	int i, tail;
2490 
2491 	/* If someone has already bid more than 32, then avoid
2492 	   trashing the look-ahead buffers with a seek. */
2493 	if (best_bid > 32)
2494 		return (-1);
2495 
2496 	file_size = __archive_read_seek(a, 0, SEEK_END);
2497 	if (file_size <= 0)
2498 		return 0;
2499 
2500 	/* Search last 16k of file for end-of-central-directory
2501 	 * record (which starts with PK\005\006) */
2502 	tail = (int)zipmin(1024 * 16, file_size);
2503 	current_offset = __archive_read_seek(a, -tail, SEEK_END);
2504 	if (current_offset < 0)
2505 		return 0;
2506 	if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
2507 		return 0;
2508 	/* Boyer-Moore search backwards from the end, since we want
2509 	 * to match the last EOCD in the file (there can be more than
2510 	 * one if there is an uncompressed Zip archive as a member
2511 	 * within this Zip archive). */
2512 	for (i = tail - 22; i > 0;) {
2513 		switch (p[i]) {
2514 		case 'P':
2515 			if (memcmp(p + i, "PK\005\006", 4) == 0) {
2516 				int ret = read_eocd(zip, p + i,
2517 				    current_offset + i);
2518 				/* Zip64 EOCD locator precedes
2519 				 * regular EOCD if present. */
2520 				if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
2521 					int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
2522 					if (ret_zip64 > ret)
2523 						ret = ret_zip64;
2524 				}
2525 				return (ret);
2526 			}
2527 			i -= 4;
2528 			break;
2529 		case 'K': i -= 1; break;
2530 		case 005: i -= 2; break;
2531 		case 006: i -= 3; break;
2532 		default: i -= 4; break;
2533 		}
2534 	}
2535 	return 0;
2536 }
2537 
2538 /* The red-black trees are only used in seeking mode to manage
2539  * the in-memory copy of the central directory. */
2540 
2541 static int
2542 cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
2543 {
2544 	const struct zip_entry *e1 = (const struct zip_entry *)n1;
2545 	const struct zip_entry *e2 = (const struct zip_entry *)n2;
2546 
2547 	if (e1->local_header_offset > e2->local_header_offset)
2548 		return -1;
2549 	if (e1->local_header_offset < e2->local_header_offset)
2550 		return 1;
2551 	return 0;
2552 }
2553 
2554 static int
2555 cmp_key(const struct archive_rb_node *n, const void *key)
2556 {
2557 	/* This function won't be called */
2558 	(void)n; /* UNUSED */
2559 	(void)key; /* UNUSED */
2560 	return 1;
2561 }
2562 
2563 static const struct archive_rb_tree_ops rb_ops = {
2564 	&cmp_node, &cmp_key
2565 };
2566 
2567 static int
2568 rsrc_cmp_node(const struct archive_rb_node *n1,
2569     const struct archive_rb_node *n2)
2570 {
2571 	const struct zip_entry *e1 = (const struct zip_entry *)n1;
2572 	const struct zip_entry *e2 = (const struct zip_entry *)n2;
2573 
2574 	return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
2575 }
2576 
2577 static int
2578 rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
2579 {
2580 	const struct zip_entry *e = (const struct zip_entry *)n;
2581 	return (strcmp((const char *)key, e->rsrcname.s));
2582 }
2583 
2584 static const struct archive_rb_tree_ops rb_rsrc_ops = {
2585 	&rsrc_cmp_node, &rsrc_cmp_key
2586 };
2587 
2588 static const char *
2589 rsrc_basename(const char *name, size_t name_length)
2590 {
2591 	const char *s, *r;
2592 
2593 	r = s = name;
2594 	for (;;) {
2595 		s = memchr(s, '/', name_length - (s - name));
2596 		if (s == NULL)
2597 			break;
2598 		r = ++s;
2599 	}
2600 	return (r);
2601 }
2602 
2603 static void
2604 expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
2605 {
2606 	struct archive_string str;
2607 	struct zip_entry *dir;
2608 	char *s;
2609 
2610 	archive_string_init(&str);
2611 	archive_strncpy(&str, name, name_length);
2612 	for (;;) {
2613 		s = strrchr(str.s, '/');
2614 		if (s == NULL)
2615 			break;
2616 		*s = '\0';
2617 		/* Transfer the parent directory from zip->tree_rsrc RB
2618 		 * tree to zip->tree RB tree to expose. */
2619 		dir = (struct zip_entry *)
2620 		    __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
2621 		if (dir == NULL)
2622 			break;
2623 		__archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
2624 		archive_string_free(&dir->rsrcname);
2625 		__archive_rb_tree_insert_node(&zip->tree, &dir->node);
2626 	}
2627 	archive_string_free(&str);
2628 }
2629 
2630 static int
2631 slurp_central_directory(struct archive_read *a, struct zip *zip)
2632 {
2633 	ssize_t i;
2634 	unsigned found;
2635 	int64_t correction;
2636 	ssize_t bytes_avail;
2637 	const char *p;
2638 
2639 	/*
2640 	 * Find the start of the central directory.  The end-of-CD
2641 	 * record has our starting point, but there are lots of
2642 	 * Zip archives which have had other data prepended to the
2643 	 * file, which makes the recorded offsets all too small.
2644 	 * So we search forward from the specified offset until we
2645 	 * find the real start of the central directory.  Then we
2646 	 * know the correction we need to apply to account for leading
2647 	 * padding.
2648 	 */
2649 	if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
2650 		return ARCHIVE_FATAL;
2651 
2652 	found = 0;
2653 	while (!found) {
2654 		if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
2655 			return ARCHIVE_FATAL;
2656 		for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
2657 			switch (p[i + 3]) {
2658 			case 'P': i += 3; break;
2659 			case 'K': i += 2; break;
2660 			case 001: i += 1; break;
2661 			case 002:
2662 				if (memcmp(p + i, "PK\001\002", 4) == 0) {
2663 					p += i;
2664 					found = 1;
2665 				} else
2666 					i += 4;
2667 				break;
2668 			case 005: i += 1; break;
2669 			case 006:
2670 				if (memcmp(p + i, "PK\005\006", 4) == 0) {
2671 					p += i;
2672 					found = 1;
2673 				} else if (memcmp(p + i, "PK\006\006", 4) == 0) {
2674 					p += i;
2675 					found = 1;
2676 				} else
2677 					i += 1;
2678 				break;
2679 			default: i += 4; break;
2680 			}
2681 		}
2682 		__archive_read_consume(a, i);
2683 	}
2684 	correction = archive_filter_bytes(&a->archive, 0)
2685 			- zip->central_directory_offset;
2686 
2687 	__archive_rb_tree_init(&zip->tree, &rb_ops);
2688 	__archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
2689 
2690 	zip->central_directory_entries_total = 0;
2691 	while (1) {
2692 		struct zip_entry *zip_entry;
2693 		size_t filename_length, extra_length, comment_length;
2694 		uint32_t external_attributes;
2695 		const char *name, *r;
2696 
2697 		if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
2698 			return ARCHIVE_FATAL;
2699 		if (memcmp(p, "PK\006\006", 4) == 0
2700 		    || memcmp(p, "PK\005\006", 4) == 0) {
2701 			break;
2702 		} else if (memcmp(p, "PK\001\002", 4) != 0) {
2703 			archive_set_error(&a->archive,
2704 			    -1, "Invalid central directory signature");
2705 			return ARCHIVE_FATAL;
2706 		}
2707 		if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
2708 			return ARCHIVE_FATAL;
2709 
2710 		zip_entry = calloc(1, sizeof(struct zip_entry));
2711 		zip_entry->next = zip->zip_entries;
2712 		zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
2713 		zip->zip_entries = zip_entry;
2714 		zip->central_directory_entries_total++;
2715 
2716 		/* version = p[4]; */
2717 		zip_entry->system = p[5];
2718 		/* version_required = archive_le16dec(p + 6); */
2719 		zip_entry->zip_flags = archive_le16dec(p + 8);
2720 		if (zip_entry->zip_flags
2721 		      & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
2722 			zip->has_encrypted_entries = 1;
2723 		}
2724 		zip_entry->compression = (char)archive_le16dec(p + 10);
2725 		zip_entry->mtime = zip_time(p + 12);
2726 		zip_entry->crc32 = archive_le32dec(p + 16);
2727 		if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
2728 			zip_entry->decdat = p[13];
2729 		else
2730 			zip_entry->decdat = p[19];
2731 		zip_entry->compressed_size = archive_le32dec(p + 20);
2732 		zip_entry->uncompressed_size = archive_le32dec(p + 24);
2733 		filename_length = archive_le16dec(p + 28);
2734 		extra_length = archive_le16dec(p + 30);
2735 		comment_length = archive_le16dec(p + 32);
2736 		/* disk_start = archive_le16dec(p + 34); */ /* Better be zero. */
2737 		/* internal_attributes = archive_le16dec(p + 36); */ /* text bit */
2738 		external_attributes = archive_le32dec(p + 38);
2739 		zip_entry->local_header_offset =
2740 		    archive_le32dec(p + 42) + correction;
2741 
2742 		/* If we can't guess the mode, leave it zero here;
2743 		   when we read the local file header we might get
2744 		   more information. */
2745 		if (zip_entry->system == 3) {
2746 			zip_entry->mode = external_attributes >> 16;
2747 		} else if (zip_entry->system == 0) {
2748 			// Interpret MSDOS directory bit
2749 			if (0x10 == (external_attributes & 0x10)) {
2750 				zip_entry->mode = AE_IFDIR | 0775;
2751 			} else {
2752 				zip_entry->mode = AE_IFREG | 0664;
2753 			}
2754 			if (0x01 == (external_attributes & 0x01)) {
2755 				// Read-only bit; strip write permissions
2756 				zip_entry->mode &= 0555;
2757 			}
2758 		} else {
2759 			zip_entry->mode = 0;
2760 		}
2761 
2762 		/* We're done with the regular data; get the filename and
2763 		 * extra data. */
2764 		__archive_read_consume(a, 46);
2765 		p = __archive_read_ahead(a, filename_length + extra_length,
2766 			NULL);
2767 		if (p == NULL) {
2768 			archive_set_error(&a->archive,
2769 			    ARCHIVE_ERRNO_FILE_FORMAT,
2770 			    "Truncated ZIP file header");
2771 			return ARCHIVE_FATAL;
2772 		}
2773 		if (ARCHIVE_OK != process_extra(a, p + filename_length, extra_length, zip_entry)) {
2774 			return ARCHIVE_FATAL;
2775 		}
2776 
2777 		/*
2778 		 * Mac resource fork files are stored under the
2779 		 * "__MACOSX/" directory, so we should check if
2780 		 * it is.
2781 		 */
2782 		if (!zip->process_mac_extensions) {
2783 			/* Treat every entry as a regular entry. */
2784 			__archive_rb_tree_insert_node(&zip->tree,
2785 			    &zip_entry->node);
2786 		} else {
2787 			name = p;
2788 			r = rsrc_basename(name, filename_length);
2789 			if (filename_length >= 9 &&
2790 			    strncmp("__MACOSX/", name, 9) == 0) {
2791 				/* If this file is not a resource fork nor
2792 				 * a directory. We should treat it as a non
2793 				 * resource fork file to expose it. */
2794 				if (name[filename_length-1] != '/' &&
2795 				    (r - name < 3 || r[0] != '.' || r[1] != '_')) {
2796 					__archive_rb_tree_insert_node(
2797 					    &zip->tree, &zip_entry->node);
2798 					/* Expose its parent directories. */
2799 					expose_parent_dirs(zip, name,
2800 					    filename_length);
2801 				} else {
2802 					/* This file is a resource fork file or
2803 					 * a directory. */
2804 					archive_strncpy(&(zip_entry->rsrcname),
2805 					     name, filename_length);
2806 					__archive_rb_tree_insert_node(
2807 					    &zip->tree_rsrc, &zip_entry->node);
2808 				}
2809 			} else {
2810 				/* Generate resource fork name to find its
2811 				 * resource file at zip->tree_rsrc. */
2812 				archive_strcpy(&(zip_entry->rsrcname),
2813 				    "__MACOSX/");
2814 				archive_strncat(&(zip_entry->rsrcname),
2815 				    name, r - name);
2816 				archive_strcat(&(zip_entry->rsrcname), "._");
2817 				archive_strncat(&(zip_entry->rsrcname),
2818 				    name + (r - name),
2819 				    filename_length - (r - name));
2820 				/* Register an entry to RB tree to sort it by
2821 				 * file offset. */
2822 				__archive_rb_tree_insert_node(&zip->tree,
2823 				    &zip_entry->node);
2824 			}
2825 		}
2826 
2827 		/* Skip the comment too ... */
2828 		__archive_read_consume(a,
2829 		    filename_length + extra_length + comment_length);
2830 	}
2831 
2832 	return ARCHIVE_OK;
2833 }
2834 
2835 static ssize_t
2836 zip_get_local_file_header_size(struct archive_read *a, size_t extra)
2837 {
2838 	const char *p;
2839 	ssize_t filename_length, extra_length;
2840 
2841 	if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
2842 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2843 		    "Truncated ZIP file header");
2844 		return (ARCHIVE_WARN);
2845 	}
2846 	p += extra;
2847 
2848 	if (memcmp(p, "PK\003\004", 4) != 0) {
2849 		archive_set_error(&a->archive, -1, "Damaged Zip archive");
2850 		return ARCHIVE_WARN;
2851 	}
2852 	filename_length = archive_le16dec(p + 26);
2853 	extra_length = archive_le16dec(p + 28);
2854 
2855 	return (30 + filename_length + extra_length);
2856 }
2857 
2858 static int
2859 zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
2860     struct zip_entry *rsrc)
2861 {
2862 	struct zip *zip = (struct zip *)a->format->data;
2863 	unsigned char *metadata, *mp;
2864 	int64_t offset = archive_filter_bytes(&a->archive, 0);
2865 	size_t remaining_bytes, metadata_bytes;
2866 	ssize_t hsize;
2867 	int ret = ARCHIVE_OK, eof;
2868 
2869 	switch(rsrc->compression) {
2870 	case 0:  /* No compression. */
2871 		if (rsrc->uncompressed_size != rsrc->compressed_size) {
2872 			archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2873 			    "Malformed OS X metadata entry: inconsistent size");
2874 			return (ARCHIVE_FATAL);
2875 		}
2876 #ifdef HAVE_ZLIB_H
2877 	case 8: /* Deflate compression. */
2878 #endif
2879 		break;
2880 	default: /* Unsupported compression. */
2881 		/* Return a warning. */
2882 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2883 		    "Unsupported ZIP compression method (%s)",
2884 		    compression_name(rsrc->compression));
2885 		/* We can't decompress this entry, but we will
2886 		 * be able to skip() it and try the next entry. */
2887 		return (ARCHIVE_WARN);
2888 	}
2889 
2890 	if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
2891 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2892 		    "Mac metadata is too large: %jd > 4M bytes",
2893 		    (intmax_t)rsrc->uncompressed_size);
2894 		return (ARCHIVE_WARN);
2895 	}
2896 	if (rsrc->compressed_size > (4 * 1024 * 1024)) {
2897 		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2898 		    "Mac metadata is too large: %jd > 4M bytes",
2899 		    (intmax_t)rsrc->compressed_size);
2900 		return (ARCHIVE_WARN);
2901 	}
2902 
2903 	metadata = malloc((size_t)rsrc->uncompressed_size);
2904 	if (metadata == NULL) {
2905 		archive_set_error(&a->archive, ENOMEM,
2906 		    "Can't allocate memory for Mac metadata");
2907 		return (ARCHIVE_FATAL);
2908 	}
2909 
2910 	if (offset < rsrc->local_header_offset)
2911 		__archive_read_consume(a, rsrc->local_header_offset - offset);
2912 	else if (offset != rsrc->local_header_offset) {
2913 		__archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
2914 	}
2915 
2916 	hsize = zip_get_local_file_header_size(a, 0);
2917 	__archive_read_consume(a, hsize);
2918 
2919 	remaining_bytes = (size_t)rsrc->compressed_size;
2920 	metadata_bytes = (size_t)rsrc->uncompressed_size;
2921 	mp = metadata;
2922 	eof = 0;
2923 	while (!eof && remaining_bytes) {
2924 		const unsigned char *p;
2925 		ssize_t bytes_avail;
2926 		size_t bytes_used;
2927 
2928 		p = __archive_read_ahead(a, 1, &bytes_avail);
2929 		if (p == NULL) {
2930 			archive_set_error(&a->archive,
2931 			    ARCHIVE_ERRNO_FILE_FORMAT,
2932 			    "Truncated ZIP file header");
2933 			ret = ARCHIVE_WARN;
2934 			goto exit_mac_metadata;
2935 		}
2936 		if ((size_t)bytes_avail > remaining_bytes)
2937 			bytes_avail = remaining_bytes;
2938 		switch(rsrc->compression) {
2939 		case 0:  /* No compression. */
2940 			if ((size_t)bytes_avail > metadata_bytes)
2941 				bytes_avail = metadata_bytes;
2942 			memcpy(mp, p, bytes_avail);
2943 			bytes_used = (size_t)bytes_avail;
2944 			metadata_bytes -= bytes_used;
2945 			mp += bytes_used;
2946 			if (metadata_bytes == 0)
2947 				eof = 1;
2948 			break;
2949 #ifdef HAVE_ZLIB_H
2950 		case 8: /* Deflate compression. */
2951 		{
2952 			int r;
2953 
2954 			ret = zip_deflate_init(a, zip);
2955 			if (ret != ARCHIVE_OK)
2956 				goto exit_mac_metadata;
2957 			zip->stream.next_in =
2958 			    (Bytef *)(uintptr_t)(const void *)p;
2959 			zip->stream.avail_in = (uInt)bytes_avail;
2960 			zip->stream.total_in = 0;
2961 			zip->stream.next_out = mp;
2962 			zip->stream.avail_out = (uInt)metadata_bytes;
2963 			zip->stream.total_out = 0;
2964 
2965 			r = inflate(&zip->stream, 0);
2966 			switch (r) {
2967 			case Z_OK:
2968 				break;
2969 			case Z_STREAM_END:
2970 				eof = 1;
2971 				break;
2972 			case Z_MEM_ERROR:
2973 				archive_set_error(&a->archive, ENOMEM,
2974 				    "Out of memory for ZIP decompression");
2975 				ret = ARCHIVE_FATAL;
2976 				goto exit_mac_metadata;
2977 			default:
2978 				archive_set_error(&a->archive,
2979 				    ARCHIVE_ERRNO_MISC,
2980 				    "ZIP decompression failed (%d)", r);
2981 				ret = ARCHIVE_FATAL;
2982 				goto exit_mac_metadata;
2983 			}
2984 			bytes_used = zip->stream.total_in;
2985 			metadata_bytes -= zip->stream.total_out;
2986 			mp += zip->stream.total_out;
2987 			break;
2988 		}
2989 #endif
2990 		default:
2991 			bytes_used = 0;
2992 			break;
2993 		}
2994 		__archive_read_consume(a, bytes_used);
2995 		remaining_bytes -= bytes_used;
2996 	}
2997 	archive_entry_copy_mac_metadata(entry, metadata,
2998 	    (size_t)rsrc->uncompressed_size - metadata_bytes);
2999 
3000 exit_mac_metadata:
3001 	__archive_read_seek(a, offset, SEEK_SET);
3002 	zip->decompress_init = 0;
3003 	free(metadata);
3004 	return (ret);
3005 }
3006 
3007 static int
3008 archive_read_format_zip_seekable_read_header(struct archive_read *a,
3009 	struct archive_entry *entry)
3010 {
3011 	struct zip *zip = (struct zip *)a->format->data;
3012 	struct zip_entry *rsrc;
3013 	int64_t offset;
3014 	int r, ret = ARCHIVE_OK;
3015 
3016 	/*
3017 	 * It should be sufficient to call archive_read_next_header() for
3018 	 * a reader to determine if an entry is encrypted or not. If the
3019 	 * encryption of an entry is only detectable when calling
3020 	 * archive_read_data(), so be it. We'll do the same check there
3021 	 * as well.
3022 	 */
3023 	if (zip->has_encrypted_entries ==
3024 			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3025 		zip->has_encrypted_entries = 0;
3026 
3027 	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3028 	if (a->archive.archive_format_name == NULL)
3029 		a->archive.archive_format_name = "ZIP";
3030 
3031 	if (zip->zip_entries == NULL) {
3032 		r = slurp_central_directory(a, zip);
3033 		if (r != ARCHIVE_OK)
3034 			return r;
3035 		/* Get first entry whose local header offset is lower than
3036 		 * other entries in the archive file. */
3037 		zip->entry =
3038 		    (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
3039 	} else if (zip->entry != NULL) {
3040 		/* Get next entry in local header offset order. */
3041 		zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
3042 		    &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
3043 	}
3044 
3045 	if (zip->entry == NULL)
3046 		return ARCHIVE_EOF;
3047 
3048 	if (zip->entry->rsrcname.s)
3049 		rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
3050 		    &zip->tree_rsrc, zip->entry->rsrcname.s);
3051 	else
3052 		rsrc = NULL;
3053 
3054 	if (zip->cctx_valid)
3055 		archive_decrypto_aes_ctr_release(&zip->cctx);
3056 	if (zip->hctx_valid)
3057 		archive_hmac_sha1_cleanup(&zip->hctx);
3058 	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3059 	__archive_read_reset_passphrase(a);
3060 
3061 	/* File entries are sorted by the header offset, we should mostly
3062 	 * use __archive_read_consume to advance a read point to avoid redundant
3063 	 * data reading.  */
3064 	offset = archive_filter_bytes(&a->archive, 0);
3065 	if (offset < zip->entry->local_header_offset)
3066 		__archive_read_consume(a,
3067 		    zip->entry->local_header_offset - offset);
3068 	else if (offset != zip->entry->local_header_offset) {
3069 		__archive_read_seek(a, zip->entry->local_header_offset,
3070 		    SEEK_SET);
3071 	}
3072 	zip->unconsumed = 0;
3073 	r = zip_read_local_file_header(a, entry, zip);
3074 	if (r != ARCHIVE_OK)
3075 		return r;
3076 	if (rsrc) {
3077 		int ret2 = zip_read_mac_metadata(a, entry, rsrc);
3078 		if (ret2 < ret)
3079 			ret = ret2;
3080 	}
3081 	return (ret);
3082 }
3083 
3084 /*
3085  * We're going to seek for the next header anyway, so we don't
3086  * need to bother doing anything here.
3087  */
3088 static int
3089 archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
3090 {
3091 	struct zip *zip;
3092 	zip = (struct zip *)(a->format->data);
3093 
3094 	zip->unconsumed = 0;
3095 	return (ARCHIVE_OK);
3096 }
3097 
3098 int
3099 archive_read_support_format_zip_seekable(struct archive *_a)
3100 {
3101 	struct archive_read *a = (struct archive_read *)_a;
3102 	struct zip *zip;
3103 	int r;
3104 
3105 	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3106 	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
3107 
3108 	zip = (struct zip *)calloc(1, sizeof(*zip));
3109 	if (zip == NULL) {
3110 		archive_set_error(&a->archive, ENOMEM,
3111 		    "Can't allocate zip data");
3112 		return (ARCHIVE_FATAL);
3113 	}
3114 
3115 #ifdef HAVE_COPYFILE_H
3116 	/* Set this by default on Mac OS. */
3117 	zip->process_mac_extensions = 1;
3118 #endif
3119 
3120 	/*
3121 	 * Until enough data has been read, we cannot tell about
3122 	 * any encrypted entries yet.
3123 	 */
3124 	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3125 	zip->crc32func = real_crc32;
3126 
3127 	r = __archive_read_register_format(a,
3128 	    zip,
3129 	    "zip",
3130 	    archive_read_format_zip_seekable_bid,
3131 	    archive_read_format_zip_options,
3132 	    archive_read_format_zip_seekable_read_header,
3133 	    archive_read_format_zip_read_data,
3134 	    archive_read_format_zip_read_data_skip_seekable,
3135 	    NULL,
3136 	    archive_read_format_zip_cleanup,
3137 	    archive_read_support_format_zip_capabilities_seekable,
3138 	    archive_read_format_zip_has_encrypted_entries);
3139 
3140 	if (r != ARCHIVE_OK)
3141 		free(zip);
3142 	return (ARCHIVE_OK);
3143 }
3144