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