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