HardenedBSD src tree
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4045 lines
113KB

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