archive_read_support_format_zip.c revision 368708
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/10/contrib/libarchive/libarchive/archive_read_support_format_zip.c 368708 2020-12-16 22:25:40Z 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 * Auxiliary function to uncompress data chunk from zipx archive
904 * (zip with lzma compression).
905 */
906static int
907zipx_lzma_uncompress_buffer(const char *compressed_buffer,
908	size_t compressed_buffer_size,
909	char *uncompressed_buffer,
910	size_t uncompressed_buffer_size)
911{
912	int status = ARCHIVE_FATAL;
913	// length of 'lzma properties data' in lzma compressed
914	// data segment (stream) inside zip archive
915	const size_t lzma_params_length = 5;
916	// offset of 'lzma properties data' from the beginning of lzma stream
917	const size_t lzma_params_offset = 4;
918	// end position of 'lzma properties data' in lzma stream
919	const size_t lzma_params_end = lzma_params_offset + lzma_params_length;
920	if (compressed_buffer == NULL ||
921			compressed_buffer_size < lzma_params_end ||
922			uncompressed_buffer == NULL)
923		return status;
924
925	// prepare header for lzma_alone_decoder to replace zipx header
926	// (see comments in 'zipx_lzma_alone_init' for justification)
927#pragma pack(push)
928#pragma pack(1)
929	struct _alone_header
930	{
931		uint8_t bytes[5]; // lzma_params_length
932		uint64_t uncompressed_size;
933	} alone_header;
934#pragma pack(pop)
935	// copy 'lzma properties data' blob
936	memcpy(&alone_header.bytes[0], compressed_buffer + lzma_params_offset,
937		lzma_params_length);
938	alone_header.uncompressed_size = UINT64_MAX;
939
940	// prepare new compressed buffer, see 'zipx_lzma_alone_init' for details
941	const size_t lzma_alone_buffer_size =
942		compressed_buffer_size - lzma_params_end + sizeof(alone_header);
943	unsigned char *lzma_alone_compressed_buffer =
944		(unsigned char*) malloc(lzma_alone_buffer_size);
945	if (lzma_alone_compressed_buffer == NULL)
946		return status;
947	// copy lzma_alone header into new buffer
948	memcpy(lzma_alone_compressed_buffer, (void*) &alone_header,
949		sizeof(alone_header));
950	// copy compressed data into new buffer
951	memcpy(lzma_alone_compressed_buffer + sizeof(alone_header),
952		compressed_buffer + lzma_params_end,
953		compressed_buffer_size - lzma_params_end);
954
955	// create and fill in lzma_alone_decoder stream
956	lzma_stream stream = LZMA_STREAM_INIT;
957	lzma_ret ret = lzma_alone_decoder(&stream, UINT64_MAX);
958	if (ret == LZMA_OK)
959	{
960		stream.next_in = lzma_alone_compressed_buffer;
961		stream.avail_in = lzma_alone_buffer_size;
962		stream.total_in = 0;
963		stream.next_out = (unsigned char*)uncompressed_buffer;
964		stream.avail_out = uncompressed_buffer_size;
965		stream.total_out = 0;
966		ret = lzma_code(&stream, LZMA_RUN);
967		if (ret == LZMA_OK || ret == LZMA_STREAM_END)
968			status = ARCHIVE_OK;
969	}
970	lzma_end(&stream);
971	free(lzma_alone_compressed_buffer);
972	return status;
973}
974
975/*
976 * Assumes file pointer is at beginning of local file header.
977 */
978static int
979zip_read_local_file_header(struct archive_read *a, struct archive_entry *entry,
980    struct zip *zip)
981{
982	const char *p;
983	const void *h;
984	const wchar_t *wp;
985	const char *cp;
986	size_t len, filename_length, extra_length;
987	struct archive_string_conv *sconv;
988	struct zip_entry *zip_entry = zip->entry;
989	struct zip_entry zip_entry_central_dir;
990	int ret = ARCHIVE_OK;
991	char version;
992
993	/* Save a copy of the original for consistency checks. */
994	zip_entry_central_dir = *zip_entry;
995
996	zip->decompress_init = 0;
997	zip->end_of_entry = 0;
998	zip->entry_uncompressed_bytes_read = 0;
999	zip->entry_compressed_bytes_read = 0;
1000	zip->entry_crc32 = zip->crc32func(0, NULL, 0);
1001
1002	/* Setup default conversion. */
1003	if (zip->sconv == NULL && !zip->init_default_conversion) {
1004		zip->sconv_default =
1005		    archive_string_default_conversion_for_read(&(a->archive));
1006		zip->init_default_conversion = 1;
1007	}
1008
1009	if ((p = __archive_read_ahead(a, 30, NULL)) == NULL) {
1010		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1011		    "Truncated ZIP file header");
1012		return (ARCHIVE_FATAL);
1013	}
1014
1015	if (memcmp(p, "PK\003\004", 4) != 0) {
1016		archive_set_error(&a->archive, -1, "Damaged Zip archive");
1017		return ARCHIVE_FATAL;
1018	}
1019	version = p[4];
1020	zip_entry->system = p[5];
1021	zip_entry->zip_flags = archive_le16dec(p + 6);
1022	if (zip_entry->zip_flags & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)) {
1023		zip->has_encrypted_entries = 1;
1024		archive_entry_set_is_data_encrypted(entry, 1);
1025		if (zip_entry->zip_flags & ZIP_CENTRAL_DIRECTORY_ENCRYPTED &&
1026			zip_entry->zip_flags & ZIP_ENCRYPTED &&
1027			zip_entry->zip_flags & ZIP_STRONG_ENCRYPTED) {
1028			archive_entry_set_is_metadata_encrypted(entry, 1);
1029			return ARCHIVE_FATAL;
1030		}
1031	}
1032	zip->init_decryption = (zip_entry->zip_flags & ZIP_ENCRYPTED);
1033	zip_entry->compression = (char)archive_le16dec(p + 8);
1034	zip_entry->mtime = zip_time(p + 10);
1035	zip_entry->crc32 = archive_le32dec(p + 14);
1036	if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1037		zip_entry->decdat = p[11];
1038	else
1039		zip_entry->decdat = p[17];
1040	zip_entry->compressed_size = archive_le32dec(p + 18);
1041	zip_entry->uncompressed_size = archive_le32dec(p + 22);
1042	filename_length = archive_le16dec(p + 26);
1043	extra_length = archive_le16dec(p + 28);
1044
1045	__archive_read_consume(a, 30);
1046
1047	/* Read the filename. */
1048	if ((h = __archive_read_ahead(a, filename_length, NULL)) == NULL) {
1049		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1050		    "Truncated ZIP file header");
1051		return (ARCHIVE_FATAL);
1052	}
1053	if (zip_entry->zip_flags & ZIP_UTF8_NAME) {
1054		/* The filename is stored to be UTF-8. */
1055		if (zip->sconv_utf8 == NULL) {
1056			zip->sconv_utf8 =
1057			    archive_string_conversion_from_charset(
1058				&a->archive, "UTF-8", 1);
1059			if (zip->sconv_utf8 == NULL)
1060				return (ARCHIVE_FATAL);
1061		}
1062		sconv = zip->sconv_utf8;
1063	} else if (zip->sconv != NULL)
1064		sconv = zip->sconv;
1065	else
1066		sconv = zip->sconv_default;
1067
1068	if (archive_entry_copy_pathname_l(entry,
1069	    h, filename_length, sconv) != 0) {
1070		if (errno == ENOMEM) {
1071			archive_set_error(&a->archive, ENOMEM,
1072			    "Can't allocate memory for Pathname");
1073			return (ARCHIVE_FATAL);
1074		}
1075		archive_set_error(&a->archive,
1076		    ARCHIVE_ERRNO_FILE_FORMAT,
1077		    "Pathname cannot be converted "
1078		    "from %s to current locale.",
1079		    archive_string_conversion_charset_name(sconv));
1080		ret = ARCHIVE_WARN;
1081	}
1082	__archive_read_consume(a, filename_length);
1083
1084	/* Read the extra data. */
1085	if ((h = __archive_read_ahead(a, extra_length, NULL)) == NULL) {
1086		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1087		    "Truncated ZIP file header");
1088		return (ARCHIVE_FATAL);
1089	}
1090
1091	if (ARCHIVE_OK != process_extra(a, entry, h, extra_length,
1092	    zip_entry)) {
1093		return ARCHIVE_FATAL;
1094	}
1095	__archive_read_consume(a, extra_length);
1096
1097	/* Work around a bug in Info-Zip: When reading from a pipe, it
1098	 * stats the pipe instead of synthesizing a file entry. */
1099	if ((zip_entry->mode & AE_IFMT) == AE_IFIFO) {
1100		zip_entry->mode &= ~ AE_IFMT;
1101		zip_entry->mode |= AE_IFREG;
1102	}
1103
1104	/* If the mode is totally empty, set some sane default. */
1105	if (zip_entry->mode == 0) {
1106		zip_entry->mode |= 0664;
1107	}
1108
1109	/* Windows archivers sometimes use backslash as the directory
1110	 * separator. Normalize to slash. */
1111	if (zip_entry->system == 0 &&
1112	    (wp = archive_entry_pathname_w(entry)) != NULL) {
1113		if (wcschr(wp, L'/') == NULL && wcschr(wp, L'\\') != NULL) {
1114			size_t i;
1115			struct archive_wstring s;
1116			archive_string_init(&s);
1117			archive_wstrcpy(&s, wp);
1118			for (i = 0; i < archive_strlen(&s); i++) {
1119				if (s.s[i] == '\\')
1120					s.s[i] = '/';
1121			}
1122			archive_entry_copy_pathname_w(entry, s.s);
1123			archive_wstring_free(&s);
1124		}
1125	}
1126
1127	/* Make sure that entries with a trailing '/' are marked as directories
1128	 * even if the External File Attributes contains bogus values.  If this
1129	 * is not a directory and there is no type, assume a regular file. */
1130	if ((zip_entry->mode & AE_IFMT) != AE_IFDIR) {
1131		int has_slash;
1132
1133		wp = archive_entry_pathname_w(entry);
1134		if (wp != NULL) {
1135			len = wcslen(wp);
1136			has_slash = len > 0 && wp[len - 1] == L'/';
1137		} else {
1138			cp = archive_entry_pathname(entry);
1139			len = (cp != NULL)?strlen(cp):0;
1140			has_slash = len > 0 && cp[len - 1] == '/';
1141		}
1142		/* Correct file type as needed. */
1143		if (has_slash) {
1144			zip_entry->mode &= ~AE_IFMT;
1145			zip_entry->mode |= AE_IFDIR;
1146			zip_entry->mode |= 0111;
1147		} else if ((zip_entry->mode & AE_IFMT) == 0) {
1148			zip_entry->mode |= AE_IFREG;
1149		}
1150	}
1151
1152	/* Make sure directories end in '/' */
1153	if ((zip_entry->mode & AE_IFMT) == AE_IFDIR) {
1154		wp = archive_entry_pathname_w(entry);
1155		if (wp != NULL) {
1156			len = wcslen(wp);
1157			if (len > 0 && wp[len - 1] != L'/') {
1158				struct archive_wstring s;
1159				archive_string_init(&s);
1160				archive_wstrcat(&s, wp);
1161				archive_wstrappend_wchar(&s, L'/');
1162				archive_entry_copy_pathname_w(entry, s.s);
1163				archive_wstring_free(&s);
1164			}
1165		} else {
1166			cp = archive_entry_pathname(entry);
1167			len = (cp != NULL)?strlen(cp):0;
1168			if (len > 0 && cp[len - 1] != '/') {
1169				struct archive_string s;
1170				archive_string_init(&s);
1171				archive_strcat(&s, cp);
1172				archive_strappend_char(&s, '/');
1173				archive_entry_set_pathname(entry, s.s);
1174				archive_string_free(&s);
1175			}
1176		}
1177	}
1178
1179	if (zip_entry->flags & LA_FROM_CENTRAL_DIRECTORY) {
1180		/* If this came from the central dir, its size info
1181		 * is definitive, so ignore the length-at-end flag. */
1182		zip_entry->zip_flags &= ~ZIP_LENGTH_AT_END;
1183		/* If local header is missing a value, use the one from
1184		   the central directory.  If both have it, warn about
1185		   mismatches. */
1186		if (zip_entry->crc32 == 0) {
1187			zip_entry->crc32 = zip_entry_central_dir.crc32;
1188		} else if (!zip->ignore_crc32
1189		    && zip_entry->crc32 != zip_entry_central_dir.crc32) {
1190			archive_set_error(&a->archive,
1191			    ARCHIVE_ERRNO_FILE_FORMAT,
1192			    "Inconsistent CRC32 values");
1193			ret = ARCHIVE_WARN;
1194		}
1195		if (zip_entry->compressed_size == 0) {
1196			zip_entry->compressed_size
1197			    = zip_entry_central_dir.compressed_size;
1198		} else if (zip_entry->compressed_size
1199		    != zip_entry_central_dir.compressed_size) {
1200			archive_set_error(&a->archive,
1201			    ARCHIVE_ERRNO_FILE_FORMAT,
1202			    "Inconsistent compressed size: "
1203			    "%jd in central directory, %jd in local header",
1204			    (intmax_t)zip_entry_central_dir.compressed_size,
1205			    (intmax_t)zip_entry->compressed_size);
1206			ret = ARCHIVE_WARN;
1207		}
1208		if (zip_entry->uncompressed_size == 0) {
1209			zip_entry->uncompressed_size
1210			    = zip_entry_central_dir.uncompressed_size;
1211		} else if (zip_entry->uncompressed_size
1212		    != zip_entry_central_dir.uncompressed_size) {
1213			archive_set_error(&a->archive,
1214			    ARCHIVE_ERRNO_FILE_FORMAT,
1215			    "Inconsistent uncompressed size: "
1216			    "%jd in central directory, %jd in local header",
1217			    (intmax_t)zip_entry_central_dir.uncompressed_size,
1218			    (intmax_t)zip_entry->uncompressed_size);
1219			ret = ARCHIVE_WARN;
1220		}
1221	}
1222
1223	/* Populate some additional entry fields: */
1224	archive_entry_set_mode(entry, zip_entry->mode);
1225	archive_entry_set_uid(entry, zip_entry->uid);
1226	archive_entry_set_gid(entry, zip_entry->gid);
1227	archive_entry_set_mtime(entry, zip_entry->mtime, 0);
1228	archive_entry_set_ctime(entry, zip_entry->ctime, 0);
1229	archive_entry_set_atime(entry, zip_entry->atime, 0);
1230
1231	if ((zip->entry->mode & AE_IFMT) == AE_IFLNK) {
1232		size_t linkname_length;
1233
1234		if (zip_entry->compressed_size > 64 * 1024) {
1235			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1236			    "Zip file with oversized link entry");
1237			return ARCHIVE_FATAL;
1238		}
1239
1240		linkname_length = (size_t)zip_entry->compressed_size;
1241
1242		archive_entry_set_size(entry, 0);
1243		p = __archive_read_ahead(a, linkname_length, NULL);
1244		if (p == NULL) {
1245			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1246			    "Truncated Zip file");
1247			return ARCHIVE_FATAL;
1248		}
1249		// take into account link compression if any
1250		size_t linkname_full_length = linkname_length;
1251		if (zip->entry->compression != 0)
1252		{
1253			// symlink target string appeared to be compressed
1254			int status = ARCHIVE_FATAL;
1255			char *uncompressed_buffer =
1256				(char*) malloc(zip_entry->uncompressed_size);
1257			if (uncompressed_buffer == NULL)
1258			{
1259				archive_set_error(&a->archive, ENOMEM,
1260					"No memory for lzma decompression");
1261				return status;
1262			}
1263
1264			switch (zip->entry->compression)
1265			{
1266#if HAVE_LZMA_H && HAVE_LIBLZMA
1267				case 14: /* ZIPx LZMA compression. */
1268					/*(see zip file format specification, section 4.4.5)*/
1269					status = zipx_lzma_uncompress_buffer(p,
1270						linkname_length,
1271						uncompressed_buffer,
1272						(size_t)zip_entry->uncompressed_size);
1273					break;
1274#endif
1275				default: /* Unsupported compression. */
1276					break;
1277			}
1278			if (status == ARCHIVE_OK)
1279			{
1280				p = uncompressed_buffer;
1281				linkname_full_length =
1282					(size_t)zip_entry->uncompressed_size;
1283			}
1284			else
1285			{
1286				archive_set_error(&a->archive,
1287					ARCHIVE_ERRNO_FILE_FORMAT,
1288					"Unsupported ZIP compression method "
1289					"during decompression of link entry (%d: %s)",
1290					zip->entry->compression,
1291					compression_name(zip->entry->compression));
1292				return ARCHIVE_FAILED;
1293			}
1294		}
1295
1296		sconv = zip->sconv;
1297		if (sconv == NULL && (zip->entry->zip_flags & ZIP_UTF8_NAME))
1298			sconv = zip->sconv_utf8;
1299		if (sconv == NULL)
1300			sconv = zip->sconv_default;
1301		if (archive_entry_copy_symlink_l(entry, p, linkname_full_length,
1302		    sconv) != 0) {
1303			if (errno != ENOMEM && sconv == zip->sconv_utf8 &&
1304			    (zip->entry->zip_flags & ZIP_UTF8_NAME))
1305			    archive_entry_copy_symlink_l(entry, p,
1306				linkname_full_length, NULL);
1307			if (errno == ENOMEM) {
1308				archive_set_error(&a->archive, ENOMEM,
1309				    "Can't allocate memory for Symlink");
1310				return (ARCHIVE_FATAL);
1311			}
1312			/*
1313			 * Since there is no character-set regulation for
1314			 * symlink name, do not report the conversion error
1315			 * in an automatic conversion.
1316			 */
1317			if (sconv != zip->sconv_utf8 ||
1318			    (zip->entry->zip_flags & ZIP_UTF8_NAME) == 0) {
1319				archive_set_error(&a->archive,
1320				    ARCHIVE_ERRNO_FILE_FORMAT,
1321				    "Symlink cannot be converted "
1322				    "from %s to current locale.",
1323				    archive_string_conversion_charset_name(
1324					sconv));
1325				ret = ARCHIVE_WARN;
1326			}
1327		}
1328		zip_entry->uncompressed_size = zip_entry->compressed_size = 0;
1329
1330		if (__archive_read_consume(a, linkname_length) < 0) {
1331			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1332			    "Read error skipping symlink target name");
1333			return ARCHIVE_FATAL;
1334		}
1335	} else if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1336	    || zip_entry->uncompressed_size > 0) {
1337		/* Set the size only if it's meaningful. */
1338		archive_entry_set_size(entry, zip_entry->uncompressed_size);
1339	}
1340	zip->entry_bytes_remaining = zip_entry->compressed_size;
1341
1342	/* If there's no body, force read_data() to return EOF immediately. */
1343	if (0 == (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
1344	    && zip->entry_bytes_remaining < 1)
1345		zip->end_of_entry = 1;
1346
1347	/* Set up a more descriptive format name. */
1348        archive_string_empty(&zip->format_name);
1349	archive_string_sprintf(&zip->format_name, "ZIP %d.%d (%s)",
1350	    version / 10, version % 10,
1351	    compression_name(zip->entry->compression));
1352	a->archive.archive_format_name = zip->format_name.s;
1353
1354	return (ret);
1355}
1356
1357static int
1358check_authentication_code(struct archive_read *a, const void *_p)
1359{
1360	struct zip *zip = (struct zip *)(a->format->data);
1361
1362	/* Check authentication code. */
1363	if (zip->hctx_valid) {
1364		const void *p;
1365		uint8_t hmac[20];
1366		size_t hmac_len = 20;
1367		int cmp;
1368
1369		archive_hmac_sha1_final(&zip->hctx, hmac, &hmac_len);
1370		if (_p == NULL) {
1371			/* Read authentication code. */
1372			p = __archive_read_ahead(a, AUTH_CODE_SIZE, NULL);
1373			if (p == NULL) {
1374				archive_set_error(&a->archive,
1375				    ARCHIVE_ERRNO_FILE_FORMAT,
1376				    "Truncated ZIP file data");
1377				return (ARCHIVE_FATAL);
1378			}
1379		} else {
1380			p = _p;
1381		}
1382		cmp = memcmp(hmac, p, AUTH_CODE_SIZE);
1383		__archive_read_consume(a, AUTH_CODE_SIZE);
1384		if (cmp != 0) {
1385			archive_set_error(&a->archive,
1386			    ARCHIVE_ERRNO_MISC,
1387			    "ZIP bad Authentication code");
1388			return (ARCHIVE_WARN);
1389		}
1390	}
1391	return (ARCHIVE_OK);
1392}
1393
1394/*
1395 * Read "uncompressed" data.  There are three cases:
1396 *  1) We know the size of the data.  This is always true for the
1397 * seeking reader (we've examined the Central Directory already).
1398 *  2) ZIP_LENGTH_AT_END was set, but only the CRC was deferred.
1399 * Info-ZIP seems to do this; we know the size but have to grab
1400 * the CRC from the data descriptor afterwards.
1401 *  3) We're streaming and ZIP_LENGTH_AT_END was specified and
1402 * we have no size information.  In this case, we can do pretty
1403 * well by watching for the data descriptor record.  The data
1404 * descriptor is 16 bytes and includes a computed CRC that should
1405 * provide a strong check.
1406 *
1407 * TODO: Technically, the PK\007\010 signature is optional.
1408 * In the original spec, the data descriptor contained CRC
1409 * and size fields but had no leading signature.  In practice,
1410 * newer writers seem to provide the signature pretty consistently.
1411 *
1412 * For uncompressed data, the PK\007\010 marker seems essential
1413 * to be sure we've actually seen the end of the entry.
1414 *
1415 * Returns ARCHIVE_OK if successful, ARCHIVE_FATAL otherwise, sets
1416 * zip->end_of_entry if it consumes all of the data.
1417 */
1418static int
1419zip_read_data_none(struct archive_read *a, const void **_buff,
1420    size_t *size, int64_t *offset)
1421{
1422	struct zip *zip;
1423	const char *buff;
1424	ssize_t bytes_avail;
1425	int r;
1426
1427	(void)offset; /* UNUSED */
1428
1429	zip = (struct zip *)(a->format->data);
1430
1431	if (zip->entry->zip_flags & ZIP_LENGTH_AT_END) {
1432		const char *p;
1433		ssize_t grabbing_bytes = 24;
1434
1435		if (zip->hctx_valid)
1436			grabbing_bytes += AUTH_CODE_SIZE;
1437		/* Grab at least 24 bytes. */
1438		buff = __archive_read_ahead(a, grabbing_bytes, &bytes_avail);
1439		if (bytes_avail < grabbing_bytes) {
1440			/* Zip archives have end-of-archive markers
1441			   that are longer than this, so a failure to get at
1442			   least 24 bytes really does indicate a truncated
1443			   file. */
1444			archive_set_error(&a->archive,
1445			    ARCHIVE_ERRNO_FILE_FORMAT,
1446			    "Truncated ZIP file data");
1447			return (ARCHIVE_FATAL);
1448		}
1449		/* Check for a complete PK\007\010 signature, followed
1450		 * by the correct 4-byte CRC. */
1451		p = buff;
1452		if (zip->hctx_valid)
1453			p += AUTH_CODE_SIZE;
1454		if (p[0] == 'P' && p[1] == 'K'
1455		    && p[2] == '\007' && p[3] == '\010'
1456		    && (archive_le32dec(p + 4) == zip->entry_crc32
1457			|| zip->ignore_crc32
1458			|| (zip->hctx_valid
1459			 && zip->entry->aes_extra.vendor == AES_VENDOR_AE_2))) {
1460			if (zip->entry->flags & LA_USED_ZIP64) {
1461				uint64_t compressed, uncompressed;
1462				zip->entry->crc32 = archive_le32dec(p + 4);
1463				compressed = archive_le64dec(p + 8);
1464				uncompressed = archive_le64dec(p + 16);
1465				if (compressed > INT64_MAX || uncompressed >
1466				    INT64_MAX) {
1467					archive_set_error(&a->archive,
1468					    ARCHIVE_ERRNO_FILE_FORMAT,
1469					    "Overflow of 64-bit file sizes");
1470					return ARCHIVE_FAILED;
1471				}
1472				zip->entry->compressed_size = compressed;
1473				zip->entry->uncompressed_size = uncompressed;
1474				zip->unconsumed = 24;
1475			} else {
1476				zip->entry->crc32 = archive_le32dec(p + 4);
1477				zip->entry->compressed_size =
1478					archive_le32dec(p + 8);
1479				zip->entry->uncompressed_size =
1480					archive_le32dec(p + 12);
1481				zip->unconsumed = 16;
1482			}
1483			if (zip->hctx_valid) {
1484				r = check_authentication_code(a, buff);
1485				if (r != ARCHIVE_OK)
1486					return (r);
1487			}
1488			zip->end_of_entry = 1;
1489			return (ARCHIVE_OK);
1490		}
1491		/* If not at EOF, ensure we consume at least one byte. */
1492		++p;
1493
1494		/* Scan forward until we see where a PK\007\010 signature
1495		 * might be. */
1496		/* Return bytes up until that point.  On the next call,
1497		 * the code above will verify the data descriptor. */
1498		while (p < buff + bytes_avail - 4) {
1499			if (p[3] == 'P') { p += 3; }
1500			else if (p[3] == 'K') { p += 2; }
1501			else if (p[3] == '\007') { p += 1; }
1502			else if (p[3] == '\010' && p[2] == '\007'
1503			    && p[1] == 'K' && p[0] == 'P') {
1504				if (zip->hctx_valid)
1505					p -= AUTH_CODE_SIZE;
1506				break;
1507			} else { p += 4; }
1508		}
1509		bytes_avail = p - buff;
1510	} else {
1511		if (zip->entry_bytes_remaining == 0) {
1512			zip->end_of_entry = 1;
1513			if (zip->hctx_valid) {
1514				r = check_authentication_code(a, NULL);
1515				if (r != ARCHIVE_OK)
1516					return (r);
1517			}
1518			return (ARCHIVE_OK);
1519		}
1520		/* Grab a bunch of bytes. */
1521		buff = __archive_read_ahead(a, 1, &bytes_avail);
1522		if (bytes_avail <= 0) {
1523			archive_set_error(&a->archive,
1524			    ARCHIVE_ERRNO_FILE_FORMAT,
1525			    "Truncated ZIP file data");
1526			return (ARCHIVE_FATAL);
1527		}
1528		if (bytes_avail > zip->entry_bytes_remaining)
1529			bytes_avail = (ssize_t)zip->entry_bytes_remaining;
1530	}
1531	if (zip->tctx_valid || zip->cctx_valid) {
1532		size_t dec_size = bytes_avail;
1533
1534		if (dec_size > zip->decrypted_buffer_size)
1535			dec_size = zip->decrypted_buffer_size;
1536		if (zip->tctx_valid) {
1537			trad_enc_decrypt_update(&zip->tctx,
1538			    (const uint8_t *)buff, dec_size,
1539			    zip->decrypted_buffer, dec_size);
1540		} else {
1541			size_t dsize = dec_size;
1542			archive_hmac_sha1_update(&zip->hctx,
1543			    (const uint8_t *)buff, dec_size);
1544			archive_decrypto_aes_ctr_update(&zip->cctx,
1545			    (const uint8_t *)buff, dec_size,
1546			    zip->decrypted_buffer, &dsize);
1547		}
1548		bytes_avail = dec_size;
1549		buff = (const char *)zip->decrypted_buffer;
1550	}
1551	*size = bytes_avail;
1552	zip->entry_bytes_remaining -= bytes_avail;
1553	zip->entry_uncompressed_bytes_read += bytes_avail;
1554	zip->entry_compressed_bytes_read += bytes_avail;
1555	zip->unconsumed += bytes_avail;
1556	*_buff = buff;
1557	return (ARCHIVE_OK);
1558}
1559
1560static int
1561consume_optional_marker(struct archive_read *a, struct zip *zip)
1562{
1563	if (zip->end_of_entry && (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
1564		const char *p;
1565
1566		if (NULL == (p = __archive_read_ahead(a, 24, NULL))) {
1567			archive_set_error(&a->archive,
1568			    ARCHIVE_ERRNO_FILE_FORMAT,
1569			    "Truncated ZIP end-of-file record");
1570			return (ARCHIVE_FATAL);
1571		}
1572		/* Consume the optional PK\007\010 marker. */
1573		if (p[0] == 'P' && p[1] == 'K' &&
1574		    p[2] == '\007' && p[3] == '\010') {
1575			p += 4;
1576			zip->unconsumed = 4;
1577		}
1578		if (zip->entry->flags & LA_USED_ZIP64) {
1579			uint64_t compressed, uncompressed;
1580			zip->entry->crc32 = archive_le32dec(p);
1581			compressed = archive_le64dec(p + 4);
1582			uncompressed = archive_le64dec(p + 12);
1583			if (compressed > INT64_MAX ||
1584			    uncompressed > INT64_MAX) {
1585				archive_set_error(&a->archive,
1586				    ARCHIVE_ERRNO_FILE_FORMAT,
1587				    "Overflow of 64-bit file sizes");
1588				return ARCHIVE_FAILED;
1589			}
1590			zip->entry->compressed_size = compressed;
1591			zip->entry->uncompressed_size = uncompressed;
1592			zip->unconsumed += 20;
1593		} else {
1594			zip->entry->crc32 = archive_le32dec(p);
1595			zip->entry->compressed_size = archive_le32dec(p + 4);
1596			zip->entry->uncompressed_size = archive_le32dec(p + 8);
1597			zip->unconsumed += 12;
1598		}
1599	}
1600
1601    return (ARCHIVE_OK);
1602}
1603
1604#if HAVE_LZMA_H && HAVE_LIBLZMA
1605static int
1606zipx_xz_init(struct archive_read *a, struct zip *zip)
1607{
1608	lzma_ret r;
1609
1610	if(zip->zipx_lzma_valid) {
1611		lzma_end(&zip->zipx_lzma_stream);
1612		zip->zipx_lzma_valid = 0;
1613	}
1614
1615	memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1616	r = lzma_stream_decoder(&zip->zipx_lzma_stream, UINT64_MAX, 0);
1617	if (r != LZMA_OK) {
1618		archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1619		    "xz initialization failed(%d)",
1620		    r);
1621
1622		return (ARCHIVE_FAILED);
1623	}
1624
1625	zip->zipx_lzma_valid = 1;
1626
1627	free(zip->uncompressed_buffer);
1628
1629	zip->uncompressed_buffer_size = 256 * 1024;
1630	zip->uncompressed_buffer =
1631	    (uint8_t*) malloc(zip->uncompressed_buffer_size);
1632	if (zip->uncompressed_buffer == NULL) {
1633		archive_set_error(&a->archive, ENOMEM,
1634		    "No memory for xz decompression");
1635		    return (ARCHIVE_FATAL);
1636	}
1637
1638	zip->decompress_init = 1;
1639	return (ARCHIVE_OK);
1640}
1641
1642static int
1643zipx_lzma_alone_init(struct archive_read *a, struct zip *zip)
1644{
1645	lzma_ret r;
1646	const uint8_t* p;
1647
1648#pragma pack(push)
1649#pragma pack(1)
1650	struct _alone_header {
1651	    uint8_t bytes[5];
1652	    uint64_t uncompressed_size;
1653	} alone_header;
1654#pragma pack(pop)
1655
1656	if(zip->zipx_lzma_valid) {
1657		lzma_end(&zip->zipx_lzma_stream);
1658		zip->zipx_lzma_valid = 0;
1659	}
1660
1661	/* To unpack ZIPX's "LZMA" (id 14) stream we can use standard liblzma
1662	 * that is a part of XZ Utils. The stream format stored inside ZIPX
1663	 * file is a modified "lzma alone" file format, that was used by the
1664	 * `lzma` utility which was later deprecated in favour of `xz` utility. 	 * Since those formats are nearly the same, we can use a standard
1665	 * "lzma alone" decoder from XZ Utils. */
1666
1667	memset(&zip->zipx_lzma_stream, 0, sizeof(zip->zipx_lzma_stream));
1668	r = lzma_alone_decoder(&zip->zipx_lzma_stream, UINT64_MAX);
1669	if (r != LZMA_OK) {
1670		archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
1671		    "lzma initialization failed(%d)", r);
1672
1673		return (ARCHIVE_FAILED);
1674	}
1675
1676	/* Flag the cleanup function that we want our lzma-related structures
1677	 * to be freed later. */
1678	zip->zipx_lzma_valid = 1;
1679
1680	/* The "lzma alone" file format and the stream format inside ZIPx are
1681	 * almost the same. Here's an example of a structure of "lzma alone"
1682	 * format:
1683	 *
1684	 * $ cat /bin/ls | lzma | xxd | head -n 1
1685	 * 00000000: 5d00 0080 00ff ffff ffff ffff ff00 2814
1686	 *
1687	 *    5 bytes        8 bytes        n bytes
1688	 * <lzma_params><uncompressed_size><data...>
1689	 *
1690	 * lzma_params is a 5-byte blob that has to be decoded to extract
1691	 * parameters of this LZMA stream. The uncompressed_size field is an
1692	 * uint64_t value that contains information about the size of the
1693	 * uncompressed file, or UINT64_MAX if this value is unknown.
1694	 * The <data...> part is the actual lzma-compressed data stream.
1695	 *
1696	 * Now here's the structure of the stream inside the ZIPX file:
1697	 *
1698	 * $ cat stream_inside_zipx | xxd | head -n 1
1699	 * 00000000: 0914 0500 5d00 8000 0000 2814 .... ....
1700	 *
1701	 *  2byte   2byte    5 bytes     n bytes
1702	 * <magic1><magic2><lzma_params><data...>
1703	 *
1704	 * This means that the ZIPX file contains an additional magic1 and
1705	 * magic2 headers, the lzma_params field contains the same parameter
1706	 * set as in the "lzma alone" format, and the <data...> field is the
1707	 * same as in the "lzma alone" format as well. Note that also the zipx
1708	 * format is missing the uncompressed_size field.
1709	 *
1710	 * So, in order to use the "lzma alone" decoder for the zipx lzma
1711	 * stream, we simply need to shuffle around some fields, prepare a new
1712	 * lzma alone header, feed it into lzma alone decoder so it will
1713	 * initialize itself properly, and then we can start feeding normal
1714	 * zipx lzma stream into the decoder.
1715	 */
1716
1717	/* Read magic1,magic2,lzma_params from the ZIPX stream. */
1718	if((p = __archive_read_ahead(a, 9, NULL)) == NULL) {
1719		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1720		    "Truncated lzma data");
1721		return (ARCHIVE_FATAL);
1722	}
1723
1724	if(p[2] != 0x05 || p[3] != 0x00) {
1725		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1726		    "Invalid lzma data");
1727		return (ARCHIVE_FATAL);
1728	}
1729
1730	/* Prepare an lzma alone header: copy the lzma_params blob into
1731	 * a proper place into the lzma alone header. */
1732	memcpy(&alone_header.bytes[0], p + 4, 5);
1733
1734	/* Initialize the 'uncompressed size' field to unknown; we'll manually
1735	 * monitor how many bytes there are still to be uncompressed. */
1736	alone_header.uncompressed_size = UINT64_MAX;
1737
1738	if(!zip->uncompressed_buffer) {
1739		zip->uncompressed_buffer_size = 256 * 1024;
1740		zip->uncompressed_buffer =
1741			(uint8_t*) malloc(zip->uncompressed_buffer_size);
1742
1743		if (zip->uncompressed_buffer == NULL) {
1744			archive_set_error(&a->archive, ENOMEM,
1745			    "No memory for lzma decompression");
1746			return (ARCHIVE_FATAL);
1747		}
1748	}
1749
1750	zip->zipx_lzma_stream.next_in = (void*) &alone_header;
1751	zip->zipx_lzma_stream.avail_in = sizeof(alone_header);
1752	zip->zipx_lzma_stream.total_in = 0;
1753	zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1754	zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1755	zip->zipx_lzma_stream.total_out = 0;
1756
1757	/* Feed only the header into the lzma alone decoder. This will
1758	 * effectively initialize the decoder, and will not produce any
1759	 * output bytes yet. */
1760	r = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1761	if (r != LZMA_OK) {
1762		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
1763		    "lzma stream initialization error");
1764		return ARCHIVE_FATAL;
1765	}
1766
1767	/* We've already consumed some bytes, so take this into account. */
1768	__archive_read_consume(a, 9);
1769	zip->entry_bytes_remaining -= 9;
1770	zip->entry_compressed_bytes_read += 9;
1771
1772	zip->decompress_init = 1;
1773	return (ARCHIVE_OK);
1774}
1775
1776static int
1777zip_read_data_zipx_xz(struct archive_read *a, const void **buff,
1778	size_t *size, int64_t *offset)
1779{
1780	struct zip* zip = (struct zip *)(a->format->data);
1781	int ret;
1782	lzma_ret lz_ret;
1783	const void* compressed_buf;
1784	ssize_t bytes_avail, in_bytes, to_consume = 0;
1785
1786	(void) offset; /* UNUSED */
1787
1788	/* Initialize decompressor if not yet initialized. */
1789	if (!zip->decompress_init) {
1790		ret = zipx_xz_init(a, zip);
1791		if (ret != ARCHIVE_OK)
1792			return (ret);
1793	}
1794
1795	compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1796	if (bytes_avail < 0) {
1797		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1798		    "Truncated xz file body");
1799		return (ARCHIVE_FATAL);
1800	}
1801
1802	in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1803	zip->zipx_lzma_stream.next_in = compressed_buf;
1804	zip->zipx_lzma_stream.avail_in = in_bytes;
1805	zip->zipx_lzma_stream.total_in = 0;
1806	zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1807	zip->zipx_lzma_stream.avail_out = zip->uncompressed_buffer_size;
1808	zip->zipx_lzma_stream.total_out = 0;
1809
1810	/* Perform the decompression. */
1811	lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1812	switch(lz_ret) {
1813		case LZMA_DATA_ERROR:
1814			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1815			    "xz data error (error %d)", (int) lz_ret);
1816			return (ARCHIVE_FATAL);
1817
1818		case LZMA_NO_CHECK:
1819		case LZMA_OK:
1820			break;
1821
1822		default:
1823			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1824			    "xz unknown error %d", (int) lz_ret);
1825			return (ARCHIVE_FATAL);
1826
1827		case LZMA_STREAM_END:
1828			lzma_end(&zip->zipx_lzma_stream);
1829			zip->zipx_lzma_valid = 0;
1830
1831			if((int64_t) zip->zipx_lzma_stream.total_in !=
1832			    zip->entry_bytes_remaining)
1833			{
1834				archive_set_error(&a->archive,
1835				    ARCHIVE_ERRNO_MISC,
1836				    "xz premature end of stream");
1837				return (ARCHIVE_FATAL);
1838			}
1839
1840			zip->end_of_entry = 1;
1841			break;
1842	}
1843
1844	to_consume = zip->zipx_lzma_stream.total_in;
1845
1846	__archive_read_consume(a, to_consume);
1847	zip->entry_bytes_remaining -= to_consume;
1848	zip->entry_compressed_bytes_read += to_consume;
1849	zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1850
1851	*size = zip->zipx_lzma_stream.total_out;
1852	*buff = zip->uncompressed_buffer;
1853
1854	ret = consume_optional_marker(a, zip);
1855	if (ret != ARCHIVE_OK)
1856		return (ret);
1857
1858	return (ARCHIVE_OK);
1859}
1860
1861static int
1862zip_read_data_zipx_lzma_alone(struct archive_read *a, const void **buff,
1863    size_t *size, int64_t *offset)
1864{
1865	struct zip* zip = (struct zip *)(a->format->data);
1866	int ret;
1867	lzma_ret lz_ret;
1868	const void* compressed_buf;
1869	ssize_t bytes_avail, in_bytes, to_consume;
1870
1871	(void) offset; /* UNUSED */
1872
1873	/* Initialize decompressor if not yet initialized. */
1874	if (!zip->decompress_init) {
1875		ret = zipx_lzma_alone_init(a, zip);
1876		if (ret != ARCHIVE_OK)
1877			return (ret);
1878	}
1879
1880	/* Fetch more compressed data. The same note as in deflate handler
1881	 * applies here as well:
1882	 *
1883	 * Note: '1' here is a performance optimization. Recall that the
1884	 * decompression layer returns a count of available bytes; asking for
1885	 * more than that forces the decompressor to combine reads by copying
1886	 * data.
1887	 */
1888	compressed_buf = __archive_read_ahead(a, 1, &bytes_avail);
1889	if (bytes_avail < 0) {
1890		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
1891		    "Truncated lzma file body");
1892		return (ARCHIVE_FATAL);
1893	}
1894
1895	/* Set decompressor parameters. */
1896	in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
1897
1898	zip->zipx_lzma_stream.next_in = compressed_buf;
1899	zip->zipx_lzma_stream.avail_in = in_bytes;
1900	zip->zipx_lzma_stream.total_in = 0;
1901	zip->zipx_lzma_stream.next_out = zip->uncompressed_buffer;
1902	zip->zipx_lzma_stream.avail_out =
1903		/* These lzma_alone streams lack end of stream marker, so let's
1904		 * make sure the unpacker won't try to unpack more than it's
1905		 * supposed to. */
1906		zipmin((int64_t) zip->uncompressed_buffer_size,
1907		    zip->entry->uncompressed_size -
1908		    zip->entry_uncompressed_bytes_read);
1909	zip->zipx_lzma_stream.total_out = 0;
1910
1911	/* Perform the decompression. */
1912	lz_ret = lzma_code(&zip->zipx_lzma_stream, LZMA_RUN);
1913	switch(lz_ret) {
1914		case LZMA_DATA_ERROR:
1915			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1916			    "lzma data error (error %d)", (int) lz_ret);
1917			return (ARCHIVE_FATAL);
1918
1919		/* This case is optional in lzma alone format. It can happen,
1920		 * but most of the files don't have it. (GitHub #1257) */
1921		case LZMA_STREAM_END:
1922			lzma_end(&zip->zipx_lzma_stream);
1923			zip->zipx_lzma_valid = 0;
1924			if((int64_t) zip->zipx_lzma_stream.total_in !=
1925			    zip->entry_bytes_remaining)
1926			{
1927				archive_set_error(&a->archive,
1928				    ARCHIVE_ERRNO_MISC,
1929				    "lzma alone premature end of stream");
1930				return (ARCHIVE_FATAL);
1931			}
1932
1933			zip->end_of_entry = 1;
1934			break;
1935
1936		case LZMA_OK:
1937			break;
1938
1939		default:
1940			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1941			    "lzma unknown error %d", (int) lz_ret);
1942			return (ARCHIVE_FATAL);
1943	}
1944
1945	to_consume = zip->zipx_lzma_stream.total_in;
1946
1947	/* Update pointers. */
1948	__archive_read_consume(a, to_consume);
1949	zip->entry_bytes_remaining -= to_consume;
1950	zip->entry_compressed_bytes_read += to_consume;
1951	zip->entry_uncompressed_bytes_read += zip->zipx_lzma_stream.total_out;
1952
1953	if(zip->entry_bytes_remaining == 0) {
1954		zip->end_of_entry = 1;
1955	}
1956
1957	/* Return values. */
1958	*size = zip->zipx_lzma_stream.total_out;
1959	*buff = zip->uncompressed_buffer;
1960
1961	/* Behave the same way as during deflate decompression. */
1962	ret = consume_optional_marker(a, zip);
1963	if (ret != ARCHIVE_OK)
1964		return (ret);
1965
1966	/* Free lzma decoder handle because we'll no longer need it. */
1967	if(zip->end_of_entry) {
1968		lzma_end(&zip->zipx_lzma_stream);
1969		zip->zipx_lzma_valid = 0;
1970	}
1971
1972	/* If we're here, then we're good! */
1973	return (ARCHIVE_OK);
1974}
1975#endif /* HAVE_LZMA_H && HAVE_LIBLZMA */
1976
1977static int
1978zipx_ppmd8_init(struct archive_read *a, struct zip *zip)
1979{
1980	const void* p;
1981	uint32_t val;
1982	uint32_t order;
1983	uint32_t mem;
1984	uint32_t restore_method;
1985
1986	/* Remove previous decompression context if it exists. */
1987	if(zip->ppmd8_valid) {
1988		__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
1989		zip->ppmd8_valid = 0;
1990	}
1991
1992	/* Create a new decompression context. */
1993	__archive_ppmd8_functions.Ppmd8_Construct(&zip->ppmd8);
1994	zip->ppmd8_stream_failed = 0;
1995
1996	/* Setup function pointers required by Ppmd8 decompressor. The
1997	 * 'ppmd_read' function will feed new bytes to the decompressor,
1998	 * and will increment the 'zip->zipx_ppmd_read_compressed' counter. */
1999	zip->ppmd8.Stream.In = &zip->zipx_ppmd_stream;
2000	zip->zipx_ppmd_stream.a = a;
2001	zip->zipx_ppmd_stream.Read = &ppmd_read;
2002
2003	/* Reset number of read bytes to 0. */
2004	zip->zipx_ppmd_read_compressed = 0;
2005
2006	/* Read Ppmd8 header (2 bytes). */
2007	p = __archive_read_ahead(a, 2, NULL);
2008	if(!p) {
2009		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2010		    "Truncated file data in PPMd8 stream");
2011		return (ARCHIVE_FATAL);
2012	}
2013	__archive_read_consume(a, 2);
2014
2015	/* Decode the stream's compression parameters. */
2016	val = archive_le16dec(p);
2017	order = (val & 15) + 1;
2018	mem = ((val >> 4) & 0xff) + 1;
2019	restore_method = (val >> 12);
2020
2021	if(order < 2 || restore_method > 2) {
2022		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2023		    "Invalid parameter set in PPMd8 stream (order=%" PRId32 ", "
2024		    "restore=%" PRId32 ")", order, restore_method);
2025		return (ARCHIVE_FAILED);
2026	}
2027
2028	/* Allocate the memory needed to properly decompress the file. */
2029	if(!__archive_ppmd8_functions.Ppmd8_Alloc(&zip->ppmd8, mem << 20)) {
2030		archive_set_error(&a->archive, ENOMEM,
2031		    "Unable to allocate memory for PPMd8 stream: %" PRId32 " bytes",
2032		    mem << 20);
2033		return (ARCHIVE_FATAL);
2034	}
2035
2036	/* Signal the cleanup function to release Ppmd8 context in the
2037	 * cleanup phase. */
2038	zip->ppmd8_valid = 1;
2039
2040	/* Perform further Ppmd8 initialization. */
2041	if(!__archive_ppmd8_functions.Ppmd8_RangeDec_Init(&zip->ppmd8)) {
2042		archive_set_error(&a->archive, ARCHIVE_ERRNO_PROGRAMMER,
2043		    "PPMd8 stream range decoder initialization error");
2044		return (ARCHIVE_FATAL);
2045	}
2046
2047	__archive_ppmd8_functions.Ppmd8_Init(&zip->ppmd8, order,
2048	    restore_method);
2049
2050	/* Allocate the buffer that will hold uncompressed data. */
2051	free(zip->uncompressed_buffer);
2052
2053	zip->uncompressed_buffer_size = 256 * 1024;
2054	zip->uncompressed_buffer =
2055	    (uint8_t*) malloc(zip->uncompressed_buffer_size);
2056
2057	if(zip->uncompressed_buffer == NULL) {
2058		archive_set_error(&a->archive, ENOMEM,
2059		    "No memory for PPMd8 decompression");
2060		return ARCHIVE_FATAL;
2061	}
2062
2063	/* Ppmd8 initialization is done. */
2064	zip->decompress_init = 1;
2065
2066	/* We've already read 2 bytes in the output stream. Additionally,
2067	 * Ppmd8 initialization code could read some data as well. So we
2068	 * are advancing the stream by 2 bytes plus whatever number of
2069	 * bytes Ppmd8 init function used. */
2070	zip->entry_compressed_bytes_read += 2 + zip->zipx_ppmd_read_compressed;
2071
2072	return ARCHIVE_OK;
2073}
2074
2075static int
2076zip_read_data_zipx_ppmd(struct archive_read *a, const void **buff,
2077    size_t *size, int64_t *offset)
2078{
2079	struct zip* zip = (struct zip *)(a->format->data);
2080	int ret;
2081	size_t consumed_bytes = 0;
2082	ssize_t bytes_avail = 0;
2083
2084	(void) offset; /* UNUSED */
2085
2086	/* If we're here for the first time, initialize Ppmd8 decompression
2087	 * context first. */
2088	if(!zip->decompress_init) {
2089		ret = zipx_ppmd8_init(a, zip);
2090		if(ret != ARCHIVE_OK)
2091			return ret;
2092	}
2093
2094	/* Fetch for more data. We're reading 1 byte here, but libarchive
2095	 * should prefetch more bytes. */
2096	(void) __archive_read_ahead(a, 1, &bytes_avail);
2097	if(bytes_avail < 0) {
2098		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2099		    "Truncated PPMd8 file body");
2100		return (ARCHIVE_FATAL);
2101	}
2102
2103	/* This counter will be updated inside ppmd_read(), which at one
2104	 * point will be called by Ppmd8_DecodeSymbol. */
2105	zip->zipx_ppmd_read_compressed = 0;
2106
2107	/* Decompression loop. */
2108	do {
2109		int sym = __archive_ppmd8_functions.Ppmd8_DecodeSymbol(
2110		    &zip->ppmd8);
2111		if(sym < 0) {
2112			zip->end_of_entry = 1;
2113			break;
2114		}
2115
2116		/* This field is set by ppmd_read() when there was no more data
2117		 * to be read. */
2118		if(zip->ppmd8_stream_failed) {
2119			archive_set_error(&a->archive,
2120			    ARCHIVE_ERRNO_FILE_FORMAT,
2121			    "Truncated PPMd8 file body");
2122			return (ARCHIVE_FATAL);
2123		}
2124
2125		zip->uncompressed_buffer[consumed_bytes] = (uint8_t) sym;
2126		++consumed_bytes;
2127	} while(consumed_bytes < zip->uncompressed_buffer_size);
2128
2129	/* Update pointers for libarchive. */
2130	*buff = zip->uncompressed_buffer;
2131	*size = consumed_bytes;
2132
2133	/* Update pointers so we can continue decompression in another call. */
2134	zip->entry_bytes_remaining -= zip->zipx_ppmd_read_compressed;
2135	zip->entry_compressed_bytes_read += zip->zipx_ppmd_read_compressed;
2136	zip->entry_uncompressed_bytes_read += consumed_bytes;
2137
2138	/* If we're at the end of stream, deinitialize Ppmd8 context. */
2139	if(zip->end_of_entry) {
2140		__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
2141		zip->ppmd8_valid = 0;
2142	}
2143
2144	/* Seek for optional marker, same way as in each zip entry. */
2145	ret = consume_optional_marker(a, zip);
2146	if (ret != ARCHIVE_OK)
2147		return ret;
2148
2149	return ARCHIVE_OK;
2150}
2151
2152#ifdef HAVE_BZLIB_H
2153static int
2154zipx_bzip2_init(struct archive_read *a, struct zip *zip)
2155{
2156	int r;
2157
2158	/* Deallocate already existing BZ2 decompression context if it
2159	 * exists. */
2160	if(zip->bzstream_valid) {
2161		BZ2_bzDecompressEnd(&zip->bzstream);
2162		zip->bzstream_valid = 0;
2163	}
2164
2165	/* Allocate a new BZ2 decompression context. */
2166	memset(&zip->bzstream, 0, sizeof(bz_stream));
2167	r = BZ2_bzDecompressInit(&zip->bzstream, 0, 1);
2168	if(r != BZ_OK) {
2169		archive_set_error(&(a->archive), ARCHIVE_ERRNO_MISC,
2170		    "bzip2 initialization failed(%d)",
2171		    r);
2172
2173		return ARCHIVE_FAILED;
2174	}
2175
2176	/* Mark the bzstream field to be released in cleanup phase. */
2177	zip->bzstream_valid = 1;
2178
2179	/* (Re)allocate the buffer that will contain decompressed bytes. */
2180	free(zip->uncompressed_buffer);
2181
2182	zip->uncompressed_buffer_size = 256 * 1024;
2183	zip->uncompressed_buffer =
2184	    (uint8_t*) malloc(zip->uncompressed_buffer_size);
2185	if (zip->uncompressed_buffer == NULL) {
2186		archive_set_error(&a->archive, ENOMEM,
2187		    "No memory for bzip2 decompression");
2188		    return ARCHIVE_FATAL;
2189	}
2190
2191	/* Initialization done. */
2192	zip->decompress_init = 1;
2193	return ARCHIVE_OK;
2194}
2195
2196static int
2197zip_read_data_zipx_bzip2(struct archive_read *a, const void **buff,
2198    size_t *size, int64_t *offset)
2199{
2200	struct zip *zip = (struct zip *)(a->format->data);
2201	ssize_t bytes_avail = 0, in_bytes, to_consume;
2202	const void *compressed_buff;
2203	int r;
2204	uint64_t total_out;
2205
2206	(void) offset; /* UNUSED */
2207
2208	/* Initialize decompression context if we're here for the first time. */
2209	if(!zip->decompress_init) {
2210		r = zipx_bzip2_init(a, zip);
2211		if(r != ARCHIVE_OK)
2212			return r;
2213	}
2214
2215	/* Fetch more compressed bytes. */
2216	compressed_buff = __archive_read_ahead(a, 1, &bytes_avail);
2217	if(bytes_avail < 0) {
2218		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2219		    "Truncated bzip2 file body");
2220		return (ARCHIVE_FATAL);
2221	}
2222
2223	in_bytes = zipmin(zip->entry_bytes_remaining, bytes_avail);
2224	if(in_bytes < 1) {
2225		/* libbz2 doesn't complain when caller feeds avail_in == 0.
2226		 * It will actually return success in this case, which is
2227		 * undesirable. This is why we need to make this check
2228		 * manually. */
2229
2230		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2231		    "Truncated bzip2 file body");
2232		return (ARCHIVE_FATAL);
2233	}
2234
2235	/* Setup buffer boundaries. */
2236	zip->bzstream.next_in = (char*)(uintptr_t) compressed_buff;
2237	zip->bzstream.avail_in = in_bytes;
2238	zip->bzstream.total_in_hi32 = 0;
2239	zip->bzstream.total_in_lo32 = 0;
2240	zip->bzstream.next_out = (char*) zip->uncompressed_buffer;
2241	zip->bzstream.avail_out = zip->uncompressed_buffer_size;
2242	zip->bzstream.total_out_hi32 = 0;
2243	zip->bzstream.total_out_lo32 = 0;
2244
2245	/* Perform the decompression. */
2246	r = BZ2_bzDecompress(&zip->bzstream);
2247	switch(r) {
2248		case BZ_STREAM_END:
2249			/* If we're at the end of the stream, deinitialize the
2250			 * decompression context now. */
2251			switch(BZ2_bzDecompressEnd(&zip->bzstream)) {
2252				case BZ_OK:
2253					break;
2254				default:
2255					archive_set_error(&a->archive,
2256					    ARCHIVE_ERRNO_MISC,
2257					    "Failed to clean up bzip2 "
2258					    "decompressor");
2259					return ARCHIVE_FATAL;
2260			}
2261
2262			zip->end_of_entry = 1;
2263			break;
2264		case BZ_OK:
2265			/* The decompressor has successfully decoded this
2266			 * chunk of data, but more data is still in queue. */
2267			break;
2268		default:
2269			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2270			    "bzip2 decompression failed");
2271			return ARCHIVE_FATAL;
2272	}
2273
2274	/* Update the pointers so decompressor can continue decoding. */
2275	to_consume = zip->bzstream.total_in_lo32;
2276	__archive_read_consume(a, to_consume);
2277
2278	total_out = ((uint64_t) zip->bzstream.total_out_hi32 << 32) +
2279	    zip->bzstream.total_out_lo32;
2280
2281	zip->entry_bytes_remaining -= to_consume;
2282	zip->entry_compressed_bytes_read += to_consume;
2283	zip->entry_uncompressed_bytes_read += total_out;
2284
2285	/* Give libarchive its due. */
2286	*size = total_out;
2287	*buff = zip->uncompressed_buffer;
2288
2289	/* Seek for optional marker, like in other entries. */
2290	r = consume_optional_marker(a, zip);
2291	if(r != ARCHIVE_OK)
2292		return r;
2293
2294	return ARCHIVE_OK;
2295}
2296
2297#endif
2298
2299#ifdef HAVE_ZLIB_H
2300static int
2301zip_deflate_init(struct archive_read *a, struct zip *zip)
2302{
2303	int r;
2304
2305	/* If we haven't yet read any data, initialize the decompressor. */
2306	if (!zip->decompress_init) {
2307		if (zip->stream_valid)
2308			r = inflateReset(&zip->stream);
2309		else
2310			r = inflateInit2(&zip->stream,
2311			    -15 /* Don't check for zlib header */);
2312		if (r != Z_OK) {
2313			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2314			    "Can't initialize ZIP decompression.");
2315			return (ARCHIVE_FATAL);
2316		}
2317		/* Stream structure has been set up. */
2318		zip->stream_valid = 1;
2319		/* We've initialized decompression for this stream. */
2320		zip->decompress_init = 1;
2321	}
2322	return (ARCHIVE_OK);
2323}
2324
2325static int
2326zip_read_data_deflate(struct archive_read *a, const void **buff,
2327    size_t *size, int64_t *offset)
2328{
2329	struct zip *zip;
2330	ssize_t bytes_avail;
2331	const void *compressed_buff, *sp;
2332	int r;
2333
2334	(void)offset; /* UNUSED */
2335
2336	zip = (struct zip *)(a->format->data);
2337
2338	/* If the buffer hasn't been allocated, allocate it now. */
2339	if (zip->uncompressed_buffer == NULL) {
2340		zip->uncompressed_buffer_size = 256 * 1024;
2341		zip->uncompressed_buffer
2342		    = (unsigned char *)malloc(zip->uncompressed_buffer_size);
2343		if (zip->uncompressed_buffer == NULL) {
2344			archive_set_error(&a->archive, ENOMEM,
2345			    "No memory for ZIP decompression");
2346			return (ARCHIVE_FATAL);
2347		}
2348	}
2349
2350	r = zip_deflate_init(a, zip);
2351	if (r != ARCHIVE_OK)
2352		return (r);
2353
2354	/*
2355	 * Note: '1' here is a performance optimization.
2356	 * Recall that the decompression layer returns a count of
2357	 * available bytes; asking for more than that forces the
2358	 * decompressor to combine reads by copying data.
2359	 */
2360	compressed_buff = sp = __archive_read_ahead(a, 1, &bytes_avail);
2361	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2362	    && bytes_avail > zip->entry_bytes_remaining) {
2363		bytes_avail = (ssize_t)zip->entry_bytes_remaining;
2364	}
2365	if (bytes_avail < 0) {
2366		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2367		    "Truncated ZIP file body");
2368		return (ARCHIVE_FATAL);
2369	}
2370
2371	if (zip->tctx_valid || zip->cctx_valid) {
2372		if (zip->decrypted_bytes_remaining < (size_t)bytes_avail) {
2373			size_t buff_remaining =
2374			    (zip->decrypted_buffer +
2375			    zip->decrypted_buffer_size)
2376			    - (zip->decrypted_ptr +
2377			    zip->decrypted_bytes_remaining);
2378
2379			if (buff_remaining > (size_t)bytes_avail)
2380				buff_remaining = (size_t)bytes_avail;
2381
2382			if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END) &&
2383			      zip->entry_bytes_remaining > 0) {
2384				if ((int64_t)(zip->decrypted_bytes_remaining
2385				    + buff_remaining)
2386				      > zip->entry_bytes_remaining) {
2387					if (zip->entry_bytes_remaining <
2388					    (int64_t)zip->decrypted_bytes_remaining)
2389						buff_remaining = 0;
2390					else
2391						buff_remaining =
2392						    (size_t)zip->entry_bytes_remaining
2393						    - zip->decrypted_bytes_remaining;
2394				}
2395			}
2396			if (buff_remaining > 0) {
2397				if (zip->tctx_valid) {
2398					trad_enc_decrypt_update(&zip->tctx,
2399					    compressed_buff, buff_remaining,
2400					    zip->decrypted_ptr
2401					      + zip->decrypted_bytes_remaining,
2402					    buff_remaining);
2403				} else {
2404					size_t dsize = buff_remaining;
2405					archive_decrypto_aes_ctr_update(
2406					    &zip->cctx,
2407					    compressed_buff, buff_remaining,
2408					    zip->decrypted_ptr
2409					      + zip->decrypted_bytes_remaining,
2410					    &dsize);
2411				}
2412				zip->decrypted_bytes_remaining +=
2413				    buff_remaining;
2414			}
2415		}
2416		bytes_avail = zip->decrypted_bytes_remaining;
2417		compressed_buff = (const char *)zip->decrypted_ptr;
2418	}
2419
2420	/*
2421	 * A bug in zlib.h: stream.next_in should be marked 'const'
2422	 * but isn't (the library never alters data through the
2423	 * next_in pointer, only reads it).  The result: this ugly
2424	 * cast to remove 'const'.
2425	 */
2426	zip->stream.next_in = (Bytef *)(uintptr_t)(const void *)compressed_buff;
2427	zip->stream.avail_in = (uInt)bytes_avail;
2428	zip->stream.total_in = 0;
2429	zip->stream.next_out = zip->uncompressed_buffer;
2430	zip->stream.avail_out = (uInt)zip->uncompressed_buffer_size;
2431	zip->stream.total_out = 0;
2432
2433	r = inflate(&zip->stream, 0);
2434	switch (r) {
2435	case Z_OK:
2436		break;
2437	case Z_STREAM_END:
2438		zip->end_of_entry = 1;
2439		break;
2440	case Z_MEM_ERROR:
2441		archive_set_error(&a->archive, ENOMEM,
2442		    "Out of memory for ZIP decompression");
2443		return (ARCHIVE_FATAL);
2444	default:
2445		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2446		    "ZIP decompression failed (%d)", r);
2447		return (ARCHIVE_FATAL);
2448	}
2449
2450	/* Consume as much as the compressor actually used. */
2451	bytes_avail = zip->stream.total_in;
2452	if (zip->tctx_valid || zip->cctx_valid) {
2453		zip->decrypted_bytes_remaining -= bytes_avail;
2454		if (zip->decrypted_bytes_remaining == 0)
2455			zip->decrypted_ptr = zip->decrypted_buffer;
2456		else
2457			zip->decrypted_ptr += bytes_avail;
2458	}
2459	/* Calculate compressed data as much as we used.*/
2460	if (zip->hctx_valid)
2461		archive_hmac_sha1_update(&zip->hctx, sp, bytes_avail);
2462	__archive_read_consume(a, bytes_avail);
2463	zip->entry_bytes_remaining -= bytes_avail;
2464	zip->entry_compressed_bytes_read += bytes_avail;
2465
2466	*size = zip->stream.total_out;
2467	zip->entry_uncompressed_bytes_read += zip->stream.total_out;
2468	*buff = zip->uncompressed_buffer;
2469
2470	if (zip->end_of_entry && zip->hctx_valid) {
2471		r = check_authentication_code(a, NULL);
2472		if (r != ARCHIVE_OK)
2473			return (r);
2474	}
2475
2476	r = consume_optional_marker(a, zip);
2477	if (r != ARCHIVE_OK)
2478		return (r);
2479
2480	return (ARCHIVE_OK);
2481}
2482#endif
2483
2484static int
2485read_decryption_header(struct archive_read *a)
2486{
2487	struct zip *zip = (struct zip *)(a->format->data);
2488	const char *p;
2489	unsigned int remaining_size;
2490	unsigned int ts;
2491
2492	/*
2493	 * Read an initialization vector data field.
2494	 */
2495	p = __archive_read_ahead(a, 2, NULL);
2496	if (p == NULL)
2497		goto truncated;
2498	ts = zip->iv_size;
2499	zip->iv_size = archive_le16dec(p);
2500	__archive_read_consume(a, 2);
2501	if (ts < zip->iv_size) {
2502		free(zip->iv);
2503		zip->iv = NULL;
2504	}
2505	p = __archive_read_ahead(a, zip->iv_size, NULL);
2506	if (p == NULL)
2507		goto truncated;
2508	if (zip->iv == NULL) {
2509		zip->iv = malloc(zip->iv_size);
2510		if (zip->iv == NULL)
2511			goto nomem;
2512	}
2513	memcpy(zip->iv, p, zip->iv_size);
2514	__archive_read_consume(a, zip->iv_size);
2515
2516	/*
2517	 * Read a size of remaining decryption header field.
2518	 */
2519	p = __archive_read_ahead(a, 14, NULL);
2520	if (p == NULL)
2521		goto truncated;
2522	remaining_size = archive_le32dec(p);
2523	if (remaining_size < 16 || remaining_size > (1 << 18))
2524		goto corrupted;
2525
2526	/* Check if format version is supported. */
2527	if (archive_le16dec(p+4) != 3) {
2528		archive_set_error(&a->archive,
2529		    ARCHIVE_ERRNO_FILE_FORMAT,
2530		    "Unsupported encryption format version: %u",
2531		    archive_le16dec(p+4));
2532		return (ARCHIVE_FAILED);
2533	}
2534
2535	/*
2536	 * Read an encryption algorithm field.
2537	 */
2538	zip->alg_id = archive_le16dec(p+6);
2539	switch (zip->alg_id) {
2540	case 0x6601:/* DES */
2541	case 0x6602:/* RC2 */
2542	case 0x6603:/* 3DES 168 */
2543	case 0x6609:/* 3DES 112 */
2544	case 0x660E:/* AES 128 */
2545	case 0x660F:/* AES 192 */
2546	case 0x6610:/* AES 256 */
2547	case 0x6702:/* RC2 (version >= 5.2) */
2548	case 0x6720:/* Blowfish */
2549	case 0x6721:/* Twofish */
2550	case 0x6801:/* RC4 */
2551		/* Supported encryption algorithm. */
2552		break;
2553	default:
2554		archive_set_error(&a->archive,
2555		    ARCHIVE_ERRNO_FILE_FORMAT,
2556		    "Unknown encryption algorithm: %u", zip->alg_id);
2557		return (ARCHIVE_FAILED);
2558	}
2559
2560	/*
2561	 * Read a bit length field.
2562	 */
2563	zip->bit_len = archive_le16dec(p+8);
2564
2565	/*
2566	 * Read a flags field.
2567	 */
2568	zip->flags = archive_le16dec(p+10);
2569	switch (zip->flags & 0xf000) {
2570	case 0x0001: /* Password is required to decrypt. */
2571	case 0x0002: /* Certificates only. */
2572	case 0x0003: /* Password or certificate required to decrypt. */
2573		break;
2574	default:
2575		archive_set_error(&a->archive,
2576		    ARCHIVE_ERRNO_FILE_FORMAT,
2577		    "Unknown encryption flag: %u", zip->flags);
2578		return (ARCHIVE_FAILED);
2579	}
2580	if ((zip->flags & 0xf000) == 0 ||
2581	    (zip->flags & 0xf000) == 0x4000) {
2582		archive_set_error(&a->archive,
2583		    ARCHIVE_ERRNO_FILE_FORMAT,
2584		    "Unknown encryption flag: %u", zip->flags);
2585		return (ARCHIVE_FAILED);
2586	}
2587
2588	/*
2589	 * Read an encrypted random data field.
2590	 */
2591	ts = zip->erd_size;
2592	zip->erd_size = archive_le16dec(p+12);
2593	__archive_read_consume(a, 14);
2594	if ((zip->erd_size & 0xf) != 0 ||
2595	    (zip->erd_size + 16) > remaining_size ||
2596	    (zip->erd_size + 16) < zip->erd_size)
2597		goto corrupted;
2598
2599	if (ts < zip->erd_size) {
2600		free(zip->erd);
2601		zip->erd = NULL;
2602	}
2603	p = __archive_read_ahead(a, zip->erd_size, NULL);
2604	if (p == NULL)
2605		goto truncated;
2606	if (zip->erd == NULL) {
2607		zip->erd = malloc(zip->erd_size);
2608		if (zip->erd == NULL)
2609			goto nomem;
2610	}
2611	memcpy(zip->erd, p, zip->erd_size);
2612	__archive_read_consume(a, zip->erd_size);
2613
2614	/*
2615	 * Read a reserved data field.
2616	 */
2617	p = __archive_read_ahead(a, 4, NULL);
2618	if (p == NULL)
2619		goto truncated;
2620	/* Reserved data size should be zero. */
2621	if (archive_le32dec(p) != 0)
2622		goto corrupted;
2623	__archive_read_consume(a, 4);
2624
2625	/*
2626	 * Read a password validation data field.
2627	 */
2628	p = __archive_read_ahead(a, 2, NULL);
2629	if (p == NULL)
2630		goto truncated;
2631	ts = zip->v_size;
2632	zip->v_size = archive_le16dec(p);
2633	__archive_read_consume(a, 2);
2634	if ((zip->v_size & 0x0f) != 0 ||
2635	    (zip->erd_size + zip->v_size + 16) > remaining_size ||
2636	    (zip->erd_size + zip->v_size + 16) < (zip->erd_size + zip->v_size))
2637		goto corrupted;
2638	if (ts < zip->v_size) {
2639		free(zip->v_data);
2640		zip->v_data = NULL;
2641	}
2642	p = __archive_read_ahead(a, zip->v_size, NULL);
2643	if (p == NULL)
2644		goto truncated;
2645	if (zip->v_data == NULL) {
2646		zip->v_data = malloc(zip->v_size);
2647		if (zip->v_data == NULL)
2648			goto nomem;
2649	}
2650	memcpy(zip->v_data, p, zip->v_size);
2651	__archive_read_consume(a, zip->v_size);
2652
2653	p = __archive_read_ahead(a, 4, NULL);
2654	if (p == NULL)
2655		goto truncated;
2656	zip->v_crc32 = archive_le32dec(p);
2657	__archive_read_consume(a, 4);
2658
2659	/*return (ARCHIVE_OK);
2660	 * This is not fully implemented yet.*/
2661	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2662	    "Encrypted file is unsupported");
2663	return (ARCHIVE_FAILED);
2664truncated:
2665	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2666	    "Truncated ZIP file data");
2667	return (ARCHIVE_FATAL);
2668corrupted:
2669	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2670	    "Corrupted ZIP file data");
2671	return (ARCHIVE_FATAL);
2672nomem:
2673	archive_set_error(&a->archive, ENOMEM,
2674	    "No memory for ZIP decryption");
2675	return (ARCHIVE_FATAL);
2676}
2677
2678static int
2679zip_alloc_decryption_buffer(struct archive_read *a)
2680{
2681	struct zip *zip = (struct zip *)(a->format->data);
2682	size_t bs = 256 * 1024;
2683
2684	if (zip->decrypted_buffer == NULL) {
2685		zip->decrypted_buffer_size = bs;
2686		zip->decrypted_buffer = malloc(bs);
2687		if (zip->decrypted_buffer == NULL) {
2688			archive_set_error(&a->archive, ENOMEM,
2689			    "No memory for ZIP decryption");
2690			return (ARCHIVE_FATAL);
2691		}
2692	}
2693	zip->decrypted_ptr = zip->decrypted_buffer;
2694	return (ARCHIVE_OK);
2695}
2696
2697static int
2698init_traditional_PKWARE_decryption(struct archive_read *a)
2699{
2700	struct zip *zip = (struct zip *)(a->format->data);
2701	const void *p;
2702	int retry;
2703	int r;
2704
2705	if (zip->tctx_valid)
2706		return (ARCHIVE_OK);
2707
2708	/*
2709	   Read the 12 bytes encryption header stored at
2710	   the start of the data area.
2711	 */
2712#define ENC_HEADER_SIZE	12
2713	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2714	    && zip->entry_bytes_remaining < ENC_HEADER_SIZE) {
2715		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2716		    "Truncated Zip encrypted body: only %jd bytes available",
2717		    (intmax_t)zip->entry_bytes_remaining);
2718		return (ARCHIVE_FATAL);
2719	}
2720
2721	p = __archive_read_ahead(a, ENC_HEADER_SIZE, NULL);
2722	if (p == NULL) {
2723		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2724		    "Truncated ZIP file data");
2725		return (ARCHIVE_FATAL);
2726	}
2727
2728	for (retry = 0;; retry++) {
2729		const char *passphrase;
2730		uint8_t crcchk;
2731
2732		passphrase = __archive_read_next_passphrase(a);
2733		if (passphrase == NULL) {
2734			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2735			    (retry > 0)?
2736				"Incorrect passphrase":
2737				"Passphrase required for this entry");
2738			return (ARCHIVE_FAILED);
2739		}
2740
2741		/*
2742		 * Initialize ctx for Traditional PKWARE Decryption.
2743		 */
2744		r = trad_enc_init(&zip->tctx, passphrase, strlen(passphrase),
2745			p, ENC_HEADER_SIZE, &crcchk);
2746		if (r == 0 && crcchk == zip->entry->decdat)
2747			break;/* The passphrase is OK. */
2748		if (retry > 10000) {
2749			/* Avoid infinity loop. */
2750			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2751			    "Too many incorrect passphrases");
2752			return (ARCHIVE_FAILED);
2753		}
2754	}
2755
2756	__archive_read_consume(a, ENC_HEADER_SIZE);
2757	zip->tctx_valid = 1;
2758	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)) {
2759	    zip->entry_bytes_remaining -= ENC_HEADER_SIZE;
2760	}
2761	/*zip->entry_uncompressed_bytes_read += ENC_HEADER_SIZE;*/
2762	zip->entry_compressed_bytes_read += ENC_HEADER_SIZE;
2763	zip->decrypted_bytes_remaining = 0;
2764
2765	return (zip_alloc_decryption_buffer(a));
2766#undef ENC_HEADER_SIZE
2767}
2768
2769static int
2770init_WinZip_AES_decryption(struct archive_read *a)
2771{
2772	struct zip *zip = (struct zip *)(a->format->data);
2773	const void *p;
2774	const uint8_t *pv;
2775	size_t key_len, salt_len;
2776	uint8_t derived_key[MAX_DERIVED_KEY_BUF_SIZE];
2777	int retry;
2778	int r;
2779
2780	if (zip->cctx_valid || zip->hctx_valid)
2781		return (ARCHIVE_OK);
2782
2783	switch (zip->entry->aes_extra.strength) {
2784	case 1: salt_len = 8;  key_len = 16; break;
2785	case 2: salt_len = 12; key_len = 24; break;
2786	case 3: salt_len = 16; key_len = 32; break;
2787	default: goto corrupted;
2788	}
2789	p = __archive_read_ahead(a, salt_len + 2, NULL);
2790	if (p == NULL)
2791		goto truncated;
2792
2793	for (retry = 0;; retry++) {
2794		const char *passphrase;
2795
2796		passphrase = __archive_read_next_passphrase(a);
2797		if (passphrase == NULL) {
2798			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2799			    (retry > 0)?
2800				"Incorrect passphrase":
2801				"Passphrase required for this entry");
2802			return (ARCHIVE_FAILED);
2803		}
2804		memset(derived_key, 0, sizeof(derived_key));
2805		r = archive_pbkdf2_sha1(passphrase, strlen(passphrase),
2806		    p, salt_len, 1000, derived_key, key_len * 2 + 2);
2807		if (r != 0) {
2808			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2809			    "Decryption is unsupported due to lack of "
2810			    "crypto library");
2811			return (ARCHIVE_FAILED);
2812		}
2813
2814		/* Check password verification value. */
2815		pv = ((const uint8_t *)p) + salt_len;
2816		if (derived_key[key_len * 2] == pv[0] &&
2817		    derived_key[key_len * 2 + 1] == pv[1])
2818			break;/* The passphrase is OK. */
2819		if (retry > 10000) {
2820			/* Avoid infinity loop. */
2821			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2822			    "Too many incorrect passphrases");
2823			return (ARCHIVE_FAILED);
2824		}
2825	}
2826
2827	r = archive_decrypto_aes_ctr_init(&zip->cctx, derived_key, key_len);
2828	if (r != 0) {
2829		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2830		    "Decryption is unsupported due to lack of crypto library");
2831		return (ARCHIVE_FAILED);
2832	}
2833	r = archive_hmac_sha1_init(&zip->hctx, derived_key + key_len, key_len);
2834	if (r != 0) {
2835		archive_decrypto_aes_ctr_release(&zip->cctx);
2836		archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2837		    "Failed to initialize HMAC-SHA1");
2838		return (ARCHIVE_FAILED);
2839	}
2840	zip->cctx_valid = zip->hctx_valid = 1;
2841	__archive_read_consume(a, salt_len + 2);
2842	zip->entry_bytes_remaining -= salt_len + 2 + AUTH_CODE_SIZE;
2843	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
2844	    && zip->entry_bytes_remaining < 0)
2845		goto corrupted;
2846	zip->entry_compressed_bytes_read += salt_len + 2 + AUTH_CODE_SIZE;
2847	zip->decrypted_bytes_remaining = 0;
2848
2849	zip->entry->compression = zip->entry->aes_extra.compression;
2850	return (zip_alloc_decryption_buffer(a));
2851
2852truncated:
2853	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2854	    "Truncated ZIP file data");
2855	return (ARCHIVE_FATAL);
2856corrupted:
2857	archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2858	    "Corrupted ZIP file data");
2859	return (ARCHIVE_FATAL);
2860}
2861
2862static int
2863archive_read_format_zip_read_data(struct archive_read *a,
2864    const void **buff, size_t *size, int64_t *offset)
2865{
2866	int r;
2867	struct zip *zip = (struct zip *)(a->format->data);
2868
2869	if (zip->has_encrypted_entries ==
2870			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW) {
2871		zip->has_encrypted_entries = 0;
2872	}
2873
2874	*offset = zip->entry_uncompressed_bytes_read;
2875	*size = 0;
2876	*buff = NULL;
2877
2878	/* If we hit end-of-entry last time, return ARCHIVE_EOF. */
2879	if (zip->end_of_entry)
2880		return (ARCHIVE_EOF);
2881
2882	/* Return EOF immediately if this is a non-regular file. */
2883	if (AE_IFREG != (zip->entry->mode & AE_IFMT))
2884		return (ARCHIVE_EOF);
2885
2886	__archive_read_consume(a, zip->unconsumed);
2887	zip->unconsumed = 0;
2888
2889	if (zip->init_decryption) {
2890		zip->has_encrypted_entries = 1;
2891		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
2892			r = read_decryption_header(a);
2893		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
2894			r = init_WinZip_AES_decryption(a);
2895		else
2896			r = init_traditional_PKWARE_decryption(a);
2897		if (r != ARCHIVE_OK)
2898			return (r);
2899		zip->init_decryption = 0;
2900	}
2901
2902	switch(zip->entry->compression) {
2903	case 0:  /* No compression. */
2904		r =  zip_read_data_none(a, buff, size, offset);
2905		break;
2906#ifdef HAVE_BZLIB_H
2907	case 12: /* ZIPx bzip2 compression. */
2908		r = zip_read_data_zipx_bzip2(a, buff, size, offset);
2909		break;
2910#endif
2911#if HAVE_LZMA_H && HAVE_LIBLZMA
2912	case 14: /* ZIPx LZMA compression. */
2913		r = zip_read_data_zipx_lzma_alone(a, buff, size, offset);
2914		break;
2915	case 95: /* ZIPx XZ compression. */
2916		r = zip_read_data_zipx_xz(a, buff, size, offset);
2917		break;
2918#endif
2919	/* PPMd support is built-in, so we don't need any #if guards. */
2920	case 98: /* ZIPx PPMd compression. */
2921		r = zip_read_data_zipx_ppmd(a, buff, size, offset);
2922		break;
2923
2924#ifdef HAVE_ZLIB_H
2925	case 8: /* Deflate compression. */
2926		r =  zip_read_data_deflate(a, buff, size, offset);
2927		break;
2928#endif
2929	default: /* Unsupported compression. */
2930		/* Return a warning. */
2931		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
2932		    "Unsupported ZIP compression method (%d: %s)",
2933		    zip->entry->compression, compression_name(zip->entry->compression));
2934		/* We can't decompress this entry, but we will
2935		 * be able to skip() it and try the next entry. */
2936		return (ARCHIVE_FAILED);
2937		break;
2938	}
2939	if (r != ARCHIVE_OK)
2940		return (r);
2941	/* Update checksum */
2942	if (*size)
2943		zip->entry_crc32 = zip->crc32func(zip->entry_crc32, *buff,
2944		    (unsigned)*size);
2945	/* If we hit the end, swallow any end-of-data marker. */
2946	if (zip->end_of_entry) {
2947		/* Check file size, CRC against these values. */
2948		if (zip->entry->compressed_size !=
2949		    zip->entry_compressed_bytes_read) {
2950			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2951			    "ZIP compressed data is wrong size "
2952			    "(read %jd, expected %jd)",
2953			    (intmax_t)zip->entry_compressed_bytes_read,
2954			    (intmax_t)zip->entry->compressed_size);
2955			return (ARCHIVE_WARN);
2956		}
2957		/* Size field only stores the lower 32 bits of the actual
2958		 * size. */
2959		if ((zip->entry->uncompressed_size & UINT32_MAX)
2960		    != (zip->entry_uncompressed_bytes_read & UINT32_MAX)) {
2961			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2962			    "ZIP uncompressed data is wrong size "
2963			    "(read %jd, expected %jd)\n",
2964			    (intmax_t)zip->entry_uncompressed_bytes_read,
2965			    (intmax_t)zip->entry->uncompressed_size);
2966			return (ARCHIVE_WARN);
2967		}
2968		/* Check computed CRC against header */
2969		if ((!zip->hctx_valid ||
2970		      zip->entry->aes_extra.vendor != AES_VENDOR_AE_2) &&
2971		   zip->entry->crc32 != zip->entry_crc32
2972		    && !zip->ignore_crc32) {
2973			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
2974			    "ZIP bad CRC: 0x%lx should be 0x%lx",
2975			    (unsigned long)zip->entry_crc32,
2976			    (unsigned long)zip->entry->crc32);
2977			return (ARCHIVE_WARN);
2978		}
2979	}
2980
2981	return (ARCHIVE_OK);
2982}
2983
2984static int
2985archive_read_format_zip_cleanup(struct archive_read *a)
2986{
2987	struct zip *zip;
2988	struct zip_entry *zip_entry, *next_zip_entry;
2989
2990	zip = (struct zip *)(a->format->data);
2991
2992#ifdef HAVE_ZLIB_H
2993	if (zip->stream_valid)
2994		inflateEnd(&zip->stream);
2995#endif
2996
2997#if HAVE_LZMA_H && HAVE_LIBLZMA
2998    if (zip->zipx_lzma_valid) {
2999		lzma_end(&zip->zipx_lzma_stream);
3000	}
3001#endif
3002
3003#ifdef HAVE_BZLIB_H
3004	if (zip->bzstream_valid) {
3005		BZ2_bzDecompressEnd(&zip->bzstream);
3006	}
3007#endif
3008
3009	free(zip->uncompressed_buffer);
3010
3011	if (zip->ppmd8_valid)
3012		__archive_ppmd8_functions.Ppmd8_Free(&zip->ppmd8);
3013
3014	if (zip->zip_entries) {
3015		zip_entry = zip->zip_entries;
3016		while (zip_entry != NULL) {
3017			next_zip_entry = zip_entry->next;
3018			archive_string_free(&zip_entry->rsrcname);
3019			free(zip_entry);
3020			zip_entry = next_zip_entry;
3021		}
3022	}
3023	free(zip->decrypted_buffer);
3024	if (zip->cctx_valid)
3025		archive_decrypto_aes_ctr_release(&zip->cctx);
3026	if (zip->hctx_valid)
3027		archive_hmac_sha1_cleanup(&zip->hctx);
3028	free(zip->iv);
3029	free(zip->erd);
3030	free(zip->v_data);
3031	archive_string_free(&zip->format_name);
3032	free(zip);
3033	(a->format->data) = NULL;
3034	return (ARCHIVE_OK);
3035}
3036
3037static int
3038archive_read_format_zip_has_encrypted_entries(struct archive_read *_a)
3039{
3040	if (_a && _a->format) {
3041		struct zip * zip = (struct zip *)_a->format->data;
3042		if (zip) {
3043			return zip->has_encrypted_entries;
3044		}
3045	}
3046	return ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3047}
3048
3049static int
3050archive_read_format_zip_options(struct archive_read *a,
3051    const char *key, const char *val)
3052{
3053	struct zip *zip;
3054	int ret = ARCHIVE_FAILED;
3055
3056	zip = (struct zip *)(a->format->data);
3057	if (strcmp(key, "compat-2x")  == 0) {
3058		/* Handle filenames as libarchive 2.x */
3059		zip->init_default_conversion = (val != NULL) ? 1 : 0;
3060		return (ARCHIVE_OK);
3061	} else if (strcmp(key, "hdrcharset")  == 0) {
3062		if (val == NULL || val[0] == 0)
3063			archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
3064			    "zip: hdrcharset option needs a character-set name"
3065			);
3066		else {
3067			zip->sconv = archive_string_conversion_from_charset(
3068			    &a->archive, val, 0);
3069			if (zip->sconv != NULL) {
3070				if (strcmp(val, "UTF-8") == 0)
3071					zip->sconv_utf8 = zip->sconv;
3072				ret = ARCHIVE_OK;
3073			} else
3074				ret = ARCHIVE_FATAL;
3075		}
3076		return (ret);
3077	} else if (strcmp(key, "ignorecrc32") == 0) {
3078		/* Mostly useful for testing. */
3079		if (val == NULL || val[0] == 0) {
3080			zip->crc32func = real_crc32;
3081			zip->ignore_crc32 = 0;
3082		} else {
3083			zip->crc32func = fake_crc32;
3084			zip->ignore_crc32 = 1;
3085		}
3086		return (ARCHIVE_OK);
3087	} else if (strcmp(key, "mac-ext") == 0) {
3088		zip->process_mac_extensions = (val != NULL && val[0] != 0);
3089		return (ARCHIVE_OK);
3090	}
3091
3092	/* Note: The "warn" return is just to inform the options
3093	 * supervisor that we didn't handle it.  It will generate
3094	 * a suitable error if no one used this option. */
3095	return (ARCHIVE_WARN);
3096}
3097
3098int
3099archive_read_support_format_zip(struct archive *a)
3100{
3101	int r;
3102	r = archive_read_support_format_zip_streamable(a);
3103	if (r != ARCHIVE_OK)
3104		return r;
3105	return (archive_read_support_format_zip_seekable(a));
3106}
3107
3108/* ------------------------------------------------------------------------ */
3109
3110/*
3111 * Streaming-mode support
3112 */
3113
3114
3115static int
3116archive_read_support_format_zip_capabilities_streamable(struct archive_read * a)
3117{
3118	(void)a; /* UNUSED */
3119	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3120		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3121}
3122
3123static int
3124archive_read_format_zip_streamable_bid(struct archive_read *a, int best_bid)
3125{
3126	const char *p;
3127
3128	(void)best_bid; /* UNUSED */
3129
3130	if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3131		return (-1);
3132
3133	/*
3134	 * Bid of 29 here comes from:
3135	 *  + 16 bits for "PK",
3136	 *  + next 16-bit field has 6 options so contributes
3137	 *    about 16 - log_2(6) ~= 16 - 2.6 ~= 13 bits
3138	 *
3139	 * So we've effectively verified ~29 total bits of check data.
3140	 */
3141	if (p[0] == 'P' && p[1] == 'K') {
3142		if ((p[2] == '\001' && p[3] == '\002')
3143		    || (p[2] == '\003' && p[3] == '\004')
3144		    || (p[2] == '\005' && p[3] == '\006')
3145		    || (p[2] == '\006' && p[3] == '\006')
3146		    || (p[2] == '\007' && p[3] == '\010')
3147		    || (p[2] == '0' && p[3] == '0'))
3148			return (29);
3149	}
3150
3151	/* TODO: It's worth looking ahead a little bit for a valid
3152	 * PK signature.  In particular, that would make it possible
3153	 * to read some UUEncoded SFX files or SFX files coming from
3154	 * a network socket. */
3155
3156	return (0);
3157}
3158
3159static int
3160archive_read_format_zip_streamable_read_header(struct archive_read *a,
3161    struct archive_entry *entry)
3162{
3163	struct zip *zip;
3164
3165	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
3166	if (a->archive.archive_format_name == NULL)
3167		a->archive.archive_format_name = "ZIP";
3168
3169	zip = (struct zip *)(a->format->data);
3170
3171	/*
3172	 * It should be sufficient to call archive_read_next_header() for
3173	 * a reader to determine if an entry is encrypted or not. If the
3174	 * encryption of an entry is only detectable when calling
3175	 * archive_read_data(), so be it. We'll do the same check there
3176	 * as well.
3177	 */
3178	if (zip->has_encrypted_entries ==
3179			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
3180		zip->has_encrypted_entries = 0;
3181
3182	/* Make sure we have a zip_entry structure to use. */
3183	if (zip->zip_entries == NULL) {
3184		zip->zip_entries = malloc(sizeof(struct zip_entry));
3185		if (zip->zip_entries == NULL) {
3186			archive_set_error(&a->archive, ENOMEM,
3187			    "Out  of memory");
3188			return ARCHIVE_FATAL;
3189		}
3190	}
3191	zip->entry = zip->zip_entries;
3192	memset(zip->entry, 0, sizeof(struct zip_entry));
3193
3194	if (zip->cctx_valid)
3195		archive_decrypto_aes_ctr_release(&zip->cctx);
3196	if (zip->hctx_valid)
3197		archive_hmac_sha1_cleanup(&zip->hctx);
3198	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
3199	__archive_read_reset_passphrase(a);
3200
3201	/* Search ahead for the next local file header. */
3202	__archive_read_consume(a, zip->unconsumed);
3203	zip->unconsumed = 0;
3204	for (;;) {
3205		int64_t skipped = 0;
3206		const char *p, *end;
3207		ssize_t bytes;
3208
3209		p = __archive_read_ahead(a, 4, &bytes);
3210		if (p == NULL)
3211			return (ARCHIVE_FATAL);
3212		end = p + bytes;
3213
3214		while (p + 4 <= end) {
3215			if (p[0] == 'P' && p[1] == 'K') {
3216				if (p[2] == '\003' && p[3] == '\004') {
3217					/* Regular file entry. */
3218					__archive_read_consume(a, skipped);
3219					return zip_read_local_file_header(a,
3220					    entry, zip);
3221				}
3222
3223                              /*
3224                               * TODO: We cannot restore permissions
3225                               * based only on the local file headers.
3226                               * Consider scanning the central
3227                               * directory and returning additional
3228                               * entries for at least directories.
3229                               * This would allow us to properly set
3230                               * directory permissions.
3231			       *
3232			       * This won't help us fix symlinks
3233			       * and may not help with regular file
3234			       * permissions, either.  <sigh>
3235                               */
3236                              if (p[2] == '\001' && p[3] == '\002') {
3237                                      return (ARCHIVE_EOF);
3238                              }
3239
3240                              /* End of central directory?  Must be an
3241                               * empty archive. */
3242                              if ((p[2] == '\005' && p[3] == '\006')
3243                                  || (p[2] == '\006' && p[3] == '\006'))
3244                                      return (ARCHIVE_EOF);
3245			}
3246			++p;
3247			++skipped;
3248		}
3249		__archive_read_consume(a, skipped);
3250	}
3251}
3252
3253static int
3254archive_read_format_zip_read_data_skip_streamable(struct archive_read *a)
3255{
3256	struct zip *zip;
3257	int64_t bytes_skipped;
3258
3259	zip = (struct zip *)(a->format->data);
3260	bytes_skipped = __archive_read_consume(a, zip->unconsumed);
3261	zip->unconsumed = 0;
3262	if (bytes_skipped < 0)
3263		return (ARCHIVE_FATAL);
3264
3265	/* If we've already read to end of data, we're done. */
3266	if (zip->end_of_entry)
3267		return (ARCHIVE_OK);
3268
3269	/* So we know we're streaming... */
3270	if (0 == (zip->entry->zip_flags & ZIP_LENGTH_AT_END)
3271	    || zip->entry->compressed_size > 0) {
3272		/* We know the compressed length, so we can just skip. */
3273		bytes_skipped = __archive_read_consume(a,
3274					zip->entry_bytes_remaining);
3275		if (bytes_skipped < 0)
3276			return (ARCHIVE_FATAL);
3277		return (ARCHIVE_OK);
3278	}
3279
3280	if (zip->init_decryption) {
3281		int r;
3282
3283		zip->has_encrypted_entries = 1;
3284		if (zip->entry->zip_flags & ZIP_STRONG_ENCRYPTED)
3285			r = read_decryption_header(a);
3286		else if (zip->entry->compression == WINZIP_AES_ENCRYPTION)
3287			r = init_WinZip_AES_decryption(a);
3288		else
3289			r = init_traditional_PKWARE_decryption(a);
3290		if (r != ARCHIVE_OK)
3291			return (r);
3292		zip->init_decryption = 0;
3293	}
3294
3295	/* We're streaming and we don't know the length. */
3296	/* If the body is compressed and we know the format, we can
3297	 * find an exact end-of-entry by decompressing it. */
3298	switch (zip->entry->compression) {
3299#ifdef HAVE_ZLIB_H
3300	case 8: /* Deflate compression. */
3301		while (!zip->end_of_entry) {
3302			int64_t offset = 0;
3303			const void *buff = NULL;
3304			size_t size = 0;
3305			int r;
3306			r =  zip_read_data_deflate(a, &buff, &size, &offset);
3307			if (r != ARCHIVE_OK)
3308				return (r);
3309		}
3310		return ARCHIVE_OK;
3311#endif
3312	default: /* Uncompressed or unknown. */
3313		/* Scan for a PK\007\010 signature. */
3314		for (;;) {
3315			const char *p, *buff;
3316			ssize_t bytes_avail;
3317			buff = __archive_read_ahead(a, 16, &bytes_avail);
3318			if (bytes_avail < 16) {
3319				archive_set_error(&a->archive,
3320				    ARCHIVE_ERRNO_FILE_FORMAT,
3321				    "Truncated ZIP file data");
3322				return (ARCHIVE_FATAL);
3323			}
3324			p = buff;
3325			while (p <= buff + bytes_avail - 16) {
3326				if (p[3] == 'P') { p += 3; }
3327				else if (p[3] == 'K') { p += 2; }
3328				else if (p[3] == '\007') { p += 1; }
3329				else if (p[3] == '\010' && p[2] == '\007'
3330				    && p[1] == 'K' && p[0] == 'P') {
3331					if (zip->entry->flags & LA_USED_ZIP64)
3332						__archive_read_consume(a,
3333						    p - buff + 24);
3334					else
3335						__archive_read_consume(a,
3336						    p - buff + 16);
3337					return ARCHIVE_OK;
3338				} else { p += 4; }
3339			}
3340			__archive_read_consume(a, p - buff);
3341		}
3342	}
3343}
3344
3345int
3346archive_read_support_format_zip_streamable(struct archive *_a)
3347{
3348	struct archive_read *a = (struct archive_read *)_a;
3349	struct zip *zip;
3350	int r;
3351
3352	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
3353	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip");
3354
3355	zip = (struct zip *)calloc(1, sizeof(*zip));
3356	if (zip == NULL) {
3357		archive_set_error(&a->archive, ENOMEM,
3358		    "Can't allocate zip data");
3359		return (ARCHIVE_FATAL);
3360	}
3361
3362	/* Streamable reader doesn't support mac extensions. */
3363	zip->process_mac_extensions = 0;
3364
3365	/*
3366	 * Until enough data has been read, we cannot tell about
3367	 * any encrypted entries yet.
3368	 */
3369	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
3370	zip->crc32func = real_crc32;
3371
3372	r = __archive_read_register_format(a,
3373	    zip,
3374	    "zip",
3375	    archive_read_format_zip_streamable_bid,
3376	    archive_read_format_zip_options,
3377	    archive_read_format_zip_streamable_read_header,
3378	    archive_read_format_zip_read_data,
3379	    archive_read_format_zip_read_data_skip_streamable,
3380	    NULL,
3381	    archive_read_format_zip_cleanup,
3382	    archive_read_support_format_zip_capabilities_streamable,
3383	    archive_read_format_zip_has_encrypted_entries);
3384
3385	if (r != ARCHIVE_OK)
3386		free(zip);
3387	return (ARCHIVE_OK);
3388}
3389
3390/* ------------------------------------------------------------------------ */
3391
3392/*
3393 * Seeking-mode support
3394 */
3395
3396static int
3397archive_read_support_format_zip_capabilities_seekable(struct archive_read * a)
3398{
3399	(void)a; /* UNUSED */
3400	return (ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_DATA |
3401		ARCHIVE_READ_FORMAT_CAPS_ENCRYPT_METADATA);
3402}
3403
3404/*
3405 * TODO: This is a performance sink because it forces the read core to
3406 * drop buffered data from the start of file, which will then have to
3407 * be re-read again if this bidder loses.
3408 *
3409 * We workaround this a little by passing in the best bid so far so
3410 * that later bidders can do nothing if they know they'll never
3411 * outbid.  But we can certainly do better...
3412 */
3413static int
3414read_eocd(struct zip *zip, const char *p, int64_t current_offset)
3415{
3416	/* Sanity-check the EOCD we've found. */
3417
3418	/* This must be the first volume. */
3419	if (archive_le16dec(p + 4) != 0)
3420		return 0;
3421	/* Central directory must be on this volume. */
3422	if (archive_le16dec(p + 4) != archive_le16dec(p + 6))
3423		return 0;
3424	/* All central directory entries must be on this volume. */
3425	if (archive_le16dec(p + 10) != archive_le16dec(p + 8))
3426		return 0;
3427	/* Central directory can't extend beyond start of EOCD record. */
3428	if (archive_le32dec(p + 16) + archive_le32dec(p + 12)
3429	    > current_offset)
3430		return 0;
3431
3432	/* Save the central directory location for later use. */
3433	zip->central_directory_offset = archive_le32dec(p + 16);
3434
3435	/* This is just a tiny bit higher than the maximum
3436	   returned by the streaming Zip bidder.  This ensures
3437	   that the more accurate seeking Zip parser wins
3438	   whenever seek is available. */
3439	return 32;
3440}
3441
3442/*
3443 * Examine Zip64 EOCD locator:  If it's valid, store the information
3444 * from it.
3445 */
3446static int
3447read_zip64_eocd(struct archive_read *a, struct zip *zip, const char *p)
3448{
3449	int64_t eocd64_offset;
3450	int64_t eocd64_size;
3451
3452	/* Sanity-check the locator record. */
3453
3454	/* Central dir must be on first volume. */
3455	if (archive_le32dec(p + 4) != 0)
3456		return 0;
3457	/* Must be only a single volume. */
3458	if (archive_le32dec(p + 16) != 1)
3459		return 0;
3460
3461	/* Find the Zip64 EOCD record. */
3462	eocd64_offset = archive_le64dec(p + 8);
3463	if (__archive_read_seek(a, eocd64_offset, SEEK_SET) < 0)
3464		return 0;
3465	if ((p = __archive_read_ahead(a, 56, NULL)) == NULL)
3466		return 0;
3467	/* Make sure we can read all of it. */
3468	eocd64_size = archive_le64dec(p + 4) + 12;
3469	if (eocd64_size < 56 || eocd64_size > 16384)
3470		return 0;
3471	if ((p = __archive_read_ahead(a, (size_t)eocd64_size, NULL)) == NULL)
3472		return 0;
3473
3474	/* Sanity-check the EOCD64 */
3475	if (archive_le32dec(p + 16) != 0) /* Must be disk #0 */
3476		return 0;
3477	if (archive_le32dec(p + 20) != 0) /* CD must be on disk #0 */
3478		return 0;
3479	/* CD can't be split. */
3480	if (archive_le64dec(p + 24) != archive_le64dec(p + 32))
3481		return 0;
3482
3483	/* Save the central directory offset for later use. */
3484	zip->central_directory_offset = archive_le64dec(p + 48);
3485
3486	return 32;
3487}
3488
3489static int
3490archive_read_format_zip_seekable_bid(struct archive_read *a, int best_bid)
3491{
3492	struct zip *zip = (struct zip *)a->format->data;
3493	int64_t file_size, current_offset;
3494	const char *p;
3495	int i, tail;
3496
3497	/* If someone has already bid more than 32, then avoid
3498	   trashing the look-ahead buffers with a seek. */
3499	if (best_bid > 32)
3500		return (-1);
3501
3502	file_size = __archive_read_seek(a, 0, SEEK_END);
3503	if (file_size <= 0)
3504		return 0;
3505
3506	/* Search last 16k of file for end-of-central-directory
3507	 * record (which starts with PK\005\006) */
3508	tail = (int)zipmin(1024 * 16, file_size);
3509	current_offset = __archive_read_seek(a, -tail, SEEK_END);
3510	if (current_offset < 0)
3511		return 0;
3512	if ((p = __archive_read_ahead(a, (size_t)tail, NULL)) == NULL)
3513		return 0;
3514	/* Boyer-Moore search backwards from the end, since we want
3515	 * to match the last EOCD in the file (there can be more than
3516	 * one if there is an uncompressed Zip archive as a member
3517	 * within this Zip archive). */
3518	for (i = tail - 22; i > 0;) {
3519		switch (p[i]) {
3520		case 'P':
3521			if (memcmp(p + i, "PK\005\006", 4) == 0) {
3522				int ret = read_eocd(zip, p + i,
3523				    current_offset + i);
3524				/* Zip64 EOCD locator precedes
3525				 * regular EOCD if present. */
3526				if (i >= 20 && memcmp(p + i - 20, "PK\006\007", 4) == 0) {
3527					int ret_zip64 = read_zip64_eocd(a, zip, p + i - 20);
3528					if (ret_zip64 > ret)
3529						ret = ret_zip64;
3530				}
3531				return (ret);
3532			}
3533			i -= 4;
3534			break;
3535		case 'K': i -= 1; break;
3536		case 005: i -= 2; break;
3537		case 006: i -= 3; break;
3538		default: i -= 4; break;
3539		}
3540	}
3541	return 0;
3542}
3543
3544/* The red-black trees are only used in seeking mode to manage
3545 * the in-memory copy of the central directory. */
3546
3547static int
3548cmp_node(const struct archive_rb_node *n1, const struct archive_rb_node *n2)
3549{
3550	const struct zip_entry *e1 = (const struct zip_entry *)n1;
3551	const struct zip_entry *e2 = (const struct zip_entry *)n2;
3552
3553	if (e1->local_header_offset > e2->local_header_offset)
3554		return -1;
3555	if (e1->local_header_offset < e2->local_header_offset)
3556		return 1;
3557	return 0;
3558}
3559
3560static int
3561cmp_key(const struct archive_rb_node *n, const void *key)
3562{
3563	/* This function won't be called */
3564	(void)n; /* UNUSED */
3565	(void)key; /* UNUSED */
3566	return 1;
3567}
3568
3569static const struct archive_rb_tree_ops rb_ops = {
3570	&cmp_node, &cmp_key
3571};
3572
3573static int
3574rsrc_cmp_node(const struct archive_rb_node *n1,
3575    const struct archive_rb_node *n2)
3576{
3577	const struct zip_entry *e1 = (const struct zip_entry *)n1;
3578	const struct zip_entry *e2 = (const struct zip_entry *)n2;
3579
3580	return (strcmp(e2->rsrcname.s, e1->rsrcname.s));
3581}
3582
3583static int
3584rsrc_cmp_key(const struct archive_rb_node *n, const void *key)
3585{
3586	const struct zip_entry *e = (const struct zip_entry *)n;
3587	return (strcmp((const char *)key, e->rsrcname.s));
3588}
3589
3590static const struct archive_rb_tree_ops rb_rsrc_ops = {
3591	&rsrc_cmp_node, &rsrc_cmp_key
3592};
3593
3594static const char *
3595rsrc_basename(const char *name, size_t name_length)
3596{
3597	const char *s, *r;
3598
3599	r = s = name;
3600	for (;;) {
3601		s = memchr(s, '/', name_length - (s - name));
3602		if (s == NULL)
3603			break;
3604		r = ++s;
3605	}
3606	return (r);
3607}
3608
3609static void
3610expose_parent_dirs(struct zip *zip, const char *name, size_t name_length)
3611{
3612	struct archive_string str;
3613	struct zip_entry *dir;
3614	char *s;
3615
3616	archive_string_init(&str);
3617	archive_strncpy(&str, name, name_length);
3618	for (;;) {
3619		s = strrchr(str.s, '/');
3620		if (s == NULL)
3621			break;
3622		*s = '\0';
3623		/* Transfer the parent directory from zip->tree_rsrc RB
3624		 * tree to zip->tree RB tree to expose. */
3625		dir = (struct zip_entry *)
3626		    __archive_rb_tree_find_node(&zip->tree_rsrc, str.s);
3627		if (dir == NULL)
3628			break;
3629		__archive_rb_tree_remove_node(&zip->tree_rsrc, &dir->node);
3630		archive_string_free(&dir->rsrcname);
3631		__archive_rb_tree_insert_node(&zip->tree, &dir->node);
3632	}
3633	archive_string_free(&str);
3634}
3635
3636static int
3637slurp_central_directory(struct archive_read *a, struct archive_entry* entry,
3638    struct zip *zip)
3639{
3640	ssize_t i;
3641	unsigned found;
3642	int64_t correction;
3643	ssize_t bytes_avail;
3644	const char *p;
3645
3646	/*
3647	 * Find the start of the central directory.  The end-of-CD
3648	 * record has our starting point, but there are lots of
3649	 * Zip archives which have had other data prepended to the
3650	 * file, which makes the recorded offsets all too small.
3651	 * So we search forward from the specified offset until we
3652	 * find the real start of the central directory.  Then we
3653	 * know the correction we need to apply to account for leading
3654	 * padding.
3655	 */
3656	if (__archive_read_seek(a, zip->central_directory_offset, SEEK_SET) < 0)
3657		return ARCHIVE_FATAL;
3658
3659	found = 0;
3660	while (!found) {
3661		if ((p = __archive_read_ahead(a, 20, &bytes_avail)) == NULL)
3662			return ARCHIVE_FATAL;
3663		for (found = 0, i = 0; !found && i < bytes_avail - 4;) {
3664			switch (p[i + 3]) {
3665			case 'P': i += 3; break;
3666			case 'K': i += 2; break;
3667			case 001: i += 1; break;
3668			case 002:
3669				if (memcmp(p + i, "PK\001\002", 4) == 0) {
3670					p += i;
3671					found = 1;
3672				} else
3673					i += 4;
3674				break;
3675			case 005: i += 1; break;
3676			case 006:
3677				if (memcmp(p + i, "PK\005\006", 4) == 0) {
3678					p += i;
3679					found = 1;
3680				} else if (memcmp(p + i, "PK\006\006", 4) == 0) {
3681					p += i;
3682					found = 1;
3683				} else
3684					i += 1;
3685				break;
3686			default: i += 4; break;
3687			}
3688		}
3689		__archive_read_consume(a, i);
3690	}
3691	correction = archive_filter_bytes(&a->archive, 0)
3692			- zip->central_directory_offset;
3693
3694	__archive_rb_tree_init(&zip->tree, &rb_ops);
3695	__archive_rb_tree_init(&zip->tree_rsrc, &rb_rsrc_ops);
3696
3697	zip->central_directory_entries_total = 0;
3698	while (1) {
3699		struct zip_entry *zip_entry;
3700		size_t filename_length, extra_length, comment_length;
3701		uint32_t external_attributes;
3702		const char *name, *r;
3703
3704		if ((p = __archive_read_ahead(a, 4, NULL)) == NULL)
3705			return ARCHIVE_FATAL;
3706		if (memcmp(p, "PK\006\006", 4) == 0
3707		    || memcmp(p, "PK\005\006", 4) == 0) {
3708			break;
3709		} else if (memcmp(p, "PK\001\002", 4) != 0) {
3710			archive_set_error(&a->archive,
3711			    -1, "Invalid central directory signature");
3712			return ARCHIVE_FATAL;
3713		}
3714		if ((p = __archive_read_ahead(a, 46, NULL)) == NULL)
3715			return ARCHIVE_FATAL;
3716
3717		zip_entry = calloc(1, sizeof(struct zip_entry));
3718		if (zip_entry == NULL) {
3719			archive_set_error(&a->archive, ENOMEM,
3720				"Can't allocate zip entry");
3721			return ARCHIVE_FATAL;
3722		}
3723		zip_entry->next = zip->zip_entries;
3724		zip_entry->flags |= LA_FROM_CENTRAL_DIRECTORY;
3725		zip->zip_entries = zip_entry;
3726		zip->central_directory_entries_total++;
3727
3728		/* version = p[4]; */
3729		zip_entry->system = p[5];
3730		/* version_required = archive_le16dec(p + 6); */
3731		zip_entry->zip_flags = archive_le16dec(p + 8);
3732		if (zip_entry->zip_flags
3733		      & (ZIP_ENCRYPTED | ZIP_STRONG_ENCRYPTED)){
3734			zip->has_encrypted_entries = 1;
3735		}
3736		zip_entry->compression = (char)archive_le16dec(p + 10);
3737		zip_entry->mtime = zip_time(p + 12);
3738		zip_entry->crc32 = archive_le32dec(p + 16);
3739		if (zip_entry->zip_flags & ZIP_LENGTH_AT_END)
3740			zip_entry->decdat = p[13];
3741		else
3742			zip_entry->decdat = p[19];
3743		zip_entry->compressed_size = archive_le32dec(p + 20);
3744		zip_entry->uncompressed_size = archive_le32dec(p + 24);
3745		filename_length = archive_le16dec(p + 28);
3746		extra_length = archive_le16dec(p + 30);
3747		comment_length = archive_le16dec(p + 32);
3748		/* disk_start = archive_le16dec(p + 34);
3749		 *   Better be zero.
3750		 * internal_attributes = archive_le16dec(p + 36);
3751		 *   text bit */
3752		external_attributes = archive_le32dec(p + 38);
3753		zip_entry->local_header_offset =
3754		    archive_le32dec(p + 42) + correction;
3755
3756		/* If we can't guess the mode, leave it zero here;
3757		   when we read the local file header we might get
3758		   more information. */
3759		if (zip_entry->system == 3) {
3760			zip_entry->mode = external_attributes >> 16;
3761		} else if (zip_entry->system == 0) {
3762			// Interpret MSDOS directory bit
3763			if (0x10 == (external_attributes & 0x10)) {
3764				zip_entry->mode = AE_IFDIR | 0775;
3765			} else {
3766				zip_entry->mode = AE_IFREG | 0664;
3767			}
3768			if (0x01 == (external_attributes & 0x01)) {
3769				// Read-only bit; strip write permissions
3770				zip_entry->mode &= 0555;
3771			}
3772		} else {
3773			zip_entry->mode = 0;
3774		}
3775
3776		/* We're done with the regular data; get the filename and
3777		 * extra data. */
3778		__archive_read_consume(a, 46);
3779		p = __archive_read_ahead(a, filename_length + extra_length,
3780			NULL);
3781		if (p == NULL) {
3782			archive_set_error(&a->archive,
3783			    ARCHIVE_ERRNO_FILE_FORMAT,
3784			    "Truncated ZIP file header");
3785			return ARCHIVE_FATAL;
3786		}
3787		if (ARCHIVE_OK != process_extra(a, entry, p + filename_length,
3788		    extra_length, zip_entry)) {
3789			return ARCHIVE_FATAL;
3790		}
3791
3792		/*
3793		 * Mac resource fork files are stored under the
3794		 * "__MACOSX/" directory, so we should check if
3795		 * it is.
3796		 */
3797		if (!zip->process_mac_extensions) {
3798			/* Treat every entry as a regular entry. */
3799			__archive_rb_tree_insert_node(&zip->tree,
3800			    &zip_entry->node);
3801		} else {
3802			name = p;
3803			r = rsrc_basename(name, filename_length);
3804			if (filename_length >= 9 &&
3805			    strncmp("__MACOSX/", name, 9) == 0) {
3806				/* If this file is not a resource fork nor
3807				 * a directory. We should treat it as a non
3808				 * resource fork file to expose it. */
3809				if (name[filename_length-1] != '/' &&
3810				    (r - name < 3 || r[0] != '.' ||
3811				     r[1] != '_')) {
3812					__archive_rb_tree_insert_node(
3813					    &zip->tree, &zip_entry->node);
3814					/* Expose its parent directories. */
3815					expose_parent_dirs(zip, name,
3816					    filename_length);
3817				} else {
3818					/* This file is a resource fork file or
3819					 * a directory. */
3820					archive_strncpy(&(zip_entry->rsrcname),
3821					     name, filename_length);
3822					__archive_rb_tree_insert_node(
3823					    &zip->tree_rsrc, &zip_entry->node);
3824				}
3825			} else {
3826				/* Generate resource fork name to find its
3827				 * resource file at zip->tree_rsrc. */
3828				archive_strcpy(&(zip_entry->rsrcname),
3829				    "__MACOSX/");
3830				archive_strncat(&(zip_entry->rsrcname),
3831				    name, r - name);
3832				archive_strcat(&(zip_entry->rsrcname), "._");
3833				archive_strncat(&(zip_entry->rsrcname),
3834				    name + (r - name),
3835				    filename_length - (r - name));
3836				/* Register an entry to RB tree to sort it by
3837				 * file offset. */
3838				__archive_rb_tree_insert_node(&zip->tree,
3839				    &zip_entry->node);
3840			}
3841		}
3842
3843		/* Skip the comment too ... */
3844		__archive_read_consume(a,
3845		    filename_length + extra_length + comment_length);
3846	}
3847
3848	return ARCHIVE_OK;
3849}
3850
3851static ssize_t
3852zip_get_local_file_header_size(struct archive_read *a, size_t extra)
3853{
3854	const char *p;
3855	ssize_t filename_length, extra_length;
3856
3857	if ((p = __archive_read_ahead(a, extra + 30, NULL)) == NULL) {
3858		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3859		    "Truncated ZIP file header");
3860		return (ARCHIVE_WARN);
3861	}
3862	p += extra;
3863
3864	if (memcmp(p, "PK\003\004", 4) != 0) {
3865		archive_set_error(&a->archive, -1, "Damaged Zip archive");
3866		return ARCHIVE_WARN;
3867	}
3868	filename_length = archive_le16dec(p + 26);
3869	extra_length = archive_le16dec(p + 28);
3870
3871	return (30 + filename_length + extra_length);
3872}
3873
3874static int
3875zip_read_mac_metadata(struct archive_read *a, struct archive_entry *entry,
3876    struct zip_entry *rsrc)
3877{
3878	struct zip *zip = (struct zip *)a->format->data;
3879	unsigned char *metadata, *mp;
3880	int64_t offset = archive_filter_bytes(&a->archive, 0);
3881	size_t remaining_bytes, metadata_bytes;
3882	ssize_t hsize;
3883	int ret = ARCHIVE_OK, eof;
3884
3885	switch(rsrc->compression) {
3886	case 0:  /* No compression. */
3887		if (rsrc->uncompressed_size != rsrc->compressed_size) {
3888			archive_set_error(&a->archive,
3889			    ARCHIVE_ERRNO_FILE_FORMAT,
3890			    "Malformed OS X metadata entry: "
3891			    "inconsistent size");
3892			return (ARCHIVE_FATAL);
3893		}
3894#ifdef HAVE_ZLIB_H
3895	case 8: /* Deflate compression. */
3896#endif
3897		break;
3898	default: /* Unsupported compression. */
3899		/* Return a warning. */
3900		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3901		    "Unsupported ZIP compression method (%s)",
3902		    compression_name(rsrc->compression));
3903		/* We can't decompress this entry, but we will
3904		 * be able to skip() it and try the next entry. */
3905		return (ARCHIVE_WARN);
3906	}
3907
3908	if (rsrc->uncompressed_size > (4 * 1024 * 1024)) {
3909		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3910		    "Mac metadata is too large: %jd > 4M bytes",
3911		    (intmax_t)rsrc->uncompressed_size);
3912		return (ARCHIVE_WARN);
3913	}
3914	if (rsrc->compressed_size > (4 * 1024 * 1024)) {
3915		archive_set_error(&a->archive, ARCHIVE_ERRNO_FILE_FORMAT,
3916		    "Mac metadata is too large: %jd > 4M bytes",
3917		    (intmax_t)rsrc->compressed_size);
3918		return (ARCHIVE_WARN);
3919	}
3920
3921	metadata = malloc((size_t)rsrc->uncompressed_size);
3922	if (metadata == NULL) {
3923		archive_set_error(&a->archive, ENOMEM,
3924		    "Can't allocate memory for Mac metadata");
3925		return (ARCHIVE_FATAL);
3926	}
3927
3928	if (offset < rsrc->local_header_offset)
3929		__archive_read_consume(a, rsrc->local_header_offset - offset);
3930	else if (offset != rsrc->local_header_offset) {
3931		__archive_read_seek(a, rsrc->local_header_offset, SEEK_SET);
3932	}
3933
3934	hsize = zip_get_local_file_header_size(a, 0);
3935	__archive_read_consume(a, hsize);
3936
3937	remaining_bytes = (size_t)rsrc->compressed_size;
3938	metadata_bytes = (size_t)rsrc->uncompressed_size;
3939	mp = metadata;
3940	eof = 0;
3941	while (!eof && remaining_bytes) {
3942		const unsigned char *p;
3943		ssize_t bytes_avail;
3944		size_t bytes_used;
3945
3946		p = __archive_read_ahead(a, 1, &bytes_avail);
3947		if (p == NULL) {
3948			archive_set_error(&a->archive,
3949			    ARCHIVE_ERRNO_FILE_FORMAT,
3950			    "Truncated ZIP file header");
3951			ret = ARCHIVE_WARN;
3952			goto exit_mac_metadata;
3953		}
3954		if ((size_t)bytes_avail > remaining_bytes)
3955			bytes_avail = remaining_bytes;
3956		switch(rsrc->compression) {
3957		case 0:  /* No compression. */
3958			if ((size_t)bytes_avail > metadata_bytes)
3959				bytes_avail = metadata_bytes;
3960			memcpy(mp, p, bytes_avail);
3961			bytes_used = (size_t)bytes_avail;
3962			metadata_bytes -= bytes_used;
3963			mp += bytes_used;
3964			if (metadata_bytes == 0)
3965				eof = 1;
3966			break;
3967#ifdef HAVE_ZLIB_H
3968		case 8: /* Deflate compression. */
3969		{
3970			int r;
3971
3972			ret = zip_deflate_init(a, zip);
3973			if (ret != ARCHIVE_OK)
3974				goto exit_mac_metadata;
3975			zip->stream.next_in =
3976			    (Bytef *)(uintptr_t)(const void *)p;
3977			zip->stream.avail_in = (uInt)bytes_avail;
3978			zip->stream.total_in = 0;
3979			zip->stream.next_out = mp;
3980			zip->stream.avail_out = (uInt)metadata_bytes;
3981			zip->stream.total_out = 0;
3982
3983			r = inflate(&zip->stream, 0);
3984			switch (r) {
3985			case Z_OK:
3986				break;
3987			case Z_STREAM_END:
3988				eof = 1;
3989				break;
3990			case Z_MEM_ERROR:
3991				archive_set_error(&a->archive, ENOMEM,
3992				    "Out of memory for ZIP decompression");
3993				ret = ARCHIVE_FATAL;
3994				goto exit_mac_metadata;
3995			default:
3996				archive_set_error(&a->archive,
3997				    ARCHIVE_ERRNO_MISC,
3998				    "ZIP decompression failed (%d)", r);
3999				ret = ARCHIVE_FATAL;
4000				goto exit_mac_metadata;
4001			}
4002			bytes_used = zip->stream.total_in;
4003			metadata_bytes -= zip->stream.total_out;
4004			mp += zip->stream.total_out;
4005			break;
4006		}
4007#endif
4008		default:
4009			bytes_used = 0;
4010			break;
4011		}
4012		__archive_read_consume(a, bytes_used);
4013		remaining_bytes -= bytes_used;
4014	}
4015	archive_entry_copy_mac_metadata(entry, metadata,
4016	    (size_t)rsrc->uncompressed_size - metadata_bytes);
4017
4018exit_mac_metadata:
4019	__archive_read_seek(a, offset, SEEK_SET);
4020	zip->decompress_init = 0;
4021	free(metadata);
4022	return (ret);
4023}
4024
4025static int
4026archive_read_format_zip_seekable_read_header(struct archive_read *a,
4027	struct archive_entry *entry)
4028{
4029	struct zip *zip = (struct zip *)a->format->data;
4030	struct zip_entry *rsrc;
4031	int64_t offset;
4032	int r, ret = ARCHIVE_OK;
4033
4034	/*
4035	 * It should be sufficient to call archive_read_next_header() for
4036	 * a reader to determine if an entry is encrypted or not. If the
4037	 * encryption of an entry is only detectable when calling
4038	 * archive_read_data(), so be it. We'll do the same check there
4039	 * as well.
4040	 */
4041	if (zip->has_encrypted_entries ==
4042			ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW)
4043		zip->has_encrypted_entries = 0;
4044
4045	a->archive.archive_format = ARCHIVE_FORMAT_ZIP;
4046	if (a->archive.archive_format_name == NULL)
4047		a->archive.archive_format_name = "ZIP";
4048
4049	if (zip->zip_entries == NULL) {
4050		r = slurp_central_directory(a, entry, zip);
4051		if (r != ARCHIVE_OK)
4052			return r;
4053		/* Get first entry whose local header offset is lower than
4054		 * other entries in the archive file. */
4055		zip->entry =
4056		    (struct zip_entry *)ARCHIVE_RB_TREE_MIN(&zip->tree);
4057	} else if (zip->entry != NULL) {
4058		/* Get next entry in local header offset order. */
4059		zip->entry = (struct zip_entry *)__archive_rb_tree_iterate(
4060		    &zip->tree, &zip->entry->node, ARCHIVE_RB_DIR_RIGHT);
4061	}
4062
4063	if (zip->entry == NULL)
4064		return ARCHIVE_EOF;
4065
4066	if (zip->entry->rsrcname.s)
4067		rsrc = (struct zip_entry *)__archive_rb_tree_find_node(
4068		    &zip->tree_rsrc, zip->entry->rsrcname.s);
4069	else
4070		rsrc = NULL;
4071
4072	if (zip->cctx_valid)
4073		archive_decrypto_aes_ctr_release(&zip->cctx);
4074	if (zip->hctx_valid)
4075		archive_hmac_sha1_cleanup(&zip->hctx);
4076	zip->tctx_valid = zip->cctx_valid = zip->hctx_valid = 0;
4077	__archive_read_reset_passphrase(a);
4078
4079	/* File entries are sorted by the header offset, we should mostly
4080	 * use __archive_read_consume to advance a read point to avoid
4081	 * redundant data reading.  */
4082	offset = archive_filter_bytes(&a->archive, 0);
4083	if (offset < zip->entry->local_header_offset)
4084		__archive_read_consume(a,
4085		    zip->entry->local_header_offset - offset);
4086	else if (offset != zip->entry->local_header_offset) {
4087		__archive_read_seek(a, zip->entry->local_header_offset,
4088		    SEEK_SET);
4089	}
4090	zip->unconsumed = 0;
4091	r = zip_read_local_file_header(a, entry, zip);
4092	if (r != ARCHIVE_OK)
4093		return r;
4094	if (rsrc) {
4095		int ret2 = zip_read_mac_metadata(a, entry, rsrc);
4096		if (ret2 < ret)
4097			ret = ret2;
4098	}
4099	return (ret);
4100}
4101
4102/*
4103 * We're going to seek for the next header anyway, so we don't
4104 * need to bother doing anything here.
4105 */
4106static int
4107archive_read_format_zip_read_data_skip_seekable(struct archive_read *a)
4108{
4109	struct zip *zip;
4110	zip = (struct zip *)(a->format->data);
4111
4112	zip->unconsumed = 0;
4113	return (ARCHIVE_OK);
4114}
4115
4116int
4117archive_read_support_format_zip_seekable(struct archive *_a)
4118{
4119	struct archive_read *a = (struct archive_read *)_a;
4120	struct zip *zip;
4121	int r;
4122
4123	archive_check_magic(_a, ARCHIVE_READ_MAGIC,
4124	    ARCHIVE_STATE_NEW, "archive_read_support_format_zip_seekable");
4125
4126	zip = (struct zip *)calloc(1, sizeof(*zip));
4127	if (zip == NULL) {
4128		archive_set_error(&a->archive, ENOMEM,
4129		    "Can't allocate zip data");
4130		return (ARCHIVE_FATAL);
4131	}
4132
4133#ifdef HAVE_COPYFILE_H
4134	/* Set this by default on Mac OS. */
4135	zip->process_mac_extensions = 1;
4136#endif
4137
4138	/*
4139	 * Until enough data has been read, we cannot tell about
4140	 * any encrypted entries yet.
4141	 */
4142	zip->has_encrypted_entries = ARCHIVE_READ_FORMAT_ENCRYPTION_DONT_KNOW;
4143	zip->crc32func = real_crc32;
4144
4145	r = __archive_read_register_format(a,
4146	    zip,
4147	    "zip",
4148	    archive_read_format_zip_seekable_bid,
4149	    archive_read_format_zip_options,
4150	    archive_read_format_zip_seekable_read_header,
4151	    archive_read_format_zip_read_data,
4152	    archive_read_format_zip_read_data_skip_seekable,
4153	    NULL,
4154	    archive_read_format_zip_cleanup,
4155	    archive_read_support_format_zip_capabilities_seekable,
4156	    archive_read_format_zip_has_encrypted_entries);
4157
4158	if (r != ARCHIVE_OK)
4159		free(zip);
4160	return (ARCHIVE_OK);
4161}
4162
4163/*# vim:set noet:*/
4164