archive_read_support_format_zip.c revision 358088
1/*-
2 * Copyright (c) 2004-2013 Tim Kientzle
3 * Copyright (c) 2011-2012,2014 Michihiro NAKAJIMA
4 * Copyright (c) 2013 Konrad Kleine
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include "archive_platform.h"
29__FBSDID("$FreeBSD: stable/11/contrib/libarchive/libarchive/archive_read_support_format_zip.c 358088 2020-02-19 01:50:47Z mm $");
30
31/*
32 * The definitive documentation of the Zip file format is:
33 *   http://www.pkware.com/documents/casestudies/APPNOTE.TXT
34 *
35 * The Info-Zip project has pioneered various extensions to better
36 * support Zip on Unix, including the 0x5455 "UT", 0x5855 "UX", 0x7855
37 * "Ux", and 0x7875 "ux" extensions for time and ownership
38 * information.
39 *
40 * History of this code: The streaming Zip reader was first added to
41 * libarchive in January 2005.  Support for seekable input sources was
42 * added in Nov 2011.  Zip64 support (including a significant code
43 * refactoring) was added in 2014.
44 */
45
46#ifdef HAVE_ERRNO_H
47#include <errno.h>
48#endif
49#ifdef HAVE_STDLIB_H
50#include <stdlib.h>
51#endif
52#ifdef HAVE_ZLIB_H
53#include <zlib.h>
54#endif
55#ifdef HAVE_BZLIB_H
56#include <bzlib.h>
57#endif
58#ifdef HAVE_LZMA_H
59#include <lzma.h>
60#endif
61
62#include "archive.h"
63#include "archive_digest_private.h"
64#include "archive_cryptor_private.h"
65#include "archive_endian.h"
66#include "archive_entry.h"
67#include "archive_entry_locale.h"
68#include "archive_hmac_private.h"
69#include "archive_private.h"
70#include "archive_rb.h"
71#include "archive_read_private.h"
72#include "archive_ppmd8_private.h"
73
74#ifndef HAVE_ZLIB_H
75#include "archive_crc32.h"
76#endif
77
78struct zip_entry {
79	struct archive_rb_node	node;
80	struct zip_entry	*next;
81	int64_t			local_header_offset;
82	int64_t			compressed_size;
83	int64_t			uncompressed_size;
84	int64_t			gid;
85	int64_t			uid;
86	struct archive_string	rsrcname;
87	time_t			mtime;
88	time_t			atime;
89	time_t			ctime;
90	uint32_t		crc32;
91	uint16_t		mode;
92	uint16_t		zip_flags; /* From GP Flags Field */
93	unsigned char		compression;
94	unsigned char		system; /* From "version written by" */
95	unsigned char		flags; /* Our extra markers. */
96	unsigned char		decdat;/* Used for Decryption check */
97
98	/* WinZip AES encryption extra field should be available
99	 * when compression is 99. */
100	struct {
101		/* Vendor version: AE-1 - 0x0001, AE-2 - 0x0002 */
102		unsigned	vendor;
103#define AES_VENDOR_AE_1	0x0001
104#define AES_VENDOR_AE_2	0x0002
105		/* AES encryption strength:
106		 * 1 - 128 bits, 2 - 192 bits, 2 - 256 bits. */
107		unsigned	strength;
108		/* Actual compression method. */
109		unsigned char	compression;
110	}			aes_extra;
111};
112
113struct trad_enc_ctx {
114	uint32_t	keys[3];
115};
116
117/* Bits used in zip_flags. */
118#define ZIP_ENCRYPTED	(1 << 0)
119#define ZIP_LENGTH_AT_END	(1 << 3)
120#define ZIP_STRONG_ENCRYPTED	(1 << 6)
121#define ZIP_UTF8_NAME	(1 << 11)
122/* See "7.2 Single Password Symmetric Encryption Method"
123   in http://www.pkware.com/documents/casestudies/APPNOTE.TXT */
124#define ZIP_CENTRAL_DIRECTORY_ENCRYPTED	(1 << 13)
125
126/* Bits used in flags. */
127#define LA_USED_ZIP64	(1 << 0)
128#define LA_FROM_CENTRAL_DIRECTORY (1 << 1)
129
130/*
131 * See "WinZip - AES Encryption Information"
132 *     http://www.winzip.com/aes_info.htm
133 */
134/* Value used in compression method. */
135#define WINZIP_AES_ENCRYPTION	99
136/* Authentication code size. */
137#define AUTH_CODE_SIZE	10
138/**/
139#define MAX_DERIVED_KEY_BUF_SIZE	(AES_MAX_KEY_SIZE * 2 + 2)
140
141struct zip {
142	/* Structural information about the archive. */
143	struct archive_string	format_name;
144	int64_t			central_directory_offset;
145	size_t			central_directory_entries_total;
146	size_t			central_directory_entries_on_this_disk;
147	int			has_encrypted_entries;
148
149	/* List of entries (seekable Zip only) */
150	struct zip_entry	*zip_entries;
151	struct archive_rb_tree	tree;
152	struct archive_rb_tree	tree_rsrc;
153
154	/* Bytes read but not yet consumed via __archive_read_consume() */
155	size_t			unconsumed;
156
157	/* Information about entry we're currently reading. */
158	struct zip_entry	*entry;
159	int64_t			entry_bytes_remaining;
160
161	/* These count the number of bytes actually read for the entry. */
162	int64_t			entry_compressed_bytes_read;
163	int64_t			entry_uncompressed_bytes_read;
164
165	/* Running CRC32 of the decompressed data */
166	unsigned long		entry_crc32;
167	unsigned long		(*crc32func)(unsigned long, const void *,
168				    size_t);
169	char			ignore_crc32;
170
171	/* Flags to mark progress of decompression. */
172	char			decompress_init;
173	char			end_of_entry;
174
175	unsigned char 		*uncompressed_buffer;
176	size_t 			uncompressed_buffer_size;
177
178#ifdef HAVE_ZLIB_H
179	z_stream		stream;
180	char			stream_valid;
181#endif
182
183#if HAVE_LZMA_H && HAVE_LIBLZMA
184	lzma_stream		zipx_lzma_stream;
185	char            zipx_lzma_valid;
186#endif
187
188#ifdef HAVE_BZLIB_H
189	bz_stream		bzstream;
190	char            bzstream_valid;
191#endif
192
193	IByteIn			zipx_ppmd_stream;
194	ssize_t			zipx_ppmd_read_compressed;
195	CPpmd8			ppmd8;
196	char			ppmd8_valid;
197	char			ppmd8_stream_failed;
198
199	struct archive_string_conv *sconv;
200	struct archive_string_conv *sconv_default;
201	struct archive_string_conv *sconv_utf8;
202	int			init_default_conversion;
203	int			process_mac_extensions;
204
205	char			init_decryption;
206
207	/* Decryption buffer. */
208	/*
209	 * The decrypted data starts at decrypted_ptr and
210	 * extends for decrypted_bytes_remaining.  Decryption
211	 * adds new data to the end of this block, data is returned
212	 * to clients from the beginning.  When the block hits the
213	 * end of decrypted_buffer, it has to be shuffled back to
214	 * the beginning of the buffer.
215	 */
216	unsigned char 		*decrypted_buffer;
217	unsigned char 		*decrypted_ptr;
218	size_t 			decrypted_buffer_size;
219	size_t 			decrypted_bytes_remaining;
220	size_t 			decrypted_unconsumed_bytes;
221
222	/* Traditional PKWARE decryption. */
223	struct trad_enc_ctx	tctx;
224	char			tctx_valid;
225
226	/* WinZip AES decryption. */
227	/* Contexts used for AES decryption. */
228	archive_crypto_ctx	cctx;
229	char			cctx_valid;
230	archive_hmac_sha1_ctx	hctx;
231	char			hctx_valid;
232
233	/* Strong encryption's decryption header information. */
234	unsigned		iv_size;
235	unsigned		alg_id;
236	unsigned		bit_len;
237	unsigned		flags;
238	unsigned		erd_size;
239	unsigned		v_size;
240	unsigned		v_crc32;
241	uint8_t			*iv;
242	uint8_t			*erd;
243	uint8_t			*v_data;
244};
245
246/* Many systems define min or MIN, but not all. */
247#define	zipmin(a,b) ((a) < (b) ? (a) : (b))
248
249/* This function is used by Ppmd8_DecodeSymbol during decompression of Ppmd8
250 * streams inside ZIP files. It has 2 purposes: one is to fetch the next
251 * compressed byte from the stream, second one is to increase the counter how
252 * many compressed bytes were read. */
253static Byte
254ppmd_read(void* p) {
255	/* Get the handle to current decompression context. */
256	struct archive_read *a = ((IByteIn*)p)->a;
257	struct zip *zip = (struct zip*) a->format->data;
258	ssize_t bytes_avail = 0;
259
260	/* Fetch next byte. */
261	const uint8_t* data = __archive_read_ahead(a, 1, &bytes_avail);
262	if(bytes_avail < 1) {
263		zip->ppmd8_stream_failed = 1;
264		return 0;
265	}
266
267	__archive_read_consume(a, 1);
268
269	/* Increment the counter. */
270	++zip->zipx_ppmd_read_compressed;
271
272	/* Return the next compressed byte. */
273	return data[0];
274}
275
276/* ------------------------------------------------------------------------ */
277
278/*
279  Traditional PKWARE Decryption functions.
280 */
281
282static void
283trad_enc_update_keys(struct trad_enc_ctx *ctx, uint8_t c)
284{
285	uint8_t t;
286#define CRC32(c, b) (crc32(c ^ 0xffffffffUL, &b, 1) ^ 0xffffffffUL)
287
288	ctx->keys[0] = CRC32(ctx->keys[0], c);
289	ctx->keys[1] = (ctx->keys[1] + (ctx->keys[0] & 0xff)) * 134775813L + 1;
290	t = (ctx->keys[1] >> 24) & 0xff;
291	ctx->keys[2] = CRC32(ctx->keys[2], t);
292#undef CRC32
293}
294
295static uint8_t
296trad_enc_decrypt_byte(struct trad_enc_ctx *ctx)
297{
298	unsigned temp = ctx->keys[2] | 2;
299	return (uint8_t)((temp * (temp ^ 1)) >> 8) & 0xff;
300}
301
302static void
303trad_enc_decrypt_update(struct trad_enc_ctx *ctx, const uint8_t *in,
304    size_t in_len, uint8_t *out, size_t out_len)
305{
306	unsigned i, max;
307
308	max = (unsigned)((in_len < out_len)? in_len: out_len);
309
310	for (i = 0; i < max; i++) {
311		uint8_t t = in[i] ^ trad_enc_decrypt_byte(ctx);
312		out[i] = t;
313		trad_enc_update_keys(ctx, t);
314	}
315}
316
317static int
318trad_enc_init(struct trad_enc_ctx *ctx, const char *pw, size_t pw_len,
319    const uint8_t *key, size_t key_len, uint8_t *crcchk)
320{
321	uint8_t header[12];
322
323	if (key_len < 12) {
324		*crcchk = 0xff;
325		return -1;
326	}
327
328	ctx->keys[0] = 305419896L;
329	ctx->keys[1] = 591751049L;
330	ctx->keys[2] = 878082192L;
331
332	for (;pw_len; --pw_len)
333		trad_enc_update_keys(ctx, *pw++);
334
335	trad_enc_decrypt_update(ctx, key, 12, header, 12);
336	/* Return the last byte for CRC check. */
337	*crcchk = header[11];
338	return 0;
339}
340
341#if 0
342static void
343crypt_derive_key_sha1(const void *p, int size, unsigned char *key,
344    int key_size)
345{
346#define MD_SIZE 20
347	archive_sha1_ctx ctx;
348	unsigned char md1[MD_SIZE];
349	unsigned char md2[MD_SIZE * 2];
350	unsigned char mkb[64];
351	int i;
352
353	archive_sha1_init(&ctx);
354	archive_sha1_update(&ctx, p, size);
355	archive_sha1_final(&ctx, md1);
356
357	memset(mkb, 0x36, sizeof(mkb));
358	for (i = 0; i < MD_SIZE; i++)
359		mkb[i] ^= md1[i];
360	archive_sha1_init(&ctx);
361	archive_sha1_update(&ctx, mkb, sizeof(mkb));
362	archive_sha1_final(&ctx, md2);
363
364	memset(mkb, 0x5C, sizeof(mkb));
365	for (i = 0; i < MD_SIZE; i++)
366		mkb[i] ^= md1[i];
367	archive_sha1_init(&ctx);
368	archive_sha1_update(&ctx, mkb, sizeof(mkb));
369	archive_sha1_final(&ctx, md2 + MD_SIZE);
370
371	if (key_size > 32)
372		key_size = 32;
373	memcpy(key, md2, key_size);
374#undef MD_SIZE
375}
376#endif
377
378/*
379 * Common code for streaming or seeking modes.
380 *
381 * Includes code to read local file headers, decompress data
382 * from entry bodies, and common API.
383 */
384
385static unsigned long
386real_crc32(unsigned long crc, const void *buff, size_t len)
387{
388	return crc32(crc, buff, (unsigned int)len);
389}
390
391/* Used by "ignorecrc32" option to speed up tests. */
392static unsigned long
393fake_crc32(unsigned long crc, const void *buff, size_t len)
394{
395	(void)crc; /* UNUSED */
396	(void)buff; /* UNUSED */
397	(void)len; /* UNUSED */
398	return 0;
399}
400
401static const struct {
402	int id;
403	const char * name;
404} compression_methods[] = {
405	{0, "uncompressed"}, /* The file is stored (no compression) */
406	{1, "shrinking"}, /* The file is Shrunk */
407	{2, "reduced-1"}, /* The file is Reduced with compression factor 1 */
408	{3, "reduced-2"}, /* The file is Reduced with compression factor 2 */
409	{4, "reduced-3"}, /* The file is Reduced with compression factor 3 */
410	{5, "reduced-4"}, /* The file is Reduced with compression factor 4 */
411	{6, "imploded"},  /* The file is Imploded */
412	{7, "reserved"},  /* Reserved for Tokenizing compression algorithm */
413	{8, "deflation"}, /* The file is Deflated */
414	{9, "deflation-64-bit"}, /* Enhanced Deflating using Deflate64(tm) */
415	{10, "ibm-terse"},/* PKWARE Data Compression Library Imploding
416			   * (old IBM TERSE) */
417	{11, "reserved"}, /* Reserved by PKWARE */
418	{12, "bzip"},     /* File is compressed using BZIP2 algorithm */
419	{13, "reserved"}, /* Reserved by PKWARE */
420	{14, "lzma"},     /* LZMA (EFS) */
421	{15, "reserved"}, /* Reserved by PKWARE */
422	{16, "reserved"}, /* Reserved by PKWARE */
423	{17, "reserved"}, /* Reserved by PKWARE */
424	{18, "ibm-terse-new"}, /* File is compressed using IBM TERSE (new) */
425	{19, "ibm-lz777"},/* IBM LZ77 z Architecture (PFS) */
426	{95, "xz"},       /* XZ compressed data */
427	{96, "jpeg"},     /* JPEG compressed data */
428	{97, "wav-pack"}, /* WavPack compressed data */
429	{98, "ppmd-1"},   /* PPMd version I, Rev 1 */
430	{99, "aes"}       /* WinZip AES encryption  */
431};
432
433static const char *
434compression_name(const int compression)
435{
436	static const int num_compression_methods =
437		sizeof(compression_methods)/sizeof(compression_methods[0]);
438	int i=0;
439
440	while(compression >= 0 && i < num_compression_methods) {
441		if (compression_methods[i].id == compression)
442			return compression_methods[i].name;
443		i++;
444	}
445	return "??";
446}
447
448/* Convert an MSDOS-style date/time into Unix-style time. */
449static time_t
450zip_time(const char *p)
451{
452	int msTime, msDate;
453	struct tm ts;
454
455	msTime = (0xff & (unsigned)p[0]) + 256 * (0xff & (unsigned)p[1]);
456	msDate = (0xff & (unsigned)p[2]) + 256 * (0xff & (unsigned)p[3]);
457
458	memset(&ts, 0, sizeof(ts));
459	ts.tm_year = ((msDate >> 9) & 0x7f) + 80; /* Years since 1900. */
460	ts.tm_mon = ((msDate >> 5) & 0x0f) - 1; /* Month number. */
461	ts.tm_mday = msDate & 0x1f; /* Day of month. */
462	ts.tm_hour = (msTime >> 11) & 0x1f;
463	ts.tm_min = (msTime >> 5) & 0x3f;
464	ts.tm_sec = (msTime << 1) & 0x3e;
465	ts.tm_isdst = -1;
466	return mktime(&ts);
467}
468
469/*
470 * The extra data is stored as a list of
471 *	id1+size1+data1 + id2+size2+data2 ...
472 *  triplets.  id and size are 2 bytes each.
473 */
474static int
475process_extra(struct archive_read *a, struct archive_entry *entry,
476     const char *p, size_t extra_length, struct zip_entry* zip_entry)
477{
478	unsigned offset = 0;
479	struct zip *zip = (struct zip *)(a->format->data);
480
481	if (extra_length == 0) {
482		return ARCHIVE_OK;
483	}
484
485	if (extra_length < 4) {
486		size_t i = 0;
487		/* Some ZIP files may have trailing 0 bytes. Let's check they
488		 * are all 0 and ignore them instead of returning an error.
489		 *
490		 * This is not technically correct, but some ZIP files look
491		 * like this and other tools support those files - so let's
492		 * also  support them.
493		 */
494		for (; i < extra_length; i++) {
495			if (p[i] != 0) {
496				archive_set_error(&a->archive,
497				    ARCHIVE_ERRNO_FILE_FORMAT,
498				    "Too-small extra data: "
499				    "Need at least 4 bytes, "
500				    "but only found %d bytes",
501				    (int)extra_length);
502				return ARCHIVE_FAILED;
503			}
504		}
505
506		return ARCHIVE_OK;
507	}
508
509	while (offset <= extra_length - 4) {
510		unsigned short headerid = archive_le16dec(p + offset);
511		unsigned short datasize = archive_le16dec(p + offset + 2);
512
513		offset += 4;
514		if (offset + datasize > extra_length) {
515			archive_set_error(&a->archive,
516			    ARCHIVE_ERRNO_FILE_FORMAT, "Extra data overflow: "
517			    "Need %d bytes but only found %d bytes",
518			    (int)datasize, (int)(extra_length - offset));
519			return ARCHIVE_FAILED;
520		}
521#ifdef DEBUG
522		fprintf(stderr, "Header id 0x%04x, length %d\n",
523		    headerid, datasize);
524#endif
525		switch (headerid) {
526		case 0x0001:
527			/* Zip64 extended information extra field. */
528			zip_entry->flags |= LA_USED_ZIP64;
529			if (zip_entry->uncompressed_size == 0xffffffff) {
530				uint64_t t = 0;
531				if (datasize < 8
532				    || (t = archive_le64dec(p + offset)) >
533				    INT64_MAX) {
534					archive_set_error(&a->archive,
535					    ARCHIVE_ERRNO_FILE_FORMAT,
536					    "Malformed 64-bit "
537					    "uncompressed size");
538					return ARCHIVE_FAILED;
539				}
540				zip_entry->uncompressed_size = t;
541				offset += 8;
542				datasize -= 8;
543			}
544			if (zip_entry->compressed_size == 0xffffffff) {
545				uint64_t t = 0;
546				if (datasize < 8
547				    || (t = archive_le64dec(p + offset)) >
548				    INT64_MAX) {
549					archive_set_error(&a->archive,
550					    ARCHIVE_ERRNO_FILE_FORMAT,
551					    "Malformed 64-bit "
552					    "compressed size");
553					return ARCHIVE_FAILED;
554				}
555				zip_entry->compressed_size = t;
556				offset += 8;
557				datasize -= 8;
558			}
559			if (zip_entry->local_header_offset == 0xffffffff) {
560				uint64_t t = 0;
561				if (datasize < 8
562				    || (t = archive_le64dec(p + offset)) >
563				    INT64_MAX) {
564					archive_set_error(&a->archive,
565					    ARCHIVE_ERRNO_FILE_FORMAT,
566					    "Malformed 64-bit "
567					    "local header offset");
568					return ARCHIVE_FAILED;
569				}
570				zip_entry->local_header_offset = t;
571				offset += 8;
572				datasize -= 8;
573			}
574			/* archive_le32dec(p + offset) gives disk
575			 * on which file starts, but we don't handle
576			 * multi-volume Zip files. */
577			break;
578#ifdef DEBUG
579		case 0x0017:
580		{
581			/* Strong encryption field. */
582			if (archive_le16dec(p + offset) == 2) {
583				unsigned algId =
584					archive_le16dec(p + offset + 2);
585				unsigned bitLen =
586					archive_le16dec(p + offset + 4);
587				int	 flags =
588					archive_le16dec(p + offset + 6);
589				fprintf(stderr, "algId=0x%04x, bitLen=%u, "
590				    "flgas=%d\n", algId, bitLen,flags);
591			}
592			break;
593		}
594#endif
595		case 0x5455:
596		{
597			/* Extended time field "UT". */
598			int flags;
599			if (datasize == 0) {
600				archive_set_error(&a->archive,
601				    ARCHIVE_ERRNO_FILE_FORMAT,
602				    "Incomplete extended time field");
603				return ARCHIVE_FAILED;
604			}
605			flags = p[offset];
606			offset++;
607			datasize--;
608			/* Flag bits indicate which dates are present. */
609			if (flags & 0x01)
610			{
611#ifdef DEBUG
612				fprintf(stderr, "mtime: %lld -> %d\n",
613				    (long long)zip_entry->mtime,
614				    archive_le32dec(p + offset));
615#endif
616				if (datasize < 4)
617					break;
618				zip_entry->mtime = archive_le32dec(p + offset);
619				offset += 4;
620				datasize -= 4;
621			}
622			if (flags & 0x02)
623			{
624				if (datasize < 4)
625					break;
626				zip_entry->atime = archive_le32dec(p + offset);
627				offset += 4;
628				datasize -= 4;
629			}
630			if (flags & 0x04)
631			{
632				if (datasize < 4)
633					break;
634				zip_entry->ctime = archive_le32dec(p + offset);
635				offset += 4;
636				datasize -= 4;
637			}
638			break;
639		}
640		case 0x5855:
641		{
642			/* Info-ZIP Unix Extra Field (old version) "UX". */
643			if (datasize >= 8) {
644				zip_entry->atime = archive_le32dec(p + offset);
645				zip_entry->mtime =
646				    archive_le32dec(p + offset + 4);
647			}
648			if (datasize >= 12) {
649				zip_entry->uid =
650				    archive_le16dec(p + offset + 8);
651				zip_entry->gid =
652				    archive_le16dec(p + offset + 10);
653			}
654			break;
655		}
656		case 0x6c78:
657		{
658			/* Experimental 'xl' field */
659			/*
660			 * Introduced Dec 2013 to provide a way to
661			 * include external file attributes (and other
662			 * fields that ordinarily appear only in
663			 * central directory) in local file header.
664			 * This provides file type and permission
665			 * information necessary to support full
666			 * streaming extraction.  Currently being
667			 * discussed with other Zip developers
668			 * ... subject to change.
669			 *
670			 * Format:
671			 *  The field starts with a bitmap that specifies
672			 *  which additional fields are included.  The
673			 *  bitmap is variable length and can be extended in
674			 *  the future.
675			 *
676			 *  n bytes - feature bitmap: first byte has low-order
677			 *    7 bits.  If high-order bit is set, a subsequent
678			 *    byte holds the next 7 bits, etc.
679			 *
680			 *  if bitmap & 1, 2 byte "version made by"
681			 *  if bitmap & 2, 2 byte "internal file attributes"
682			 *  if bitmap & 4, 4 byte "external file attributes"
683			 *  if bitmap & 8, 2 byte comment length + n byte
684			 *  comment
685			 */
686			int bitmap, bitmap_last;
687
688			if (datasize < 1)
689				break;
690			bitmap_last = bitmap = 0xff & p[offset];
691			offset += 1;
692			datasize -= 1;
693
694			/* We only support first 7 bits of bitmap; skip rest. */
695			while ((bitmap_last & 0x80) != 0
696			    && datasize >= 1) {
697				bitmap_last = p[offset];
698				offset += 1;
699				datasize -= 1;
700			}
701
702			if (bitmap & 1) {
703				/* 2 byte "version made by" */
704				if (datasize < 2)
705					break;
706				zip_entry->system
707				    = archive_le16dec(p + offset) >> 8;
708				offset += 2;
709				datasize -= 2;
710			}
711			if (bitmap & 2) {
712				/* 2 byte "internal file attributes" */
713				uint32_t internal_attributes;
714				if (datasize < 2)
715					break;
716				internal_attributes
717				    = archive_le16dec(p + offset);
718				/* Not used by libarchive at present. */
719				(void)internal_attributes; /* UNUSED */
720				offset += 2;
721				datasize -= 2;
722			}
723			if (bitmap & 4) {
724				/* 4 byte "external file attributes" */
725				uint32_t external_attributes;
726				if (datasize < 4)
727					break;
728				external_attributes
729				    = archive_le32dec(p + offset);
730				if (zip_entry->system == 3) {
731					zip_entry->mode
732					    = external_attributes >> 16;
733				} else if (zip_entry->system == 0) {
734					// Interpret MSDOS directory bit
735					if (0x10 == (external_attributes &
736					    0x10)) {
737						zip_entry->mode =
738						    AE_IFDIR | 0775;
739					} else {
740						zip_entry->mode =
741						    AE_IFREG | 0664;
742					}
743					if (0x01 == (external_attributes &
744					    0x01)) {
745						/* Read-only bit;
746						 * strip write permissions */
747						zip_entry->mode &= 0555;
748					}
749				} else {
750					zip_entry->mode = 0;
751				}
752				offset += 4;
753				datasize -= 4;
754			}
755			if (bitmap & 8) {
756				/* 2 byte comment length + comment */
757				uint32_t comment_length;
758				if (datasize < 2)
759					break;
760				comment_length
761				    = archive_le16dec(p + offset);
762				offset += 2;
763				datasize -= 2;
764
765				if (datasize < comment_length)
766					break;
767				/* Comment is not supported by libarchive */
768				offset += comment_length;
769				datasize -= comment_length;
770			}
771			break;
772		}
773		case 0x7075:
774		{
775			/* Info-ZIP Unicode Path Extra Field. */
776			if (datasize < 5 || entry == NULL)
777				break;
778			offset += 5;
779			datasize -= 5;
780
781			/* The path name in this field is always encoded
782			 * in UTF-8. */
783			if (zip->sconv_utf8 == NULL) {
784				zip->sconv_utf8 =
785					archive_string_conversion_from_charset(
786					&a->archive, "UTF-8", 1);
787				/* If the converter from UTF-8 is not
788				 * available, then the path name from the main
789				 * field will more likely be correct. */
790				if (zip->sconv_utf8 == NULL)
791					break;
792			}
793
794			/* Make sure the CRC32 of the filename matches. */
795			if (!zip->ignore_crc32) {
796				const char *cp = archive_entry_pathname(entry);
797				if (cp) {
798					unsigned long file_crc =
799					    zip->crc32func(0, cp, strlen(cp));
800					unsigned long utf_crc =
801					    archive_le32dec(p + offset - 4);
802					if (file_crc != utf_crc) {
803#ifdef DEBUG
804						fprintf(stderr,
805						    "CRC filename mismatch; "
806						    "CDE is %lx, but UTF8 "
807						    "is outdated with %lx\n",
808						    file_crc, utf_crc);
809#endif
810						break;
811					}
812				}
813			}
814
815			if (archive_entry_copy_pathname_l(entry,
816			    p + offset, datasize, zip->sconv_utf8) != 0) {
817				/* Ignore the error, and fallback to the path
818				 * name from the main field. */
819#ifdef DEBUG
820				fprintf(stderr, "Failed to read the ZIP "
821				    "0x7075 extra field path.\n");
822#endif
823			}
824			break;
825		}
826		case 0x7855:
827			/* Info-ZIP Unix Extra Field (type 2) "Ux". */
828#ifdef DEBUG
829			fprintf(stderr, "uid %d gid %d\n",
830			    archive_le16dec(p + offset),
831			    archive_le16dec(p + offset + 2));
832#endif
833			if (datasize >= 2)
834				zip_entry->uid = archive_le16dec(p + offset);
835			if (datasize >= 4)
836				zip_entry->gid =
837				    archive_le16dec(p + offset + 2);
838			break;
839		case 0x7875:
840		{
841			/* Info-Zip Unix Extra Field (type 3) "ux". */
842			int uidsize = 0, gidsize = 0;
843
844			/* TODO: support arbitrary uidsize/gidsize. */
845			if (datasize >= 1 && p[offset] == 1) {/* version=1 */
846				if (datasize >= 4) {
847					/* get a uid size. */
848					uidsize = 0xff & (int)p[offset+1];
849					if (uidsize == 2)
850						zip_entry->uid =
851						    archive_le16dec(
852						        p + offset + 2);
853					else if (uidsize == 4 && datasize >= 6)
854						zip_entry->uid =
855						    archive_le32dec(
856						        p + offset + 2);
857				}
858				if (datasize >= (2 + uidsize + 3)) {
859					/* get a gid size. */
860					gidsize = 0xff &
861					    (int)p[offset+2+uidsize];
862					if (gidsize == 2)
863						zip_entry->gid =
864						    archive_le16dec(
865						        p+offset+2+uidsize+1);
866					else if (gidsize == 4 &&
867					    datasize >= (2 + uidsize + 5))
868						zip_entry->gid =
869						    archive_le32dec(
870						        p+offset+2+uidsize+1);
871				}
872			}
873			break;
874		}
875		case 0x9901:
876			/* WinZip AES extra data field. */
877			if (datasize < 6) {
878				archive_set_error(&a->archive,
879				    ARCHIVE_ERRNO_FILE_FORMAT,
880				    "Incomplete AES field");
881				return ARCHIVE_FAILED;
882			}
883			if (p[offset + 2] == 'A' && p[offset + 3] == 'E') {
884				/* Vendor version. */
885				zip_entry->aes_extra.vendor =
886				    archive_le16dec(p + offset);
887				/* AES encryption strength. */
888				zip_entry->aes_extra.strength = p[offset + 4];
889				/* Actual compression method. */
890				zip_entry->aes_extra.compression =
891				    p[offset + 5];
892			}
893			break;
894		default:
895			break;
896		}
897		offset += datasize;
898	}
899	return ARCHIVE_OK;
900}
901
902/*
903 * Assumes file pointer is at beginning of local file header.
904 */
905static int
906zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
907    struct zip *zip)
908{
909	const char *p;
910	const void *h;
911	const wchar_t *wp;
912	const char *cp;
913	size_t len, filename_length, extra_length;
914	struct archive_string_conv *sconv;
915	struct zip_entry *zip_entry = zip->entry;
916	struct zip_entry zip_entry_central_dir;
917	int ret = ARCHIVE_OK;
918	char version;
919
920	/* Save a copy of the original for consistency checks. */
921	zip_entry_central_dir = *zip_entry;
922
923	zip->decompress_init = 0;
924	zip->end_of_entry = 0;
925	zip->entry_uncompressed_bytes_read = 0;
926	zip->entry_compressed_bytes_read = 0;
927	zip->entry_crc32 = zip->crc32func(0, NULL, 0);
928
929	/* Setup default conversion. */
930	if (zip->sconv == NULL && !zip->init_default_conversion) {
931		zip->sconv_default =
932		    archive_string_default_conversion_for_read(&(a->archive));
933		zip->init_default_conversion = 1;
934	}
935
936	if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
937		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
938		    "Truncated ZIP file header");
939		return (ARCHIVE_FATAL);
940	}
941
942	if (memcmp(p, "PK\003\004", 4) != 0) {
943		archive_set_error(&a->archive, -1, "Damaged Zip archive");
944		return ARCHIVE_FATAL;
945	}
946	version = p[4];
947	zip_entry->system = p[5];
948	zip_entry->zip_flags = archive_le16dec(p + 6);
949	if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
950		zip->has_encrypted_entries = 1;
951		archive_entry_set_is_data_encrypted(entry, 1);
952		if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
953			zip_entry->zip_flags & ZIP_ENCRYPTED &&
954			zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
955			archive_entry_set_is_metadata_encrypted(entry, 1);
956			return ARCHIVE_FATAL;
957		}
958	}
959	zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
960	zip_entry->compression = (char)archive_le16dec(p + 8);
961	zip_entry->mtime = zip_time(p + 10);
962	zip_entry->crc32 = archive_le32dec(p + 14);
963	if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
964		zip_entry->decdat = p[11];
965	else
966		zip_entry->decdat = p[17];
967	zip_entry->compressed_size = archive_le32dec(p + 18);
968	zip_entry->uncompressed_size = archive_le32dec(p + 22);
969	filename_length = archive_le16dec(p + 26);
970	extra_length = archive_le16dec(p + 28);
971
972	__archive_read_consume(a, 30);
973
974	/* Read the filename. */
975	if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
976		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
977		    "Truncated ZIP file header");
978		return (ARCHIVE_FATAL);
979	}
980	if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
981		/* The filename is stored to be UTF-8. */
982		if (zip->sconv_utf8 == NULL) {
983			zip->sconv_utf8 =
984			    archive_string_conversion_from_charset(
985				&a->archive, "UTF-8", 1);
986			if (zip->sconv_utf8 == NULL)
987				return (ARCHIVE_FATAL);
988		}
989		sconv = zip->sconv_utf8;
990	} else if (zip->sconv != NULL)
991		sconv = zip->sconv;
992	else
993		sconv = zip->sconv_default;
994
995	if (archive_entry_copy_pathname_l(entry,
996	    h, filename_length, sconv) != 0) {
997		if (errno == ENOMEM) {
998			archive_set_error(&a->archive, ENOMEM,
999			    "Can't allocate memory for Pathname");
1000			return (ARCHIVE_FATAL);
1001		}
1002		archive_set_error(&a->archive,
1003		    ARCHIVE_ERRNO_FILE_FORMAT,
1004		    "Pathname cannot be converted "
1005		    "from %s to current locale.",
1006		    archive_string_conversion_charset_name(sconv));
1007		ret = ARCHIVE_WARN;
1008	}
1009	__archive_read_consume(a, filename_length);
1010
1011	/* Read the extra data. */
1012	if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
1013		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1014		    "Truncated ZIP file header");
1015		return (ARCHIVE_FATAL);
1016	}
1017
1018	if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
1019	    zip_entry)) {
1020		return ARCHIVE_FATAL;
1021	}
1022	__archive_read_consume(a, extra_length);
1023
1024	/* Work around a bug in Info-Zip: When reading from a pipe, it
1025	 * stats the pipe instead of synthesizing a file entry. */
1026	if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
1027		zip_entry->mode &= ~ AE_IFMT;
1028		zip_entry->mode |= AE_IFREG;
1029	}
1030
1031	/* If the mode is totally empty, set some sane default. */
1032	if (zip_entry->mode == 0) {
1033		zip_entry->mode |= 0664;
1034	}
1035
1036	/* Windows archivers sometimes use backslash as the directory
1037	 * separator. Normalize to slash. */
1038	if (zip_entry->system == 0 &&
1039	    (wp = archive_entry_pathname_w(entry)) != NULL) {
1040		if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
1041			size_t i;
1042			struct archive_wstring s;
1043			archive_string_init(&s);
1044			archive_wstrcpy(&s, wp);
1045			for (i = 0; i < archive_strlen(&s); i++) {
1046				if (s.s[i] == '\\')
1047					s.s[i] = '/';
1048			}
1049			archive_entry_copy_pathname_w(entry, s.s);
1050			archive_wstring_free(&s);
1051		}
1052	}
1053
1054	/* Make sure that entries with a trailing '/' are marked as directories
1055	 * even if the External File Attributes contains bogus values.  If this
1056	 * is not a directory and there is no type, assume a regular file. */
1057	if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
1058		int has_slash;
1059
1060		wp = archive_entry_pathname_w(entry);
1061		if (wp != NULL) {
1062			len = wcslen(wp);
1063			has_slash = len > 0 && wp[len - 1] == L'/';
1064		} else {
1065			cp = archive_entry_pathname(entry);
1066			len = (cp != NULL)?strlen(cp):0;
1067			has_slash = len > 0 && cp[len - 1] == '/';
1068		}
1069		/* Correct file type as needed. */
1070		if (has_slash) {
1071			zip_entry->mode &= ~AE_IFMT;
1072			zip_entry->mode |= AE_IFDIR;
1073			zip_entry->mode |= 0111;
1074		} else if ((zip_entry->mode & AE_IFMT) == 0) {
1075			zip_entry->mode |= AE_IFREG;
1076		}
1077	}
1078
1079	/* Make sure directories end in '/' */
1080	if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
1081		wp = archive_entry_pathname_w(entry);
1082		if (wp != NULL) {
1083			len = wcslen(wp);
1084			if (len > 0 && wp[len - 1] != L'/') {
1085				struct archive_wstring s;
1086				archive_string_init(&s);
1087				archive_wstrcat(&s, wp);
1088				archive_wstrappend_wchar(&s, L'/');
1089				archive_entry_copy_pathname_w(entry, s.s);
1090				archive_wstring_free(&s);
1091			}
1092		} else {
1093			cp = archive_entry_pathname(entry);
1094			len = (cp != NULL)?strlen(cp):0;
1095			if (len > 0 && cp[len - 1] != '/') {
1096				struct archive_string s;
1097				archive_string_init(&s);
1098				archive_strcat(&s, cp);
1099				archive_strappend_char(&s, '/');
1100				archive_entry_set_pathname(entry, s.s);
1101				archive_string_free(&s);
1102			}
1103		}
1104	}
1105
1106	if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1107		/* If this came from the central dir, its size info
1108		 * is definitive, so ignore the length-at-end flag. */
1109		zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1110		/* If local header is missing a value, use the one from
1111		   the central directory.  If both have it, warn about
1112		   mismatches. */
1113		if (zip_entry->crc32 == 0) {
1114			zip_entry->crc32 = zip_entry_central_dir.crc32;
1115		} else if (!zip->ignore_crc32
1116		    && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1117			archive_set_error(&a->archive,
1118			    ARCHIVE_ERRNO_FILE_FORMAT,
1119			    "Inconsistent CRC32 values");
1120			ret = ARCHIVE_WARN;
1121		}
1122		if (zip_entry->compressed_size == 0) {
1123			zip_entry->compressed_size
1124			    = zip_entry_central_dir.compressed_size;
1125		} else if (zip_entry->compressed_size
1126		    != zip_entry_central_dir.compressed_size) {
1127			archive_set_error(&a->archive,
1128			    ARCHIVE_ERRNO_FILE_FORMAT,
1129			    "Inconsistent compressed size: "
1130			    "%jd in central directory, %jd in local header",
1131			    (intmax_t)zip_entry_central_dir.compressed_size,
1132			    (intmax_t)zip_entry->compressed_size);
1133			ret = ARCHIVE_WARN;
1134		}
1135		if (zip_entry->uncompressed_size == 0) {
1136			zip_entry->uncompressed_size
1137			    = zip_entry_central_dir.uncompressed_size;
1138		} else if (zip_entry->uncompressed_size
1139		    != zip_entry_central_dir.uncompressed_size) {
1140			archive_set_error(&a->archive,
1141			    ARCHIVE_ERRNO_FILE_FORMAT,
1142			    "Inconsistent uncompressed size: "
1143			    "%jd in central directory, %jd in local header",
1144			    (intmax_t)zip_entry_central_dir.uncompressed_size,
1145			    (intmax_t)zip_entry->uncompressed_size);
1146			ret = ARCHIVE_WARN;
1147		}
1148	}
1149
1150	/* Populate some additional entry fields: */
1151	archive_entry_set_mode(entry, zip_entry->mode);
1152	archive_entry_set_uid(entry, zip_entry->uid);
1153	archive_entry_set_gid(entry, zip_entry->gid);
1154	archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1155	archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1156	archive_entry_set_atime(entry, zip_entry->atime, 0);
1157
1158	if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1159		size_t linkname_length;
1160
1161		if (zip_entry->compressed_size > 64 * 1024) {
1162			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1163			    "Zip file with oversized link entry");
1164			return ARCHIVE_FATAL;
1165		}
1166
1167		linkname_length = (size_t)zip_entry->compressed_size;
1168
1169		archive_entry_set_size(entry, 0);
1170		p = __archive_read_ahead(a, linkname_length, NULL);
1171		if (p == NULL) {
1172			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1173			    "Truncated Zip file");
1174			return ARCHIVE_FATAL;
1175		}
1176
1177		sconv = zip->sconv;
1178		if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1179			sconv = zip->sconv_utf8;
1180		if (sconv == NULL)
1181			sconv = zip->sconv_default;
1182		if (archive_entry_copy_symlink_l(entry, p, linkname_length,
1183		    sconv) != 0) {
1184			if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1185			    (zip->entry->zip_flags & ZIP_UTF8_NAME))
1186			    archive_entry_copy_symlink_l(entry, p,
1187				linkname_length, NULL);
1188			if (errno == ENOMEM) {
1189				archive_set_error(&a->archive, ENOMEM,
1190				    "Can't allocate memory for Symlink");
1191				return (ARCHIVE_FATAL);
1192			}
1193			/*
1194			 * Since there is no character-set regulation for
1195			 * symlink name, do not report the conversion error
1196			 * in an automatic conversion.
1197			 */
1198			if (sconv != zip->sconv_utf8 ||
1199			    (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1200				archive_set_error(&a->archive,
1201				    ARCHIVE_ERRNO_FILE_FORMAT,
1202				    "Symlink cannot be converted "
1203				    "from %s to current locale.",
1204				    archive_string_conversion_charset_name(
1205					sconv));
1206				ret = ARCHIVE_WARN;
1207			}
1208		}
1209		zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1210
1211		if (__archive_read_consume(a, linkname_length) < 0) {
1212			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1213			    "Read error skipping symlink target name");
1214			return ARCHIVE_FATAL;
1215		}
1216	} else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1217	    || zip_entry->uncompressed_size > 0) {
1218		/* Set the size only if it's meaningful. */
1219		archive_entry_set_size(entry, zip_entry->uncompressed_size);
1220	}
1221	zip->entry_bytes_remaining = zip_entry->compressed_size;
1222
1223	/* If there's no body, force read_data() to return EOF immediately. */
1224	if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1225	    && zip->entry_bytes_remaining < 1)
1226		zip->end_of_entry = 1;
1227
1228	/* Set up a more descriptive format name. */
1229        archive_string_empty(&zip->format_name);
1230	archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1231	    version / 10, version % 10,
1232	    compression_name(zip->entry->compression));
1233	a->archive.archive_format_name = zip->format_name.s;
1234
1235	return (ret);
1236}
1237
1238static int
1239check_authentication_code(struct archive_read *a, const void *_p)
1240{
1241	struct zip *zip = (struct zip *)(a->format->data);
1242
1243	/* Check authentication code. */
1244	if (zip->hctx_valid) {
1245		const void *p;
1246		uint8_t hmac[20];
1247		size_t hmac_len = 20;
1248		int cmp;
1249
1250		archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1251		if (_p == NULL) {
1252			/* Read authentication code. */
1253			p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1254			if (p == NULL) {
1255				archive_set_error(&a->archive,
1256				    ARCHIVE_ERRNO_FILE_FORMAT,
1257				    "Truncated ZIP file data");
1258				return (ARCHIVE_FATAL);
1259			}
1260		} else {
1261			p = _p;
1262		}
1263		cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1264		__archive_read_consume(a, AUTH_CODE_SIZE);
1265		if (cmp != 0) {
1266			archive_set_error(&a->archive,
1267			    ARCHIVE_ERRNO_MISC,
1268			    "ZIP bad Authentication code");
1269			return (ARCHIVE_WARN);
1270		}
1271	}
1272	return (ARCHIVE_OK);
1273}
1274
1275/*
1276 * Read "uncompressed" data.  There are three cases:
1277 *  1) We know the size of the data.  This is always true for the
1278 * seeking reader (we've examined the Central Directory already).
1279 *  2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1280 * Info-ZIP seems to do this; we know the size but have to grab
1281 * the CRC from the data descriptor afterwards.
1282 *  3) We're streaming and ZIP_LENGTH_AT_END was specified and
1283 * we have no size information.  In this case, we can do pretty
1284 * well by watching for the data descriptor record.  The data
1285 * descriptor is 16 bytes and includes a computed CRC that should
1286 * provide a strong check.
1287 *
1288 * TODO: Technically, the PK\007\010 signature is optional.
1289 * In the original spec, the data descriptor contained CRC
1290 * and size fields but had no leading signature.  In practice,
1291 * newer writers seem to provide the signature pretty consistently.
1292 *
1293 * For uncompressed data, the PK\007\010 marker seems essential
1294 * to be sure we've actually seen the end of the entry.
1295 *
1296 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1297 * zip->end_of_entry if it consumes all of the data.
1298 */
1299static int
1300zip_read_data_none(struct archive_read *a, const void **_buff,
1301    size_t *size, int64_t *offset)
1302{
1303	struct zip *zip;
1304	const char *buff;
1305	ssize_t bytes_avail;
1306	int r;
1307
1308	(void)offset; /* UNUSED */
1309
1310	zip = (struct zip *)(a->format->data);
1311
1312	if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1313		const char *p;
1314		ssize_t grabbing_bytes = 24;
1315
1316		if (zip->hctx_valid)
1317			grabbing_bytes += AUTH_CODE_SIZE;
1318		/* Grab at least 24 bytes. */
1319		buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1320		if (bytes_avail < grabbing_bytes) {
1321			/* Zip archives have end-of-archive markers
1322			   that are longer than this, so a failure to get at
1323			   least 24 bytes really does indicate a truncated
1324			   file. */
1325			archive_set_error(&a->archive,
1326			    ARCHIVE_ERRNO_FILE_FORMAT,
1327			    "Truncated ZIP file data");
1328			return (ARCHIVE_FATAL);
1329		}
1330		/* Check for a complete PK\007\010 signature, followed
1331		 * by the correct 4-byte CRC. */
1332		p = buff;
1333		if (zip->hctx_valid)
1334			p += AUTH_CODE_SIZE;
1335		if (p[0] == 'P' && p[1] == 'K'
1336		    && p[2] == '\007' && p[3] == '\010'
1337		    && (archive_le32dec(p + 4) == zip->entry_crc32
1338			|| zip->ignore_crc32
1339			|| (zip->hctx_valid
1340			 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1341			if (zip->entry->flags & LA_USED_ZIP64) {
1342				uint64_t compressed, uncompressed;
1343				zip->entry->crc32 = archive_le32dec(p + 4);
1344				compressed = archive_le64dec(p + 8);
1345				uncompressed = archive_le64dec(p + 16);
1346				if (compressed > INT64_MAX || uncompressed >
1347				    INT64_MAX) {
1348					archive_set_error(&a->archive,
1349					    ARCHIVE_ERRNO_FILE_FORMAT,
1350					    "Overflow of 64-bit file sizes");
1351					return ARCHIVE_FAILED;
1352				}
1353				zip->entry->compressed_size = compressed;
1354				zip->entry->uncompressed_size = uncompressed;
1355				zip->unconsumed = 24;
1356			} else {
1357				zip->entry->crc32 = archive_le32dec(p + 4);
1358				zip->entry->compressed_size =
1359					archive_le32dec(p + 8);
1360				zip->entry->uncompressed_size =
1361					archive_le32dec(p + 12);
1362				zip->unconsumed = 16;
1363			}
1364			if (zip->hctx_valid) {
1365				r = check_authentication_code(a, buff);
1366				if (r != ARCHIVE_OK)
1367					return (r);
1368			}
1369			zip->end_of_entry = 1;
1370			return (ARCHIVE_OK);
1371		}
1372		/* If not at EOF, ensure we consume at least one byte. */
1373		++p;
1374
1375		/* Scan forward until we see where a PK\007\010 signature
1376		 * might be. */
1377		/* Return bytes up until that point.  On the next call,
1378		 * the code above will verify the data descriptor. */
1379		while (p < buff + bytes_avail - 4) {
1380			if (p[3] == 'P') { p += 3; }
1381			else if (p[3] == 'K') { p += 2; }
1382			else if (p[3] == '\007') { p += 1; }
1383			else if (p[3] == '\010' && p[2] == '\007'
1384			    && p[1] == 'K' && p[0] == 'P') {
1385				if (zip->hctx_valid)
1386					p -= AUTH_CODE_SIZE;
1387				break;
1388			} else { p += 4; }
1389		}
1390		bytes_avail = p - buff;
1391	} else {
1392		if (zip->entry_bytes_remaining == 0) {
1393			zip->end_of_entry = 1;
1394			if (zip->hctx_valid) {
1395				r = check_authentication_code(a, NULL);
1396				if (r != ARCHIVE_OK)
1397					return (r);
1398			}
1399			return (ARCHIVE_OK);
1400		}
1401		/* Grab a bunch of bytes. */
1402		buff = __archive_read_ahead(a, 1, &bytes_avail);
1403		if (bytes_avail <= 0) {
1404			archive_set_error(&a->archive,
1405			    ARCHIVE_ERRNO_FILE_FORMAT,
1406			    "Truncated ZIP file data");
1407			return (ARCHIVE_FATAL);
1408		}
1409		if (bytes_avail > zip->entry_bytes_remaining)
1410			bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1411	}
1412	if (zip->tctx_valid || zip->cctx_valid) {
1413		size_t dec_size = bytes_avail;
1414
1415		if (dec_size > zip->decrypted_buffer_size)
1416			dec_size = zip->decrypted_buffer_size;
1417		if (zip->tctx_valid) {
1418			trad_enc_decrypt_update(&zip->tctx,
1419			    (const uint8_t *)buff, dec_size,
1420			    zip->decrypted_buffer, dec_size);
1421		} else {
1422			size_t dsize = dec_size;
1423			archive_hmac_sha1_update(&zip->hctx,
1424			    (const uint8_t *)buff, dec_size);
1425			archive_decrypto_aes_ctr_update(&zip->cctx,
1426			    (const uint8_t *)buff, dec_size,
1427			    zip->decrypted_buffer, &dsize);
1428		}
1429		bytes_avail = dec_size;
1430		buff = (const char *)zip->decrypted_buffer;
1431	}
1432	*size = bytes_avail;
1433	zip->entry_bytes_remaining -= bytes_avail;
1434	zip->entry_uncompressed_bytes_read += bytes_avail;
1435	zip->entry_compressed_bytes_read += bytes_avail;
1436	zip->unconsumed += bytes_avail;
1437	*_buff = buff;
1438	return (ARCHIVE_OK);
1439}
1440
1441static int
1442consume_optional_marker(struct archive_read *a, struct zip *zip)
1443{
1444	if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1445		const char *p;
1446
1447		if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1448			archive_set_error(&a->archive,
1449			    ARCHIVE_ERRNO_FILE_FORMAT,
1450			    "Truncated ZIP end-of-file record");
1451			return (ARCHIVE_FATAL);
1452		}
1453		/* Consume the optional PK\007\010 marker. */
1454		if (p[0] == 'P' && p[1] == 'K' &&
1455		    p[2] == '\007' && p[3] == '\010') {
1456			p += 4;
1457			zip->unconsumed = 4;
1458		}
1459		if (zip->entry->flags & LA_USED_ZIP64) {
1460			uint64_t compressed, uncompressed;
1461			zip->entry->crc32 = archive_le32dec(p);
1462			compressed = archive_le64dec(p + 4);
1463			uncompressed = archive_le64dec(p + 12);
1464			if (compressed > INT64_MAX ||
1465			    uncompressed > INT64_MAX) {
1466				archive_set_error(&a->archive,
1467				    ARCHIVE_ERRNO_FILE_FORMAT,
1468				    "Overflow of 64-bit file sizes");
1469				return ARCHIVE_FAILED;
1470			}
1471			zip->entry->compressed_size = compressed;
1472			zip->entry->uncompressed_size = uncompressed;
1473			zip->unconsumed += 20;
1474		} else {
1475			zip->entry->crc32 = archive_le32dec(p);
1476			zip->entry->compressed_size = archive_le32dec(p + 4);
1477			zip->entry->uncompressed_size = archive_le32dec(p + 8);
1478			zip->unconsumed += 12;
1479		}
1480	}
1481
1482    return (ARCHIVE_OK);
1483}
1484
1485#if HAVE_LZMA_H && HAVE_LIBLZMA
1486static int
1487zipx_xz_init(struct archive_read *a, struct zip *zip)
1488{
1489	lzma_ret r;
1490
1491	if(zip->zipx_lzma_valid) {
1492		lzma_end(&zip->zipx_lzma_stream);
1493		zip->zipx_lzma_valid = 0;
1494	}
1495
1496	memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1497	r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1498	if (r != LZMA_OK) {
1499		archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1500		    "xz initialization failed(%d)",
1501		    r);
1502
1503		return (ARCHIVE_FAILED);
1504	}
1505
1506	zip->zipx_lzma_valid = 1;
1507
1508	free(zip->uncompressed_buffer);
1509
1510	zip->uncompressed_buffer_size = 256 * 1024;
1511	zip->uncompressed_buffer =
1512	    (uint8_t*) malloc(zip->uncompressed_buffer_size);
1513	if (zip->uncompressed_buffer == NULL) {
1514		archive_set_error(&a->archive, ENOMEM,
1515		    "No memory for xz decompression");
1516		    return (ARCHIVE_FATAL);
1517	}
1518
1519	zip->decompress_init = 1;
1520	return (ARCHIVE_OK);
1521}
1522
1523static int
1524zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1525{
1526	lzma_ret r;
1527	const uint8_t* p;
1528
1529#pragma pack(push)
1530#pragma pack(1)
1531	struct _alone_header {
1532	    uint8_t bytes[5];
1533	    uint64_t uncompressed_size;
1534	} alone_header;
1535#pragma pack(pop)
1536
1537	if(zip->zipx_lzma_valid) {
1538		lzma_end(&zip->zipx_lzma_stream);
1539		zip->zipx_lzma_valid = 0;
1540	}
1541
1542	/* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
1543	 * that is a part of XZ Utils. The stream format stored inside ZIPX
1544	 * file is a modified "lzma alone" file format, that was used by the
1545	 * `lzma` utility which was later deprecated in favour of `xz` utility. 	 * Since those formats are nearly the same, we can use a standard
1546	 * "lzma alone" decoder from XZ Utils. */
1547
1548	memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1549	r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1550	if (r != LZMA_OK) {
1551		archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1552		    "lzma initialization failed(%d)", r);
1553
1554		return (ARCHIVE_FAILED);
1555	}
1556
1557	/* Flag the cleanup function that we want our lzma-related structures
1558	 * to be freed later. */
1559	zip->zipx_lzma_valid = 1;
1560
1561	/* The "lzma alone" file format and the stream format inside ZIPx are
1562	 * almost the same. Here's an example of a structure of "lzma alone"
1563	 * format:
1564	 *
1565	 * $ cat /bin/ls | lzma | xxd | head -n 1
1566	 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1567	 *
1568	 *    5 bytes        8 bytes        n bytes
1569	 * <lzma_params><uncompressed_size><data...>
1570	 *
1571	 * lzma_params is a 5-byte blob that has to be decoded to extract
1572	 * parameters of this LZMA stream. The uncompressed_size field is an
1573	 * uint64_t value that contains information about the size of the
1574	 * uncompressed file, or UINT64_MAX if this value is unknown.
1575	 * The <data...> part is the actual lzma-compressed data stream.
1576	 *
1577	 * Now here's the structure of the stream inside the ZIPX file:
1578	 *
1579	 * $ cat stream_inside_zipx | xxd | head -n 1
1580	 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1581	 *
1582	 *  2byte   2byte    5 bytes     n bytes
1583	 * <magic1><magic2><lzma_params><data...>
1584	 *
1585	 * This means that the ZIPX file contains an additional magic1 and
1586	 * magic2 headers, the lzma_params field contains the same parameter
1587	 * set as in the "lzma alone" format, and the <data...> field is the
1588	 * same as in the "lzma alone" format as well. Note that also the zipx
1589	 * format is missing the uncompressed_size field.
1590	 *
1591	 * So, in order to use the "lzma alone" decoder for the zipx lzma
1592	 * stream, we simply need to shuffle around some fields, prepare a new
1593	 * lzma alone header, feed it into lzma alone decoder so it will
1594	 * initialize itself properly, and then we can start feeding normal
1595	 * zipx lzma stream into the decoder.
1596	 */
1597
1598	/* Read magic1,magic2,lzma_params from the ZIPX stream. */
1599	if((p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1600		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1601		    "Truncated lzma data");
1602		return (ARCHIVE_FATAL);
1603	}
1604
1605	if(p[2] != 0x05 || p[3] != 0x00) {
1606		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1607		    "Invalid lzma data");
1608		return (ARCHIVE_FATAL);
1609	}
1610
1611	/* Prepare an lzma alone header: copy the lzma_params blob into
1612	 * a proper place into the lzma alone header. */
1613	memcpy(&alone_header.bytes[0], p + 4, 5);
1614
1615	/* Initialize the 'uncompressed size' field to unknown; we'll manually
1616	 * monitor how many bytes there are still to be uncompressed. */
1617	alone_header.uncompressed_size = UINT64_MAX;
1618
1619	if(!zip->uncompressed_buffer) {
1620		zip->uncompressed_buffer_size = 256 * 1024;
1621		zip->uncompressed_buffer =
1622			(uint8_t*) malloc(zip->uncompressed_buffer_size);
1623
1624		if (zip->uncompressed_buffer == NULL) {
1625			archive_set_error(&a->archive, ENOMEM,
1626			    "No memory for lzma decompression");
1627			return (ARCHIVE_FATAL);
1628		}
1629	}
1630
1631	zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1632	zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1633	zip->zipx_lzma_stream.total_in = 0;
1634	zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1635	zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1636	zip->zipx_lzma_stream.total_out = 0;
1637
1638	/* Feed only the header into the lzma alone decoder. This will
1639	 * effectively initialize the decoder, and will not produce any
1640	 * output bytes yet. */
1641	r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1642	if (r != LZMA_OK) {
1643		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1644		    "lzma stream initialization error");
1645		return ARCHIVE_FATAL;
1646	}
1647
1648	/* We've already consumed some bytes, so take this into account. */
1649	__archive_read_consume(a, 9);
1650	zip->entry_bytes_remaining -= 9;
1651	zip->entry_compressed_bytes_read += 9;
1652
1653	zip->decompress_init = 1;
1654	return (ARCHIVE_OK);
1655}
1656
1657static int
1658zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1659	size_t *size, int64_t *offset)
1660{
1661	struct zip* zip = (struct zip *)(a->format->data);
1662	int ret;
1663	lzma_ret lz_ret;
1664	const void* compressed_buf;
1665	ssize_t bytes_avail, in_bytes, to_consume = 0;
1666
1667	(void) offset; /* UNUSED */
1668
1669	/* Initialize decompressor if not yet initialized. */
1670	if (!zip->decompress_init) {
1671		ret = zipx_xz_init(a, zip);
1672		if (ret != ARCHIVE_OK)
1673			return (ret);
1674	}
1675
1676	compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1677	if (bytes_avail < 0) {
1678		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1679		    "Truncated xz file body");
1680		return (ARCHIVE_FATAL);
1681	}
1682
1683	in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1684	zip->zipx_lzma_stream.next_in = compressed_buf;
1685	zip->zipx_lzma_stream.avail_in = in_bytes;
1686	zip->zipx_lzma_stream.total_in = 0;
1687	zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1688	zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1689	zip->zipx_lzma_stream.total_out = 0;
1690
1691	/* Perform the decompression. */
1692	lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1693	switch(lz_ret) {
1694		case LZMA_DATA_ERROR:
1695			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1696			    "xz data error (error %d)", (int) lz_ret);
1697			return (ARCHIVE_FATAL);
1698
1699		case LZMA_NO_CHECK:
1700		case LZMA_OK:
1701			break;
1702
1703		default:
1704			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1705			    "xz unknown error %d", (int) lz_ret);
1706			return (ARCHIVE_FATAL);
1707
1708		case LZMA_STREAM_END:
1709			lzma_end(&zip->zipx_lzma_stream);
1710			zip->zipx_lzma_valid = 0;
1711
1712			if((int64_t) zip->zipx_lzma_stream.total_in !=
1713			    zip->entry_bytes_remaining)
1714			{
1715				archive_set_error(&a->archive,
1716				    ARCHIVE_ERRNO_MISC,
1717				    "xz premature end of stream");
1718				return (ARCHIVE_FATAL);
1719			}
1720
1721			zip->end_of_entry = 1;
1722			break;
1723	}
1724
1725	to_consume = zip->zipx_lzma_stream.total_in;
1726
1727	__archive_read_consume(a, to_consume);
1728	zip->entry_bytes_remaining -= to_consume;
1729	zip->entry_compressed_bytes_read += to_consume;
1730	zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1731
1732	*size = zip->zipx_lzma_stream.total_out;
1733	*buff = zip->uncompressed_buffer;
1734
1735	ret = consume_optional_marker(a, zip);
1736	if (ret != ARCHIVE_OK)
1737		return (ret);
1738
1739	return (ARCHIVE_OK);
1740}
1741
1742static int
1743zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1744    size_t *size, int64_t *offset)
1745{
1746	struct zip* zip = (struct zip *)(a->format->data);
1747	int ret;
1748	lzma_ret lz_ret;
1749	const void* compressed_buf;
1750	ssize_t bytes_avail, in_bytes, to_consume;
1751
1752	(void) offset; /* UNUSED */
1753
1754	/* Initialize decompressor if not yet initialized. */
1755	if (!zip->decompress_init) {
1756		ret = zipx_lzma_alone_init(a, zip);
1757		if (ret != ARCHIVE_OK)
1758			return (ret);
1759	}
1760
1761	/* Fetch more compressed data. The same note as in deflate handler
1762	 * applies here as well:
1763	 *
1764	 * Note: '1' here is a performance optimization. Recall that the
1765	 * decompression layer returns a count of available bytes; asking for
1766	 * more than that forces the decompressor to combine reads by copying
1767	 * data.
1768	 */
1769	compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1770	if (bytes_avail < 0) {
1771		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1772		    "Truncated lzma file body");
1773		return (ARCHIVE_FATAL);
1774	}
1775
1776	/* Set decompressor parameters. */
1777	in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1778
1779	zip->zipx_lzma_stream.next_in = compressed_buf;
1780	zip->zipx_lzma_stream.avail_in = in_bytes;
1781	zip->zipx_lzma_stream.total_in = 0;
1782	zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1783	zip->zipx_lzma_stream.avail_out =
1784		/* These lzma_alone streams lack end of stream marker, so let's
1785		 * make sure the unpacker won't try to unpack more than it's
1786		 * supposed to. */
1787		zipmin((int64_t) zip->uncompressed_buffer_size,
1788		    zip->entry->uncompressed_size -
1789		    zip->entry_uncompressed_bytes_read);
1790	zip->zipx_lzma_stream.total_out = 0;
1791
1792	/* Perform the decompression. */
1793	lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1794	switch(lz_ret) {
1795		case LZMA_DATA_ERROR:
1796			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1797			    "lzma data error (error %d)", (int) lz_ret);
1798			return (ARCHIVE_FATAL);
1799
1800		/* This case is optional in lzma alone format. It can happen,
1801		 * but most of the files don't have it. (GitHub #1257) */
1802		case LZMA_STREAM_END:
1803			lzma_end(&zip->zipx_lzma_stream);
1804			zip->zipx_lzma_valid = 0;
1805			if((int64_t) zip->zipx_lzma_stream.total_in !=
1806			    zip->entry_bytes_remaining)
1807			{
1808				archive_set_error(&a->archive,
1809				    ARCHIVE_ERRNO_MISC,
1810				    "lzma alone premature end of stream");
1811				return (ARCHIVE_FATAL);
1812			}
1813
1814			zip->end_of_entry = 1;
1815			break;
1816
1817		case LZMA_OK:
1818			break;
1819
1820		default:
1821			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1822			    "lzma unknown error %d", (int) lz_ret);
1823			return (ARCHIVE_FATAL);
1824	}
1825
1826	to_consume = zip->zipx_lzma_stream.total_in;
1827
1828	/* Update pointers. */
1829	__archive_read_consume(a, to_consume);
1830	zip->entry_bytes_remaining -= to_consume;
1831	zip->entry_compressed_bytes_read += to_consume;
1832	zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1833
1834	if(zip->entry_bytes_remaining == 0) {
1835		zip->end_of_entry = 1;
1836	}
1837
1838	/* Return values. */
1839	*size = zip->zipx_lzma_stream.total_out;
1840	*buff = zip->uncompressed_buffer;
1841
1842	/* Behave the same way as during deflate decompression. */
1843	ret = consume_optional_marker(a, zip);
1844	if (ret != ARCHIVE_OK)
1845		return (ret);
1846
1847	/* Free lzma decoder handle because we'll no longer need it. */
1848	if(zip->end_of_entry) {
1849		lzma_end(&zip->zipx_lzma_stream);
1850		zip->zipx_lzma_valid = 0;
1851	}
1852
1853	/* If we're here, then we're good! */
1854	return (ARCHIVE_OK);
1855}
1856#endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1857
1858static int
1859zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1860{
1861	const void* p;
1862	uint32_t val;
1863	uint32_t order;
1864	uint32_t mem;
1865	uint32_t restore_method;
1866
1867	/* Remove previous decompression context if it exists. */
1868	if(zip->ppmd8_valid) {
1869		__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1870		zip->ppmd8_valid = 0;
1871	}
1872
1873	/* Create a new decompression context. */
1874	__archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1875	zip->ppmd8_stream_failed = 0;
1876
1877	/* Setup function pointers required by Ppmd8 decompressor. The
1878	 * 'ppmd_read' function will feed new bytes to the decompressor,
1879	 * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
1880	zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
1881	zip->zipx_ppmd_stream.a = a;
1882	zip->zipx_ppmd_stream.Read = &ppmd_read;
1883
1884	/* Reset number of read bytes to 0. */
1885	zip->zipx_ppmd_read_compressed = 0;
1886
1887	/* Read Ppmd8 header (2 bytes). */
1888	p = __archive_read_ahead(a, 2, NULL);
1889	if(!p) {
1890		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1891		    "Truncated file data in PPMd8 stream");
1892		return (ARCHIVE_FATAL);
1893	}
1894	__archive_read_consume(a, 2);
1895
1896	/* Decode the stream's compression parameters. */
1897	val = archive_le16dec(p);
1898	order = (val & 15) + 1;
1899	mem = ((val >> 4) & 0xff) + 1;
1900	restore_method = (val >> 12);
1901
1902	if(order < 2 || restore_method > 2) {
1903		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1904		    "Invalid parameter set in PPMd8 stream (order=%d, "
1905		    "restore=%d)", order, restore_method);
1906		return (ARCHIVE_FAILED);
1907	}
1908
1909	/* Allocate the memory needed to properly decompress the file. */
1910	if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
1911		archive_set_error(&a->archive, ENOMEM,
1912		    "Unable to allocate memory for PPMd8 stream: %d bytes",
1913		    mem << 20);
1914		return (ARCHIVE_FATAL);
1915	}
1916
1917	/* Signal the cleanup function to release Ppmd8 context in the
1918	 * cleanup phase. */
1919	zip->ppmd8_valid = 1;
1920
1921	/* Perform further Ppmd8 initialization. */
1922	if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
1923		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1924		    "PPMd8 stream range decoder initialization error");
1925		return (ARCHIVE_FATAL);
1926	}
1927
1928	__archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
1929	    restore_method);
1930
1931	/* Allocate the buffer that will hold uncompressed data. */
1932	free(zip->uncompressed_buffer);
1933
1934	zip->uncompressed_buffer_size = 256 * 1024;
1935	zip->uncompressed_buffer =
1936	    (uint8_t*) malloc(zip->uncompressed_buffer_size);
1937
1938	if(zip->uncompressed_buffer == NULL) {
1939		archive_set_error(&a->archive, ENOMEM,
1940		    "No memory for PPMd8 decompression");
1941		return ARCHIVE_FATAL;
1942	}
1943
1944	/* Ppmd8 initialization is done. */
1945	zip->decompress_init = 1;
1946
1947	/* We've already read 2 bytes in the output stream. Additionally,
1948	 * Ppmd8 initialization code could read some data as well. So we
1949	 * are advancing the stream by 2 bytes plus whatever number of
1950	 * bytes Ppmd8 init function used. */
1951	zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
1952
1953	return ARCHIVE_OK;
1954}
1955
1956static int
1957zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
1958    size_t *size, int64_t *offset)
1959{
1960	struct zip* zip = (struct zip *)(a->format->data);
1961	int ret;
1962	size_t consumed_bytes = 0;
1963	ssize_t bytes_avail = 0;
1964
1965	(void) offset; /* UNUSED */
1966
1967	/* If we're here for the first time, initialize Ppmd8 decompression
1968	 * context first. */
1969	if(!zip->decompress_init) {
1970		ret = zipx_ppmd8_init(a, zip);
1971		if(ret != ARCHIVE_OK)
1972			return ret;
1973	}
1974
1975	/* Fetch for more data. We're reading 1 byte here, but libarchive
1976	 * should prefetch more bytes. */
1977	(void) __archive_read_ahead(a, 1, &bytes_avail);
1978	if(bytes_avail < 0) {
1979		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1980		    "Truncated PPMd8 file body");
1981		return (ARCHIVE_FATAL);
1982	}
1983
1984	/* This counter will be updated inside ppmd_read(), which at one
1985	 * point will be called by Ppmd8_DecodeSymbol. */
1986	zip->zipx_ppmd_read_compressed = 0;
1987
1988	/* Decompression loop. */
1989	do {
1990		int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
1991		    &zip->ppmd8);
1992		if(sym < 0) {
1993			zip->end_of_entry = 1;
1994			break;
1995		}
1996
1997		/* This field is set by ppmd_read() when there was no more data
1998		 * to be read. */
1999		if(zip->ppmd8_stream_failed) {
2000			archive_set_error(&a->archive,
2001			    ARCHIVE_ERRNO_FILE_FORMAT,
2002			    "Truncated PPMd8 file body");
2003			return (ARCHIVE_FATAL);
2004		}
2005
2006		zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
2007		++consumed_bytes;
2008	} while(consumed_bytes < zip->uncompressed_buffer_size);
2009
2010	/* Update pointers for libarchive. */
2011	*buff = zip->uncompressed_buffer;
2012	*size = consumed_bytes;
2013
2014	/* Update pointers so we can continue decompression in another call. */
2015	zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
2016	zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
2017	zip->entry_uncompressed_bytes_read += consumed_bytes;
2018
2019	/* If we're at the end of stream, deinitialize Ppmd8 context. */
2020	if(zip->end_of_entry) {
2021		__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2022		zip->ppmd8_valid = 0;
2023	}
2024
2025	/* Seek for optional marker, same way as in each zip entry. */
2026	ret = consume_optional_marker(a, zip);
2027	if (ret != ARCHIVE_OK)
2028		return ret;
2029
2030	return ARCHIVE_OK;
2031}
2032
2033#ifdef HAVE_BZLIB_H
2034static int
2035zipx_bzip2_init(struct archive_read *a, struct zip *zip)
2036{
2037	int r;
2038
2039	/* Deallocate already existing BZ2 decompression context if it
2040	 * exists. */
2041	if(zip->bzstream_valid) {
2042		BZ2_bzDecompressEnd(&zip->bzstream);
2043		zip->bzstream_valid = 0;
2044	}
2045
2046	/* Allocate a new BZ2 decompression context. */
2047	memset(&zip->bzstream, 0, sizeof(bz_stream));
2048	r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
2049	if(r != BZ_OK) {
2050		archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
2051		    "bzip2 initialization failed(%d)",
2052		    r);
2053
2054		return ARCHIVE_FAILED;
2055	}
2056
2057	/* Mark the bzstream field to be released in cleanup phase. */
2058	zip->bzstream_valid = 1;
2059
2060	/* (Re)allocate the buffer that will contain decompressed bytes. */
2061	free(zip->uncompressed_buffer);
2062
2063	zip->uncompressed_buffer_size = 256 * 1024;
2064	zip->uncompressed_buffer =
2065	    (uint8_t*) malloc(zip->uncompressed_buffer_size);
2066	if (zip->uncompressed_buffer == NULL) {
2067		archive_set_error(&a->archive, ENOMEM,
2068		    "No memory for bzip2 decompression");
2069		    return ARCHIVE_FATAL;
2070	}
2071
2072	/* Initialization done. */
2073	zip->decompress_init = 1;
2074	return ARCHIVE_OK;
2075}
2076
2077static int
2078zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
2079    size_t *size, int64_t *offset)
2080{
2081	struct zip *zip = (struct zip *)(a->format->data);
2082	ssize_t bytes_avail = 0, in_bytes, to_consume;
2083	const void *compressed_buff;
2084	int r;
2085	uint64_t total_out;
2086
2087	(void) offset; /* UNUSED */
2088
2089	/* Initialize decompression context if we're here for the first time. */
2090	if(!zip->decompress_init) {
2091		r = zipx_bzip2_init(a, zip);
2092		if(r != ARCHIVE_OK)
2093			return r;
2094	}
2095
2096	/* Fetch more compressed bytes. */
2097	compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2098	if(bytes_avail < 0) {
2099		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2100		    "Truncated bzip2 file body");
2101		return (ARCHIVE_FATAL);
2102	}
2103
2104	in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2105	if(in_bytes < 1) {
2106		/* libbz2 doesn't complain when caller feeds avail_in == 0.
2107		 * It will actually return success in this case, which is
2108		 * undesirable. This is why we need to make this check
2109		 * manually. */
2110
2111		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2112		    "Truncated bzip2 file body");
2113		return (ARCHIVE_FATAL);
2114	}
2115
2116	/* Setup buffer boundaries. */
2117	zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
2118	zip->bzstream.avail_in = in_bytes;
2119	zip->bzstream.total_in_hi32 = 0;
2120	zip->bzstream.total_in_lo32 = 0;
2121	zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2122	zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2123	zip->bzstream.total_out_hi32 = 0;
2124	zip->bzstream.total_out_lo32 = 0;
2125
2126	/* Perform the decompression. */
2127	r = BZ2_bzDecompress(&zip->bzstream);
2128	switch(r) {
2129		case BZ_STREAM_END:
2130			/* If we're at the end of the stream, deinitialize the
2131			 * decompression context now. */
2132			switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2133				case BZ_OK:
2134					break;
2135				default:
2136					archive_set_error(&a->archive,
2137					    ARCHIVE_ERRNO_MISC,
2138					    "Failed to clean up bzip2 "
2139					    "decompressor");
2140					return ARCHIVE_FATAL;
2141			}
2142
2143			zip->end_of_entry = 1;
2144			break;
2145		case BZ_OK:
2146			/* The decompressor has successfully decoded this
2147			 * chunk of data, but more data is still in queue. */
2148			break;
2149		default:
2150			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2151			    "bzip2 decompression failed");
2152			return ARCHIVE_FATAL;
2153	}
2154
2155	/* Update the pointers so decompressor can continue decoding. */
2156	to_consume = zip->bzstream.total_in_lo32;
2157	__archive_read_consume(a, to_consume);
2158
2159	total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2160	    zip->bzstream.total_out_lo32;
2161
2162	zip->entry_bytes_remaining -= to_consume;
2163	zip->entry_compressed_bytes_read += to_consume;
2164	zip->entry_uncompressed_bytes_read += total_out;
2165
2166	/* Give libarchive its due. */
2167	*size = total_out;
2168	*buff = zip->uncompressed_buffer;
2169
2170	/* Seek for optional marker, like in other entries. */
2171	r = consume_optional_marker(a, zip);
2172	if(r != ARCHIVE_OK)
2173		return r;
2174
2175	return ARCHIVE_OK;
2176}
2177
2178#endif
2179
2180#ifdef HAVE_ZLIB_H
2181static int
2182zip_deflate_init(struct archive_read *a, struct zip *zip)
2183{
2184	int r;
2185
2186	/* If we haven't yet read any data, initialize the decompressor. */
2187	if (!zip->decompress_init) {
2188		if (zip->stream_valid)
2189			r = inflateReset(&zip->stream);
2190		else
2191			r = inflateInit2(&zip->stream,
2192			    -15 /* Don't check for zlib header */);
2193		if (r != Z_OK) {
2194			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2195			    "Can't initialize ZIP decompression.");
2196			return (ARCHIVE_FATAL);
2197		}
2198		/* Stream structure has been set up. */
2199		zip->stream_valid = 1;
2200		/* We've initialized decompression for this stream. */
2201		zip->decompress_init = 1;
2202	}
2203	return (ARCHIVE_OK);
2204}
2205
2206static int
2207zip_read_data_deflate(struct archive_read *a, const void **buff,
2208    size_t *size, int64_t *offset)
2209{
2210	struct zip *zip;
2211	ssize_t bytes_avail;
2212	const void *compressed_buff, *sp;
2213	int r;
2214
2215	(void)offset; /* UNUSED */
2216
2217	zip = (struct zip *)(a->format->data);
2218
2219	/* If the buffer hasn't been allocated, allocate it now. */
2220	if (zip->uncompressed_buffer == NULL) {
2221		zip->uncompressed_buffer_size = 256 * 1024;
2222		zip->uncompressed_buffer
2223		    = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2224		if (zip->uncompressed_buffer == NULL) {
2225			archive_set_error(&a->archive, ENOMEM,
2226			    "No memory for ZIP decompression");
2227			return (ARCHIVE_FATAL);
2228		}
2229	}
2230
2231	r = zip_deflate_init(a, zip);
2232	if (r != ARCHIVE_OK)
2233		return (r);
2234
2235	/*
2236	 * Note: '1' here is a performance optimization.
2237	 * Recall that the decompression layer returns a count of
2238	 * available bytes; asking for more than that forces the
2239	 * decompressor to combine reads by copying data.
2240	 */
2241	compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2242	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2243	    && bytes_avail > zip->entry_bytes_remaining) {
2244		bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2245	}
2246	if (bytes_avail < 0) {
2247		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2248		    "Truncated ZIP file body");
2249		return (ARCHIVE_FATAL);
2250	}
2251
2252	if (zip->tctx_valid || zip->cctx_valid) {
2253		if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2254			size_t buff_remaining =
2255			    (zip->decrypted_buffer +
2256			    zip->decrypted_buffer_size)
2257			    - (zip->decrypted_ptr +
2258			    zip->decrypted_bytes_remaining);
2259
2260			if (buff_remaining > (size_t)bytes_avail)
2261				buff_remaining = (size_t)bytes_avail;
2262
2263			if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2264			      zip->entry_bytes_remaining > 0) {
2265				if ((int64_t)(zip->decrypted_bytes_remaining
2266				    + buff_remaining)
2267				      > zip->entry_bytes_remaining) {
2268					if (zip->entry_bytes_remaining <
2269					    (int64_t)zip->decrypted_bytes_remaining)
2270						buff_remaining = 0;
2271					else
2272						buff_remaining =
2273						    (size_t)zip->entry_bytes_remaining
2274						    - zip->decrypted_bytes_remaining;
2275				}
2276			}
2277			if (buff_remaining > 0) {
2278				if (zip->tctx_valid) {
2279					trad_enc_decrypt_update(&zip->tctx,
2280					    compressed_buff, buff_remaining,
2281					    zip->decrypted_ptr
2282					      + zip->decrypted_bytes_remaining,
2283					    buff_remaining);
2284				} else {
2285					size_t dsize = buff_remaining;
2286					archive_decrypto_aes_ctr_update(
2287					    &zip->cctx,
2288					    compressed_buff, buff_remaining,
2289					    zip->decrypted_ptr
2290					      + zip->decrypted_bytes_remaining,
2291					    &dsize);
2292				}
2293				zip->decrypted_bytes_remaining +=
2294				    buff_remaining;
2295			}
2296		}
2297		bytes_avail = zip->decrypted_bytes_remaining;
2298		compressed_buff = (const char *)zip->decrypted_ptr;
2299	}
2300
2301	/*
2302	 * A bug in zlib.h: stream.next_in should be marked 'const'
2303	 * but isn't (the library never alters data through the
2304	 * next_in pointer, only reads it).  The result: this ugly
2305	 * cast to remove 'const'.
2306	 */
2307	zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2308	zip->stream.avail_in = (uInt)bytes_avail;
2309	zip->stream.total_in = 0;
2310	zip->stream.next_out = zip->uncompressed_buffer;
2311	zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2312	zip->stream.total_out = 0;
2313
2314	r = inflate(&zip->stream, 0);
2315	switch (r) {
2316	case Z_OK:
2317		break;
2318	case Z_STREAM_END:
2319		zip->end_of_entry = 1;
2320		break;
2321	case Z_MEM_ERROR:
2322		archive_set_error(&a->archive, ENOMEM,
2323		    "Out of memory for ZIP decompression");
2324		return (ARCHIVE_FATAL);
2325	default:
2326		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2327		    "ZIP decompression failed (%d)", r);
2328		return (ARCHIVE_FATAL);
2329	}
2330
2331	/* Consume as much as the compressor actually used. */
2332	bytes_avail = zip->stream.total_in;
2333	if (zip->tctx_valid || zip->cctx_valid) {
2334		zip->decrypted_bytes_remaining -= bytes_avail;
2335		if (zip->decrypted_bytes_remaining == 0)
2336			zip->decrypted_ptr = zip->decrypted_buffer;
2337		else
2338			zip->decrypted_ptr += bytes_avail;
2339	}
2340	/* Calculate compressed data as much as we used.*/
2341	if (zip->hctx_valid)
2342		archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2343	__archive_read_consume(a, bytes_avail);
2344	zip->entry_bytes_remaining -= bytes_avail;
2345	zip->entry_compressed_bytes_read += bytes_avail;
2346
2347	*size = zip->stream.total_out;
2348	zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2349	*buff = zip->uncompressed_buffer;
2350
2351	if (zip->end_of_entry && zip->hctx_valid) {
2352		r = check_authentication_code(a, NULL);
2353		if (r != ARCHIVE_OK)
2354			return (r);
2355	}
2356
2357	r = consume_optional_marker(a, zip);
2358	if (r != ARCHIVE_OK)
2359		return (r);
2360
2361	return (ARCHIVE_OK);
2362}
2363#endif
2364
2365static int
2366read_decryption_header(struct archive_read *a)
2367{
2368	struct zip *zip = (struct zip *)(a->format->data);
2369	const char *p;
2370	unsigned int remaining_size;
2371	unsigned int ts;
2372
2373	/*
2374	 * Read an initialization vector data field.
2375	 */
2376	p = __archive_read_ahead(a, 2, NULL);
2377	if (p == NULL)
2378		goto truncated;
2379	ts = zip->iv_size;
2380	zip->iv_size = archive_le16dec(p);
2381	__archive_read_consume(a, 2);
2382	if (ts < zip->iv_size) {
2383		free(zip->iv);
2384		zip->iv = NULL;
2385	}
2386	p = __archive_read_ahead(a, zip->iv_size, NULL);
2387	if (p == NULL)
2388		goto truncated;
2389	if (zip->iv == NULL) {
2390		zip->iv = malloc(zip->iv_size);
2391		if (zip->iv == NULL)
2392			goto nomem;
2393	}
2394	memcpy(zip->iv, p, zip->iv_size);
2395	__archive_read_consume(a, zip->iv_size);
2396
2397	/*
2398	 * Read a size of remaining decryption header field.
2399	 */
2400	p = __archive_read_ahead(a, 14, NULL);
2401	if (p == NULL)
2402		goto truncated;
2403	remaining_size = archive_le32dec(p);
2404	if (remaining_size < 16 || remaining_size > (1 << 18))
2405		goto corrupted;
2406
2407	/* Check if format version is supported. */
2408	if (archive_le16dec(p+4) != 3) {
2409		archive_set_error(&a->archive,
2410		    ARCHIVE_ERRNO_FILE_FORMAT,
2411		    "Unsupported encryption format version: %u",
2412		    archive_le16dec(p+4));
2413		return (ARCHIVE_FAILED);
2414	}
2415
2416	/*
2417	 * Read an encryption algorithm field.
2418	 */
2419	zip->alg_id = archive_le16dec(p+6);
2420	switch (zip->alg_id) {
2421	case 0x6601:/* DES */
2422	case 0x6602:/* RC2 */
2423	case 0x6603:/* 3DES 168 */
2424	case 0x6609:/* 3DES 112 */
2425	case 0x660E:/* AES 128 */
2426	case 0x660F:/* AES 192 */
2427	case 0x6610:/* AES 256 */
2428	case 0x6702:/* RC2 (version >= 5.2) */
2429	case 0x6720:/* Blowfish */
2430	case 0x6721:/* Twofish */
2431	case 0x6801:/* RC4 */
2432		/* Supported encryption algorithm. */
2433		break;
2434	default:
2435		archive_set_error(&a->archive,
2436		    ARCHIVE_ERRNO_FILE_FORMAT,
2437		    "Unknown encryption algorithm: %u", zip->alg_id);
2438		return (ARCHIVE_FAILED);
2439	}
2440
2441	/*
2442	 * Read a bit length field.
2443	 */
2444	zip->bit_len = archive_le16dec(p+8);
2445
2446	/*
2447	 * Read a flags field.
2448	 */
2449	zip->flags = archive_le16dec(p+10);
2450	switch (zip->flags & 0xf000) {
2451	case 0x0001: /* Password is required to decrypt. */
2452	case 0x0002: /* Certificates only. */
2453	case 0x0003: /* Password or certificate required to decrypt. */
2454		break;
2455	default:
2456		archive_set_error(&a->archive,
2457		    ARCHIVE_ERRNO_FILE_FORMAT,
2458		    "Unknown encryption flag: %u", zip->flags);
2459		return (ARCHIVE_FAILED);
2460	}
2461	if ((zip->flags & 0xf000) == 0 ||
2462	    (zip->flags & 0xf000) == 0x4000) {
2463		archive_set_error(&a->archive,
2464		    ARCHIVE_ERRNO_FILE_FORMAT,
2465		    "Unknown encryption flag: %u", zip->flags);
2466		return (ARCHIVE_FAILED);
2467	}
2468
2469	/*
2470	 * Read an encrypted random data field.
2471	 */
2472	ts = zip->erd_size;
2473	zip->erd_size = archive_le16dec(p+12);
2474	__archive_read_consume(a, 14);
2475	if ((zip->erd_size & 0xf) != 0 ||
2476	    (zip->erd_size + 16) > remaining_size ||
2477	    (zip->erd_size + 16) < zip->erd_size)
2478		goto corrupted;
2479
2480	if (ts < zip->erd_size) {
2481		free(zip->erd);
2482		zip->erd = NULL;
2483	}
2484	p = __archive_read_ahead(a, zip->erd_size, NULL);
2485	if (p == NULL)
2486		goto truncated;
2487	if (zip->erd == NULL) {
2488		zip->erd = malloc(zip->erd_size);
2489		if (zip->erd == NULL)
2490			goto nomem;
2491	}
2492	memcpy(zip->erd, p, zip->erd_size);
2493	__archive_read_consume(a, zip->erd_size);
2494
2495	/*
2496	 * Read a reserved data field.
2497	 */
2498	p = __archive_read_ahead(a, 4, NULL);
2499	if (p == NULL)
2500		goto truncated;
2501	/* Reserved data size should be zero. */
2502	if (archive_le32dec(p) != 0)
2503		goto corrupted;
2504	__archive_read_consume(a, 4);
2505
2506	/*
2507	 * Read a password validation data field.
2508	 */
2509	p = __archive_read_ahead(a, 2, NULL);
2510	if (p == NULL)
2511		goto truncated;
2512	ts = zip->v_size;
2513	zip->v_size = archive_le16dec(p);
2514	__archive_read_consume(a, 2);
2515	if ((zip->v_size & 0x0f) != 0 ||
2516	    (zip->erd_size + zip->v_size + 16) > remaining_size ||
2517	    (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2518		goto corrupted;
2519	if (ts < zip->v_size) {
2520		free(zip->v_data);
2521		zip->v_data = NULL;
2522	}
2523	p = __archive_read_ahead(a, zip->v_size, NULL);
2524	if (p == NULL)
2525		goto truncated;
2526	if (zip->v_data == NULL) {
2527		zip->v_data = malloc(zip->v_size);
2528		if (zip->v_data == NULL)
2529			goto nomem;
2530	}
2531	memcpy(zip->v_data, p, zip->v_size);
2532	__archive_read_consume(a, zip->v_size);
2533
2534	p = __archive_read_ahead(a, 4, NULL);
2535	if (p == NULL)
2536		goto truncated;
2537	zip->v_crc32 = archive_le32dec(p);
2538	__archive_read_consume(a, 4);
2539
2540	/*return (ARCHIVE_OK);
2541	 * This is not fully implemented yet.*/
2542	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2543	    "Encrypted file is unsupported");
2544	return (ARCHIVE_FAILED);
2545truncated:
2546	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2547	    "Truncated ZIP file data");
2548	return (ARCHIVE_FATAL);
2549corrupted:
2550	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2551	    "Corrupted ZIP file data");
2552	return (ARCHIVE_FATAL);
2553nomem:
2554	archive_set_error(&a->archive, ENOMEM,
2555	    "No memory for ZIP decryption");
2556	return (ARCHIVE_FATAL);
2557}
2558
2559static int
2560zip_alloc_decryption_buffer(struct archive_read *a)
2561{
2562	struct zip *zip = (struct zip *)(a->format->data);
2563	size_t bs = 256 * 1024;
2564
2565	if (zip->decrypted_buffer == NULL) {
2566		zip->decrypted_buffer_size = bs;
2567		zip->decrypted_buffer = malloc(bs);
2568		if (zip->decrypted_buffer == NULL) {
2569			archive_set_error(&a->archive, ENOMEM,
2570			    "No memory for ZIP decryption");
2571			return (ARCHIVE_FATAL);
2572		}
2573	}
2574	zip->decrypted_ptr = zip->decrypted_buffer;
2575	return (ARCHIVE_OK);
2576}
2577
2578static int
2579init_traditional_PKWARE_decryption(struct archive_read *a)
2580{
2581	struct zip *zip = (struct zip *)(a->format->data);
2582	const void *p;
2583	int retry;
2584	int r;
2585
2586	if (zip->tctx_valid)
2587		return (ARCHIVE_OK);
2588
2589	/*
2590	   Read the 12 bytes encryption header stored at
2591	   the start of the data area.
2592	 */
2593#define ENC_HEADER_SIZE	12
2594	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2595	    && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2596		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2597		    "Truncated Zip encrypted body: only %jd bytes available",
2598		    (intmax_t)zip->entry_bytes_remaining);
2599		return (ARCHIVE_FATAL);
2600	}
2601
2602	p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2603	if (p == NULL) {
2604		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2605		    "Truncated ZIP file data");
2606		return (ARCHIVE_FATAL);
2607	}
2608
2609	for (retry = 0;; retry++) {
2610		const char *passphrase;
2611		uint8_t crcchk;
2612
2613		passphrase = __archive_read_next_passphrase(a);
2614		if (passphrase == NULL) {
2615			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2616			    (retry > 0)?
2617				"Incorrect passphrase":
2618				"Passphrase required for this entry");
2619			return (ARCHIVE_FAILED);
2620		}
2621
2622		/*
2623		 * Initialize ctx for Traditional PKWARE Decryption.
2624		 */
2625		r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2626			p, ENC_HEADER_SIZE, &crcchk);
2627		if (r == 0 && crcchk == zip->entry->decdat)
2628			break;/* The passphrase is OK. */
2629		if (retry > 10000) {
2630			/* Avoid infinity loop. */
2631			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2632			    "Too many incorrect passphrases");
2633			return (ARCHIVE_FAILED);
2634		}
2635	}
2636
2637	__archive_read_consume(a, ENC_HEADER_SIZE);
2638	zip->tctx_valid = 1;
2639	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2640	    zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2641	}
2642	/*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2643	zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2644	zip->decrypted_bytes_remaining = 0;
2645
2646	return (zip_alloc_decryption_buffer(a));
2647#undef ENC_HEADER_SIZE
2648}
2649
2650static int
2651init_WinZip_AES_decryption(struct archive_read *a)
2652{
2653	struct zip *zip = (struct zip *)(a->format->data);
2654	const void *p;
2655	const uint8_t *pv;
2656	size_t key_len, salt_len;
2657	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2658	int retry;
2659	int r;
2660
2661	if (zip->cctx_valid || zip->hctx_valid)
2662		return (ARCHIVE_OK);
2663
2664	switch (zip->entry->aes_extra.strength) {
2665	case 1: salt_len = 8;  key_len = 16; break;
2666	case 2: salt_len = 12; key_len = 24; break;
2667	case 3: salt_len = 16; key_len = 32; break;
2668	default: goto corrupted;
2669	}
2670	p = __archive_read_ahead(a, salt_len + 2, NULL);
2671	if (p == NULL)
2672		goto truncated;
2673
2674	for (retry = 0;; retry++) {
2675		const char *passphrase;
2676
2677		passphrase = __archive_read_next_passphrase(a);
2678		if (passphrase == NULL) {
2679			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2680			    (retry > 0)?
2681				"Incorrect passphrase":
2682				"Passphrase required for this entry");
2683			return (ARCHIVE_FAILED);
2684		}
2685		memset(derived_key, 0, sizeof(derived_key));
2686		r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2687		    p, salt_len, 1000, derived_key, key_len * 2 + 2);
2688		if (r != 0) {
2689			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2690			    "Decryption is unsupported due to lack of "
2691			    "crypto library");
2692			return (ARCHIVE_FAILED);
2693		}
2694
2695		/* Check password verification value. */
2696		pv = ((const uint8_t *)p) + salt_len;
2697		if (derived_key[key_len * 2] == pv[0] &&
2698		    derived_key[key_len * 2 + 1] == pv[1])
2699			break;/* The passphrase is OK. */
2700		if (retry > 10000) {
2701			/* Avoid infinity loop. */
2702			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2703			    "Too many incorrect passphrases");
2704			return (ARCHIVE_FAILED);
2705		}
2706	}
2707
2708	r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2709	if (r != 0) {
2710		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2711		    "Decryption is unsupported due to lack of crypto library");
2712		return (ARCHIVE_FAILED);
2713	}
2714	r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2715	if (r != 0) {
2716		archive_decrypto_aes_ctr_release(&zip->cctx);
2717		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2718		    "Failed to initialize HMAC-SHA1");
2719		return (ARCHIVE_FAILED);
2720	}
2721	zip->cctx_valid = zip->hctx_valid = 1;
2722	__archive_read_consume(a, salt_len + 2);
2723	zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2724	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2725	    && zip->entry_bytes_remaining < 0)
2726		goto corrupted;
2727	zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2728	zip->decrypted_bytes_remaining = 0;
2729
2730	zip->entry->compression = zip->entry->aes_extra.compression;
2731	return (zip_alloc_decryption_buffer(a));
2732
2733truncated:
2734	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2735	    "Truncated ZIP file data");
2736	return (ARCHIVE_FATAL);
2737corrupted:
2738	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2739	    "Corrupted ZIP file data");
2740	return (ARCHIVE_FATAL);
2741}
2742
2743static int
2744archive_read_format_zip_read_data(struct archive_read *a,
2745    const void **buff, size_t *size, int64_t *offset)
2746{
2747	int r;
2748	struct zip *zip = (struct zip *)(a->format->data);
2749
2750	if (zip->has_encrypted_entries ==
2751			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2752		zip->has_encrypted_entries = 0;
2753	}
2754
2755	*offset = zip->entry_uncompressed_bytes_read;
2756	*size = 0;
2757	*buff = NULL;
2758
2759	/* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2760	if (zip->end_of_entry)
2761		return (ARCHIVE_EOF);
2762
2763	/* Return EOF immediately if this is a non-regular file. */
2764	if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2765		return (ARCHIVE_EOF);
2766
2767	__archive_read_consume(a, zip->unconsumed);
2768	zip->unconsumed = 0;
2769
2770	if (zip->init_decryption) {
2771		zip->has_encrypted_entries = 1;
2772		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2773			r = read_decryption_header(a);
2774		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2775			r = init_WinZip_AES_decryption(a);
2776		else
2777			r = init_traditional_PKWARE_decryption(a);
2778		if (r != ARCHIVE_OK)
2779			return (r);
2780		zip->init_decryption = 0;
2781	}
2782
2783	switch(zip->entry->compression) {
2784	case 0:  /* No compression. */
2785		r =  zip_read_data_none(a, buff, size, offset);
2786		break;
2787#ifdef HAVE_BZLIB_H
2788	case 12: /* ZIPx bzip2 compression. */
2789		r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2790		break;
2791#endif
2792#if HAVE_LZMA_H && HAVE_LIBLZMA
2793	case 14: /* ZIPx LZMA compression. */
2794		r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
2795		break;
2796	case 95: /* ZIPx XZ compression. */
2797		r = zip_read_data_zipx_xz(a, buff, size, offset);
2798		break;
2799#endif
2800	/* PPMd support is built-in, so we don't need any #if guards. */
2801	case 98: /* ZIPx PPMd compression. */
2802		r = zip_read_data_zipx_ppmd(a, buff, size, offset);
2803		break;
2804
2805#ifdef HAVE_ZLIB_H
2806	case 8: /* Deflate compression. */
2807		r =  zip_read_data_deflate(a, buff, size, offset);
2808		break;
2809#endif
2810	default: /* Unsupported compression. */
2811		/* Return a warning. */
2812		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2813		    "Unsupported ZIP compression method (%d: %s)",
2814		    zip->entry->compression, compression_name(zip->entry->compression));
2815		/* We can't decompress this entry, but we will
2816		 * be able to skip() it and try the next entry. */
2817		return (ARCHIVE_FAILED);
2818		break;
2819	}
2820	if (r != ARCHIVE_OK)
2821		return (r);
2822	/* Update checksum */
2823	if (*size)
2824		zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
2825		    (unsigned)*size);
2826	/* If we hit the end, swallow any end-of-data marker. */
2827	if (zip->end_of_entry) {
2828		/* Check file size, CRC against these values. */
2829		if (zip->entry->compressed_size !=
2830		    zip->entry_compressed_bytes_read) {
2831			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2832			    "ZIP compressed data is wrong size "
2833			    "(read %jd, expected %jd)",
2834			    (intmax_t)zip->entry_compressed_bytes_read,
2835			    (intmax_t)zip->entry->compressed_size);
2836			return (ARCHIVE_WARN);
2837		}
2838		/* Size field only stores the lower 32 bits of the actual
2839		 * size. */
2840		if ((zip->entry->uncompressed_size & UINT32_MAX)
2841		    != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
2842			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2843			    "ZIP uncompressed data is wrong size "
2844			    "(read %jd, expected %jd)\n",
2845			    (intmax_t)zip->entry_uncompressed_bytes_read,
2846			    (intmax_t)zip->entry->uncompressed_size);
2847			return (ARCHIVE_WARN);
2848		}
2849		/* Check computed CRC against header */
2850		if ((!zip->hctx_valid ||
2851		      zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
2852		   zip->entry->crc32 != zip->entry_crc32
2853		    && !zip->ignore_crc32) {
2854			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2855			    "ZIP bad CRC: 0x%lx should be 0x%lx",
2856			    (unsigned long)zip->entry_crc32,
2857			    (unsigned long)zip->entry->crc32);
2858			return (ARCHIVE_WARN);
2859		}
2860	}
2861
2862	return (ARCHIVE_OK);
2863}
2864
2865static int
2866archive_read_format_zip_cleanup(struct archive_read *a)
2867{
2868	struct zip *zip;
2869	struct zip_entry *zip_entry, *next_zip_entry;
2870
2871	zip = (struct zip *)(a->format->data);
2872
2873#ifdef HAVE_ZLIB_H
2874	if (zip->stream_valid)
2875		inflateEnd(&zip->stream);
2876#endif
2877
2878#if HAVE_LZMA_H && HAVE_LIBLZMA
2879    if (zip->zipx_lzma_valid) {
2880		lzma_end(&zip->zipx_lzma_stream);
2881	}
2882#endif
2883
2884#ifdef HAVE_BZLIB_H
2885	if (zip->bzstream_valid) {
2886		BZ2_bzDecompressEnd(&zip->bzstream);
2887	}
2888#endif
2889
2890	free(zip->uncompressed_buffer);
2891
2892	if (zip->ppmd8_valid)
2893		__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2894
2895	if (zip->zip_entries) {
2896		zip_entry = zip->zip_entries;
2897		while (zip_entry != NULL) {
2898			next_zip_entry = zip_entry->next;
2899			archive_string_free(&zip_entry->rsrcname);
2900			free(zip_entry);
2901			zip_entry = next_zip_entry;
2902		}
2903	}
2904	free(zip->decrypted_buffer);
2905	if (zip->cctx_valid)
2906		archive_decrypto_aes_ctr_release(&zip->cctx);
2907	if (zip->hctx_valid)
2908		archive_hmac_sha1_cleanup(&zip->hctx);
2909	free(zip->iv);
2910	free(zip->erd);
2911	free(zip->v_data);
2912	archive_string_free(&zip->format_name);
2913	free(zip);
2914	(a->format->data) = NULL;
2915	return (ARCHIVE_OK);
2916}
2917
2918static int
2919archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
2920{
2921	if (_a && _a->format) {
2922		struct zip * zip = (struct zip *)_a->format->data;
2923		if (zip) {
2924			return zip->has_encrypted_entries;
2925		}
2926	}
2927	return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
2928}
2929
2930static int
2931archive_read_format_zip_options(struct archive_read *a,
2932    const char *key, const char *val)
2933{
2934	struct zip *zip;
2935	int ret = ARCHIVE_FAILED;
2936
2937	zip = (struct zip *)(a->format->data);
2938	if (strcmp(key, "compat-2x")  == 0) {
2939		/* Handle filenames as libarchive 2.x */
2940		zip->init_default_conversion = (val != NULL) ? 1 : 0;
2941		return (ARCHIVE_OK);
2942	} else if (strcmp(key, "hdrcharset")  == 0) {
2943		if (val == NULL || val[0] == 0)
2944			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2945			    "zip: hdrcharset option needs a character-set name"
2946			);
2947		else {
2948			zip->sconv = archive_string_conversion_from_charset(
2949			    &a->archive, val, 0);
2950			if (zip->sconv != NULL) {
2951				if (strcmp(val, "UTF-8") == 0)
2952					zip->sconv_utf8 = zip->sconv;
2953				ret = ARCHIVE_OK;
2954			} else
2955				ret = ARCHIVE_FATAL;
2956		}
2957		return (ret);
2958	} else if (strcmp(key, "ignorecrc32") == 0) {
2959		/* Mostly useful for testing. */
2960		if (val == NULL || val[0] == 0) {
2961			zip->crc32func = real_crc32;
2962			zip->ignore_crc32 = 0;
2963		} else {
2964			zip->crc32func = fake_crc32;
2965			zip->ignore_crc32 = 1;
2966		}
2967		return (ARCHIVE_OK);
2968	} else if (strcmp(key, "mac-ext") == 0) {
2969		zip->process_mac_extensions = (val != NULL && val[0] != 0);
2970		return (ARCHIVE_OK);
2971	}
2972
2973	/* Note: The "warn" return is just to inform the options
2974	 * supervisor that we didn't handle it.  It will generate
2975	 * a suitable error if no one used this option. */
2976	return (ARCHIVE_WARN);
2977}
2978
2979int
2980archive_read_support_format_zip(struct archive *a)
2981{
2982	int r;
2983	r = archive_read_support_format_zip_streamable(a);
2984	if (r != ARCHIVE_OK)
2985		return r;
2986	return (archive_read_support_format_zip_seekable(a));
2987}
2988
2989/* ------------------------------------------------------------------------ */
2990
2991/*
2992 * Streaming-mode support
2993 */
2994
2995
2996static int
2997archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
2998{
2999	(void)a; /* UNUSED */
3000	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3001		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3002}
3003
3004static int
3005archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
3006{
3007	const char *p;
3008
3009	(void)best_bid; /* UNUSED */
3010
3011	if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3012		return (-1);
3013
3014	/*
3015	 * Bid of 29 here comes from:
3016	 *  + 16 bits for "PK",
3017	 *  + next 16-bit field has 6 options so contributes
3018	 *    about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
3019	 *
3020	 * So we've effectively verified ~29 total bits of check data.
3021	 */
3022	if (p[0] == 'P' && p[1] == 'K') {
3023		if ((p[2] == '\001' && p[3] == '\002')
3024		    || (p[2] == '\003' && p[3] == '\004')
3025		    || (p[2] == '\005' && p[3] == '\006')
3026		    || (p[2] == '\006' && p[3] == '\006')
3027		    || (p[2] == '\007' && p[3] == '\010')
3028		    || (p[2] == '0' && p[3] == '0'))
3029			return (29);
3030	}
3031
3032	/* TODO: It's worth looking ahead a little bit for a valid
3033	 * PK signature.  In particular, that would make it possible
3034	 * to read some UUEncoded SFX files or SFX files coming from
3035	 * a network socket. */
3036
3037	return (0);
3038}
3039
3040static int
3041archive_read_format_zip_streamable_read_header(struct archive_read *a,
3042    struct archive_entry *entry)
3043{
3044	struct zip *zip;
3045
3046	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3047	if (a->archive.archive_format_name == NULL)
3048		a->archive.archive_format_name = "ZIP";
3049
3050	zip = (struct zip *)(a->format->data);
3051
3052	/*
3053	 * It should be sufficient to call archive_read_next_header() for
3054	 * a reader to determine if an entry is encrypted or not. If the
3055	 * encryption of an entry is only detectable when calling
3056	 * archive_read_data(), so be it. We'll do the same check there
3057	 * as well.
3058	 */
3059	if (zip->has_encrypted_entries ==
3060			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3061		zip->has_encrypted_entries = 0;
3062
3063	/* Make sure we have a zip_entry structure to use. */
3064	if (zip->zip_entries == NULL) {
3065		zip->zip_entries = malloc(sizeof(struct zip_entry));
3066		if (zip->zip_entries == NULL) {
3067			archive_set_error(&a->archive, ENOMEM,
3068			    "Out  of memory");
3069			return ARCHIVE_FATAL;
3070		}
3071	}
3072	zip->entry = zip->zip_entries;
3073	memset(zip->entry, 0, sizeof(struct zip_entry));
3074
3075	if (zip->cctx_valid)
3076		archive_decrypto_aes_ctr_release(&zip->cctx);
3077	if (zip->hctx_valid)
3078		archive_hmac_sha1_cleanup(&zip->hctx);
3079	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3080	__archive_read_reset_passphrase(a);
3081
3082	/* Search ahead for the next local file header. */
3083	__archive_read_consume(a, zip->unconsumed);
3084	zip->unconsumed = 0;
3085	for (;;) {
3086		int64_t skipped = 0;
3087		const char *p, *end;
3088		ssize_t bytes;
3089
3090		p = __archive_read_ahead(a, 4, &bytes);
3091		if (p == NULL)
3092			return (ARCHIVE_FATAL);
3093		end = p + bytes;
3094
3095		while (p + 4 <= end) {
3096			if (p[0] == 'P' && p[1] == 'K') {
3097				if (p[2] == '\003' && p[3] == '\004') {
3098					/* Regular file entry. */
3099					__archive_read_consume(a, skipped);
3100					return zip_read_local_file_header(a,
3101					    entry, zip);
3102				}
3103
3104                              /*
3105                               * TODO: We cannot restore permissions
3106                               * based only on the local file headers.
3107                               * Consider scanning the central
3108                               * directory and returning additional
3109                               * entries for at least directories.
3110                               * This would allow us to properly set
3111                               * directory permissions.
3112			       *
3113			       * This won't help us fix symlinks
3114			       * and may not help with regular file
3115			       * permissions, either.  <sigh>
3116                               */
3117                              if (p[2] == '\001' && p[3] == '\002') {
3118                                      return (ARCHIVE_EOF);
3119                              }
3120
3121                              /* End of central directory?  Must be an
3122                               * empty archive. */
3123                              if ((p[2] == '\005' && p[3] == '\006')
3124                                  || (p[2] == '\006' && p[3] == '\006'))
3125                                      return (ARCHIVE_EOF);
3126			}
3127			++p;
3128			++skipped;
3129		}
3130		__archive_read_consume(a, skipped);
3131	}
3132}
3133
3134static int
3135archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3136{
3137	struct zip *zip;
3138	int64_t bytes_skipped;
3139
3140	zip = (struct zip *)(a->format->data);
3141	bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3142	zip->unconsumed = 0;
3143	if (bytes_skipped < 0)
3144		return (ARCHIVE_FATAL);
3145
3146	/* If we've already read to end of data, we're done. */
3147	if (zip->end_of_entry)
3148		return (ARCHIVE_OK);
3149
3150	/* So we know we're streaming... */
3151	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3152	    || zip->entry->compressed_size > 0) {
3153		/* We know the compressed length, so we can just skip. */
3154		bytes_skipped = __archive_read_consume(a,
3155					zip->entry_bytes_remaining);
3156		if (bytes_skipped < 0)
3157			return (ARCHIVE_FATAL);
3158		return (ARCHIVE_OK);
3159	}
3160
3161	if (zip->init_decryption) {
3162		int r;
3163
3164		zip->has_encrypted_entries = 1;
3165		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3166			r = read_decryption_header(a);
3167		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3168			r = init_WinZip_AES_decryption(a);
3169		else
3170			r = init_traditional_PKWARE_decryption(a);
3171		if (r != ARCHIVE_OK)
3172			return (r);
3173		zip->init_decryption = 0;
3174	}
3175
3176	/* We're streaming and we don't know the length. */
3177	/* If the body is compressed and we know the format, we can
3178	 * find an exact end-of-entry by decompressing it. */
3179	switch (zip->entry->compression) {
3180#ifdef HAVE_ZLIB_H
3181	case 8: /* Deflate compression. */
3182		while (!zip->end_of_entry) {
3183			int64_t offset = 0;
3184			const void *buff = NULL;
3185			size_t size = 0;
3186			int r;
3187			r =  zip_read_data_deflate(a, &buff, &size, &offset);
3188			if (r != ARCHIVE_OK)
3189				return (r);
3190		}
3191		return ARCHIVE_OK;
3192#endif
3193	default: /* Uncompressed or unknown. */
3194		/* Scan for a PK\007\010 signature. */
3195		for (;;) {
3196			const char *p, *buff;
3197			ssize_t bytes_avail;
3198			buff = __archive_read_ahead(a, 16, &bytes_avail);
3199			if (bytes_avail < 16) {
3200				archive_set_error(&a->archive,
3201				    ARCHIVE_ERRNO_FILE_FORMAT,
3202				    "Truncated ZIP file data");
3203				return (ARCHIVE_FATAL);
3204			}
3205			p = buff;
3206			while (p <= buff + bytes_avail - 16) {
3207				if (p[3] == 'P') { p += 3; }
3208				else if (p[3] == 'K') { p += 2; }
3209				else if (p[3] == '\007') { p += 1; }
3210				else if (p[3] == '\010' && p[2] == '\007'
3211				    && p[1] == 'K' && p[0] == 'P') {
3212					if (zip->entry->flags & LA_USED_ZIP64)
3213						__archive_read_consume(a,
3214						    p - buff + 24);
3215					else
3216						__archive_read_consume(a,
3217						    p - buff + 16);
3218					return ARCHIVE_OK;
3219				} else { p += 4; }
3220			}
3221			__archive_read_consume(a, p - buff);
3222		}
3223	}
3224}
3225
3226int
3227archive_read_support_format_zip_streamable(struct archive *_a)
3228{
3229	struct archive_read *a = (struct archive_read *)_a;
3230	struct zip *zip;
3231	int r;
3232
3233	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3234	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3235
3236	zip = (struct zip *)calloc(1, sizeof(*zip));
3237	if (zip == NULL) {
3238		archive_set_error(&a->archive, ENOMEM,
3239		    "Can't allocate zip data");
3240		return (ARCHIVE_FATAL);
3241	}
3242
3243	/* Streamable reader doesn't support mac extensions. */
3244	zip->process_mac_extensions = 0;
3245
3246	/*
3247	 * Until enough data has been read, we cannot tell about
3248	 * any encrypted entries yet.
3249	 */
3250	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3251	zip->crc32func = real_crc32;
3252
3253	r = __archive_read_register_format(a,
3254	    zip,
3255	    "zip",
3256	    archive_read_format_zip_streamable_bid,
3257	    archive_read_format_zip_options,
3258	    archive_read_format_zip_streamable_read_header,
3259	    archive_read_format_zip_read_data,
3260	    archive_read_format_zip_read_data_skip_streamable,
3261	    NULL,
3262	    archive_read_format_zip_cleanup,
3263	    archive_read_support_format_zip_capabilities_streamable,
3264	    archive_read_format_zip_has_encrypted_entries);
3265
3266	if (r != ARCHIVE_OK)
3267		free(zip);
3268	return (ARCHIVE_OK);
3269}
3270
3271/* ------------------------------------------------------------------------ */
3272
3273/*
3274 * Seeking-mode support
3275 */
3276
3277static int
3278archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3279{
3280	(void)a; /* UNUSED */
3281	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3282		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3283}
3284
3285/*
3286 * TODO: This is a performance sink because it forces the read core to
3287 * drop buffered data from the start of file, which will then have to
3288 * be re-read again if this bidder loses.
3289 *
3290 * We workaround this a little by passing in the best bid so far so
3291 * that later bidders can do nothing if they know they'll never
3292 * outbid.  But we can certainly do better...
3293 */
3294static int
3295read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3296{
3297	/* Sanity-check the EOCD we've found. */
3298
3299	/* This must be the first volume. */
3300	if (archive_le16dec(p + 4) != 0)
3301		return 0;
3302	/* Central directory must be on this volume. */
3303	if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
3304		return 0;
3305	/* All central directory entries must be on this volume. */
3306	if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3307		return 0;
3308	/* Central directory can't extend beyond start of EOCD record. */
3309	if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
3310	    > current_offset)
3311		return 0;
3312
3313	/* Save the central directory location for later use. */
3314	zip->central_directory_offset = archive_le32dec(p + 16);
3315
3316	/* This is just a tiny bit higher than the maximum
3317	   returned by the streaming Zip bidder.  This ensures
3318	   that the more accurate seeking Zip parser wins
3319	   whenever seek is available. */
3320	return 32;
3321}
3322
3323/*
3324 * Examine Zip64 EOCD locator:  If it's valid, store the information
3325 * from it.
3326 */
3327static int
3328read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3329{
3330	int64_t eocd64_offset;
3331	int64_t eocd64_size;
3332
3333	/* Sanity-check the locator record. */
3334
3335	/* Central dir must be on first volume. */
3336	if (archive_le32dec(p + 4) != 0)
3337		return 0;
3338	/* Must be only a single volume. */
3339	if (archive_le32dec(p + 16) != 1)
3340		return 0;
3341
3342	/* Find the Zip64 EOCD record. */
3343	eocd64_offset = archive_le64dec(p + 8);
3344	if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3345		return 0;
3346	if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3347		return 0;
3348	/* Make sure we can read all of it. */
3349	eocd64_size = archive_le64dec(p + 4) + 12;
3350	if (eocd64_size < 56 || eocd64_size > 16384)
3351		return 0;
3352	if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3353		return 0;
3354
3355	/* Sanity-check the EOCD64 */
3356	if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3357		return 0;
3358	if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3359		return 0;
3360	/* CD can't be split. */
3361	if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3362		return 0;
3363
3364	/* Save the central directory offset for later use. */
3365	zip->central_directory_offset = archive_le64dec(p + 48);
3366
3367	return 32;
3368}
3369
3370static int
3371archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3372{
3373	struct zip *zip = (struct zip *)a->format->data;
3374	int64_t file_size, current_offset;
3375	const char *p;
3376	int i, tail;
3377
3378	/* If someone has already bid more than 32, then avoid
3379	   trashing the look-ahead buffers with a seek. */
3380	if (best_bid > 32)
3381		return (-1);
3382
3383	file_size = __archive_read_seek(a, 0, SEEK_END);
3384	if (file_size <= 0)
3385		return 0;
3386
3387	/* Search last 16k of file for end-of-central-directory
3388	 * record (which starts with PK\005\006) */
3389	tail = (int)zipmin(1024 * 16, file_size);
3390	current_offset = __archive_read_seek(a, -tail, SEEK_END);
3391	if (current_offset < 0)
3392		return 0;
3393	if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3394		return 0;
3395	/* Boyer-Moore search backwards from the end, since we want
3396	 * to match the last EOCD in the file (there can be more than
3397	 * one if there is an uncompressed Zip archive as a member
3398	 * within this Zip archive). */
3399	for (i = tail - 22; i > 0;) {
3400		switch (p[i]) {
3401		case 'P':
3402			if (memcmp(p + i, "PK\005\006", 4) == 0) {
3403				int ret = read_eocd(zip, p + i,
3404				    current_offset + i);
3405				/* Zip64 EOCD locator precedes
3406				 * regular EOCD if present. */
3407				if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3408					int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3409					if (ret_zip64 > ret)
3410						ret = ret_zip64;
3411				}
3412				return (ret);
3413			}
3414			i -= 4;
3415			break;
3416		case 'K': i -= 1; break;
3417		case 005: i -= 2; break;
3418		case 006: i -= 3; break;
3419		default: i -= 4; break;
3420		}
3421	}
3422	return 0;
3423}
3424
3425/* The red-black trees are only used in seeking mode to manage
3426 * the in-memory copy of the central directory. */
3427
3428static int
3429cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3430{
3431	const struct zip_entry *e1 = (const struct zip_entry *)n1;
3432	const struct zip_entry *e2 = (const struct zip_entry *)n2;
3433
3434	if (e1->local_header_offset > e2->local_header_offset)
3435		return -1;
3436	if (e1->local_header_offset < e2->local_header_offset)
3437		return 1;
3438	return 0;
3439}
3440
3441static int
3442cmp_key(const struct archive_rb_node *n, const void *key)
3443{
3444	/* This function won't be called */
3445	(void)n; /* UNUSED */
3446	(void)key; /* UNUSED */
3447	return 1;
3448}
3449
3450static const struct archive_rb_tree_ops rb_ops = {
3451	&cmp_node, &cmp_key
3452};
3453
3454static int
3455rsrc_cmp_node(const struct archive_rb_node *n1,
3456    const struct archive_rb_node *n2)
3457{
3458	const struct zip_entry *e1 = (const struct zip_entry *)n1;
3459	const struct zip_entry *e2 = (const struct zip_entry *)n2;
3460
3461	return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3462}
3463
3464static int
3465rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3466{
3467	const struct zip_entry *e = (const struct zip_entry *)n;
3468	return (strcmp((const char *)key, e->rsrcname.s));
3469}
3470
3471static const struct archive_rb_tree_ops rb_rsrc_ops = {
3472	&rsrc_cmp_node, &rsrc_cmp_key
3473};
3474
3475static const char *
3476rsrc_basename(const char *name, size_t name_length)
3477{
3478	const char *s, *r;
3479
3480	r = s = name;
3481	for (;;) {
3482		s = memchr(s, '/', name_length - (s - name));
3483		if (s == NULL)
3484			break;
3485		r = ++s;
3486	}
3487	return (r);
3488}
3489
3490static void
3491expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3492{
3493	struct archive_string str;
3494	struct zip_entry *dir;
3495	char *s;
3496
3497	archive_string_init(&str);
3498	archive_strncpy(&str, name, name_length);
3499	for (;;) {
3500		s = strrchr(str.s, '/');
3501		if (s == NULL)
3502			break;
3503		*s = '\0';
3504		/* Transfer the parent directory from zip->tree_rsrc RB
3505		 * tree to zip->tree RB tree to expose. */
3506		dir = (struct zip_entry *)
3507		    __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3508		if (dir == NULL)
3509			break;
3510		__archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3511		archive_string_free(&dir->rsrcname);
3512		__archive_rb_tree_insert_node(&zip->tree, &dir->node);
3513	}
3514	archive_string_free(&str);
3515}
3516
3517static int
3518slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
3519    struct zip *zip)
3520{
3521	ssize_t i;
3522	unsigned found;
3523	int64_t correction;
3524	ssize_t bytes_avail;
3525	const char *p;
3526
3527	/*
3528	 * Find the start of the central directory.  The end-of-CD
3529	 * record has our starting point, but there are lots of
3530	 * Zip archives which have had other data prepended to the
3531	 * file, which makes the recorded offsets all too small.
3532	 * So we search forward from the specified offset until we
3533	 * find the real start of the central directory.  Then we
3534	 * know the correction we need to apply to account for leading
3535	 * padding.
3536	 */
3537	if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
3538		return ARCHIVE_FATAL;
3539
3540	found = 0;
3541	while (!found) {
3542		if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3543			return ARCHIVE_FATAL;
3544		for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3545			switch (p[i + 3]) {
3546			case 'P': i += 3; break;
3547			case 'K': i += 2; break;
3548			case 001: i += 1; break;
3549			case 002:
3550				if (memcmp(p + i, "PK\001\002", 4) == 0) {
3551					p += i;
3552					found = 1;
3553				} else
3554					i += 4;
3555				break;
3556			case 005: i += 1; break;
3557			case 006:
3558				if (memcmp(p + i, "PK\005\006", 4) == 0) {
3559					p += i;
3560					found = 1;
3561				} else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3562					p += i;
3563					found = 1;
3564				} else
3565					i += 1;
3566				break;
3567			default: i += 4; break;
3568			}
3569		}
3570		__archive_read_consume(a, i);
3571	}
3572	correction = archive_filter_bytes(&a->archive, 0)
3573			- zip->central_directory_offset;
3574
3575	__archive_rb_tree_init(&zip->tree, &rb_ops);
3576	__archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3577
3578	zip->central_directory_entries_total = 0;
3579	while (1) {
3580		struct zip_entry *zip_entry;
3581		size_t filename_length, extra_length, comment_length;
3582		uint32_t external_attributes;
3583		const char *name, *r;
3584
3585		if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3586			return ARCHIVE_FATAL;
3587		if (memcmp(p, "PK\006\006", 4) == 0
3588		    || memcmp(p, "PK\005\006", 4) == 0) {
3589			break;
3590		} else if (memcmp(p, "PK\001\002", 4) != 0) {
3591			archive_set_error(&a->archive,
3592			    -1, "Invalid central directory signature");
3593			return ARCHIVE_FATAL;
3594		}
3595		if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3596			return ARCHIVE_FATAL;
3597
3598		zip_entry = calloc(1, sizeof(struct zip_entry));
3599		if (zip_entry == NULL) {
3600			archive_set_error(&a->archive, ENOMEM,
3601				"Can't allocate zip entry");
3602			return ARCHIVE_FATAL;
3603		}
3604		zip_entry->next = zip->zip_entries;
3605		zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3606		zip->zip_entries = zip_entry;
3607		zip->central_directory_entries_total++;
3608
3609		/* version = p[4]; */
3610		zip_entry->system = p[5];
3611		/* version_required = archive_le16dec(p + 6); */
3612		zip_entry->zip_flags = archive_le16dec(p + 8);
3613		if (zip_entry->zip_flags
3614		      & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3615			zip->has_encrypted_entries = 1;
3616		}
3617		zip_entry->compression = (char)archive_le16dec(p + 10);
3618		zip_entry->mtime = zip_time(p + 12);
3619		zip_entry->crc32 = archive_le32dec(p + 16);
3620		if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3621			zip_entry->decdat = p[13];
3622		else
3623			zip_entry->decdat = p[19];
3624		zip_entry->compressed_size = archive_le32dec(p + 20);
3625		zip_entry->uncompressed_size = archive_le32dec(p + 24);
3626		filename_length = archive_le16dec(p + 28);
3627		extra_length = archive_le16dec(p + 30);
3628		comment_length = archive_le16dec(p + 32);
3629		/* disk_start = archive_le16dec(p + 34);
3630		 *   Better be zero.
3631		 * internal_attributes = archive_le16dec(p + 36);
3632		 *   text bit */
3633		external_attributes = archive_le32dec(p + 38);
3634		zip_entry->local_header_offset =
3635		    archive_le32dec(p + 42) + correction;
3636
3637		/* If we can't guess the mode, leave it zero here;
3638		   when we read the local file header we might get
3639		   more information. */
3640		if (zip_entry->system == 3) {
3641			zip_entry->mode = external_attributes >> 16;
3642		} else if (zip_entry->system == 0) {
3643			// Interpret MSDOS directory bit
3644			if (0x10 == (external_attributes & 0x10)) {
3645				zip_entry->mode = AE_IFDIR | 0775;
3646			} else {
3647				zip_entry->mode = AE_IFREG | 0664;
3648			}
3649			if (0x01 == (external_attributes & 0x01)) {
3650				// Read-only bit; strip write permissions
3651				zip_entry->mode &= 0555;
3652			}
3653		} else {
3654			zip_entry->mode = 0;
3655		}
3656
3657		/* We're done with the regular data; get the filename and
3658		 * extra data. */
3659		__archive_read_consume(a, 46);
3660		p = __archive_read_ahead(a, filename_length + extra_length,
3661			NULL);
3662		if (p == NULL) {
3663			archive_set_error(&a->archive,
3664			    ARCHIVE_ERRNO_FILE_FORMAT,
3665			    "Truncated ZIP file header");
3666			return ARCHIVE_FATAL;
3667		}
3668		if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
3669		    extra_length, zip_entry)) {
3670			return ARCHIVE_FATAL;
3671		}
3672
3673		/*
3674		 * Mac resource fork files are stored under the
3675		 * "__MACOSX/" directory, so we should check if
3676		 * it is.
3677		 */
3678		if (!zip->process_mac_extensions) {
3679			/* Treat every entry as a regular entry. */
3680			__archive_rb_tree_insert_node(&zip->tree,
3681			    &zip_entry->node);
3682		} else {
3683			name = p;
3684			r = rsrc_basename(name, filename_length);
3685			if (filename_length >= 9 &&
3686			    strncmp("__MACOSX/", name, 9) == 0) {
3687				/* If this file is not a resource fork nor
3688				 * a directory. We should treat it as a non
3689				 * resource fork file to expose it. */
3690				if (name[filename_length-1] != '/' &&
3691				    (r - name < 3 || r[0] != '.' ||
3692				     r[1] != '_')) {
3693					__archive_rb_tree_insert_node(
3694					    &zip->tree, &zip_entry->node);
3695					/* Expose its parent directories. */
3696					expose_parent_dirs(zip, name,
3697					    filename_length);
3698				} else {
3699					/* This file is a resource fork file or
3700					 * a directory. */
3701					archive_strncpy(&(zip_entry->rsrcname),
3702					     name, filename_length);
3703					__archive_rb_tree_insert_node(
3704					    &zip->tree_rsrc, &zip_entry->node);
3705				}
3706			} else {
3707				/* Generate resource fork name to find its
3708				 * resource file at zip->tree_rsrc. */
3709				archive_strcpy(&(zip_entry->rsrcname),
3710				    "__MACOSX/");
3711				archive_strncat(&(zip_entry->rsrcname),
3712				    name, r - name);
3713				archive_strcat(&(zip_entry->rsrcname), "._");
3714				archive_strncat(&(zip_entry->rsrcname),
3715				    name + (r - name),
3716				    filename_length - (r - name));
3717				/* Register an entry to RB tree to sort it by
3718				 * file offset. */
3719				__archive_rb_tree_insert_node(&zip->tree,
3720				    &zip_entry->node);
3721			}
3722		}
3723
3724		/* Skip the comment too ... */
3725		__archive_read_consume(a,
3726		    filename_length + extra_length + comment_length);
3727	}
3728
3729	return ARCHIVE_OK;
3730}
3731
3732static ssize_t
3733zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3734{
3735	const char *p;
3736	ssize_t filename_length, extra_length;
3737
3738	if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3739		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3740		    "Truncated ZIP file header");
3741		return (ARCHIVE_WARN);
3742	}
3743	p += extra;
3744
3745	if (memcmp(p, "PK\003\004", 4) != 0) {
3746		archive_set_error(&a->archive, -1, "Damaged Zip archive");
3747		return ARCHIVE_WARN;
3748	}
3749	filename_length = archive_le16dec(p + 26);
3750	extra_length = archive_le16dec(p + 28);
3751
3752	return (30 + filename_length + extra_length);
3753}
3754
3755static int
3756zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3757    struct zip_entry *rsrc)
3758{
3759	struct zip *zip = (struct zip *)a->format->data;
3760	unsigned char *metadata, *mp;
3761	int64_t offset = archive_filter_bytes(&a->archive, 0);
3762	size_t remaining_bytes, metadata_bytes;
3763	ssize_t hsize;
3764	int ret = ARCHIVE_OK, eof;
3765
3766	switch(rsrc->compression) {
3767	case 0:  /* No compression. */
3768		if (rsrc->uncompressed_size != rsrc->compressed_size) {
3769			archive_set_error(&a->archive,
3770			    ARCHIVE_ERRNO_FILE_FORMAT,
3771			    "Malformed OS X metadata entry: "
3772			    "inconsistent size");
3773			return (ARCHIVE_FATAL);
3774		}
3775#ifdef HAVE_ZLIB_H
3776	case 8: /* Deflate compression. */
3777#endif
3778		break;
3779	default: /* Unsupported compression. */
3780		/* Return a warning. */
3781		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3782		    "Unsupported ZIP compression method (%s)",
3783		    compression_name(rsrc->compression));
3784		/* We can't decompress this entry, but we will
3785		 * be able to skip() it and try the next entry. */
3786		return (ARCHIVE_WARN);
3787	}
3788
3789	if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
3790		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3791		    "Mac metadata is too large: %jd > 4M bytes",
3792		    (intmax_t)rsrc->uncompressed_size);
3793		return (ARCHIVE_WARN);
3794	}
3795	if (rsrc->compressed_size > (4 * 1024 * 1024)) {
3796		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3797		    "Mac metadata is too large: %jd > 4M bytes",
3798		    (intmax_t)rsrc->compressed_size);
3799		return (ARCHIVE_WARN);
3800	}
3801
3802	metadata = malloc((size_t)rsrc->uncompressed_size);
3803	if (metadata == NULL) {
3804		archive_set_error(&a->archive, ENOMEM,
3805		    "Can't allocate memory for Mac metadata");
3806		return (ARCHIVE_FATAL);
3807	}
3808
3809	if (offset < rsrc->local_header_offset)
3810		__archive_read_consume(a, rsrc->local_header_offset - offset);
3811	else if (offset != rsrc->local_header_offset) {
3812		__archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
3813	}
3814
3815	hsize = zip_get_local_file_header_size(a, 0);
3816	__archive_read_consume(a, hsize);
3817
3818	remaining_bytes = (size_t)rsrc->compressed_size;
3819	metadata_bytes = (size_t)rsrc->uncompressed_size;
3820	mp = metadata;
3821	eof = 0;
3822	while (!eof && remaining_bytes) {
3823		const unsigned char *p;
3824		ssize_t bytes_avail;
3825		size_t bytes_used;
3826
3827		p = __archive_read_ahead(a, 1, &bytes_avail);
3828		if (p == NULL) {
3829			archive_set_error(&a->archive,
3830			    ARCHIVE_ERRNO_FILE_FORMAT,
3831			    "Truncated ZIP file header");
3832			ret = ARCHIVE_WARN;
3833			goto exit_mac_metadata;
3834		}
3835		if ((size_t)bytes_avail > remaining_bytes)
3836			bytes_avail = remaining_bytes;
3837		switch(rsrc->compression) {
3838		case 0:  /* No compression. */
3839			if ((size_t)bytes_avail > metadata_bytes)
3840				bytes_avail = metadata_bytes;
3841			memcpy(mp, p, bytes_avail);
3842			bytes_used = (size_t)bytes_avail;
3843			metadata_bytes -= bytes_used;
3844			mp += bytes_used;
3845			if (metadata_bytes == 0)
3846				eof = 1;
3847			break;
3848#ifdef HAVE_ZLIB_H
3849		case 8: /* Deflate compression. */
3850		{
3851			int r;
3852
3853			ret = zip_deflate_init(a, zip);
3854			if (ret != ARCHIVE_OK)
3855				goto exit_mac_metadata;
3856			zip->stream.next_in =
3857			    (Bytef *)(uintptr_t)(const void *)p;
3858			zip->stream.avail_in = (uInt)bytes_avail;
3859			zip->stream.total_in = 0;
3860			zip->stream.next_out = mp;
3861			zip->stream.avail_out = (uInt)metadata_bytes;
3862			zip->stream.total_out = 0;
3863
3864			r = inflate(&zip->stream, 0);
3865			switch (r) {
3866			case Z_OK:
3867				break;
3868			case Z_STREAM_END:
3869				eof = 1;
3870				break;
3871			case Z_MEM_ERROR:
3872				archive_set_error(&a->archive, ENOMEM,
3873				    "Out of memory for ZIP decompression");
3874				ret = ARCHIVE_FATAL;
3875				goto exit_mac_metadata;
3876			default:
3877				archive_set_error(&a->archive,
3878				    ARCHIVE_ERRNO_MISC,
3879				    "ZIP decompression failed (%d)", r);
3880				ret = ARCHIVE_FATAL;
3881				goto exit_mac_metadata;
3882			}
3883			bytes_used = zip->stream.total_in;
3884			metadata_bytes -= zip->stream.total_out;
3885			mp += zip->stream.total_out;
3886			break;
3887		}
3888#endif
3889		default:
3890			bytes_used = 0;
3891			break;
3892		}
3893		__archive_read_consume(a, bytes_used);
3894		remaining_bytes -= bytes_used;
3895	}
3896	archive_entry_copy_mac_metadata(entry, metadata,
3897	    (size_t)rsrc->uncompressed_size - metadata_bytes);
3898
3899exit_mac_metadata:
3900	__archive_read_seek(a, offset, SEEK_SET);
3901	zip->decompress_init = 0;
3902	free(metadata);
3903	return (ret);
3904}
3905
3906static int
3907archive_read_format_zip_seekable_read_header(struct archive_read *a,
3908	struct archive_entry *entry)
3909{
3910	struct zip *zip = (struct zip *)a->format->data;
3911	struct zip_entry *rsrc;
3912	int64_t offset;
3913	int r, ret = ARCHIVE_OK;
3914
3915	/*
3916	 * It should be sufficient to call archive_read_next_header() for
3917	 * a reader to determine if an entry is encrypted or not. If the
3918	 * encryption of an entry is only detectable when calling
3919	 * archive_read_data(), so be it. We'll do the same check there
3920	 * as well.
3921	 */
3922	if (zip->has_encrypted_entries ==
3923			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3924		zip->has_encrypted_entries = 0;
3925
3926	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3927	if (a->archive.archive_format_name == NULL)
3928		a->archive.archive_format_name = "ZIP";
3929
3930	if (zip->zip_entries == NULL) {
3931		r = slurp_central_directory(a, entry, zip);
3932		if (r != ARCHIVE_OK)
3933			return r;
3934		/* Get first entry whose local header offset is lower than
3935		 * other entries in the archive file. */
3936		zip->entry =
3937		    (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
3938	} else if (zip->entry != NULL) {
3939		/* Get next entry in local header offset order. */
3940		zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
3941		    &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
3942	}
3943
3944	if (zip->entry == NULL)
3945		return ARCHIVE_EOF;
3946
3947	if (zip->entry->rsrcname.s)
3948		rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
3949		    &zip->tree_rsrc, zip->entry->rsrcname.s);
3950	else
3951		rsrc = NULL;
3952
3953	if (zip->cctx_valid)
3954		archive_decrypto_aes_ctr_release(&zip->cctx);
3955	if (zip->hctx_valid)
3956		archive_hmac_sha1_cleanup(&zip->hctx);
3957	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3958	__archive_read_reset_passphrase(a);
3959
3960	/* File entries are sorted by the header offset, we should mostly
3961	 * use __archive_read_consume to advance a read point to avoid
3962	 * redundant data reading.  */
3963	offset = archive_filter_bytes(&a->archive, 0);
3964	if (offset < zip->entry->local_header_offset)
3965		__archive_read_consume(a,
3966		    zip->entry->local_header_offset - offset);
3967	else if (offset != zip->entry->local_header_offset) {
3968		__archive_read_seek(a, zip->entry->local_header_offset,
3969		    SEEK_SET);
3970	}
3971	zip->unconsumed = 0;
3972	r = zip_read_local_file_header(a, entry, zip);
3973	if (r != ARCHIVE_OK)
3974		return r;
3975	if (rsrc) {
3976		int ret2 = zip_read_mac_metadata(a, entry, rsrc);
3977		if (ret2 < ret)
3978			ret = ret2;
3979	}
3980	return (ret);
3981}
3982
3983/*
3984 * We're going to seek for the next header anyway, so we don't
3985 * need to bother doing anything here.
3986 */
3987static int
3988archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
3989{
3990	struct zip *zip;
3991	zip = (struct zip *)(a->format->data);
3992
3993	zip->unconsumed = 0;
3994	return (ARCHIVE_OK);
3995}
3996
3997int
3998archive_read_support_format_zip_seekable(struct archive *_a)
3999{
4000	struct archive_read *a = (struct archive_read *)_a;
4001	struct zip *zip;
4002	int r;
4003
4004	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
4005	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
4006
4007	zip = (struct zip *)calloc(1, sizeof(*zip));
4008	if (zip == NULL) {
4009		archive_set_error(&a->archive, ENOMEM,
4010		    "Can't allocate zip data");
4011		return (ARCHIVE_FATAL);
4012	}
4013
4014#ifdef HAVE_COPYFILE_H
4015	/* Set this by default on Mac OS. */
4016	zip->process_mac_extensions = 1;
4017#endif
4018
4019	/*
4020	 * Until enough data has been read, we cannot tell about
4021	 * any encrypted entries yet.
4022	 */
4023	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4024	zip->crc32func = real_crc32;
4025
4026	r = __archive_read_register_format(a,
4027	    zip,
4028	    "zip",
4029	    archive_read_format_zip_seekable_bid,
4030	    archive_read_format_zip_options,
4031	    archive_read_format_zip_seekable_read_header,
4032	    archive_read_format_zip_read_data,
4033	    archive_read_format_zip_read_data_skip_seekable,
4034	    NULL,
4035	    archive_read_format_zip_cleanup,
4036	    archive_read_support_format_zip_capabilities_seekable,
4037	    archive_read_format_zip_has_encrypted_entries);
4038
4039	if (r != ARCHIVE_OK)
4040		free(zip);
4041	return (ARCHIVE_OK);
4042}
4043
4044/*# vim:set noet:*/
4045