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