blob: 4451507802a76e846473aeb43aa59921745c1548 [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
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800109// Convert a ZipEntry to a hash table index, verifying that it's in a valid range.
110std::pair<int32_t, uint64_t> CdEntryMapZip32::GetCdEntryOffset(std::string_view name,
111 const uint8_t* start) const {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100112 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000113
114 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800115 uint32_t ent = hash & (hash_table_size_ - 1);
116 while (hash_table_[ent].name_offset != 0) {
117 if (hash_table_[ent].ToStringView(start) == name) {
118 return {0, hash_table_[ent].name_offset};
Narayan Kamath7462f022013-11-21 13:05:04 +0000119 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800120 ent = (ent + 1) & (hash_table_size_ - 1);
Narayan Kamath7462f022013-11-21 13:05:04 +0000121 }
122
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700123 ALOGV("Zip: Unable to find entry %.*s", static_cast<int>(name.size()), name.data());
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800124 return {kEntryNotFound, 0};
Narayan Kamath7462f022013-11-21 13:05:04 +0000125}
126
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800127int32_t CdEntryMapZip32::AddToMap(std::string_view name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100128 const uint64_t hash = ComputeHash(name);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800129 uint32_t ent = hash & (hash_table_size_ - 1);
Narayan Kamath7462f022013-11-21 13:05:04 +0000130
131 /*
132 * We over-allocated the table, so we're guaranteed to find an empty slot.
133 * Further, we guarantee that the hashtable size is not 0.
134 */
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800135 while (hash_table_[ent].name_offset != 0) {
136 if (hash_table_[ent].ToStringView(start) == name) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700137 // We've found a duplicate entry. We don't accept duplicates.
138 ALOGW("Zip: Found duplicate entry %.*s", static_cast<int>(name.size()), name.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000139 return kDuplicateEntry;
140 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800141 ent = (ent + 1) & (hash_table_size_ - 1);
Narayan Kamath7462f022013-11-21 13:05:04 +0000142 }
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700143
144 // `name` has already been validated before entry.
145 const char* start_char = reinterpret_cast<const char*>(start);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800146 hash_table_[ent].name_offset = static_cast<uint32_t>(name.data() - start_char);
147 hash_table_[ent].name_length = static_cast<uint16_t>(name.size());
Narayan Kamath7462f022013-11-21 13:05:04 +0000148 return 0;
149}
150
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800151void CdEntryMapZip32::ResetIteration() {
152 current_position_ = 0;
153}
154
155std::pair<std::string_view, uint64_t> CdEntryMapZip32::Next(const uint8_t* cd_start) {
156 while (current_position_ < hash_table_size_) {
157 const auto& entry = hash_table_[current_position_];
158 current_position_ += 1;
159
160 if (entry.name_offset != 0) {
161 return {entry.ToStringView(cd_start), entry.name_offset};
162 }
163 }
164 // We have reached the end of the hash table.
165 return {};
166}
167
168CdEntryMapZip32::CdEntryMapZip32(uint16_t num_entries) {
169 hash_table_size_ = RoundUpPower2(1 + (num_entries * 4) / 3);
170 hash_table_ = {
171 reinterpret_cast<ZipStringOffset*>(calloc(hash_table_size_, sizeof(ZipStringOffset))), free};
172}
173
174std::unique_ptr<CdEntryMapInterface> CdEntryMapZip32::Create(uint16_t num_entries) {
175 auto entry_map = new CdEntryMapZip32(num_entries);
176 CHECK(entry_map->hash_table_ != nullptr)
177 << "Zip: unable to allocate the " << entry_map->hash_table_size_
178 << " entry hash_table, entry size: " << sizeof(ZipStringOffset);
179 return std::unique_ptr<CdEntryMapInterface>(entry_map);
180}
181
Josh Gaoabdfc242018-09-07 12:44:40 -0700182#if defined(__BIONIC__)
183uint64_t GetOwnerTag(const ZipArchive* archive) {
184 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
185 reinterpret_cast<uint64_t>(archive));
186}
187#endif
188
Josh Gao1b496342018-07-17 11:08:48 -0700189ZipArchive::ZipArchive(const int fd, bool assume_ownership)
190 : mapped_zip(fd),
191 close_file(assume_ownership),
192 directory_offset(0),
193 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700194 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800195 num_entries(0) {
Josh Gao1b496342018-07-17 11:08:48 -0700196#if defined(__BIONIC__)
197 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700198 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700199 }
200#endif
201}
202
Elliott Hughesf66460b2019-10-22 11:44:50 -0700203ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700204 : mapped_zip(address, length),
205 close_file(false),
206 directory_offset(0),
207 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700208 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800209 num_entries(0) {}
Josh Gao1b496342018-07-17 11:08:48 -0700210
211ZipArchive::~ZipArchive() {
212 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
213#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700214 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700215#else
216 close(mapped_zip.GetFileDescriptor());
217#endif
218 }
Josh Gao1b496342018-07-17 11:08:48 -0700219}
220
Tianjie Xu18c25922016-09-29 15:27:41 -0700221static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Andreas Gampe964b95c2019-04-05 13:48:02 -0700222 off64_t file_length, uint32_t read_amount,
Zimuzo5a503ef2018-09-17 19:49:55 +0100223 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000224 const off64_t search_start = file_length - read_amount;
225
Jiyong Parkcd997e62017-06-30 17:23:33 +0900226 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
227 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
228 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000229 return kIoError;
230 }
231
232 /*
233 * Scan backward for the EOCD magic. In an archive without a trailing
234 * comment, we'll find it on the first try. (We may want to consider
235 * doing an initial minimal read; if we don't find it, retry with a
236 * second read as above.)
237 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700238 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
239 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100240 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700241 if (scan_buffer[i] == 0x50) {
242 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
243 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
244 ALOGV("+++ Found EOCD at buf+%d", i);
245 break;
246 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000247 }
248 }
249 if (i < 0) {
250 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
251 return kInvalidFile;
252 }
253
254 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100255 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000256 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100257 * Verify that there's no trailing space at the end of the central directory
258 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000259 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900260 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100261 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100262 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100263 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100264 return kInvalidFile;
265 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000266
Narayan Kamath926973e2014-06-09 14:18:14 +0100267 /*
268 * Grab the CD offset and size, and the number of entries in the
269 * archive and verify that they look reasonable.
270 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700271 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100272 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900273 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000274 return kInvalidOffset;
275 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100276 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000277#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000278 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000279#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000280 return kEmptyArchive;
281 }
282
Jiyong Parkcd997e62017-06-30 17:23:33 +0900283 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
284 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000285
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800286 // It all looks good. Create a mapping for the CD, and set the fields
287 // in archive.
Elliott Hughese8f4b142018-10-19 16:09:39 -0700288 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700289 static_cast<size_t>(eocd->cd_size))) {
Narayan Kamatheaf98852013-12-11 14:51:51 +0000290 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000291 }
292
Narayan Kamath926973e2014-06-09 14:18:14 +0100293 archive->num_entries = eocd->num_records;
294 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000295
296 return 0;
297}
298
299/*
300 * Find the zip Central Directory and memory-map it.
301 *
302 * On success, returns 0 after populating fields from the EOCD area:
303 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700304 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000305 * num_entries
306 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700307static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000308 // Test file length. We use lseek64 to make sure the file
309 // is small enough to be a zip file (Its size must be less than
310 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700311 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000312 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000313 return kInvalidFile;
314 }
315
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800316 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100317 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000318 return kInvalidFile;
319 }
320
Narayan Kamath926973e2014-06-09 14:18:14 +0100321 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
322 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000323 return kInvalidFile;
324 }
325
326 /*
327 * Perform the traditional EOCD snipe hunt.
328 *
329 * We're searching for the End of Central Directory magic number,
330 * which appears at the start of the EOCD block. It's followed by
331 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
332 * need to read the last part of the file into a buffer, dig through
333 * it to find the magic number, parse some values out, and use those
334 * to determine the extent of the CD.
335 *
336 * We start by pulling in the last part of the file.
337 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700338 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100339 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700340 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000341 }
342
Tianjie Xu18c25922016-09-29 15:27:41 -0700343 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900344 int32_t result =
345 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000346 return result;
347}
348
349/*
350 * Parses the Zip archive's Central Directory. Allocates and populates the
351 * hash table.
352 *
353 * Returns 0 on success.
354 */
355static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700356 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
357 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100358 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000359
360 /*
361 * Create hash table. We have a minimum 75% load factor, possibly as
362 * low as 50% after we round off to a power of 2. There must be at
363 * least one unused entry to avoid an infinite loop during creation.
364 */
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800365 archive->cd_entry_map = CdEntryMapZip32::Create(num_entries);
366 if (archive->cd_entry_map == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800367 return kAllocationFailed;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700368 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000369
370 /*
371 * Walk through the central directory, adding entries to the hash
372 * table and verifying values.
373 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100374 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000375 const uint8_t* ptr = cd_ptr;
376 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700377 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800378 ALOGW("Zip: ran off the end (item #%" PRIu16 ", %zu bytes of central directory)", i,
379 cd_length);
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700380#if defined(__ANDROID__)
381 android_errorWriteLog(0x534e4554, "36392138");
382#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800383 return kInvalidFile;
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700384 }
385
Jiyong Parkcd997e62017-06-30 17:23:33 +0900386 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100387 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700388 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800389 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000390 }
391
Narayan Kamath926973e2014-06-09 14:18:14 +0100392 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000393 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800394 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900395 static_cast<int64_t>(local_header_offset), i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800396 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000397 }
398
Narayan Kamath926973e2014-06-09 14:18:14 +0100399 const uint16_t file_name_length = cdr->file_name_length;
400 const uint16_t extra_length = cdr->extra_field_length;
401 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100402 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
403
Tianjie Xu9e020e22016-10-10 12:11:30 -0700404 if (file_name + file_name_length > cd_end) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700405 ALOGW("Zip: file name for entry %" PRIu16
406 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
407 i, file_name_length, cd_length);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800408 return kInvalidEntryName;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700409 }
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700410 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000411 if (!IsValidEntryName(file_name, file_name_length)) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700412 ALOGW("Zip: invalid file name at entry %" PRIu16, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800413 return kInvalidEntryName;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100414 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000415
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700416 // Add the CDE filename to the hash table.
417 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800418 if (auto add_result =
419 archive->cd_entry_map->AddToMap(entry_name, archive->central_directory.GetBasePtr());
420 add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000421 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800422 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000423 }
424
Narayan Kamath926973e2014-06-09 14:18:14 +0100425 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
426 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900427 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800428 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000429 }
430 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100431
432 uint32_t lfh_start_bytes;
433 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
434 sizeof(uint32_t), 0)) {
435 ALOGW("Zip: Unable to read header for entry at offset == 0.");
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800436 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100437 }
438
439 if (lfh_start_bytes != LocalFileHeader::kSignature) {
440 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
441#if defined(__ANDROID__)
442 android_errorWriteLog(0x534e4554, "64211847");
443#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800444 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100445 }
446
Mark Salyzyn088bf902014-05-08 16:02:20 -0700447 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000448
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800449 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000450}
451
Jiyong Parkcd997e62017-06-30 17:23:33 +0900452static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800453 int32_t result = MapCentralDirectory(debug_file_name, archive);
454 return result != 0 ? result : ParseZipArchive(archive);
Narayan Kamath7462f022013-11-21 13:05:04 +0000455}
456
Jiyong Parkcd997e62017-06-30 17:23:33 +0900457int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
458 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700459 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000460 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000461 return OpenArchiveInternal(archive, debug_file_name);
462}
463
464int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800465 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700466 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000467 *handle = archive;
468
Narayan Kamath7462f022013-11-21 13:05:04 +0000469 if (fd < 0) {
470 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
471 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000472 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700473
Narayan Kamath7462f022013-11-21 13:05:04 +0000474 return OpenArchiveInternal(archive, fileName);
475}
476
Elliott Hughesf66460b2019-10-22 11:44:50 -0700477int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900478 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700479 ZipArchive* archive = new ZipArchive(address, length);
480 *handle = archive;
481 return OpenArchiveInternal(archive, debug_file_name);
482}
483
Elliott Hughes26724132019-10-25 09:57:58 -0700484ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
485 ZipArchiveInfo result;
486 result.archive_size = archive->mapped_zip.GetFileLength();
487 result.entry_count = archive->num_entries;
488 return result;
489}
490
Narayan Kamath7462f022013-11-21 13:05:04 +0000491/*
492 * Close a ZipArchive, closing the file and freeing the contents.
493 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700494void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000495 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100496 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000497}
498
Narayan Kamath162b7052017-06-05 13:21:12 +0100499static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100500 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700501 off64_t offset = entry->offset;
502 if (entry->method != kCompressStored) {
503 offset += entry->compressed_length;
504 } else {
505 offset += entry->uncompressed_length;
506 }
507
508 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000509 return kIoError;
510 }
511
Narayan Kamath926973e2014-06-09 14:18:14 +0100512 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700513 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
514 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000515
Narayan Kamath162b7052017-06-05 13:21:12 +0100516 // Validate that the values in the data descriptor match those in the central
517 // directory.
518 if (entry->compressed_length != descriptor->compressed_size ||
519 entry->uncompressed_length != descriptor->uncompressed_size ||
520 entry->crc32 != descriptor->crc32) {
521 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
522 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
523 entry->compressed_length, entry->uncompressed_length, entry->crc32,
524 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
525 return kInconsistentInformation;
526 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000527
528 return 0;
529}
530
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800531static int32_t FindEntry(const ZipArchive* archive, std::string_view entryName,
532 const uint64_t nameOffset, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000533 // Recover the start of the central directory entry from the filename
534 // pointer. The filename is the first entry past the fixed-size data,
535 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700536 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800537 const uint8_t* ptr = base_ptr + nameOffset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100538 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000539
540 // This is the base of our mmapped region, we have to sanity check that
541 // the name that's in the hash table is a pointer to a location within
542 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700543 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000544 ALOGW("Zip: Invalid entry pointer");
545 return kInvalidOffset;
546 }
547
Jiyong Parkcd997e62017-06-30 17:23:33 +0900548 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100549
Narayan Kamath7462f022013-11-21 13:05:04 +0000550 // The offset of the start of the central directory in the zipfile.
551 // We keep this lying around so that we can sanity check all our lengths
552 // and our per-file structures.
553 const off64_t cd_offset = archive->directory_offset;
554
555 // Fill out the compression method, modification time, crc32
556 // and other interesting attributes from the central directory. These
557 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100558 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900559 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100560 data->crc32 = cdr->crc32;
561 data->compressed_length = cdr->compressed_size;
562 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000563
564 // Figure out the local header offset from the central directory. The
565 // actual file data will begin after the local header and the name /
566 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100567 const off64_t local_header_offset = cdr->local_file_header_offset;
568 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000569 ALOGW("Zip: bad local hdr offset in zip");
570 return kInvalidOffset;
571 }
572
Narayan Kamath926973e2014-06-09 14:18:14 +0100573 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700574 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800575 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900576 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000577 return kIoError;
578 }
579
Jiyong Parkcd997e62017-06-30 17:23:33 +0900580 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100581
582 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700583 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900584 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000585 return kInvalidOffset;
586 }
587
588 // Paranoia: Match the values specified in the local file header
589 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700590
Narayan Kamath162b7052017-06-05 13:21:12 +0100591 // Warn if central directory and local file header don't agree on the use
592 // of a trailing Data Descriptor. The reference implementation is inconsistent
593 // and appears to use the LFH value during extraction (unzip) but the CD value
594 // while displayng information about archives (zipinfo). The spec remains
595 // silent on this inconsistency as well.
596 //
597 // For now, always use the version from the LFH but make sure that the values
598 // specified in the central directory match those in the data descriptor.
599 //
600 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
601 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
602 // encoded using UTF-8). This implementation does not check for the presence of
603 // that flag and always enforces that entry names are valid UTF-8.
604 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
605 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700606 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700607 }
608
609 // If there is no trailing data descriptor, verify that the central directory and local file
610 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100611 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000612 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900613 if (data->compressed_length != lfh->compressed_size ||
614 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
615 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
616 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
617 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
618 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000619 return kInconsistentInformation;
620 }
621 } else {
622 data->has_data_descriptor = 1;
623 }
624
Elliott Hughes55fd2932017-05-28 22:59:04 -0700625 // 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 -0700626 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700627 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700628 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700629 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
630 } else {
631 data->unix_mode = 0777;
632 }
633
Elliott Hughesd5095252019-10-28 21:35:52 -0700634 // 4.4.4: general purpose bit flags.
635 data->gpbf = lfh->gpb_flags;
636
Elliott Hughes26724132019-10-25 09:57:58 -0700637 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
638 // Currently only needed to implement zipinfo.
639 data->is_text = (cdr->internal_file_attributes & 1);
640
Narayan Kamath7462f022013-11-21 13:05:04 +0000641 // Check that the local file header name matches the declared
642 // name in the central directory.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800643 CHECK_LE(entryName.size(), UINT16_MAX);
644 auto nameLen = static_cast<uint16_t>(entryName.size());
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700645 if (lfh->file_name_length != nameLen) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800646 ALOGW("Zip: lfh name length did not match central directory for %s: %" PRIu16 " %" PRIu16,
647 std::string(entryName).c_str(), lfh->file_name_length, nameLen);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700648 return kInconsistentInformation;
649 }
650 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
651 if (name_offset + lfh->file_name_length > cd_offset) {
652 ALOGW("Zip: lfh name has invalid declared length");
653 return kInvalidOffset;
654 }
655 std::vector<uint8_t> name_buf(nameLen);
656 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
657 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
658 return kIoError;
659 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800660 if (memcmp(entryName.data(), name_buf.data(), nameLen) != 0) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700661 ALOGW("Zip: lfh name did not match central directory");
Narayan Kamath7462f022013-11-21 13:05:04 +0000662 return kInconsistentInformation;
663 }
664
Jiyong Parkcd997e62017-06-30 17:23:33 +0900665 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
666 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000667 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800668 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000669 return kInvalidOffset;
670 }
671
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800672 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700673 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900674 static_cast<int64_t>(data_offset), data->compressed_length,
675 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000676 return kInvalidOffset;
677 }
678
679 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900680 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
681 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
682 static_cast<int64_t>(data_offset), data->uncompressed_length,
683 static_cast<int64_t>(cd_offset));
684 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000685 }
686
687 data->offset = data_offset;
688 return 0;
689}
690
691struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000692 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100693
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700694 std::string prefix;
695 std::string suffix;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700696
697 uint32_t position = 0;
698
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700699 IterationHandle(ZipArchive* archive, std::string_view in_prefix, std::string_view in_suffix)
700 : archive(archive), prefix(in_prefix), suffix(in_suffix) {}
Narayan Kamath7462f022013-11-21 13:05:04 +0000701};
702
Ryan Prichard3673f992018-10-10 22:41:14 -0700703int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700704 const std::string_view optional_prefix,
705 const std::string_view optional_suffix) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800706 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000707 ALOGW("Zip: Invalid ZipArchiveHandle");
708 return kInvalidHandle;
709 }
710
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700711 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
712 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
713 ALOGW("Zip: prefix/suffix too long");
714 return kInvalidEntryName;
715 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000716
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800717 archive->cd_entry_map->ResetIteration();
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700718 *cookie_ptr = new IterationHandle(archive, optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000719 return 0;
720}
721
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100722void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100723 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100724}
725
Elliott Hughesb17bf522019-05-03 22:38:44 -0700726int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
727 ZipEntry* data) {
728 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
729 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
730 return kInvalidEntryName;
731 }
732
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800733 const auto [result, offset] =
734 archive->cd_entry_map->GetCdEntryOffset(entryName, archive->central_directory.GetBasePtr());
735 if (result != 0) {
Elliott Hughesb17bf522019-05-03 22:38:44 -0700736 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800737 return static_cast<int32_t>(result); // kEntryNotFound is safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700738 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700739 // We know there are at most hash_table_size entries, safe to truncate.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800740 return FindEntry(archive, entryName, offset, data);
Elliott Hughesb17bf522019-05-03 22:38:44 -0700741}
742
Elliott Hughese06a8082019-05-22 18:56:41 -0700743int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700744 std::string_view sv;
745 int32_t result = Next(cookie, data, &sv);
746 if (result == 0 && name) {
747 *name = std::string(sv);
748 }
749 return result;
750}
751
752int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800753 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800754 if (handle == nullptr) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100755 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000756 return kInvalidHandle;
757 }
758
759 ZipArchive* archive = handle->archive;
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800760 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000761 ALOGW("Zip: Invalid ZipArchiveHandle");
762 return kInvalidHandle;
763 }
764
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800765 auto entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
766 while (entry != std::pair<std::string_view, uint64_t>()) {
767 const auto [entry_name, offset] = entry;
768 if (android::base::StartsWith(entry_name, handle->prefix) &&
769 android::base::EndsWith(entry_name, handle->suffix)) {
770 const int error = FindEntry(archive, entry_name, offset, 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 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800776 entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000777 }
778
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800779 archive->cd_entry_map->ResetIteration();
Narayan Kamath7462f022013-11-21 13:05:04 +0000780 return kIterationEnd;
781}
782
Narayan Kamathf899bd52015-04-17 11:53:14 +0100783// A Writer that writes data to a fixed size memory region.
784// The size of the memory region must be equal to the total size of
785// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100786class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100787 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900788 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100789
790 virtual bool Append(uint8_t* buf, size_t buf_size) override {
791 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700792 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900793 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100794 return false;
795 }
796
797 memcpy(buf_ + bytes_written_, buf, buf_size);
798 bytes_written_ += buf_size;
799 return true;
800 }
801
802 private:
803 uint8_t* const buf_;
804 const size_t size_;
805 size_t bytes_written_;
806};
807
808// A Writer that appends data to a file |fd| at its current position.
809// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100810class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100811 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100812 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
813 // guaranteeing that the file descriptor is valid and that there's enough
814 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800815 // is truncated to the correct length (no truncation if |fd| references a
816 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100817 //
818 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800819 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100820 const uint32_t declared_length = entry->uncompressed_length;
821 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
822 if (current_offset == -1) {
823 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800824 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100825 }
826
Narayan Kamathf899bd52015-04-17 11:53:14 +0100827#if defined(__linux__)
828 if (declared_length > 0) {
829 // Make sure we have enough space on the volume to extract the compressed
830 // entry. Note that the call to ftruncate below will change the file size but
831 // will not allocate space on disk and this call to fallocate will not
832 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700833 // Note: fallocate is only supported by the following filesystems -
834 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
835 // EOPNOTSUPP error when issued in other filesystems.
836 // Hence, check for the return error code before concluding that the
837 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700838 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700839 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700840 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100841 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
842 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800843 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100844 }
845 }
846#endif // __linux__
847
Tao Baoa456c212016-11-15 10:08:07 -0800848 struct stat sb;
849 if (fstat(fd, &sb) == -1) {
850 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800851 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100852 }
853
Tao Baoa456c212016-11-15 10:08:07 -0800854 // Block device doesn't support ftruncate(2).
855 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700856 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -0800857 if (result == -1) {
858 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
859 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800860 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800861 }
862 }
863
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800864 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100865 }
866
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700867 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800868 : fd_(other.fd_),
869 declared_length_(other.declared_length_),
870 total_bytes_written_(other.total_bytes_written_) {
871 other.fd_ = -1;
872 }
873
874 bool IsValid() const { return fd_ != -1; }
875
Narayan Kamathf899bd52015-04-17 11:53:14 +0100876 virtual bool Append(uint8_t* buf, size_t buf_size) override {
877 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700878 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900879 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100880 return false;
881 }
882
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100883 const bool result = android::base::WriteFully(fd_, buf, buf_size);
884 if (result) {
885 total_bytes_written_ += buf_size;
886 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700887 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100888 }
889
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100890 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100891 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900892
Narayan Kamathf899bd52015-04-17 11:53:14 +0100893 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800894 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900895 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100896
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800897 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100898 const size_t declared_length_;
899 size_t total_bytes_written_;
900};
901
Narayan Kamath485b3642017-10-26 14:42:39 +0100902class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100903 public:
904 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
905 : Reader(), zip_file_(zip_file), entry_(entry) {}
906
907 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
908 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
909 }
910
911 virtual ~EntryReader() {}
912
913 private:
914 const MappedZipFile& zip_file_;
915 const ZipEntry* entry_;
916};
917
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800918// This method is using libz macros with old-style-casts
919#pragma GCC diagnostic push
920#pragma GCC diagnostic ignored "-Wold-style-cast"
921static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
922 return inflateInit2(stream, window_bits);
923}
924#pragma GCC diagnostic pop
925
Narayan Kamath485b3642017-10-26 14:42:39 +0100926namespace zip_archive {
927
928// Moved out of line to avoid -Wweak-vtables.
929Reader::~Reader() {}
930Writer::~Writer() {}
931
932int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
933 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700934 const size_t kBufSize = 32768;
935 std::vector<uint8_t> read_buf(kBufSize);
936 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000937 z_stream zstream;
938 int zerr;
939
940 /*
941 * Initialize the zlib stream struct.
942 */
943 memset(&zstream, 0, sizeof(zstream));
944 zstream.zalloc = Z_NULL;
945 zstream.zfree = Z_NULL;
946 zstream.opaque = Z_NULL;
947 zstream.next_in = NULL;
948 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700949 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000950 zstream.avail_out = kBufSize;
951 zstream.data_type = Z_UNKNOWN;
952
953 /*
954 * Use the undocumented "negative window bits" feature to tell zlib
955 * that there's no zlib header waiting for it.
956 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800957 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000958 if (zerr != Z_OK) {
959 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900960 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000961 } else {
962 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
963 }
964
965 return kZlibError;
966 }
967
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800968 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900969 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800970 };
971
972 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
973
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000974 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700975 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100976 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000977 do {
978 /* read as much as we can */
979 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700980 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100981 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700982 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100983 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700984 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800985 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000986 }
987
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100988 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000989
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700990 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100991 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000992 }
993
994 /* uncompress the data */
995 zerr = inflate(&zstream, Z_NO_FLUSH);
996 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900997 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
998 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800999 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001000 }
1001
1002 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001003 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001004 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001005 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001006 return kIoError;
1007 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001008 DCHECK_LE(write_size, kBufSize);
1009 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +00001010 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001011
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001012 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001013 zstream.avail_out = kBufSize;
1014 }
1015 } while (zerr == Z_OK);
1016
Elliott Hughese8f4b142018-10-19 16:09:39 -07001017 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001018
Narayan Kamath162b7052017-06-05 13:21:12 +01001019 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1020 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1021 // doesn't bother calculating the checksum in that scenario. We just do
1022 // it ourselves above because there are no additional gains to be made by
1023 // having zlib calculate it for us, since they do it by calling crc32 in
1024 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001025 if (compute_crc) {
1026 *crc_out = crc;
1027 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001028
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001029 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001030 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1031 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001032 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001033 }
1034
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001035 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001036}
Narayan Kamath485b3642017-10-26 14:42:39 +01001037} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001038
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001039static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001040 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001041 const EntryReader reader(mapped_zip, entry);
1042
Narayan Kamath485b3642017-10-26 14:42:39 +01001043 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1044 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001045}
1046
Narayan Kamath485b3642017-10-26 14:42:39 +01001047static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1048 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001049 static const uint32_t kBufSize = 32768;
1050 std::vector<uint8_t> buf(kBufSize);
1051
1052 const uint32_t length = entry->uncompressed_length;
1053 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -07001054 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001055 while (count < length) {
1056 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001057 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001058
Adam Lesinskide117e42017-06-19 10:27:38 -07001059 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001060 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001061
1062 // Make sure to read at offset to ensure concurrent access to the fd.
1063 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001064 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -07001065 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001066 return kIoError;
1067 }
1068
1069 if (!writer->Append(&buf[0], block_size)) {
1070 return kIoError;
1071 }
1072 crc = crc32(crc, &buf[0], block_size);
1073 count += block_size;
1074 }
1075
1076 *crc_out = crc;
1077
1078 return 0;
1079}
1080
Ryan Prichard3673f992018-10-10 22:41:14 -07001081int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001082 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001083
1084 // this should default to kUnknownCompressionMethod.
1085 int32_t return_value = -1;
1086 uint64_t crc = 0;
1087 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001088 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001089 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001090 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001091 }
1092
1093 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001094 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001095 if (return_value) {
1096 return return_value;
1097 }
1098 }
1099
Narayan Kamath162b7052017-06-05 13:21:12 +01001100 // Validate that the CRC matches the calculated value.
1101 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001102 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001103 return kInconsistentInformation;
1104 }
1105
1106 return return_value;
1107}
1108
Ryan Prichard3673f992018-10-10 22:41:14 -07001109int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001110 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001111 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001112}
1113
Ryan Prichard3673f992018-10-10 22:41:14 -07001114int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001115 auto writer = FileWriter::Create(fd, entry);
1116 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001117 return kIoError;
1118 }
1119
Ryan Prichard3673f992018-10-10 22:41:14 -07001120 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001121}
1122
1123const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001124 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1125 // match.
1126 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1127 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1128
1129 const uint32_t idx = -error_code;
1130 if (idx < arraysize(kErrorMessages)) {
1131 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001132 }
1133
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001134 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001135}
1136
Ryan Prichard3673f992018-10-10 22:41:14 -07001137int GetFileDescriptor(const ZipArchiveHandle archive) {
1138 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001139}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001140
Tianjie Xu18c25922016-09-29 15:27:41 -07001141#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001142class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001143 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001144 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1145 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001146
1147 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1148 return proc_function_(buf, buf_size, cookie_);
1149 }
1150
1151 private:
1152 ProcessZipEntryFunction proc_function_;
1153 void* cookie_;
1154};
1155
Ryan Prichard3673f992018-10-10 22:41:14 -07001156int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001157 ProcessZipEntryFunction func, void* cookie) {
1158 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001159 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001160}
1161
Jiyong Parkcd997e62017-06-30 17:23:33 +09001162#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001163
1164int MappedZipFile::GetFileDescriptor() const {
1165 if (!has_fd_) {
1166 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1167 return -1;
1168 }
1169 return fd_;
1170}
1171
Elliott Hughesf66460b2019-10-22 11:44:50 -07001172const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001173 if (has_fd_) {
1174 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1175 return nullptr;
1176 }
1177 return base_ptr_;
1178}
1179
1180off64_t MappedZipFile::GetFileLength() const {
1181 if (has_fd_) {
1182 off64_t result = lseek64(fd_, 0, SEEK_END);
1183 if (result == -1) {
1184 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1185 }
1186 return result;
1187 } else {
1188 if (base_ptr_ == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001189 ALOGE("Zip: invalid file map");
Tianjie Xu18c25922016-09-29 15:27:41 -07001190 return -1;
1191 }
1192 return static_cast<off64_t>(data_length_);
1193 }
1194}
1195
Tianjie Xu18c25922016-09-29 15:27:41 -07001196// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001197bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001198 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001199 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001200 ALOGE("Zip: failed to read at offset %" PRId64, off);
Tianjie Xu18c25922016-09-29 15:27:41 -07001201 return false;
1202 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001203 } else {
1204 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001205 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64, off, data_length_);
Adam Lesinskide117e42017-06-19 10:27:38 -07001206 return false;
1207 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001208 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001209 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001210 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001211}
1212
Elliott Hughesf66460b2019-10-22 11:44:50 -07001213void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1214 size_t cd_size) {
1215 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001216 length_ = cd_size;
1217}
1218
Elliott Hughese8f4b142018-10-19 16:09:39 -07001219bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001220 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001221 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1222 cd_start_offset, cd_size, PROT_READ);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001223 if (!directory_map) {
1224 ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1225 cd_start_offset, cd_size, strerror(errno));
1226 return false;
1227 }
Tianjie Xu18c25922016-09-29 15:27:41 -07001228
Elliott Hughese8f4b142018-10-19 16:09:39 -07001229 CHECK_EQ(directory_map->size(), cd_size);
1230 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001231 } else {
1232 if (mapped_zip.GetBasePtr() == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001233 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
Tianjie Xu18c25922016-09-29 15:27:41 -07001234 return false;
1235 }
1236 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1237 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001238 ALOGE(
1239 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1240 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1241 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001242 return false;
1243 }
1244
1245 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1246 }
1247 return true;
1248}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001249
1250tm ZipEntry::GetModificationTime() const {
1251 tm t = {};
1252
1253 t.tm_hour = (mod_time >> 11) & 0x1f;
1254 t.tm_min = (mod_time >> 5) & 0x3f;
1255 t.tm_sec = (mod_time & 0x1f) << 1;
1256
1257 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1258 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1259 t.tm_mday = (mod_time >> 16) & 0x1f;
1260
1261 return t;
1262}