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