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