blob: ef29188fb170985437dee9b382bb73b44e3f819c [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
Elliott Hughese8f4b142018-10-19 16:09:39 -070023#include "ziparchive/zip_archive.h"
24
Narayan Kamath7462f022013-11-21 13:05:04 +000025#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070026#include <fcntl.h>
27#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000029#include <stdlib.h>
30#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070031#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000032#include <unistd.h>
33
Dan Albert1ae07642015-04-09 14:11:18 -070034#include <memory>
35#include <vector>
36
Elliott Hughes9c8bd662018-10-26 16:14:21 -070037#if defined(__APPLE__)
38#define lseek64 lseek
39#endif
40
Josh Gao1b496342018-07-17 11:08:48 -070041#if defined(__BIONIC__)
42#include <android/fdsan.h>
43#endif
44
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045#include <android-base/file.h>
46#include <android-base/logging.h>
47#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
Elliott Hughese8f4b142018-10-19 16:09:39 -070048#include <android-base/mapped_file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070049#include <android-base/memory.h>
Elliott Hughes50ef29a2019-06-18 18:23:59 -070050#include <android-base/strings.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070051#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070052#include <log/log.h>
Dan Albert1ae07642015-04-09 14:11:18 -070053#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000054
Narayan Kamath044bc8e2014-12-03 18:22:53 +000055#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070056#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080057#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070058
Dan Albert1ae07642015-04-09 14:11:18 -070059using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000060
Narayan Kamath162b7052017-06-05 13:21:12 +010061// Used to turn on crc checks - verify that the content CRC matches the values
62// specified in the local file header and the central directory.
63static const bool kCrcChecksEnabled = false;
64
Narayan Kamath926973e2014-06-09 14:18:14 +010065// The maximum number of bytes to scan backwards for the EOCD start.
66static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
67
Narayan Kamath7462f022013-11-21 13:05:04 +000068/*
69 * A Read-only Zip archive.
70 *
71 * We want "open" and "find entry by name" to be fast operations, and
72 * we want to use as little memory as possible. We memory-map the zip
73 * central directory, and load a hash table with pointers to the filenames
74 * (which aren't null-terminated). The other fields are at a fixed offset
75 * from the filename, so we don't need to extract those (but we do need
76 * to byte-read and endian-swap them every time we want them).
77 *
78 * It's possible that somebody has handed us a massive (~1GB) zip archive,
79 * so we can't expect to mmap the entire file.
80 *
81 * To speed comparisons when doing a lookup by name, we could make the mapping
82 * "private" (copy-on-write) and null-terminate the filenames after verifying
83 * the record structure. However, this requires a private mapping of
84 * every page that the Central Directory touches. Easier to tuck a copy
85 * of the string length into the hash table entry.
86 */
Narayan Kamath7462f022013-11-21 13:05:04 +000087
Narayan Kamath7462f022013-11-21 13:05:04 +000088/*
89 * Round up to the next highest power of 2.
90 *
91 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
92 */
93static uint32_t RoundUpPower2(uint32_t val) {
94 val--;
95 val |= val >> 1;
96 val |= val >> 2;
97 val |= val >> 4;
98 val |= val >> 8;
99 val |= val >> 16;
100 val++;
101
102 return val;
103}
104
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700105static uint32_t ComputeHash(std::string_view name) {
106 return static_cast<uint32_t>(std::hash<std::string_view>{}(name));
Zimuzo5a503ef2018-09-17 19:49:55 +0100107}
108
Narayan Kamath7462f022013-11-21 13:05:04 +0000109/*
110 * Convert a ZipEntry to a hash table index, verifying that it's in a
111 * valid range.
112 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100113static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700114 std::string_view name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100115 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000116
117 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
118 uint32_t ent = hash & (hash_table_size - 1);
Zimuzo5a503ef2018-09-17 19:49:55 +0100119 while (hash_table[ent].name_offset != 0) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700120 if (hash_table[ent].ToStringView(start) == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000121 return ent;
122 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000123 ent = (ent + 1) & (hash_table_size - 1);
124 }
125
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700126 ALOGV("Zip: Unable to find entry %.*s", static_cast<int>(name.size()), name.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000127 return kEntryNotFound;
128}
129
130/*
131 * Add a new entry to the hash table.
132 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700133static int32_t AddToHash(ZipStringOffset* hash_table, const uint32_t hash_table_size,
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700134 std::string_view name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100135 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000136 uint32_t ent = hash & (hash_table_size - 1);
137
138 /*
139 * We over-allocated the table, so we're guaranteed to find an empty slot.
140 * Further, we guarantee that the hashtable size is not 0.
141 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100142 while (hash_table[ent].name_offset != 0) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700143 if (hash_table[ent].ToStringView(start) == name) {
144 // We've found a duplicate entry. We don't accept duplicates.
145 ALOGW("Zip: Found duplicate entry %.*s", static_cast<int>(name.size()), name.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000146 return kDuplicateEntry;
147 }
148 ent = (ent + 1) & (hash_table_size - 1);
149 }
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700150
151 // `name` has already been validated before entry.
152 const char* start_char = reinterpret_cast<const char*>(start);
153 hash_table[ent].name_offset = static_cast<uint32_t>(name.data() - start_char);
154 hash_table[ent].name_length = static_cast<uint16_t>(name.size());
Narayan Kamath7462f022013-11-21 13:05:04 +0000155 return 0;
156}
157
Josh Gaoabdfc242018-09-07 12:44:40 -0700158#if defined(__BIONIC__)
159uint64_t GetOwnerTag(const ZipArchive* archive) {
160 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
161 reinterpret_cast<uint64_t>(archive));
162}
163#endif
164
Josh Gao1b496342018-07-17 11:08:48 -0700165ZipArchive::ZipArchive(const int fd, bool assume_ownership)
166 : mapped_zip(fd),
167 close_file(assume_ownership),
168 directory_offset(0),
169 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700170 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700171 num_entries(0),
172 hash_table_size(0),
173 hash_table(nullptr) {
174#if defined(__BIONIC__)
175 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700176 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700177 }
178#endif
179}
180
Elliott Hughesf66460b2019-10-22 11:44:50 -0700181ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700182 : mapped_zip(address, length),
183 close_file(false),
184 directory_offset(0),
185 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700186 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700187 num_entries(0),
188 hash_table_size(0),
189 hash_table(nullptr) {}
190
191ZipArchive::~ZipArchive() {
192 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
193#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700194 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700195#else
196 close(mapped_zip.GetFileDescriptor());
197#endif
198 }
199
200 free(hash_table);
201}
202
Tianjie Xu18c25922016-09-29 15:27:41 -0700203static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Andreas Gampe964b95c2019-04-05 13:48:02 -0700204 off64_t file_length, uint32_t read_amount,
Zimuzo5a503ef2018-09-17 19:49:55 +0100205 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000206 const off64_t search_start = file_length - read_amount;
207
Jiyong Parkcd997e62017-06-30 17:23:33 +0900208 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
209 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
210 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000211 return kIoError;
212 }
213
214 /*
215 * Scan backward for the EOCD magic. In an archive without a trailing
216 * comment, we'll find it on the first try. (We may want to consider
217 * doing an initial minimal read; if we don't find it, retry with a
218 * second read as above.)
219 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700220 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
221 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100222 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700223 if (scan_buffer[i] == 0x50) {
224 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
225 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
226 ALOGV("+++ Found EOCD at buf+%d", i);
227 break;
228 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000229 }
230 }
231 if (i < 0) {
232 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
233 return kInvalidFile;
234 }
235
236 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100237 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000238 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100239 * Verify that there's no trailing space at the end of the central directory
240 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000241 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900242 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100243 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100244 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100245 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100246 return kInvalidFile;
247 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000248
Narayan Kamath926973e2014-06-09 14:18:14 +0100249 /*
250 * Grab the CD offset and size, and the number of entries in the
251 * archive and verify that they look reasonable.
252 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700253 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100254 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900255 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000256 return kInvalidOffset;
257 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100258 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000259#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000260 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000261#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000262 return kEmptyArchive;
263 }
264
Jiyong Parkcd997e62017-06-30 17:23:33 +0900265 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
266 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000267
268 /*
269 * It all looks good. Create a mapping for the CD, and set the fields
270 * in archive.
271 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700272
Elliott Hughese8f4b142018-10-19 16:09:39 -0700273 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700274 static_cast<size_t>(eocd->cd_size))) {
275 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000276 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000277 }
278
Narayan Kamath926973e2014-06-09 14:18:14 +0100279 archive->num_entries = eocd->num_records;
280 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000281
282 return 0;
283}
284
285/*
286 * Find the zip Central Directory and memory-map it.
287 *
288 * On success, returns 0 after populating fields from the EOCD area:
289 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700290 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000291 * num_entries
292 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700293static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000294 // Test file length. We use lseek64 to make sure the file
295 // is small enough to be a zip file (Its size must be less than
296 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700297 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000298 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000299 return kInvalidFile;
300 }
301
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800302 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100303 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000304 return kInvalidFile;
305 }
306
Narayan Kamath926973e2014-06-09 14:18:14 +0100307 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
308 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000309 return kInvalidFile;
310 }
311
312 /*
313 * Perform the traditional EOCD snipe hunt.
314 *
315 * We're searching for the End of Central Directory magic number,
316 * which appears at the start of the EOCD block. It's followed by
317 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
318 * need to read the last part of the file into a buffer, dig through
319 * it to find the magic number, parse some values out, and use those
320 * to determine the extent of the CD.
321 *
322 * We start by pulling in the last part of the file.
323 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700324 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100325 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700326 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000327 }
328
Tianjie Xu18c25922016-09-29 15:27:41 -0700329 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900330 int32_t result =
331 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000332 return result;
333}
334
335/*
336 * Parses the Zip archive's Central Directory. Allocates and populates the
337 * hash table.
338 *
339 * Returns 0 on success.
340 */
341static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700342 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
343 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100344 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000345
346 /*
347 * Create hash table. We have a minimum 75% load factor, possibly as
348 * low as 50% after we round off to a power of 2. There must be at
349 * least one unused entry to avoid an infinite loop during creation.
350 */
351 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900352 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100353 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700354 if (archive->hash_table == nullptr) {
355 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700356 archive->hash_table_size, sizeof(ZipStringOffset));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700357 return -1;
358 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000359
360 /*
361 * Walk through the central directory, adding entries to the hash
362 * table and verifying values.
363 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100364 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000365 const uint8_t* ptr = cd_ptr;
366 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700367 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
368 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
369#if defined(__ANDROID__)
370 android_errorWriteLog(0x534e4554, "36392138");
371#endif
372 return -1;
373 }
374
Jiyong Parkcd997e62017-06-30 17:23:33 +0900375 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100376 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700377 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800378 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000379 }
380
Narayan Kamath926973e2014-06-09 14:18:14 +0100381 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000382 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800383 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900384 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800385 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000386 }
387
Narayan Kamath926973e2014-06-09 14:18:14 +0100388 const uint16_t file_name_length = cdr->file_name_length;
389 const uint16_t extra_length = cdr->extra_field_length;
390 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100391 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
392
Tianjie Xu9e020e22016-10-10 12:11:30 -0700393 if (file_name + file_name_length > cd_end) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700394 ALOGW("Zip: file name for entry %" PRIu16
395 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
396 i, file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700397 return -1;
398 }
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700399 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000400 if (!IsValidEntryName(file_name, file_name_length)) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700401 ALOGW("Zip: invalid file name at entry %" PRIu16, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800402 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100403 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000404
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700405 // Add the CDE filename to the hash table.
406 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Zimuzo5a503ef2018-09-17 19:49:55 +0100407 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
408 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800409 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000410 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800411 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000412 }
413
Narayan Kamath926973e2014-06-09 14:18:14 +0100414 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
415 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900416 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800417 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000418 }
419 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100420
421 uint32_t lfh_start_bytes;
422 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
423 sizeof(uint32_t), 0)) {
424 ALOGW("Zip: Unable to read header for entry at offset == 0.");
425 return -1;
426 }
427
428 if (lfh_start_bytes != LocalFileHeader::kSignature) {
429 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
430#if defined(__ANDROID__)
431 android_errorWriteLog(0x534e4554, "64211847");
432#endif
433 return -1;
434 }
435
Mark Salyzyn088bf902014-05-08 16:02:20 -0700436 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000437
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800438 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000439}
440
Jiyong Parkcd997e62017-06-30 17:23:33 +0900441static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000442 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700443 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000444 return result;
445 }
446
447 if ((result = ParseZipArchive(archive))) {
448 return result;
449 }
450
451 return 0;
452}
453
Jiyong Parkcd997e62017-06-30 17:23:33 +0900454int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
455 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700456 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000457 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000458 return OpenArchiveInternal(archive, debug_file_name);
459}
460
461int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800462 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700463 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000464 *handle = archive;
465
Narayan Kamath7462f022013-11-21 13:05:04 +0000466 if (fd < 0) {
467 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
468 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000469 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700470
Narayan Kamath7462f022013-11-21 13:05:04 +0000471 return OpenArchiveInternal(archive, fileName);
472}
473
Elliott Hughesf66460b2019-10-22 11:44:50 -0700474int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900475 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700476 ZipArchive* archive = new ZipArchive(address, length);
477 *handle = archive;
478 return OpenArchiveInternal(archive, debug_file_name);
479}
480
Elliott Hughes26724132019-10-25 09:57:58 -0700481ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
482 ZipArchiveInfo result;
483 result.archive_size = archive->mapped_zip.GetFileLength();
484 result.entry_count = archive->num_entries;
485 return result;
486}
487
Narayan Kamath7462f022013-11-21 13:05:04 +0000488/*
489 * Close a ZipArchive, closing the file and freeing the contents.
490 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700491void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000492 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100493 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000494}
495
Narayan Kamath162b7052017-06-05 13:21:12 +0100496static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100497 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700498 off64_t offset = entry->offset;
499 if (entry->method != kCompressStored) {
500 offset += entry->compressed_length;
501 } else {
502 offset += entry->uncompressed_length;
503 }
504
505 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000506 return kIoError;
507 }
508
Narayan Kamath926973e2014-06-09 14:18:14 +0100509 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700510 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
511 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000512
Narayan Kamath162b7052017-06-05 13:21:12 +0100513 // Validate that the values in the data descriptor match those in the central
514 // directory.
515 if (entry->compressed_length != descriptor->compressed_size ||
516 entry->uncompressed_length != descriptor->uncompressed_size ||
517 entry->crc32 != descriptor->crc32) {
518 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
519 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
520 entry->compressed_length, entry->uncompressed_length, entry->crc32,
521 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
522 return kInconsistentInformation;
523 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000524
525 return 0;
526}
527
Andreas Gampe964b95c2019-04-05 13:48:02 -0700528static int32_t FindEntry(const ZipArchive* archive, const int32_t ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000529 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000530
531 // Recover the start of the central directory entry from the filename
532 // pointer. The filename is the first entry past the fixed-size data,
533 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700534 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
535 const uint8_t* ptr = base_ptr + archive->hash_table[ent].name_offset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100536 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000537
538 // This is the base of our mmapped region, we have to sanity check that
539 // the name that's in the hash table is a pointer to a location within
540 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700541 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000542 ALOGW("Zip: Invalid entry pointer");
543 return kInvalidOffset;
544 }
545
Jiyong Parkcd997e62017-06-30 17:23:33 +0900546 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100547
Narayan Kamath7462f022013-11-21 13:05:04 +0000548 // The offset of the start of the central directory in the zipfile.
549 // We keep this lying around so that we can sanity check all our lengths
550 // and our per-file structures.
551 const off64_t cd_offset = archive->directory_offset;
552
553 // Fill out the compression method, modification time, crc32
554 // and other interesting attributes from the central directory. These
555 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100556 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900557 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100558 data->crc32 = cdr->crc32;
559 data->compressed_length = cdr->compressed_size;
560 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000561
562 // Figure out the local header offset from the central directory. The
563 // actual file data will begin after the local header and the name /
564 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100565 const off64_t local_header_offset = cdr->local_file_header_offset;
566 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000567 ALOGW("Zip: bad local hdr offset in zip");
568 return kInvalidOffset;
569 }
570
Narayan Kamath926973e2014-06-09 14:18:14 +0100571 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700572 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800573 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900574 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000575 return kIoError;
576 }
577
Jiyong Parkcd997e62017-06-30 17:23:33 +0900578 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100579
580 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700581 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900582 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000583 return kInvalidOffset;
584 }
585
586 // Paranoia: Match the values specified in the local file header
587 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700588
Narayan Kamath162b7052017-06-05 13:21:12 +0100589 // Warn if central directory and local file header don't agree on the use
590 // of a trailing Data Descriptor. The reference implementation is inconsistent
591 // and appears to use the LFH value during extraction (unzip) but the CD value
592 // while displayng information about archives (zipinfo). The spec remains
593 // silent on this inconsistency as well.
594 //
595 // For now, always use the version from the LFH but make sure that the values
596 // specified in the central directory match those in the data descriptor.
597 //
598 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
599 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
600 // encoded using UTF-8). This implementation does not check for the presence of
601 // that flag and always enforces that entry names are valid UTF-8.
602 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
603 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700604 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700605 }
606
607 // If there is no trailing data descriptor, verify that the central directory and local file
608 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100609 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000610 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900611 if (data->compressed_length != lfh->compressed_size ||
612 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
613 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
614 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
615 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
616 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000617 return kInconsistentInformation;
618 }
619 } else {
620 data->has_data_descriptor = 1;
621 }
622
Elliott Hughes55fd2932017-05-28 22:59:04 -0700623 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
Elliott Hughes26724132019-10-25 09:57:58 -0700624 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700625 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700626 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700627 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
628 } else {
629 data->unix_mode = 0777;
630 }
631
Elliott Hughesd5095252019-10-28 21:35:52 -0700632 // 4.4.4: general purpose bit flags.
633 data->gpbf = lfh->gpb_flags;
634
Elliott Hughes26724132019-10-25 09:57:58 -0700635 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
636 // Currently only needed to implement zipinfo.
637 data->is_text = (cdr->internal_file_attributes & 1);
638
Narayan Kamath7462f022013-11-21 13:05:04 +0000639 // Check that the local file header name matches the declared
640 // name in the central directory.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700641 if (lfh->file_name_length != nameLen) {
642 ALOGW("Zip: lfh name length did not match central directory");
643 return kInconsistentInformation;
644 }
645 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
646 if (name_offset + lfh->file_name_length > cd_offset) {
647 ALOGW("Zip: lfh name has invalid declared length");
648 return kInvalidOffset;
649 }
650 std::vector<uint8_t> name_buf(nameLen);
651 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
652 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
653 return kIoError;
654 }
655 const std::string_view entry_name =
656 archive->hash_table[ent].ToStringView(archive->central_directory.GetBasePtr());
657 if (memcmp(entry_name.data(), name_buf.data(), nameLen) != 0) {
658 ALOGW("Zip: lfh name did not match central directory");
Narayan Kamath7462f022013-11-21 13:05:04 +0000659 return kInconsistentInformation;
660 }
661
Jiyong Parkcd997e62017-06-30 17:23:33 +0900662 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
663 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000664 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800665 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000666 return kInvalidOffset;
667 }
668
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800669 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700670 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900671 static_cast<int64_t>(data_offset), data->compressed_length,
672 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000673 return kInvalidOffset;
674 }
675
676 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900677 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
678 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
679 static_cast<int64_t>(data_offset), data->uncompressed_length,
680 static_cast<int64_t>(cd_offset));
681 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000682 }
683
684 data->offset = data_offset;
685 return 0;
686}
687
688struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000689 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100690
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700691 std::string prefix;
692 std::string suffix;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700693
694 uint32_t position = 0;
695
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700696 IterationHandle(ZipArchive* archive, std::string_view in_prefix, std::string_view in_suffix)
697 : archive(archive), prefix(in_prefix), suffix(in_suffix) {}
Narayan Kamath7462f022013-11-21 13:05:04 +0000698};
699
Ryan Prichard3673f992018-10-10 22:41:14 -0700700int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700701 const std::string_view optional_prefix,
702 const std::string_view optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000703 if (archive == NULL || archive->hash_table == NULL) {
704 ALOGW("Zip: Invalid ZipArchiveHandle");
705 return kInvalidHandle;
706 }
707
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700708 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
709 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
710 ALOGW("Zip: prefix/suffix too long");
711 return kInvalidEntryName;
712 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000713
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700714 *cookie_ptr = new IterationHandle(archive, optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000715 return 0;
716}
717
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100718void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100719 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100720}
721
Elliott Hughesb17bf522019-05-03 22:38:44 -0700722int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
723 ZipEntry* data) {
724 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
725 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
726 return kInvalidEntryName;
727 }
728
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700729 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
730 archive->central_directory.GetBasePtr());
Elliott Hughesb17bf522019-05-03 22:38:44 -0700731 if (ent < 0) {
732 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
733 return static_cast<int32_t>(ent); // kEntryNotFound is safe to truncate.
734 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700735 // We know there are at most hash_table_size entries, safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700736 return FindEntry(archive, static_cast<uint32_t>(ent), data);
737}
738
Elliott Hughese06a8082019-05-22 18:56:41 -0700739int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700740 std::string_view sv;
741 int32_t result = Next(cookie, data, &sv);
742 if (result == 0 && name) {
743 *name = std::string(sv);
744 }
745 return result;
746}
747
748int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800749 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000750 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100751 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000752 return kInvalidHandle;
753 }
754
755 ZipArchive* archive = handle->archive;
756 if (archive == NULL || archive->hash_table == NULL) {
757 ALOGW("Zip: Invalid ZipArchiveHandle");
758 return kInvalidHandle;
759 }
760
761 const uint32_t currentOffset = handle->position;
762 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100763 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000764 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700765 const std::string_view entry_name =
766 hash_table[i].ToStringView(archive->central_directory.GetBasePtr());
767 if (hash_table[i].name_offset != 0 && (android::base::StartsWith(entry_name, handle->prefix) &&
768 android::base::EndsWith(entry_name, handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000769 handle->position = (i + 1);
770 const int error = FindEntry(archive, i, data);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700771 if (!error && name) {
772 *name = entry_name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000773 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000774 return error;
775 }
776 }
777
778 handle->position = 0;
779 return kIterationEnd;
780}
781
Narayan Kamathf899bd52015-04-17 11:53:14 +0100782// A Writer that writes data to a fixed size memory region.
783// The size of the memory region must be equal to the total size of
784// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100785class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100786 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900787 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100788
789 virtual bool Append(uint8_t* buf, size_t buf_size) override {
790 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700791 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900792 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100793 return false;
794 }
795
796 memcpy(buf_ + bytes_written_, buf, buf_size);
797 bytes_written_ += buf_size;
798 return true;
799 }
800
801 private:
802 uint8_t* const buf_;
803 const size_t size_;
804 size_t bytes_written_;
805};
806
807// A Writer that appends data to a file |fd| at its current position.
808// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100809class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100810 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100811 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
812 // guaranteeing that the file descriptor is valid and that there's enough
813 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800814 // is truncated to the correct length (no truncation if |fd| references a
815 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100816 //
817 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800818 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100819 const uint32_t declared_length = entry->uncompressed_length;
820 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
821 if (current_offset == -1) {
822 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800823 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100824 }
825
Narayan Kamathf899bd52015-04-17 11:53:14 +0100826#if defined(__linux__)
827 if (declared_length > 0) {
828 // Make sure we have enough space on the volume to extract the compressed
829 // entry. Note that the call to ftruncate below will change the file size but
830 // will not allocate space on disk and this call to fallocate will not
831 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700832 // Note: fallocate is only supported by the following filesystems -
833 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
834 // EOPNOTSUPP error when issued in other filesystems.
835 // Hence, check for the return error code before concluding that the
836 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700837 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700838 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700839 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100840 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
841 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800842 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100843 }
844 }
845#endif // __linux__
846
Tao Baoa456c212016-11-15 10:08:07 -0800847 struct stat sb;
848 if (fstat(fd, &sb) == -1) {
849 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800850 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100851 }
852
Tao Baoa456c212016-11-15 10:08:07 -0800853 // Block device doesn't support ftruncate(2).
854 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700855 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -0800856 if (result == -1) {
857 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
858 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800859 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800860 }
861 }
862
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800863 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100864 }
865
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700866 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800867 : fd_(other.fd_),
868 declared_length_(other.declared_length_),
869 total_bytes_written_(other.total_bytes_written_) {
870 other.fd_ = -1;
871 }
872
873 bool IsValid() const { return fd_ != -1; }
874
Narayan Kamathf899bd52015-04-17 11:53:14 +0100875 virtual bool Append(uint8_t* buf, size_t buf_size) override {
876 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700877 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900878 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100879 return false;
880 }
881
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100882 const bool result = android::base::WriteFully(fd_, buf, buf_size);
883 if (result) {
884 total_bytes_written_ += buf_size;
885 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700886 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100887 }
888
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100889 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100890 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900891
Narayan Kamathf899bd52015-04-17 11:53:14 +0100892 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800893 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900894 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100895
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800896 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100897 const size_t declared_length_;
898 size_t total_bytes_written_;
899};
900
Narayan Kamath485b3642017-10-26 14:42:39 +0100901class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100902 public:
903 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
904 : Reader(), zip_file_(zip_file), entry_(entry) {}
905
906 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
907 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
908 }
909
910 virtual ~EntryReader() {}
911
912 private:
913 const MappedZipFile& zip_file_;
914 const ZipEntry* entry_;
915};
916
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800917// This method is using libz macros with old-style-casts
918#pragma GCC diagnostic push
919#pragma GCC diagnostic ignored "-Wold-style-cast"
920static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
921 return inflateInit2(stream, window_bits);
922}
923#pragma GCC diagnostic pop
924
Narayan Kamath485b3642017-10-26 14:42:39 +0100925namespace zip_archive {
926
927// Moved out of line to avoid -Wweak-vtables.
928Reader::~Reader() {}
929Writer::~Writer() {}
930
931int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
932 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700933 const size_t kBufSize = 32768;
934 std::vector<uint8_t> read_buf(kBufSize);
935 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000936 z_stream zstream;
937 int zerr;
938
939 /*
940 * Initialize the zlib stream struct.
941 */
942 memset(&zstream, 0, sizeof(zstream));
943 zstream.zalloc = Z_NULL;
944 zstream.zfree = Z_NULL;
945 zstream.opaque = Z_NULL;
946 zstream.next_in = NULL;
947 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700948 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000949 zstream.avail_out = kBufSize;
950 zstream.data_type = Z_UNKNOWN;
951
952 /*
953 * Use the undocumented "negative window bits" feature to tell zlib
954 * that there's no zlib header waiting for it.
955 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800956 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000957 if (zerr != Z_OK) {
958 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900959 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000960 } else {
961 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
962 }
963
964 return kZlibError;
965 }
966
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800967 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900968 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800969 };
970
971 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
972
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000973 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700974 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100975 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000976 do {
977 /* read as much as we can */
978 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700979 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100980 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700981 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100982 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700983 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800984 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000985 }
986
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100987 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000988
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700989 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100990 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000991 }
992
993 /* uncompress the data */
994 zerr = inflate(&zstream, Z_NO_FLUSH);
995 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900996 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
997 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800998 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000999 }
1000
1001 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001002 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001003 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001004 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001005 return kIoError;
1006 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001007 DCHECK_LE(write_size, kBufSize);
1008 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +00001009 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001010
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001011 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001012 zstream.avail_out = kBufSize;
1013 }
1014 } while (zerr == Z_OK);
1015
Elliott Hughese8f4b142018-10-19 16:09:39 -07001016 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001017
Narayan Kamath162b7052017-06-05 13:21:12 +01001018 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1019 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1020 // doesn't bother calculating the checksum in that scenario. We just do
1021 // it ourselves above because there are no additional gains to be made by
1022 // having zlib calculate it for us, since they do it by calling crc32 in
1023 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001024 if (compute_crc) {
1025 *crc_out = crc;
1026 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001027
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001028 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001029 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1030 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001031 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001032 }
1033
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001034 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001035}
Narayan Kamath485b3642017-10-26 14:42:39 +01001036} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001037
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001038static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001039 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001040 const EntryReader reader(mapped_zip, entry);
1041
Narayan Kamath485b3642017-10-26 14:42:39 +01001042 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1043 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001044}
1045
Narayan Kamath485b3642017-10-26 14:42:39 +01001046static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1047 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001048 static const uint32_t kBufSize = 32768;
1049 std::vector<uint8_t> buf(kBufSize);
1050
1051 const uint32_t length = entry->uncompressed_length;
1052 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -07001053 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001054 while (count < length) {
1055 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001056 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001057
Adam Lesinskide117e42017-06-19 10:27:38 -07001058 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001059 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001060
1061 // Make sure to read at offset to ensure concurrent access to the fd.
1062 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001063 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -07001064 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001065 return kIoError;
1066 }
1067
1068 if (!writer->Append(&buf[0], block_size)) {
1069 return kIoError;
1070 }
1071 crc = crc32(crc, &buf[0], block_size);
1072 count += block_size;
1073 }
1074
1075 *crc_out = crc;
1076
1077 return 0;
1078}
1079
Ryan Prichard3673f992018-10-10 22:41:14 -07001080int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001081 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001082
1083 // this should default to kUnknownCompressionMethod.
1084 int32_t return_value = -1;
1085 uint64_t crc = 0;
1086 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001087 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001088 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001089 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001090 }
1091
1092 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001093 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001094 if (return_value) {
1095 return return_value;
1096 }
1097 }
1098
Narayan Kamath162b7052017-06-05 13:21:12 +01001099 // Validate that the CRC matches the calculated value.
1100 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001101 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001102 return kInconsistentInformation;
1103 }
1104
1105 return return_value;
1106}
1107
Ryan Prichard3673f992018-10-10 22:41:14 -07001108int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001109 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001110 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001111}
1112
Ryan Prichard3673f992018-10-10 22:41:14 -07001113int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001114 auto writer = FileWriter::Create(fd, entry);
1115 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001116 return kIoError;
1117 }
1118
Ryan Prichard3673f992018-10-10 22:41:14 -07001119 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001120}
1121
1122const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001123 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1124 // match.
1125 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1126 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1127
1128 const uint32_t idx = -error_code;
1129 if (idx < arraysize(kErrorMessages)) {
1130 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001131 }
1132
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001133 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001134}
1135
Ryan Prichard3673f992018-10-10 22:41:14 -07001136int GetFileDescriptor(const ZipArchiveHandle archive) {
1137 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001138}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001139
Tianjie Xu18c25922016-09-29 15:27:41 -07001140#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001141class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001142 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001143 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1144 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001145
1146 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1147 return proc_function_(buf, buf_size, cookie_);
1148 }
1149
1150 private:
1151 ProcessZipEntryFunction proc_function_;
1152 void* cookie_;
1153};
1154
Ryan Prichard3673f992018-10-10 22:41:14 -07001155int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001156 ProcessZipEntryFunction func, void* cookie) {
1157 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001158 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001159}
1160
Jiyong Parkcd997e62017-06-30 17:23:33 +09001161#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001162
1163int MappedZipFile::GetFileDescriptor() const {
1164 if (!has_fd_) {
1165 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1166 return -1;
1167 }
1168 return fd_;
1169}
1170
Elliott Hughesf66460b2019-10-22 11:44:50 -07001171const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001172 if (has_fd_) {
1173 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1174 return nullptr;
1175 }
1176 return base_ptr_;
1177}
1178
1179off64_t MappedZipFile::GetFileLength() const {
1180 if (has_fd_) {
1181 off64_t result = lseek64(fd_, 0, SEEK_END);
1182 if (result == -1) {
1183 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1184 }
1185 return result;
1186 } else {
1187 if (base_ptr_ == nullptr) {
1188 ALOGE("Zip: invalid file map\n");
1189 return -1;
1190 }
1191 return static_cast<off64_t>(data_length_);
1192 }
1193}
1194
Tianjie Xu18c25922016-09-29 15:27:41 -07001195// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001196bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001197 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001198 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001199 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1200 return false;
1201 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001202 } else {
1203 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1204 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1205 return false;
1206 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001207 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001208 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001209 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001210}
1211
Elliott Hughesf66460b2019-10-22 11:44:50 -07001212void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1213 size_t cd_size) {
1214 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001215 length_ = cd_size;
1216}
1217
Elliott Hughese8f4b142018-10-19 16:09:39 -07001218bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001219 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001220 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1221 cd_start_offset, cd_size, PROT_READ);
1222 if (!directory_map) return false;
Tianjie Xu18c25922016-09-29 15:27:41 -07001223
Elliott Hughese8f4b142018-10-19 16:09:39 -07001224 CHECK_EQ(directory_map->size(), cd_size);
1225 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001226 } else {
1227 if (mapped_zip.GetBasePtr() == nullptr) {
1228 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1229 return false;
1230 }
1231 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1232 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001233 ALOGE(
1234 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1235 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1236 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001237 return false;
1238 }
1239
1240 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1241 }
1242 return true;
1243}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001244
1245tm ZipEntry::GetModificationTime() const {
1246 tm t = {};
1247
1248 t.tm_hour = (mod_time >> 11) & 0x1f;
1249 t.tm_min = (mod_time >> 5) & 0x3f;
1250 t.tm_sec = (mod_time & 0x1f) << 1;
1251
1252 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1253 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1254 t.tm_mday = (mod_time >> 16) & 0x1f;
1255
1256 return t;
1257}