blob: 6a3db6bee604727e3d6af5cfe50c9ccf40cc332f [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
Mark Salyzyncfd5b082016-10-17 14:28:00 -070021#define LOG_TAG "ziparchive"
22
Narayan Kamath7462f022013-11-21 13:05:04 +000023#include <assert.h>
24#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070025#include <fcntl.h>
26#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000027#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <stdlib.h>
29#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070030#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000031#include <unistd.h>
32
Dan Albert1ae07642015-04-09 14:11:18 -070033#include <memory>
34#include <vector>
35
Josh Gao1b496342018-07-17 11:08:48 -070036#if defined(__BIONIC__)
37#include <android/fdsan.h>
38#endif
39
Mark Salyzynff2dcd92016-09-28 15:54:45 -070040#include <android-base/file.h>
41#include <android-base/logging.h>
42#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
43#include <android-base/memory.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070044#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070045#include <log/log.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070046#include <utils/Compat.h>
47#include <utils/FileMap.h>
Christopher Ferrise6884ce2015-11-10 14:55:12 -080048#include "ziparchive/zip_archive.h"
Dan Albert1ae07642015-04-09 14:11:18 -070049#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000050
Narayan Kamath044bc8e2014-12-03 18:22:53 +000051#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070052#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080053#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070054
Dan Albert1ae07642015-04-09 14:11:18 -070055using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000056
Narayan Kamath162b7052017-06-05 13:21:12 +010057// Used to turn on crc checks - verify that the content CRC matches the values
58// specified in the local file header and the central directory.
59static const bool kCrcChecksEnabled = false;
60
Narayan Kamath926973e2014-06-09 14:18:14 +010061// This is for windows. If we don't open a file in binary mode, weird
Narayan Kamath7462f022013-11-21 13:05:04 +000062// things will happen.
63#ifndef O_BINARY
64#define O_BINARY 0
65#endif
66
Narayan Kamath926973e2014-06-09 14:18:14 +010067// The maximum number of bytes to scan backwards for the EOCD start.
68static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
69
Narayan Kamath7462f022013-11-21 13:05:04 +000070/*
71 * A Read-only Zip archive.
72 *
73 * We want "open" and "find entry by name" to be fast operations, and
74 * we want to use as little memory as possible. We memory-map the zip
75 * central directory, and load a hash table with pointers to the filenames
76 * (which aren't null-terminated). The other fields are at a fixed offset
77 * from the filename, so we don't need to extract those (but we do need
78 * to byte-read and endian-swap them every time we want them).
79 *
80 * It's possible that somebody has handed us a massive (~1GB) zip archive,
81 * so we can't expect to mmap the entire file.
82 *
83 * To speed comparisons when doing a lookup by name, we could make the mapping
84 * "private" (copy-on-write) and null-terminate the filenames after verifying
85 * the record structure. However, this requires a private mapping of
86 * every page that the Central Directory touches. Easier to tuck a copy
87 * of the string length into the hash table entry.
88 */
Narayan Kamath7462f022013-11-21 13:05:04 +000089
Narayan Kamath7462f022013-11-21 13:05:04 +000090/*
91 * Round up to the next highest power of 2.
92 *
93 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
94 */
95static uint32_t RoundUpPower2(uint32_t val) {
96 val--;
97 val |= val >> 1;
98 val |= val >> 2;
99 val |= val >> 4;
100 val |= val >> 8;
101 val |= val >> 16;
102 val++;
103
104 return val;
105}
106
Yusuke Sato07447542015-06-25 14:39:19 -0700107static uint32_t ComputeHash(const ZipString& name) {
Sebastian Pop1f93d712017-11-28 16:36:48 -0600108#if !defined(_WIN32)
109 return std::hash<std::string_view>{}(
110 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length));
111#else
112 // Remove this code path once the windows compiler knows how to compile the above statement.
Narayan Kamath7462f022013-11-21 13:05:04 +0000113 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100114 uint16_t len = name.name_length;
115 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000116
117 while (len--) {
118 hash = hash * 31 + *str++;
119 }
120
121 return hash;
Sebastian Pop1f93d712017-11-28 16:36:48 -0600122#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000123}
124
Zimuzo5a503ef2018-09-17 19:49:55 +0100125static bool isZipStringEqual(const uint8_t* start, const ZipString& zip_string,
126 const ZipStringOffset& zip_string_offset) {
127 const ZipString from_offset = zip_string_offset.GetZipString(start);
128 return from_offset == zip_string;
129}
130
131/**
132 * Returns offset of ZipString#name from the start of the central directory in the memory map.
133 * For valid ZipStrings contained in the zip archive mmap, 0 < offset < 0xffffff.
134 */
135static inline uint32_t GetOffset(const uint8_t* name, const uint8_t* start) {
136 CHECK_GT(name, start);
137 CHECK_LT(name, start + 0xffffff);
138 return static_cast<uint32_t>(name - start);
139}
140
Narayan Kamath7462f022013-11-21 13:05:04 +0000141/*
142 * Convert a ZipEntry to a hash table index, verifying that it's in a
143 * valid range.
144 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100145static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
146 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100147 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000148
149 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
150 uint32_t ent = hash & (hash_table_size - 1);
Zimuzo5a503ef2018-09-17 19:49:55 +0100151 while (hash_table[ent].name_offset != 0) {
152 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000153 return ent;
154 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000155 ent = (ent + 1) & (hash_table_size - 1);
156 }
157
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100158 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000159 return kEntryNotFound;
160}
161
162/*
163 * Add a new entry to the hash table.
164 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100165static int32_t AddToHash(ZipStringOffset* hash_table, const uint64_t hash_table_size,
166 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100167 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000168 uint32_t ent = hash & (hash_table_size - 1);
169
170 /*
171 * We over-allocated the table, so we're guaranteed to find an empty slot.
172 * Further, we guarantee that the hashtable size is not 0.
173 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100174 while (hash_table[ent].name_offset != 0) {
175 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000176 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100177 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000178 return kDuplicateEntry;
179 }
180 ent = (ent + 1) & (hash_table_size - 1);
181 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100182 hash_table[ent].name_offset = GetOffset(name.name, start);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100183 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000184 return 0;
185}
186
Josh Gaoabdfc242018-09-07 12:44:40 -0700187#if defined(__BIONIC__)
188uint64_t GetOwnerTag(const ZipArchive* archive) {
189 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
190 reinterpret_cast<uint64_t>(archive));
191}
192#endif
193
Josh Gao1b496342018-07-17 11:08:48 -0700194ZipArchive::ZipArchive(const int fd, bool assume_ownership)
195 : mapped_zip(fd),
196 close_file(assume_ownership),
197 directory_offset(0),
198 central_directory(),
199 directory_map(new android::FileMap()),
200 num_entries(0),
201 hash_table_size(0),
202 hash_table(nullptr) {
203#if defined(__BIONIC__)
204 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700205 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700206 }
207#endif
208}
209
210ZipArchive::ZipArchive(void* address, size_t length)
211 : mapped_zip(address, length),
212 close_file(false),
213 directory_offset(0),
214 central_directory(),
215 directory_map(new android::FileMap()),
216 num_entries(0),
217 hash_table_size(0),
218 hash_table(nullptr) {}
219
220ZipArchive::~ZipArchive() {
221 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
222#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700223 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700224#else
225 close(mapped_zip.GetFileDescriptor());
226#endif
227 }
228
229 free(hash_table);
230}
231
Tianjie Xu18c25922016-09-29 15:27:41 -0700232static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Zimuzo5a503ef2018-09-17 19:49:55 +0100233 off64_t file_length, off64_t read_amount,
234 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000235 const off64_t search_start = file_length - read_amount;
236
Jiyong Parkcd997e62017-06-30 17:23:33 +0900237 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
238 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
239 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000240 return kIoError;
241 }
242
243 /*
244 * Scan backward for the EOCD magic. In an archive without a trailing
245 * comment, we'll find it on the first try. (We may want to consider
246 * doing an initial minimal read; if we don't find it, retry with a
247 * second read as above.)
248 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100249 int i = read_amount - sizeof(EocdRecord);
250 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700251 if (scan_buffer[i] == 0x50) {
252 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
253 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
254 ALOGV("+++ Found EOCD at buf+%d", i);
255 break;
256 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000257 }
258 }
259 if (i < 0) {
260 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
261 return kInvalidFile;
262 }
263
264 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100265 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000266 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100267 * Verify that there's no trailing space at the end of the central directory
268 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000269 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900270 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100271 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100272 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100273 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100274 return kInvalidFile;
275 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000276
Narayan Kamath926973e2014-06-09 14:18:14 +0100277 /*
278 * Grab the CD offset and size, and the number of entries in the
279 * archive and verify that they look reasonable.
280 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700281 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100282 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900283 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700284#if defined(__ANDROID__)
285 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
286 android_errorWriteLog(0x534e4554, "31251826");
287 }
288#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000289 return kInvalidOffset;
290 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100291 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000292#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000293 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000294#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000295 return kEmptyArchive;
296 }
297
Jiyong Parkcd997e62017-06-30 17:23:33 +0900298 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
299 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000300
301 /*
302 * It all looks good. Create a mapping for the CD, and set the fields
303 * in archive.
304 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700305
306 if (!archive->InitializeCentralDirectory(debug_file_name,
307 static_cast<off64_t>(eocd->cd_start_offset),
308 static_cast<size_t>(eocd->cd_size))) {
309 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000310 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000311 }
312
Narayan Kamath926973e2014-06-09 14:18:14 +0100313 archive->num_entries = eocd->num_records;
314 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000315
316 return 0;
317}
318
319/*
320 * Find the zip Central Directory and memory-map it.
321 *
322 * On success, returns 0 after populating fields from the EOCD area:
323 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700324 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000325 * num_entries
326 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700327static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000328 // Test file length. We use lseek64 to make sure the file
329 // is small enough to be a zip file (Its size must be less than
330 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700331 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000332 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000333 return kInvalidFile;
334 }
335
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800336 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100337 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000338 return kInvalidFile;
339 }
340
Narayan Kamath926973e2014-06-09 14:18:14 +0100341 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
342 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000343 return kInvalidFile;
344 }
345
346 /*
347 * Perform the traditional EOCD snipe hunt.
348 *
349 * We're searching for the End of Central Directory magic number,
350 * which appears at the start of the EOCD block. It's followed by
351 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
352 * need to read the last part of the file into a buffer, dig through
353 * it to find the magic number, parse some values out, and use those
354 * to determine the extent of the CD.
355 *
356 * We start by pulling in the last part of the file.
357 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100358 off64_t read_amount = kMaxEOCDSearch;
359 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000360 read_amount = file_length;
361 }
362
Tianjie Xu18c25922016-09-29 15:27:41 -0700363 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900364 int32_t result =
365 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000366 return result;
367}
368
369/*
370 * Parses the Zip archive's Central Directory. Allocates and populates the
371 * hash table.
372 *
373 * Returns 0 on success.
374 */
375static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700376 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
377 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100378 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000379
380 /*
381 * Create hash table. We have a minimum 75% load factor, possibly as
382 * low as 50% after we round off to a power of 2. There must be at
383 * least one unused entry to avoid an infinite loop during creation.
384 */
385 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900386 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100387 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700388 if (archive->hash_table == nullptr) {
389 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
390 archive->hash_table_size, sizeof(ZipString));
391 return -1;
392 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000393
394 /*
395 * Walk through the central directory, adding entries to the hash
396 * table and verifying values.
397 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100398 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000399 const uint8_t* ptr = cd_ptr;
400 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700401 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
402 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
403#if defined(__ANDROID__)
404 android_errorWriteLog(0x534e4554, "36392138");
405#endif
406 return -1;
407 }
408
Jiyong Parkcd997e62017-06-30 17:23:33 +0900409 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100410 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700411 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800412 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000413 }
414
Narayan Kamath926973e2014-06-09 14:18:14 +0100415 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000416 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800417 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900418 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800419 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000420 }
421
Narayan Kamath926973e2014-06-09 14:18:14 +0100422 const uint16_t file_name_length = cdr->file_name_length;
423 const uint16_t extra_length = cdr->extra_field_length;
424 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100425 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
426
Tianjie Xu9e020e22016-10-10 12:11:30 -0700427 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900428 ALOGW(
429 "Zip: file name boundary exceeds the central directory range, file_name_length: "
430 "%" PRIx16 ", cd_length: %zu",
431 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700432 return -1;
433 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000434 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
435 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800436 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100437 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000438
439 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700440 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100441 entry_name.name = file_name;
442 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100443 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
444 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800445 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000446 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800447 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000448 }
449
Narayan Kamath926973e2014-06-09 14:18:14 +0100450 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
451 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900452 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800453 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000454 }
455 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100456
457 uint32_t lfh_start_bytes;
458 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
459 sizeof(uint32_t), 0)) {
460 ALOGW("Zip: Unable to read header for entry at offset == 0.");
461 return -1;
462 }
463
464 if (lfh_start_bytes != LocalFileHeader::kSignature) {
465 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
466#if defined(__ANDROID__)
467 android_errorWriteLog(0x534e4554, "64211847");
468#endif
469 return -1;
470 }
471
Mark Salyzyn088bf902014-05-08 16:02:20 -0700472 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000473
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800474 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000475}
476
Jiyong Parkcd997e62017-06-30 17:23:33 +0900477static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000478 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700479 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000480 return result;
481 }
482
483 if ((result = ParseZipArchive(archive))) {
484 return result;
485 }
486
487 return 0;
488}
489
Jiyong Parkcd997e62017-06-30 17:23:33 +0900490int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
491 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700492 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000493 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000494 return OpenArchiveInternal(archive, debug_file_name);
495}
496
497int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Ryan Mitchellc77f9d32018-08-25 14:06:29 -0700498 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700499 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000500 *handle = archive;
501
Narayan Kamath7462f022013-11-21 13:05:04 +0000502 if (fd < 0) {
503 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
504 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000505 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700506
Narayan Kamath7462f022013-11-21 13:05:04 +0000507 return OpenArchiveInternal(archive, fileName);
508}
509
Tianjie Xu18c25922016-09-29 15:27:41 -0700510int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900511 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700512 ZipArchive* archive = new ZipArchive(address, length);
513 *handle = archive;
514 return OpenArchiveInternal(archive, debug_file_name);
515}
516
Narayan Kamath7462f022013-11-21 13:05:04 +0000517/*
518 * Close a ZipArchive, closing the file and freeing the contents.
519 */
520void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800521 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000522 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100523 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000524}
525
Narayan Kamath162b7052017-06-05 13:21:12 +0100526static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100527 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700528 off64_t offset = entry->offset;
529 if (entry->method != kCompressStored) {
530 offset += entry->compressed_length;
531 } else {
532 offset += entry->uncompressed_length;
533 }
534
535 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000536 return kIoError;
537 }
538
Narayan Kamath926973e2014-06-09 14:18:14 +0100539 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700540 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
541 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000542
Narayan Kamath162b7052017-06-05 13:21:12 +0100543 // Validate that the values in the data descriptor match those in the central
544 // directory.
545 if (entry->compressed_length != descriptor->compressed_size ||
546 entry->uncompressed_length != descriptor->uncompressed_size ||
547 entry->crc32 != descriptor->crc32) {
548 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
549 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
550 entry->compressed_length, entry->uncompressed_length, entry->crc32,
551 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
552 return kInconsistentInformation;
553 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000554
555 return 0;
556}
557
Jiyong Parkcd997e62017-06-30 17:23:33 +0900558static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000559 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000560
561 // Recover the start of the central directory entry from the filename
562 // pointer. The filename is the first entry past the fixed-size data,
563 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100564 const ZipString from_offset =
565 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
566 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100567 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000568
569 // This is the base of our mmapped region, we have to sanity check that
570 // the name that's in the hash table is a pointer to a location within
571 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700572 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
573 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000574 ALOGW("Zip: Invalid entry pointer");
575 return kInvalidOffset;
576 }
577
Jiyong Parkcd997e62017-06-30 17:23:33 +0900578 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100579
Narayan Kamath7462f022013-11-21 13:05:04 +0000580 // The offset of the start of the central directory in the zipfile.
581 // We keep this lying around so that we can sanity check all our lengths
582 // and our per-file structures.
583 const off64_t cd_offset = archive->directory_offset;
584
585 // Fill out the compression method, modification time, crc32
586 // and other interesting attributes from the central directory. These
587 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100588 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900589 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100590 data->crc32 = cdr->crc32;
591 data->compressed_length = cdr->compressed_size;
592 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000593
594 // Figure out the local header offset from the central directory. The
595 // actual file data will begin after the local header and the name /
596 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100597 const off64_t local_header_offset = cdr->local_file_header_offset;
598 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000599 ALOGW("Zip: bad local hdr offset in zip");
600 return kInvalidOffset;
601 }
602
Narayan Kamath926973e2014-06-09 14:18:14 +0100603 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700604 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800605 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900606 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000607 return kIoError;
608 }
609
Jiyong Parkcd997e62017-06-30 17:23:33 +0900610 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100611
612 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700613 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900614 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000615 return kInvalidOffset;
616 }
617
618 // Paranoia: Match the values specified in the local file header
619 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700620
Narayan Kamath162b7052017-06-05 13:21:12 +0100621 // Warn if central directory and local file header don't agree on the use
622 // of a trailing Data Descriptor. The reference implementation is inconsistent
623 // and appears to use the LFH value during extraction (unzip) but the CD value
624 // while displayng information about archives (zipinfo). The spec remains
625 // silent on this inconsistency as well.
626 //
627 // For now, always use the version from the LFH but make sure that the values
628 // specified in the central directory match those in the data descriptor.
629 //
630 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
631 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
632 // encoded using UTF-8). This implementation does not check for the presence of
633 // that flag and always enforces that entry names are valid UTF-8.
634 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
635 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700636 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700637 }
638
639 // If there is no trailing data descriptor, verify that the central directory and local file
640 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100641 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000642 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900643 if (data->compressed_length != lfh->compressed_size ||
644 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
645 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
646 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
647 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
648 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000649 return kInconsistentInformation;
650 }
651 } else {
652 data->has_data_descriptor = 1;
653 }
654
Elliott Hughes55fd2932017-05-28 22:59:04 -0700655 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
656 if ((cdr->version_made_by >> 8) == 3) {
657 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
658 } else {
659 data->unix_mode = 0777;
660 }
661
Narayan Kamath7462f022013-11-21 13:05:04 +0000662 // Check that the local file header name matches the declared
663 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100664 if (lfh->file_name_length == nameLen) {
665 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200666 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000667 ALOGW("Zip: Invalid declared length");
668 return kInvalidOffset;
669 }
670
Tianjie Xu18c25922016-09-29 15:27:41 -0700671 std::vector<uint8_t> name_buf(nameLen);
672 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800673 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000674 return kIoError;
675 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100676 const ZipString from_offset =
677 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
678 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000679 return kInconsistentInformation;
680 }
681
Narayan Kamath7462f022013-11-21 13:05:04 +0000682 } else {
683 ALOGW("Zip: lfh name did not match central directory.");
684 return kInconsistentInformation;
685 }
686
Jiyong Parkcd997e62017-06-30 17:23:33 +0900687 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
688 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000689 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800690 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000691 return kInvalidOffset;
692 }
693
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800694 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700695 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900696 static_cast<int64_t>(data_offset), data->compressed_length,
697 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000698 return kInvalidOffset;
699 }
700
701 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900702 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
703 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
704 static_cast<int64_t>(data_offset), data->uncompressed_length,
705 static_cast<int64_t>(cd_offset));
706 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000707 }
708
709 data->offset = data_offset;
710 return 0;
711}
712
713struct IterationHandle {
714 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100715 // We're not using vector here because this code is used in the Windows SDK
716 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700717 ZipString prefix;
718 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000719 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100720
Jiyong Parkcd997e62017-06-30 17:23:33 +0900721 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700722 if (in_prefix) {
723 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
724 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
725 prefix.name = name_copy;
726 prefix.name_length = in_prefix->name_length;
727 } else {
728 prefix.name = NULL;
729 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700730 }
Yusuke Sato07447542015-06-25 14:39:19 -0700731 if (in_suffix) {
732 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
733 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
734 suffix.name = name_copy;
735 suffix.name_length = in_suffix->name_length;
736 } else {
737 suffix.name = NULL;
738 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700739 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100740 }
741
742 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700743 delete[] prefix.name;
744 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100745 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000746};
747
Jiyong Parkcd997e62017-06-30 17:23:33 +0900748int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700749 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800750 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000751
752 if (archive == NULL || archive->hash_table == NULL) {
753 ALOGW("Zip: Invalid ZipArchiveHandle");
754 return kInvalidHandle;
755 }
756
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700757 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000758 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000759 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000760
Jiyong Parkcd997e62017-06-30 17:23:33 +0900761 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000762 return 0;
763}
764
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100765void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100766 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100767}
768
Jiyong Parkcd997e62017-06-30 17:23:33 +0900769int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800770 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100771 if (entryName.name_length == 0) {
772 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000773 return kInvalidEntryName;
774 }
775
Zimuzo5a503ef2018-09-17 19:49:55 +0100776 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
777 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000778 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100779 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000780 return ent;
781 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000782 return FindEntry(archive, ent, data);
783}
784
Yusuke Sato07447542015-06-25 14:39:19 -0700785int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800786 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000787 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100788 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000789 return kInvalidHandle;
790 }
791
792 ZipArchive* archive = handle->archive;
793 if (archive == NULL || archive->hash_table == NULL) {
794 ALOGW("Zip: Invalid ZipArchiveHandle");
795 return kInvalidHandle;
796 }
797
798 const uint32_t currentOffset = handle->position;
799 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100800 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000801 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100802 const ZipString from_offset =
803 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
804 if (hash_table[i].name_offset != 0 &&
805 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
806 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000807 handle->position = (i + 1);
808 const int error = FindEntry(archive, i, data);
809 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100810 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000811 name->name_length = hash_table[i].name_length;
812 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000813 return error;
814 }
815 }
816
817 handle->position = 0;
818 return kIterationEnd;
819}
820
Narayan Kamathf899bd52015-04-17 11:53:14 +0100821// A Writer that writes data to a fixed size memory region.
822// The size of the memory region must be equal to the total size of
823// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100824class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100825 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900826 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100827
828 virtual bool Append(uint8_t* buf, size_t buf_size) override {
829 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900830 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
831 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100832 return false;
833 }
834
835 memcpy(buf_ + bytes_written_, buf, buf_size);
836 bytes_written_ += buf_size;
837 return true;
838 }
839
840 private:
841 uint8_t* const buf_;
842 const size_t size_;
843 size_t bytes_written_;
844};
845
846// A Writer that appends data to a file |fd| at its current position.
847// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100848class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100849 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100850 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
851 // guaranteeing that the file descriptor is valid and that there's enough
852 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800853 // is truncated to the correct length (no truncation if |fd| references a
854 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100855 //
856 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800857 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100858 const uint32_t declared_length = entry->uncompressed_length;
859 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
860 if (current_offset == -1) {
861 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800862 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100863 }
864
865 int result = 0;
866#if defined(__linux__)
867 if (declared_length > 0) {
868 // Make sure we have enough space on the volume to extract the compressed
869 // entry. Note that the call to ftruncate below will change the file size but
870 // will not allocate space on disk and this call to fallocate will not
871 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700872 // Note: fallocate is only supported by the following filesystems -
873 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
874 // EOPNOTSUPP error when issued in other filesystems.
875 // Hence, check for the return error code before concluding that the
876 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100877 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700878 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700879 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100880 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
881 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800882 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100883 }
884 }
885#endif // __linux__
886
Tao Baoa456c212016-11-15 10:08:07 -0800887 struct stat sb;
888 if (fstat(fd, &sb) == -1) {
889 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800890 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100891 }
892
Tao Baoa456c212016-11-15 10:08:07 -0800893 // Block device doesn't support ftruncate(2).
894 if (!S_ISBLK(sb.st_mode)) {
895 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
896 if (result == -1) {
897 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
898 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800899 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800900 }
901 }
902
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800903 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100904 }
905
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700906 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800907 : fd_(other.fd_),
908 declared_length_(other.declared_length_),
909 total_bytes_written_(other.total_bytes_written_) {
910 other.fd_ = -1;
911 }
912
913 bool IsValid() const { return fd_ != -1; }
914
Narayan Kamathf899bd52015-04-17 11:53:14 +0100915 virtual bool Append(uint8_t* buf, size_t buf_size) override {
916 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900917 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
918 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100919 return false;
920 }
921
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100922 const bool result = android::base::WriteFully(fd_, buf, buf_size);
923 if (result) {
924 total_bytes_written_ += buf_size;
925 } else {
926 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100927 }
928
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100929 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100930 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900931
Narayan Kamathf899bd52015-04-17 11:53:14 +0100932 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800933 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900934 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100935
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800936 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100937 const size_t declared_length_;
938 size_t total_bytes_written_;
939};
940
Narayan Kamath485b3642017-10-26 14:42:39 +0100941class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100942 public:
943 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
944 : Reader(), zip_file_(zip_file), entry_(entry) {}
945
946 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
947 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
948 }
949
950 virtual ~EntryReader() {}
951
952 private:
953 const MappedZipFile& zip_file_;
954 const ZipEntry* entry_;
955};
956
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800957// This method is using libz macros with old-style-casts
958#pragma GCC diagnostic push
959#pragma GCC diagnostic ignored "-Wold-style-cast"
960static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
961 return inflateInit2(stream, window_bits);
962}
963#pragma GCC diagnostic pop
964
Narayan Kamath485b3642017-10-26 14:42:39 +0100965namespace zip_archive {
966
967// Moved out of line to avoid -Wweak-vtables.
968Reader::~Reader() {}
969Writer::~Writer() {}
970
971int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
972 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700973 const size_t kBufSize = 32768;
974 std::vector<uint8_t> read_buf(kBufSize);
975 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000976 z_stream zstream;
977 int zerr;
978
979 /*
980 * Initialize the zlib stream struct.
981 */
982 memset(&zstream, 0, sizeof(zstream));
983 zstream.zalloc = Z_NULL;
984 zstream.zfree = Z_NULL;
985 zstream.opaque = Z_NULL;
986 zstream.next_in = NULL;
987 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700988 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000989 zstream.avail_out = kBufSize;
990 zstream.data_type = Z_UNKNOWN;
991
992 /*
993 * Use the undocumented "negative window bits" feature to tell zlib
994 * that there's no zlib header waiting for it.
995 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800996 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000997 if (zerr != Z_OK) {
998 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900999 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +00001000 } else {
1001 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
1002 }
1003
1004 return kZlibError;
1005 }
1006
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001007 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001008 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001009 };
1010
1011 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1012
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001013 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +01001014 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001015 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +00001016 do {
1017 /* read as much as we can */
1018 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001019 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
1020 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001021 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001022 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1023 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001024 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001025 }
1026
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001027 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001028
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001029 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001030 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001031 }
1032
1033 /* uncompress the data */
1034 zerr = inflate(&zstream, Z_NO_FLUSH);
1035 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001036 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1037 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001038 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001039 }
1040
1041 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001042 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001043 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001044 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001045 return kIoError;
1046 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001047 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001048 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001049
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001050 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001051 zstream.avail_out = kBufSize;
1052 }
1053 } while (zerr == Z_OK);
1054
Jiyong Parkcd997e62017-06-30 17:23:33 +09001055 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001056
Narayan Kamath162b7052017-06-05 13:21:12 +01001057 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1058 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1059 // doesn't bother calculating the checksum in that scenario. We just do
1060 // it ourselves above because there are no additional gains to be made by
1061 // having zlib calculate it for us, since they do it by calling crc32 in
1062 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001063 if (compute_crc) {
1064 *crc_out = crc;
1065 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001066
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001067 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001068 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1069 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001070 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001071 }
1072
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001073 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001074}
Narayan Kamath485b3642017-10-26 14:42:39 +01001075} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001076
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001077static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001078 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001079 const EntryReader reader(mapped_zip, entry);
1080
Narayan Kamath485b3642017-10-26 14:42:39 +01001081 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1082 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001083}
1084
Narayan Kamath485b3642017-10-26 14:42:39 +01001085static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1086 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001087 static const uint32_t kBufSize = 32768;
1088 std::vector<uint8_t> buf(kBufSize);
1089
1090 const uint32_t length = entry->uncompressed_length;
1091 uint32_t count = 0;
1092 uint64_t crc = 0;
1093 while (count < length) {
1094 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001095 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001096
Adam Lesinskide117e42017-06-19 10:27:38 -07001097 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001098 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001099
1100 // Make sure to read at offset to ensure concurrent access to the fd.
1101 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1102 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1103 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001104 return kIoError;
1105 }
1106
1107 if (!writer->Append(&buf[0], block_size)) {
1108 return kIoError;
1109 }
1110 crc = crc32(crc, &buf[0], block_size);
1111 count += block_size;
1112 }
1113
1114 *crc_out = crc;
1115
1116 return 0;
1117}
1118
Narayan Kamath485b3642017-10-26 14:42:39 +01001119int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001120 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001121 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001122
1123 // this should default to kUnknownCompressionMethod.
1124 int32_t return_value = -1;
1125 uint64_t crc = 0;
1126 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001127 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001128 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001129 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001130 }
1131
1132 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001133 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001134 if (return_value) {
1135 return return_value;
1136 }
1137 }
1138
Narayan Kamath162b7052017-06-05 13:21:12 +01001139 // Validate that the CRC matches the calculated value.
1140 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001141 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001142 return kInconsistentInformation;
1143 }
1144
1145 return return_value;
1146}
1147
Jiyong Parkcd997e62017-06-30 17:23:33 +09001148int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001149 MemoryWriter writer(begin, size);
1150 return ExtractToWriter(handle, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001151}
1152
Jiyong Parkcd997e62017-06-30 17:23:33 +09001153int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001154 auto writer = FileWriter::Create(fd, entry);
1155 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001156 return kIoError;
1157 }
1158
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001159 return ExtractToWriter(handle, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001160}
1161
1162const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001163 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1164 // match.
1165 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1166 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1167
1168 const uint32_t idx = -error_code;
1169 if (idx < arraysize(kErrorMessages)) {
1170 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001171 }
1172
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001173 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001174}
1175
1176int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001177 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001178}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001179
Jiyong Parkcd997e62017-06-30 17:23:33 +09001180ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001181 size_t len = strlen(entry_name);
1182 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1183 name_length = static_cast<uint16_t>(len);
1184}
Tianjie Xu18c25922016-09-29 15:27:41 -07001185
1186#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001187class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001188 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001189 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1190 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001191
1192 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1193 return proc_function_(buf, buf_size, cookie_);
1194 }
1195
1196 private:
1197 ProcessZipEntryFunction proc_function_;
1198 void* cookie_;
1199};
1200
1201int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1202 ProcessZipEntryFunction func, void* cookie) {
1203 ProcessWriter writer(func, cookie);
1204 return ExtractToWriter(handle, entry, &writer);
1205}
1206
Jiyong Parkcd997e62017-06-30 17:23:33 +09001207#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001208
1209int MappedZipFile::GetFileDescriptor() const {
1210 if (!has_fd_) {
1211 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1212 return -1;
1213 }
1214 return fd_;
1215}
1216
1217void* MappedZipFile::GetBasePtr() const {
1218 if (has_fd_) {
1219 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1220 return nullptr;
1221 }
1222 return base_ptr_;
1223}
1224
1225off64_t MappedZipFile::GetFileLength() const {
1226 if (has_fd_) {
1227 off64_t result = lseek64(fd_, 0, SEEK_END);
1228 if (result == -1) {
1229 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1230 }
1231 return result;
1232 } else {
1233 if (base_ptr_ == nullptr) {
1234 ALOGE("Zip: invalid file map\n");
1235 return -1;
1236 }
1237 return static_cast<off64_t>(data_length_);
1238 }
1239}
1240
Tianjie Xu18c25922016-09-29 15:27:41 -07001241// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001242bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001243 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001244 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001245 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1246 return false;
1247 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001248 } else {
1249 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1250 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1251 return false;
1252 }
1253 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001254 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001255 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001256}
1257
1258void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1259 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1260 length_ = cd_size;
1261}
1262
1263bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1264 size_t cd_size) {
1265 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001266 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1267 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001268 return false;
1269 }
1270
1271 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001272 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001273 } else {
1274 if (mapped_zip.GetBasePtr() == nullptr) {
1275 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1276 return false;
1277 }
1278 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1279 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001280 ALOGE(
1281 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1282 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1283 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001284 return false;
1285 }
1286
1287 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1288 }
1289 return true;
1290}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001291
1292tm ZipEntry::GetModificationTime() const {
1293 tm t = {};
1294
1295 t.tm_hour = (mod_time >> 11) & 0x1f;
1296 t.tm_min = (mod_time >> 5) & 0x3f;
1297 t.tm_sec = (mod_time & 0x1f) << 1;
1298
1299 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1300 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1301 t.tm_mday = (mod_time >> 16) & 0x1f;
1302
1303 return t;
1304}