blob: cbe1b14ae49a32bde8a7008331c3f0890a94f21e [file] [log] [blame]
Narayan Kamath7462f022013-11-21 13:05:04 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Read-only access to Zip archives, with minimal heap allocation.
19 */
Narayan Kamath7462f022013-11-21 13:05:04 +000020
21#include <assert.h>
22#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070023#include <fcntl.h>
24#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000025#include <limits.h>
26#include <log/log.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000027#include <stdlib.h>
28#include <string.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000029#include <unistd.h>
Mark Salyzyn51d562d2014-05-05 14:38:05 -070030#include <utils/Compat.h>
Narayan Kamatheaf98852013-12-11 14:51:51 +000031#include <utils/FileMap.h>
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +010032#include <vector>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070033#include <zlib.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000034
35#include <JNIHelp.h> // TEMP_FAILURE_RETRY may or may not be in unistd
36
Mark Salyzyn99ef9912014-03-14 14:26:22 -070037#include "ziparchive/zip_archive.h"
38
Narayan Kamath926973e2014-06-09 14:18:14 +010039// This is for windows. If we don't open a file in binary mode, weird
Narayan Kamath7462f022013-11-21 13:05:04 +000040// things will happen.
41#ifndef O_BINARY
42#define O_BINARY 0
43#endif
44
Narayan Kamath926973e2014-06-09 14:18:14 +010045#define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
46 TypeName(); \
47 TypeName(const TypeName&); \
48 void operator=(const TypeName&)
Narayan Kamath7462f022013-11-21 13:05:04 +000049
Narayan Kamath926973e2014-06-09 14:18:14 +010050// The "end of central directory" (EOCD) record. Each archive
51// contains exactly once such record which appears at the end of
52// the archive. It contains archive wide information like the
53// number of entries in the archive and the offset to the central
54// directory of the offset.
55struct EocdRecord {
56 static const uint32_t kSignature = 0x06054b50;
Narayan Kamath7462f022013-11-21 13:05:04 +000057
Narayan Kamath926973e2014-06-09 14:18:14 +010058 // End of central directory signature, should always be
59 // |kSignature|.
60 uint32_t eocd_signature;
61 // The number of the current "disk", i.e, the "disk" that this
62 // central directory is on.
63 //
64 // This implementation assumes that each archive spans a single
65 // disk only. i.e, that disk_num == 1.
66 uint16_t disk_num;
67 // The disk where the central directory starts.
68 //
69 // This implementation assumes that each archive spans a single
70 // disk only. i.e, that cd_start_disk == 1.
71 uint16_t cd_start_disk;
72 // The number of central directory records on this disk.
73 //
74 // This implementation assumes that each archive spans a single
75 // disk only. i.e, that num_records_on_disk == num_records.
76 uint16_t num_records_on_disk;
77 // The total number of central directory records.
78 uint16_t num_records;
79 // The size of the central directory (in bytes).
80 uint32_t cd_size;
81 // The offset of the start of the central directory, relative
82 // to the start of the file.
83 uint32_t cd_start_offset;
84 // Length of the central directory comment.
85 uint16_t comment_length;
86 private:
87 DISALLOW_IMPLICIT_CONSTRUCTORS(EocdRecord);
88} __attribute__((packed));
Narayan Kamath7462f022013-11-21 13:05:04 +000089
Narayan Kamath926973e2014-06-09 14:18:14 +010090// A structure representing the fixed length fields for a single
91// record in the central directory of the archive. In addition to
92// the fixed length fields listed here, each central directory
93// record contains a variable length "file_name" and "extra_field"
94// whose lengths are given by |file_name_length| and |extra_field_length|
95// respectively.
96struct CentralDirectoryRecord {
97 static const uint32_t kSignature = 0x02014b50;
Narayan Kamath7462f022013-11-21 13:05:04 +000098
Narayan Kamath926973e2014-06-09 14:18:14 +010099 // The start of record signature. Must be |kSignature|.
100 uint32_t record_signature;
101 // Tool version. Ignored by this implementation.
102 uint16_t version_made_by;
103 // Tool version. Ignored by this implementation.
104 uint16_t version_needed;
105 // The "general purpose bit flags" for this entry. The only
106 // flag value that we currently check for is the "data descriptor"
107 // flag.
108 uint16_t gpb_flags;
109 // The compression method for this entry, one of |kCompressStored|
110 // and |kCompressDeflated|.
111 uint16_t compression_method;
112 // The file modification time and date for this entry.
113 uint16_t last_mod_time;
114 uint16_t last_mod_date;
115 // The CRC-32 checksum for this entry.
116 uint32_t crc32;
117 // The compressed size (in bytes) of this entry.
118 uint32_t compressed_size;
119 // The uncompressed size (in bytes) of this entry.
120 uint32_t uncompressed_size;
121 // The length of the entry file name in bytes. The file name
122 // will appear immediately after this record.
123 uint16_t file_name_length;
124 // The length of the extra field info (in bytes). This data
125 // will appear immediately after the entry file name.
126 uint16_t extra_field_length;
127 // The length of the entry comment (in bytes). This data will
128 // appear immediately after the extra field.
129 uint16_t comment_length;
130 // The start disk for this entry. Ignored by this implementation).
131 uint16_t file_start_disk;
132 // File attributes. Ignored by this implementation.
133 uint16_t internal_file_attributes;
134 // File attributes. Ignored by this implementation.
135 uint32_t external_file_attributes;
136 // The offset to the local file header for this entry, from the
137 // beginning of this archive.
138 uint32_t local_file_header_offset;
139 private:
140 DISALLOW_IMPLICIT_CONSTRUCTORS(CentralDirectoryRecord);
141} __attribute__((packed));
Narayan Kamath7462f022013-11-21 13:05:04 +0000142
Narayan Kamath926973e2014-06-09 14:18:14 +0100143// The local file header for a given entry. This duplicates information
144// present in the central directory of the archive. It is an error for
145// the information here to be different from the central directory
146// information for a given entry.
147struct LocalFileHeader {
148 static const uint32_t kSignature = 0x04034b50;
Narayan Kamath7462f022013-11-21 13:05:04 +0000149
Narayan Kamath926973e2014-06-09 14:18:14 +0100150 // The local file header signature, must be |kSignature|.
151 uint32_t lfh_signature;
152 // Tool version. Ignored by this implementation.
153 uint16_t version_needed;
154 // The "general purpose bit flags" for this entry. The only
155 // flag value that we currently check for is the "data descriptor"
156 // flag.
157 uint16_t gpb_flags;
158 // The compression method for this entry, one of |kCompressStored|
159 // and |kCompressDeflated|.
160 uint16_t compression_method;
161 // The file modification time and date for this entry.
162 uint16_t last_mod_time;
163 uint16_t last_mod_date;
164 // The CRC-32 checksum for this entry.
165 uint32_t crc32;
166 // The compressed size (in bytes) of this entry.
167 uint32_t compressed_size;
168 // The uncompressed size (in bytes) of this entry.
169 uint32_t uncompressed_size;
170 // The length of the entry file name in bytes. The file name
171 // will appear immediately after this record.
172 uint16_t file_name_length;
173 // The length of the extra field info (in bytes). This data
174 // will appear immediately after the entry file name.
175 uint16_t extra_field_length;
176 private:
177 DISALLOW_IMPLICIT_CONSTRUCTORS(LocalFileHeader);
178} __attribute__((packed));
179
180struct DataDescriptor {
181 // The *optional* data descriptor start signature.
182 static const uint32_t kOptSignature = 0x08074b50;
183
184 // CRC-32 checksum of the entry.
185 uint32_t crc32;
186 // Compressed size of the entry.
187 uint32_t compressed_size;
188 // Uncompressed size of the entry.
189 uint32_t uncompressed_size;
190 private:
191 DISALLOW_IMPLICIT_CONSTRUCTORS(DataDescriptor);
192} __attribute__((packed));
193
194#undef DISALLOW_IMPLICIT_CONSTRUCTORS
195
Piotr Jastrzebskibd0a7482014-08-13 09:49:25 +0000196static const uint32_t kGPBDDFlagMask = 0x0008; // mask value that signifies that the entry has a DD
Narayan Kamath7462f022013-11-21 13:05:04 +0000197static const uint32_t kMaxErrorLen = 1024;
198
Narayan Kamath926973e2014-06-09 14:18:14 +0100199// The maximum size of a central directory or a file
200// comment in bytes.
201static const uint32_t kMaxCommentLen = 65535;
202
203// The maximum number of bytes to scan backwards for the EOCD start.
204static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
205
Narayan Kamath7462f022013-11-21 13:05:04 +0000206static const char* kErrorMessages[] = {
207 "Unknown return code.",
Narayan Kamatheb41ad22013-12-09 16:26:36 +0000208 "Iteration ended",
Narayan Kamath7462f022013-11-21 13:05:04 +0000209 "Zlib error",
210 "Invalid file",
211 "Invalid handle",
212 "Duplicate entries in archive",
213 "Empty archive",
214 "Entry not found",
215 "Invalid offset",
216 "Inconsistent information",
217 "Invalid entry name",
Narayan Kamatheb41ad22013-12-09 16:26:36 +0000218 "I/O Error",
Narayan Kamatheaf98852013-12-11 14:51:51 +0000219 "File mapping failed"
Narayan Kamath7462f022013-11-21 13:05:04 +0000220};
221
222static const int32_t kErrorMessageUpperBound = 0;
223
Narayan Kamatheb41ad22013-12-09 16:26:36 +0000224static const int32_t kIterationEnd = -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000225
226// We encountered a Zlib error when inflating a stream from this file.
227// Usually indicates file corruption.
228static const int32_t kZlibError = -2;
229
230// The input file cannot be processed as a zip archive. Usually because
231// it's too small, too large or does not have a valid signature.
232static const int32_t kInvalidFile = -3;
233
234// An invalid iteration / ziparchive handle was passed in as an input
235// argument.
236static const int32_t kInvalidHandle = -4;
237
238// The zip archive contained two (or possibly more) entries with the same
239// name.
240static const int32_t kDuplicateEntry = -5;
241
242// The zip archive contains no entries.
243static const int32_t kEmptyArchive = -6;
244
245// The specified entry was not found in the archive.
246static const int32_t kEntryNotFound = -7;
247
248// The zip archive contained an invalid local file header pointer.
249static const int32_t kInvalidOffset = -8;
250
251// The zip archive contained inconsistent entry information. This could
252// be because the central directory & local file header did not agree, or
253// if the actual uncompressed length or crc32 do not match their declared
254// values.
255static const int32_t kInconsistentInformation = -9;
256
257// An invalid entry name was encountered.
258static const int32_t kInvalidEntryName = -10;
259
Narayan Kamatheb41ad22013-12-09 16:26:36 +0000260// An I/O related system call (read, lseek, ftruncate, map) failed.
261static const int32_t kIoError = -11;
Narayan Kamath7462f022013-11-21 13:05:04 +0000262
Narayan Kamatheaf98852013-12-11 14:51:51 +0000263// We were not able to mmap the central directory or entry contents.
264static const int32_t kMmapFailed = -12;
Narayan Kamath7462f022013-11-21 13:05:04 +0000265
Narayan Kamatheaf98852013-12-11 14:51:51 +0000266static const int32_t kErrorMessageLowerBound = -13;
Narayan Kamath7462f022013-11-21 13:05:04 +0000267
Narayan Kamatheaf98852013-12-11 14:51:51 +0000268static const char kTempMappingFileName[] = "zip: ExtractFileToFile";
Narayan Kamath7462f022013-11-21 13:05:04 +0000269
270/*
271 * A Read-only Zip archive.
272 *
273 * We want "open" and "find entry by name" to be fast operations, and
274 * we want to use as little memory as possible. We memory-map the zip
275 * central directory, and load a hash table with pointers to the filenames
276 * (which aren't null-terminated). The other fields are at a fixed offset
277 * from the filename, so we don't need to extract those (but we do need
278 * to byte-read and endian-swap them every time we want them).
279 *
280 * It's possible that somebody has handed us a massive (~1GB) zip archive,
281 * so we can't expect to mmap the entire file.
282 *
283 * To speed comparisons when doing a lookup by name, we could make the mapping
284 * "private" (copy-on-write) and null-terminate the filenames after verifying
285 * the record structure. However, this requires a private mapping of
286 * every page that the Central Directory touches. Easier to tuck a copy
287 * of the string length into the hash table entry.
288 */
289struct ZipArchive {
290 /* open Zip archive */
Neil Fullerb1a113f2014-07-25 14:43:04 +0100291 const int fd;
Narayan Kamath7462f022013-11-21 13:05:04 +0000292
293 /* mapped central directory area */
294 off64_t directory_offset;
Narayan Kamatheaf98852013-12-11 14:51:51 +0000295 android::FileMap* directory_map;
Narayan Kamath7462f022013-11-21 13:05:04 +0000296
297 /* number of entries in the Zip archive */
298 uint16_t num_entries;
299
300 /*
301 * We know how many entries are in the Zip archive, so we can have a
302 * fixed-size hash table. We define a load factor of 0.75 and overallocat
303 * so the maximum number entries can never be higher than
304 * ((4 * UINT16_MAX) / 3 + 1) which can safely fit into a uint32_t.
305 */
306 uint32_t hash_table_size;
307 ZipEntryName* hash_table;
Neil Fullerb1a113f2014-07-25 14:43:04 +0100308
309 ZipArchive(const int fd) :
310 fd(fd),
311 directory_offset(0),
312 directory_map(NULL),
313 num_entries(0),
314 hash_table_size(0),
315 hash_table(NULL) {}
316
317 ~ZipArchive() {
318 if (fd >= 0) {
319 close(fd);
320 }
321
322 if (directory_map != NULL) {
323 directory_map->release();
324 }
325 free(hash_table);
326 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000327};
328
329// Returns 0 on success and negative values on failure.
Narayan Kamatheaf98852013-12-11 14:51:51 +0000330static android::FileMap* MapFileSegment(const int fd, const off64_t start,
331 const size_t length, const bool read_only,
332 const char* debug_file_name) {
333 android::FileMap* file_map = new android::FileMap;
334 const bool success = file_map->create(debug_file_name, fd, start, length, read_only);
335 if (!success) {
336 file_map->release();
337 return NULL;
Narayan Kamath7462f022013-11-21 13:05:04 +0000338 }
339
Narayan Kamatheaf98852013-12-11 14:51:51 +0000340 return file_map;
Narayan Kamath7462f022013-11-21 13:05:04 +0000341}
342
343static int32_t CopyFileToFile(int fd, uint8_t* begin, const uint32_t length, uint64_t *crc_out) {
344 static const uint32_t kBufSize = 32768;
345 uint8_t buf[kBufSize];
346
347 uint32_t count = 0;
348 uint64_t crc = 0;
Narayan Kamath58aaf462013-12-10 16:47:14 +0000349 while (count < length) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000350 uint32_t remaining = length - count;
351
352 // Safe conversion because kBufSize is narrow enough for a 32 bit signed
353 // value.
354 ssize_t get_size = (remaining > kBufSize) ? kBufSize : remaining;
355 ssize_t actual = TEMP_FAILURE_RETRY(read(fd, buf, get_size));
356
357 if (actual != get_size) {
Mark Salyzyn51d562d2014-05-05 14:38:05 -0700358 ALOGW("CopyFileToFile: copy read failed (" ZD " vs " ZD ")", actual, get_size);
Narayan Kamath7462f022013-11-21 13:05:04 +0000359 return kIoError;
360 }
361
362 memcpy(begin + count, buf, get_size);
363 crc = crc32(crc, buf, get_size);
364 count += get_size;
365 }
366
367 *crc_out = crc;
368
369 return 0;
370}
371
372/*
373 * Round up to the next highest power of 2.
374 *
375 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
376 */
377static uint32_t RoundUpPower2(uint32_t val) {
378 val--;
379 val |= val >> 1;
380 val |= val >> 2;
381 val |= val >> 4;
382 val |= val >> 8;
383 val |= val >> 16;
384 val++;
385
386 return val;
387}
388
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100389static uint32_t ComputeHash(const ZipEntryName& name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000390 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100391 uint16_t len = name.name_length;
392 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000393
394 while (len--) {
395 hash = hash * 31 + *str++;
396 }
397
398 return hash;
399}
400
401/*
402 * Convert a ZipEntry to a hash table index, verifying that it's in a
403 * valid range.
404 */
405static int64_t EntryToIndex(const ZipEntryName* hash_table,
406 const uint32_t hash_table_size,
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100407 const ZipEntryName& name) {
408 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000409
410 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
411 uint32_t ent = hash & (hash_table_size - 1);
412 while (hash_table[ent].name != NULL) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100413 if (hash_table[ent].name_length == name.name_length &&
414 memcmp(hash_table[ent].name, name.name, name.name_length) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000415 return ent;
416 }
417
418 ent = (ent + 1) & (hash_table_size - 1);
419 }
420
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100421 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000422 return kEntryNotFound;
423}
424
425/*
426 * Add a new entry to the hash table.
427 */
428static int32_t AddToHash(ZipEntryName *hash_table, const uint64_t hash_table_size,
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100429 const ZipEntryName& name) {
430 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000431 uint32_t ent = hash & (hash_table_size - 1);
432
433 /*
434 * We over-allocated the table, so we're guaranteed to find an empty slot.
435 * Further, we guarantee that the hashtable size is not 0.
436 */
437 while (hash_table[ent].name != NULL) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100438 if (hash_table[ent].name_length == name.name_length &&
439 memcmp(hash_table[ent].name, name.name, name.name_length) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000440 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100441 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000442 return kDuplicateEntry;
443 }
444 ent = (ent + 1) & (hash_table_size - 1);
445 }
446
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100447 hash_table[ent].name = name.name;
448 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000449 return 0;
450}
451
Narayan Kamath7462f022013-11-21 13:05:04 +0000452static int32_t MapCentralDirectory0(int fd, const char* debug_file_name,
453 ZipArchive* archive, off64_t file_length,
Narayan Kamath926973e2014-06-09 14:18:14 +0100454 off64_t read_amount, uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000455 const off64_t search_start = file_length - read_amount;
456
457 if (lseek64(fd, search_start, SEEK_SET) != search_start) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100458 ALOGW("Zip: seek %" PRId64 " failed: %s", static_cast<int64_t>(search_start),
459 strerror(errno));
Narayan Kamath7462f022013-11-21 13:05:04 +0000460 return kIoError;
461 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100462 ssize_t actual = TEMP_FAILURE_RETRY(
463 read(fd, scan_buffer, static_cast<size_t>(read_amount)));
464 if (actual != static_cast<ssize_t>(read_amount)) {
465 ALOGW("Zip: read %" PRId64 " failed: %s", static_cast<int64_t>(read_amount),
466 strerror(errno));
Narayan Kamath7462f022013-11-21 13:05:04 +0000467 return kIoError;
468 }
469
470 /*
471 * Scan backward for the EOCD magic. In an archive without a trailing
472 * comment, we'll find it on the first try. (We may want to consider
473 * doing an initial minimal read; if we don't find it, retry with a
474 * second read as above.)
475 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100476 int i = read_amount - sizeof(EocdRecord);
477 for (; i >= 0; i--) {
478 if (scan_buffer[i] == 0x50 &&
479 ((*reinterpret_cast<uint32_t*>(&scan_buffer[i])) == EocdRecord::kSignature)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000480 ALOGV("+++ Found EOCD at buf+%d", i);
481 break;
482 }
483 }
484 if (i < 0) {
485 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
486 return kInvalidFile;
487 }
488
489 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100490 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000491 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100492 * Verify that there's no trailing space at the end of the central directory
493 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000494 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100495 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord)
496 + eocd->comment_length;
497 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100498 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100499 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100500 return kInvalidFile;
501 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000502
Narayan Kamath926973e2014-06-09 14:18:14 +0100503 /*
504 * Grab the CD offset and size, and the number of entries in the
505 * archive and verify that they look reasonable.
506 */
507 if (eocd->cd_start_offset + eocd->cd_size > eocd_offset) {
508 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
509 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000510 return kInvalidOffset;
511 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100512 if (eocd->num_records == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000513 ALOGW("Zip: empty archive?");
514 return kEmptyArchive;
515 }
516
Narayan Kamath926973e2014-06-09 14:18:14 +0100517 ALOGV("+++ num_entries=%" PRIu32 "dir_size=%" PRIu32 " dir_offset=%" PRIu32,
518 eocd->num_records, eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000519
520 /*
521 * It all looks good. Create a mapping for the CD, and set the fields
522 * in archive.
523 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100524 android::FileMap* map = MapFileSegment(fd,
525 static_cast<off64_t>(eocd->cd_start_offset),
526 static_cast<size_t>(eocd->cd_size),
527 true /* read only */, debug_file_name);
Narayan Kamatheaf98852013-12-11 14:51:51 +0000528 if (map == NULL) {
529 archive->directory_map = NULL;
530 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000531 }
532
Narayan Kamatheaf98852013-12-11 14:51:51 +0000533 archive->directory_map = map;
Narayan Kamath926973e2014-06-09 14:18:14 +0100534 archive->num_entries = eocd->num_records;
535 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000536
537 return 0;
538}
539
540/*
541 * Find the zip Central Directory and memory-map it.
542 *
543 * On success, returns 0 after populating fields from the EOCD area:
544 * directory_offset
545 * directory_map
546 * num_entries
547 */
548static int32_t MapCentralDirectory(int fd, const char* debug_file_name,
549 ZipArchive* archive) {
550
551 // Test file length. We use lseek64 to make sure the file
552 // is small enough to be a zip file (Its size must be less than
553 // 0xffffffff bytes).
554 off64_t file_length = lseek64(fd, 0, SEEK_END);
555 if (file_length == -1) {
556 ALOGV("Zip: lseek on fd %d failed", fd);
557 return kInvalidFile;
558 }
559
560 if (file_length > (off64_t) 0xffffffff) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100561 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000562 return kInvalidFile;
563 }
564
Narayan Kamath926973e2014-06-09 14:18:14 +0100565 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
566 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000567 return kInvalidFile;
568 }
569
570 /*
571 * Perform the traditional EOCD snipe hunt.
572 *
573 * We're searching for the End of Central Directory magic number,
574 * which appears at the start of the EOCD block. It's followed by
575 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
576 * need to read the last part of the file into a buffer, dig through
577 * it to find the magic number, parse some values out, and use those
578 * to determine the extent of the CD.
579 *
580 * We start by pulling in the last part of the file.
581 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100582 off64_t read_amount = kMaxEOCDSearch;
583 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000584 read_amount = file_length;
585 }
586
Narayan Kamath926973e2014-06-09 14:18:14 +0100587 uint8_t* scan_buffer = reinterpret_cast<uint8_t*>(malloc(read_amount));
Narayan Kamath7462f022013-11-21 13:05:04 +0000588 int32_t result = MapCentralDirectory0(fd, debug_file_name, archive,
589 file_length, read_amount, scan_buffer);
590
591 free(scan_buffer);
592 return result;
593}
594
595/*
596 * Parses the Zip archive's Central Directory. Allocates and populates the
597 * hash table.
598 *
599 * Returns 0 on success.
600 */
601static int32_t ParseZipArchive(ZipArchive* archive) {
602 int32_t result = -1;
Narayan Kamath926973e2014-06-09 14:18:14 +0100603 const uint8_t* const cd_ptr = (const uint8_t*) archive->directory_map->getDataPtr();
604 const size_t cd_length = archive->directory_map->getDataLength();
605 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000606
607 /*
608 * Create hash table. We have a minimum 75% load factor, possibly as
609 * low as 50% after we round off to a power of 2. There must be at
610 * least one unused entry to avoid an infinite loop during creation.
611 */
612 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
613 archive->hash_table = (ZipEntryName*) calloc(archive->hash_table_size,
614 sizeof(ZipEntryName));
615
616 /*
617 * Walk through the central directory, adding entries to the hash
618 * table and verifying values.
619 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100620 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000621 const uint8_t* ptr = cd_ptr;
622 for (uint16_t i = 0; i < num_entries; i++) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100623 const CentralDirectoryRecord* cdr =
624 reinterpret_cast<const CentralDirectoryRecord*>(ptr);
625 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700626 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000627 goto bail;
628 }
629
Narayan Kamath926973e2014-06-09 14:18:14 +0100630 if (ptr + sizeof(CentralDirectoryRecord) > cd_end) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700631 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000632 goto bail;
633 }
634
Narayan Kamath926973e2014-06-09 14:18:14 +0100635 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000636 if (local_header_offset >= archive->directory_offset) {
Mark Salyzyn56a90a02014-05-08 17:20:55 -0700637 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16, (int64_t)local_header_offset, i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000638 goto bail;
639 }
640
Narayan Kamath926973e2014-06-09 14:18:14 +0100641 const uint16_t file_name_length = cdr->file_name_length;
642 const uint16_t extra_length = cdr->extra_field_length;
643 const uint16_t comment_length = cdr->comment_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000644
645 /* add the CDE filename to the hash table */
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100646 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
647 ZipEntryName entry_name;
648 entry_name.name = file_name;
649 entry_name.name_length = file_name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000650 const int add_result = AddToHash(archive->hash_table,
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100651 archive->hash_table_size, entry_name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000652 if (add_result) {
653 ALOGW("Zip: Error adding entry to hash table %d", add_result);
654 result = add_result;
655 goto bail;
656 }
657
Narayan Kamath926973e2014-06-09 14:18:14 +0100658 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
659 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700660 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16,
661 ptr - cd_ptr, cd_length, i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000662 goto bail;
663 }
664 }
Mark Salyzyn088bf902014-05-08 16:02:20 -0700665 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000666
667 result = 0;
668
669bail:
670 return result;
671}
672
673static int32_t OpenArchiveInternal(ZipArchive* archive,
674 const char* debug_file_name) {
675 int32_t result = -1;
676 if ((result = MapCentralDirectory(archive->fd, debug_file_name, archive))) {
677 return result;
678 }
679
680 if ((result = ParseZipArchive(archive))) {
681 return result;
682 }
683
684 return 0;
685}
686
687int32_t OpenArchiveFd(int fd, const char* debug_file_name,
688 ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100689 ZipArchive* archive = new ZipArchive(fd);
Narayan Kamath7462f022013-11-21 13:05:04 +0000690 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000691 return OpenArchiveInternal(archive, debug_file_name);
692}
693
694int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100695 const int fd = open(fileName, O_RDONLY | O_BINARY, 0);
696 ZipArchive* archive = new ZipArchive(fd);
Narayan Kamath7462f022013-11-21 13:05:04 +0000697 *handle = archive;
698
Narayan Kamath7462f022013-11-21 13:05:04 +0000699 if (fd < 0) {
700 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
701 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000702 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000703 return OpenArchiveInternal(archive, fileName);
704}
705
706/*
707 * Close a ZipArchive, closing the file and freeing the contents.
708 */
709void CloseArchive(ZipArchiveHandle handle) {
710 ZipArchive* archive = (ZipArchive*) handle;
711 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100712 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000713}
714
715static int32_t UpdateEntryFromDataDescriptor(int fd,
716 ZipEntry *entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100717 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Narayan Kamath7462f022013-11-21 13:05:04 +0000718 ssize_t actual = TEMP_FAILURE_RETRY(read(fd, ddBuf, sizeof(ddBuf)));
719 if (actual != sizeof(ddBuf)) {
720 return kIoError;
721 }
722
Narayan Kamath926973e2014-06-09 14:18:14 +0100723 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
724 const uint16_t offset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
725 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000726
Narayan Kamath926973e2014-06-09 14:18:14 +0100727 entry->crc32 = descriptor->crc32;
728 entry->compressed_length = descriptor->compressed_size;
729 entry->uncompressed_length = descriptor->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000730
731 return 0;
732}
733
734// Attempts to read |len| bytes into |buf| at offset |off|.
735//
736// This method uses pread64 on platforms that support it and
737// lseek64 + read on platforms that don't. This implies that
738// callers should not rely on the |fd| offset being incremented
739// as a side effect of this call.
740static inline ssize_t ReadAtOffset(int fd, uint8_t* buf, size_t len,
741 off64_t off) {
742#ifdef HAVE_PREAD
743 return TEMP_FAILURE_RETRY(pread64(fd, buf, len, off));
744#else
745 // The only supported platform that doesn't support pread at the moment
746 // is Windows. Only recent versions of windows support unix like forks,
747 // and even there the semantics are quite different.
748 if (lseek64(fd, off, SEEK_SET) != off) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700749 ALOGW("Zip: failed seek to offset %" PRId64, off);
Narayan Kamath7462f022013-11-21 13:05:04 +0000750 return kIoError;
751 }
752
753 return TEMP_FAILURE_RETRY(read(fd, buf, len));
754#endif // HAVE_PREAD
755}
756
757static int32_t FindEntry(const ZipArchive* archive, const int ent,
758 ZipEntry* data) {
759 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000760
761 // Recover the start of the central directory entry from the filename
762 // pointer. The filename is the first entry past the fixed-size data,
763 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100764 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100765 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000766
767 // This is the base of our mmapped region, we have to sanity check that
768 // the name that's in the hash table is a pointer to a location within
769 // this mapped region.
Narayan Kamath926973e2014-06-09 14:18:14 +0100770 const uint8_t* base_ptr = reinterpret_cast<const uint8_t*>(
771 archive->directory_map->getDataPtr());
Narayan Kamatheaf98852013-12-11 14:51:51 +0000772 if (ptr < base_ptr || ptr > base_ptr + archive->directory_map->getDataLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000773 ALOGW("Zip: Invalid entry pointer");
774 return kInvalidOffset;
775 }
776
Narayan Kamath926973e2014-06-09 14:18:14 +0100777 const CentralDirectoryRecord *cdr =
778 reinterpret_cast<const CentralDirectoryRecord*>(ptr);
779
Narayan Kamath7462f022013-11-21 13:05:04 +0000780 // The offset of the start of the central directory in the zipfile.
781 // We keep this lying around so that we can sanity check all our lengths
782 // and our per-file structures.
783 const off64_t cd_offset = archive->directory_offset;
784
785 // Fill out the compression method, modification time, crc32
786 // and other interesting attributes from the central directory. These
787 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100788 data->method = cdr->compression_method;
789 data->mod_time = cdr->last_mod_time;
790 data->crc32 = cdr->crc32;
791 data->compressed_length = cdr->compressed_size;
792 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000793
794 // Figure out the local header offset from the central directory. The
795 // actual file data will begin after the local header and the name /
796 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100797 const off64_t local_header_offset = cdr->local_file_header_offset;
798 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000799 ALOGW("Zip: bad local hdr offset in zip");
800 return kInvalidOffset;
801 }
802
Narayan Kamath926973e2014-06-09 14:18:14 +0100803 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Narayan Kamath7462f022013-11-21 13:05:04 +0000804 ssize_t actual = ReadAtOffset(archive->fd, lfh_buf, sizeof(lfh_buf),
805 local_header_offset);
806 if (actual != sizeof(lfh_buf)) {
Mark Salyzyn56a90a02014-05-08 17:20:55 -0700807 ALOGW("Zip: failed reading lfh name from offset %" PRId64, (int64_t)local_header_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000808 return kIoError;
809 }
810
Narayan Kamath926973e2014-06-09 14:18:14 +0100811 const LocalFileHeader *lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
812
813 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700814 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Narayan Kamath926973e2014-06-09 14:18:14 +0100815 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000816 return kInvalidOffset;
817 }
818
819 // Paranoia: Match the values specified in the local file header
820 // to those specified in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100821 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000822 data->has_data_descriptor = 0;
Narayan Kamath926973e2014-06-09 14:18:14 +0100823 if (data->compressed_length != lfh->compressed_size
824 || data->uncompressed_length != lfh->uncompressed_size
825 || data->crc32 != lfh->crc32) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700826 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32
827 ", %" PRIx32 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
Narayan Kamath7462f022013-11-21 13:05:04 +0000828 data->compressed_length, data->uncompressed_length, data->crc32,
Narayan Kamath926973e2014-06-09 14:18:14 +0100829 lfh->compressed_size, lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000830 return kInconsistentInformation;
831 }
832 } else {
833 data->has_data_descriptor = 1;
834 }
835
836 // Check that the local file header name matches the declared
837 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100838 if (lfh->file_name_length == nameLen) {
839 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
840 if (name_offset + lfh->file_name_length >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000841 ALOGW("Zip: Invalid declared length");
842 return kInvalidOffset;
843 }
844
845 uint8_t* name_buf = (uint8_t*) malloc(nameLen);
846 ssize_t actual = ReadAtOffset(archive->fd, name_buf, nameLen,
847 name_offset);
848
849 if (actual != nameLen) {
Mark Salyzyn56a90a02014-05-08 17:20:55 -0700850 ALOGW("Zip: failed reading lfh name from offset %" PRId64, (int64_t)name_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000851 free(name_buf);
852 return kIoError;
853 }
854
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100855 if (memcmp(archive->hash_table[ent].name, name_buf, nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000856 free(name_buf);
857 return kInconsistentInformation;
858 }
859
860 free(name_buf);
861 } else {
862 ALOGW("Zip: lfh name did not match central directory.");
863 return kInconsistentInformation;
864 }
865
Narayan Kamath926973e2014-06-09 14:18:14 +0100866 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader)
867 + lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000868 if (data_offset > cd_offset) {
Mark Salyzyn56a90a02014-05-08 17:20:55 -0700869 ALOGW("Zip: bad data offset %" PRId64 " in zip", (int64_t)data_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000870 return kInvalidOffset;
871 }
872
873 if ((off64_t)(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700874 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Mark Salyzyn56a90a02014-05-08 17:20:55 -0700875 (int64_t)data_offset, data->compressed_length, (int64_t)cd_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000876 return kInvalidOffset;
877 }
878
879 if (data->method == kCompressStored &&
880 (off64_t)(data_offset + data->uncompressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700881 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Mark Salyzyn96c5c992014-05-08 19:16:40 -0700882 (int64_t)data_offset, data->uncompressed_length, (int64_t)cd_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000883 return kInvalidOffset;
884 }
885
886 data->offset = data_offset;
887 return 0;
888}
889
890struct IterationHandle {
891 uint32_t position;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100892 std::vector<uint8_t> prefix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000893 ZipArchive* archive;
894};
895
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100896int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr,
897 const ZipEntryName* optional_prefix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000898 ZipArchive* archive = (ZipArchive *) handle;
899
900 if (archive == NULL || archive->hash_table == NULL) {
901 ALOGW("Zip: Invalid ZipArchiveHandle");
902 return kInvalidHandle;
903 }
904
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100905 IterationHandle* cookie = new IterationHandle();
Narayan Kamath7462f022013-11-21 13:05:04 +0000906 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000907 cookie->archive = archive;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100908 if (optional_prefix != NULL) {
909 cookie->prefix.insert(cookie->prefix.begin(),
910 optional_prefix->name,
911 optional_prefix->name + optional_prefix->name_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000912 }
913
914 *cookie_ptr = cookie ;
915 return 0;
916}
917
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100918void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100919 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100920}
921
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100922int32_t FindEntry(const ZipArchiveHandle handle, const ZipEntryName& entryName,
Narayan Kamath7462f022013-11-21 13:05:04 +0000923 ZipEntry* data) {
924 const ZipArchive* archive = (ZipArchive*) handle;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100925 if (entryName.name_length == 0) {
926 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000927 return kInvalidEntryName;
928 }
929
930 const int64_t ent = EntryToIndex(archive->hash_table,
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100931 archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000932
933 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100934 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000935 return ent;
936 }
937
938 return FindEntry(archive, ent, data);
939}
940
941int32_t Next(void* cookie, ZipEntry* data, ZipEntryName* name) {
942 IterationHandle* handle = (IterationHandle *) cookie;
943 if (handle == NULL) {
944 return kInvalidHandle;
945 }
946
947 ZipArchive* archive = handle->archive;
948 if (archive == NULL || archive->hash_table == NULL) {
949 ALOGW("Zip: Invalid ZipArchiveHandle");
950 return kInvalidHandle;
951 }
952
953 const uint32_t currentOffset = handle->position;
954 const uint32_t hash_table_length = archive->hash_table_size;
955 const ZipEntryName *hash_table = archive->hash_table;
956
957 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
958 if (hash_table[i].name != NULL &&
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100959 (handle->prefix.empty() ||
960 (memcmp(&(handle->prefix[0]), hash_table[i].name, handle->prefix.size()) == 0))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000961 handle->position = (i + 1);
962 const int error = FindEntry(archive, i, data);
963 if (!error) {
964 name->name = hash_table[i].name;
965 name->name_length = hash_table[i].name_length;
966 }
967
968 return error;
969 }
970 }
971
972 handle->position = 0;
973 return kIterationEnd;
974}
975
976static int32_t InflateToFile(int fd, const ZipEntry* entry,
977 uint8_t* begin, uint32_t length,
978 uint64_t* crc_out) {
979 int32_t result = -1;
980 const uint32_t kBufSize = 32768;
981 uint8_t read_buf[kBufSize];
982 uint8_t write_buf[kBufSize];
983 z_stream zstream;
984 int zerr;
985
986 /*
987 * Initialize the zlib stream struct.
988 */
989 memset(&zstream, 0, sizeof(zstream));
990 zstream.zalloc = Z_NULL;
991 zstream.zfree = Z_NULL;
992 zstream.opaque = Z_NULL;
993 zstream.next_in = NULL;
994 zstream.avail_in = 0;
995 zstream.next_out = (Bytef*) write_buf;
996 zstream.avail_out = kBufSize;
997 zstream.data_type = Z_UNKNOWN;
998
999 /*
1000 * Use the undocumented "negative window bits" feature to tell zlib
1001 * that there's no zlib header waiting for it.
1002 */
1003 zerr = inflateInit2(&zstream, -MAX_WBITS);
1004 if (zerr != Z_OK) {
1005 if (zerr == Z_VERSION_ERROR) {
1006 ALOGE("Installed zlib is not compatible with linked version (%s)",
1007 ZLIB_VERSION);
1008 } else {
1009 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
1010 }
1011
1012 return kZlibError;
1013 }
1014
1015 const uint32_t uncompressed_length = entry->uncompressed_length;
1016
1017 uint32_t compressed_length = entry->compressed_length;
1018 uint32_t write_count = 0;
1019 do {
1020 /* read as much as we can */
1021 if (zstream.avail_in == 0) {
Mark Salyzyn51d562d2014-05-05 14:38:05 -07001022 const ZD_TYPE getSize = (compressed_length > kBufSize) ? kBufSize : compressed_length;
1023 const ZD_TYPE actual = TEMP_FAILURE_RETRY(read(fd, read_buf, getSize));
Narayan Kamath7462f022013-11-21 13:05:04 +00001024 if (actual != getSize) {
Mark Salyzyn51d562d2014-05-05 14:38:05 -07001025 ALOGW("Zip: inflate read failed (" ZD " vs " ZD ")", actual, getSize);
Narayan Kamath7462f022013-11-21 13:05:04 +00001026 result = kIoError;
1027 goto z_bail;
1028 }
1029
1030 compressed_length -= getSize;
1031
1032 zstream.next_in = read_buf;
1033 zstream.avail_in = getSize;
1034 }
1035
1036 /* uncompress the data */
1037 zerr = inflate(&zstream, Z_NO_FLUSH);
1038 if (zerr != Z_OK && zerr != Z_STREAM_END) {
1039 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)",
1040 zerr, zstream.next_in, zstream.avail_in,
1041 zstream.next_out, zstream.avail_out);
1042 result = kZlibError;
1043 goto z_bail;
1044 }
1045
1046 /* write when we're full or when we're done */
1047 if (zstream.avail_out == 0 ||
1048 (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
1049 const size_t write_size = zstream.next_out - write_buf;
1050 // The file might have declared a bogus length.
1051 if (write_size + write_count > length) {
1052 goto z_bail;
1053 }
1054 memcpy(begin + write_count, write_buf, write_size);
1055 write_count += write_size;
1056
1057 zstream.next_out = write_buf;
1058 zstream.avail_out = kBufSize;
1059 }
1060 } while (zerr == Z_OK);
1061
1062 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
1063
1064 // stream.adler holds the crc32 value for such streams.
1065 *crc_out = zstream.adler;
1066
1067 if (zstream.total_out != uncompressed_length || compressed_length != 0) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001068 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")",
Narayan Kamath7462f022013-11-21 13:05:04 +00001069 zstream.total_out, uncompressed_length);
1070 result = kInconsistentInformation;
1071 goto z_bail;
1072 }
1073
1074 result = 0;
1075
1076z_bail:
1077 inflateEnd(&zstream); /* free up any allocated structures */
1078
1079 return result;
1080}
1081
1082int32_t ExtractToMemory(ZipArchiveHandle handle,
1083 ZipEntry* entry, uint8_t* begin, uint32_t size) {
1084 ZipArchive* archive = (ZipArchive*) handle;
1085 const uint16_t method = entry->method;
1086 off64_t data_offset = entry->offset;
1087
1088 if (lseek64(archive->fd, data_offset, SEEK_SET) != data_offset) {
Mark Salyzyn56a90a02014-05-08 17:20:55 -07001089 ALOGW("Zip: lseek to data at %" PRId64 " failed", (int64_t)data_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +00001090 return kIoError;
1091 }
1092
1093 // this should default to kUnknownCompressionMethod.
1094 int32_t return_value = -1;
1095 uint64_t crc = 0;
1096 if (method == kCompressStored) {
1097 return_value = CopyFileToFile(archive->fd, begin, size, &crc);
1098 } else if (method == kCompressDeflated) {
1099 return_value = InflateToFile(archive->fd, entry, begin, size, &crc);
1100 }
1101
1102 if (!return_value && entry->has_data_descriptor) {
1103 return_value = UpdateEntryFromDataDescriptor(archive->fd, entry);
1104 if (return_value) {
1105 return return_value;
1106 }
1107 }
1108
1109 // TODO: Fix this check by passing the right flags to inflate2 so that
1110 // it calculates the CRC for us.
1111 if (entry->crc32 != crc && false) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001112 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001113 return kInconsistentInformation;
1114 }
1115
1116 return return_value;
1117}
1118
1119int32_t ExtractEntryToFile(ZipArchiveHandle handle,
1120 ZipEntry* entry, int fd) {
1121 const int32_t declared_length = entry->uncompressed_length;
1122
Narayan Kamath00a258c2013-12-13 16:06:19 +00001123 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
1124 if (current_offset == -1) {
1125 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd,
1126 strerror(errno));
Narayan Kamath7462f022013-11-21 13:05:04 +00001127 return kIoError;
1128 }
1129
Narayan Kamath00a258c2013-12-13 16:06:19 +00001130 int result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
1131 if (result == -1) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -07001132 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
Mark Salyzyn56a90a02014-05-08 17:20:55 -07001133 (int64_t)(declared_length + current_offset), strerror(errno));
Narayan Kamath00a258c2013-12-13 16:06:19 +00001134 return kIoError;
1135 }
1136
Narayan Kamath48953a12014-01-24 12:32:39 +00001137 // Don't attempt to map a region of length 0. We still need the
1138 // ftruncate() though, since the API guarantees that we will truncate
1139 // the file to the end of the uncompressed output.
1140 if (declared_length == 0) {
1141 return 0;
1142 }
1143
Narayan Kamath00a258c2013-12-13 16:06:19 +00001144 android::FileMap* map = MapFileSegment(fd, current_offset, declared_length,
Narayan Kamatheaf98852013-12-11 14:51:51 +00001145 false, kTempMappingFileName);
1146 if (map == NULL) {
1147 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +00001148 }
1149
Narayan Kamatheaf98852013-12-11 14:51:51 +00001150 const int32_t error = ExtractToMemory(handle, entry,
1151 reinterpret_cast<uint8_t*>(map->getDataPtr()),
1152 map->getDataLength());
1153 map->release();
Narayan Kamath7462f022013-11-21 13:05:04 +00001154 return error;
1155}
1156
1157const char* ErrorCodeString(int32_t error_code) {
1158 if (error_code > kErrorMessageLowerBound && error_code < kErrorMessageUpperBound) {
1159 return kErrorMessages[error_code * -1];
1160 }
1161
1162 return kErrorMessages[0];
1163}
1164
1165int GetFileDescriptor(const ZipArchiveHandle handle) {
1166 return ((ZipArchive*) handle)->fd;
1167}
1168