blob: 958c34b61d391b5fcf15e561ec3dbeb987c2be0c [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
Ryan Mitchellc7335762020-03-09 09:33:46 -0700165ZipArchive::ZipArchive(MappedZipFile&& map, bool assume_ownership)
166 : mapped_zip(map),
Josh Gao1b496342018-07-17 11:08:48 -0700167 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) {
Ryan Mitchellc7335762020-03-09 09:33:46 -0700176 CHECK(mapped_zip.HasFd());
177 android_fdsan_exchange_owner_tag(mapped_zip.GetFileDescriptor(), 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700178 }
179#endif
180}
181
Elliott Hughesf66460b2019-10-22 11:44:50 -0700182ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700183 : mapped_zip(address, length),
184 close_file(false),
185 directory_offset(0),
186 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700187 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700188 num_entries(0),
189 hash_table_size(0),
190 hash_table(nullptr) {}
191
192ZipArchive::~ZipArchive() {
193 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
194#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700195 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700196#else
197 close(mapped_zip.GetFileDescriptor());
198#endif
199 }
200
201 free(hash_table);
202}
203
Tianjie Xu18c25922016-09-29 15:27:41 -0700204static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Andreas Gampe964b95c2019-04-05 13:48:02 -0700205 off64_t file_length, uint32_t read_amount,
Zimuzo5a503ef2018-09-17 19:49:55 +0100206 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000207 const off64_t search_start = file_length - read_amount;
208
Jiyong Parkcd997e62017-06-30 17:23:33 +0900209 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
210 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
211 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000212 return kIoError;
213 }
214
215 /*
216 * Scan backward for the EOCD magic. In an archive without a trailing
217 * comment, we'll find it on the first try. (We may want to consider
218 * doing an initial minimal read; if we don't find it, retry with a
219 * second read as above.)
220 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700221 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
222 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100223 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700224 if (scan_buffer[i] == 0x50) {
225 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
226 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
227 ALOGV("+++ Found EOCD at buf+%d", i);
228 break;
229 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000230 }
231 }
232 if (i < 0) {
233 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
234 return kInvalidFile;
235 }
236
237 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100238 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000239 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100240 * Verify that there's no trailing space at the end of the central directory
241 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000242 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900243 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100244 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100245 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100246 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100247 return kInvalidFile;
248 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000249
Narayan Kamath926973e2014-06-09 14:18:14 +0100250 /*
251 * Grab the CD offset and size, and the number of entries in the
252 * archive and verify that they look reasonable.
253 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700254 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100255 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900256 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000257 return kInvalidOffset;
258 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100259 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000260#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000261 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000262#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000263 return kEmptyArchive;
264 }
265
Jiyong Parkcd997e62017-06-30 17:23:33 +0900266 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
267 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000268
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800269 // It all looks good. Create a mapping for the CD, and set the fields
270 // in archive.
Elliott Hughese8f4b142018-10-19 16:09:39 -0700271 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700272 static_cast<size_t>(eocd->cd_size))) {
Narayan Kamatheaf98852013-12-11 14:51:51 +0000273 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000274 }
275
Narayan Kamath926973e2014-06-09 14:18:14 +0100276 archive->num_entries = eocd->num_records;
277 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000278
279 return 0;
280}
281
282/*
283 * Find the zip Central Directory and memory-map it.
284 *
285 * On success, returns 0 after populating fields from the EOCD area:
286 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700287 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000288 * num_entries
289 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700290static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000291 // Test file length. We use lseek64 to make sure the file
292 // is small enough to be a zip file (Its size must be less than
293 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700294 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000295 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000296 return kInvalidFile;
297 }
298
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800299 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100300 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000301 return kInvalidFile;
302 }
303
Narayan Kamath926973e2014-06-09 14:18:14 +0100304 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
305 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000306 return kInvalidFile;
307 }
308
309 /*
310 * Perform the traditional EOCD snipe hunt.
311 *
312 * We're searching for the End of Central Directory magic number,
313 * which appears at the start of the EOCD block. It's followed by
314 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
315 * need to read the last part of the file into a buffer, dig through
316 * it to find the magic number, parse some values out, and use those
317 * to determine the extent of the CD.
318 *
319 * We start by pulling in the last part of the file.
320 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700321 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100322 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700323 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000324 }
325
Tianjie Xu18c25922016-09-29 15:27:41 -0700326 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900327 int32_t result =
328 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000329 return result;
330}
331
332/*
333 * Parses the Zip archive's Central Directory. Allocates and populates the
334 * hash table.
335 *
336 * Returns 0 on success.
337 */
338static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700339 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
340 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100341 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000342
343 /*
344 * Create hash table. We have a minimum 75% load factor, possibly as
345 * low as 50% after we round off to a power of 2. There must be at
346 * least one unused entry to avoid an infinite loop during creation.
347 */
348 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900349 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100350 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700351 if (archive->hash_table == nullptr) {
352 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700353 archive->hash_table_size, sizeof(ZipStringOffset));
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800354 return kAllocationFailed;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700355 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000356
357 /*
358 * Walk through the central directory, adding entries to the hash
359 * table and verifying values.
360 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100361 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000362 const uint8_t* ptr = cd_ptr;
363 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700364 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800365 ALOGW("Zip: ran off the end (item #%" PRIu16 ", %zu bytes of central directory)", i,
366 cd_length);
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700367#if defined(__ANDROID__)
368 android_errorWriteLog(0x534e4554, "36392138");
369#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800370 return kInvalidFile;
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700371 }
372
Jiyong Parkcd997e62017-06-30 17:23:33 +0900373 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100374 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700375 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800376 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000377 }
378
Narayan Kamath926973e2014-06-09 14:18:14 +0100379 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000380 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800381 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900382 static_cast<int64_t>(local_header_offset), i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800383 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000384 }
385
Narayan Kamath926973e2014-06-09 14:18:14 +0100386 const uint16_t file_name_length = cdr->file_name_length;
387 const uint16_t extra_length = cdr->extra_field_length;
388 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100389 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
390
Tianjie Xu9e020e22016-10-10 12:11:30 -0700391 if (file_name + file_name_length > cd_end) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700392 ALOGW("Zip: file name for entry %" PRIu16
393 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
394 i, file_name_length, cd_length);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800395 return kInvalidEntryName;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700396 }
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700397 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000398 if (!IsValidEntryName(file_name, file_name_length)) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700399 ALOGW("Zip: invalid file name at entry %" PRIu16, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800400 return kInvalidEntryName;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100401 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000402
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700403 // Add the CDE filename to the hash table.
404 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Zimuzo5a503ef2018-09-17 19:49:55 +0100405 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
406 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800407 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000408 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800409 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000410 }
411
Narayan Kamath926973e2014-06-09 14:18:14 +0100412 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
413 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900414 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800415 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000416 }
417 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100418
419 uint32_t lfh_start_bytes;
420 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
421 sizeof(uint32_t), 0)) {
422 ALOGW("Zip: Unable to read header for entry at offset == 0.");
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800423 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100424 }
425
426 if (lfh_start_bytes != LocalFileHeader::kSignature) {
427 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
428#if defined(__ANDROID__)
429 android_errorWriteLog(0x534e4554, "64211847");
430#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800431 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100432 }
433
Mark Salyzyn088bf902014-05-08 16:02:20 -0700434 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000435
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800436 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000437}
438
Jiyong Parkcd997e62017-06-30 17:23:33 +0900439static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800440 int32_t result = MapCentralDirectory(debug_file_name, archive);
441 return result != 0 ? result : ParseZipArchive(archive);
Narayan Kamath7462f022013-11-21 13:05:04 +0000442}
443
Jiyong Parkcd997e62017-06-30 17:23:33 +0900444int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
445 bool assume_ownership) {
Ryan Mitchellc7335762020-03-09 09:33:46 -0700446 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000447 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000448 return OpenArchiveInternal(archive, debug_file_name);
449}
450
Ryan Mitchellc7335762020-03-09 09:33:46 -0700451int32_t OpenArchiveFdRange(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
452 off64_t length, off64_t offset, bool assume_ownership) {
453 ZipArchive* archive = new ZipArchive(MappedZipFile(fd, length, offset), assume_ownership);
454 *handle = archive;
455
456 if (length < 0) {
457 ALOGW("Invalid zip length %" PRId64, length);
458 return kIoError;
459 }
460
461 if (offset < 0) {
462 ALOGW("Invalid zip offset %" PRId64, offset);
463 return kIoError;
464 }
465
466 return OpenArchiveInternal(archive, debug_file_name);
467}
468
Narayan Kamath7462f022013-11-21 13:05:04 +0000469int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800470 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Ryan Mitchellc7335762020-03-09 09:33:46 -0700471 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000472 *handle = archive;
473
Narayan Kamath7462f022013-11-21 13:05:04 +0000474 if (fd < 0) {
475 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
476 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000477 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700478
Narayan Kamath7462f022013-11-21 13:05:04 +0000479 return OpenArchiveInternal(archive, fileName);
480}
481
Elliott Hughesf66460b2019-10-22 11:44:50 -0700482int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900483 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700484 ZipArchive* archive = new ZipArchive(address, length);
485 *handle = archive;
486 return OpenArchiveInternal(archive, debug_file_name);
487}
488
Elliott Hughes26724132019-10-25 09:57:58 -0700489ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
490 ZipArchiveInfo result;
491 result.archive_size = archive->mapped_zip.GetFileLength();
492 result.entry_count = archive->num_entries;
493 return result;
494}
495
Narayan Kamath7462f022013-11-21 13:05:04 +0000496/*
497 * Close a ZipArchive, closing the file and freeing the contents.
498 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700499void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000500 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100501 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000502}
503
Narayan Kamath162b7052017-06-05 13:21:12 +0100504static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100505 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700506 off64_t offset = entry->offset;
507 if (entry->method != kCompressStored) {
508 offset += entry->compressed_length;
509 } else {
510 offset += entry->uncompressed_length;
511 }
512
513 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000514 return kIoError;
515 }
516
Narayan Kamath926973e2014-06-09 14:18:14 +0100517 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700518 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
519 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000520
Narayan Kamath162b7052017-06-05 13:21:12 +0100521 // Validate that the values in the data descriptor match those in the central
522 // directory.
523 if (entry->compressed_length != descriptor->compressed_size ||
524 entry->uncompressed_length != descriptor->uncompressed_size ||
525 entry->crc32 != descriptor->crc32) {
526 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
527 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
528 entry->compressed_length, entry->uncompressed_length, entry->crc32,
529 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
530 return kInconsistentInformation;
531 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000532
533 return 0;
534}
535
Andreas Gampe964b95c2019-04-05 13:48:02 -0700536static int32_t FindEntry(const ZipArchive* archive, const int32_t ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000537 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000538
539 // Recover the start of the central directory entry from the filename
540 // pointer. The filename is the first entry past the fixed-size data,
541 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700542 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
543 const uint8_t* ptr = base_ptr + archive->hash_table[ent].name_offset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100544 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000545
546 // This is the base of our mmapped region, we have to sanity check that
547 // the name that's in the hash table is a pointer to a location within
548 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700549 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000550 ALOGW("Zip: Invalid entry pointer");
551 return kInvalidOffset;
552 }
553
Jiyong Parkcd997e62017-06-30 17:23:33 +0900554 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100555
Narayan Kamath7462f022013-11-21 13:05:04 +0000556 // The offset of the start of the central directory in the zipfile.
557 // We keep this lying around so that we can sanity check all our lengths
558 // and our per-file structures.
559 const off64_t cd_offset = archive->directory_offset;
560
561 // Fill out the compression method, modification time, crc32
562 // and other interesting attributes from the central directory. These
563 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100564 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900565 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100566 data->crc32 = cdr->crc32;
567 data->compressed_length = cdr->compressed_size;
568 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000569
570 // Figure out the local header offset from the central directory. The
571 // actual file data will begin after the local header and the name /
572 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100573 const off64_t local_header_offset = cdr->local_file_header_offset;
574 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000575 ALOGW("Zip: bad local hdr offset in zip");
576 return kInvalidOffset;
577 }
578
Narayan Kamath926973e2014-06-09 14:18:14 +0100579 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700580 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800581 ALOGW("Zip: failed reading lfh name from 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 kIoError;
584 }
585
Jiyong Parkcd997e62017-06-30 17:23:33 +0900586 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100587
588 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700589 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900590 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000591 return kInvalidOffset;
592 }
593
594 // Paranoia: Match the values specified in the local file header
595 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700596
Narayan Kamath162b7052017-06-05 13:21:12 +0100597 // Warn if central directory and local file header don't agree on the use
598 // of a trailing Data Descriptor. The reference implementation is inconsistent
599 // and appears to use the LFH value during extraction (unzip) but the CD value
600 // while displayng information about archives (zipinfo). The spec remains
601 // silent on this inconsistency as well.
602 //
603 // For now, always use the version from the LFH but make sure that the values
604 // specified in the central directory match those in the data descriptor.
605 //
606 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
607 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
608 // encoded using UTF-8). This implementation does not check for the presence of
609 // that flag and always enforces that entry names are valid UTF-8.
610 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
611 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700612 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700613 }
614
615 // If there is no trailing data descriptor, verify that the central directory and local file
616 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100617 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000618 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900619 if (data->compressed_length != lfh->compressed_size ||
620 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
621 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
622 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
623 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
624 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000625 return kInconsistentInformation;
626 }
627 } else {
628 data->has_data_descriptor = 1;
629 }
630
Elliott Hughes55fd2932017-05-28 22:59:04 -0700631 // 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 -0700632 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700633 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700634 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700635 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
636 } else {
637 data->unix_mode = 0777;
638 }
639
Elliott Hughesd5095252019-10-28 21:35:52 -0700640 // 4.4.4: general purpose bit flags.
641 data->gpbf = lfh->gpb_flags;
642
Elliott Hughes26724132019-10-25 09:57:58 -0700643 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
644 // Currently only needed to implement zipinfo.
645 data->is_text = (cdr->internal_file_attributes & 1);
646
Narayan Kamath7462f022013-11-21 13:05:04 +0000647 // Check that the local file header name matches the declared
648 // name in the central directory.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700649 if (lfh->file_name_length != nameLen) {
650 ALOGW("Zip: lfh name length did not match central directory");
651 return kInconsistentInformation;
652 }
653 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
654 if (name_offset + lfh->file_name_length > cd_offset) {
655 ALOGW("Zip: lfh name has invalid declared length");
656 return kInvalidOffset;
657 }
658 std::vector<uint8_t> name_buf(nameLen);
659 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
660 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
661 return kIoError;
662 }
663 const std::string_view entry_name =
664 archive->hash_table[ent].ToStringView(archive->central_directory.GetBasePtr());
665 if (memcmp(entry_name.data(), name_buf.data(), nameLen) != 0) {
666 ALOGW("Zip: lfh name did not match central directory");
Narayan Kamath7462f022013-11-21 13:05:04 +0000667 return kInconsistentInformation;
668 }
669
Jiyong Parkcd997e62017-06-30 17:23:33 +0900670 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
671 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000672 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800673 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000674 return kInvalidOffset;
675 }
676
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800677 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700678 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900679 static_cast<int64_t>(data_offset), data->compressed_length,
680 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000681 return kInvalidOffset;
682 }
683
684 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900685 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
686 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
687 static_cast<int64_t>(data_offset), data->uncompressed_length,
688 static_cast<int64_t>(cd_offset));
689 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000690 }
691
692 data->offset = data_offset;
693 return 0;
694}
695
696struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000697 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100698
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700699 std::string prefix;
700 std::string suffix;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700701
702 uint32_t position = 0;
703
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700704 IterationHandle(ZipArchive* archive, std::string_view in_prefix, std::string_view in_suffix)
705 : archive(archive), prefix(in_prefix), suffix(in_suffix) {}
Narayan Kamath7462f022013-11-21 13:05:04 +0000706};
707
Ryan Prichard3673f992018-10-10 22:41:14 -0700708int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700709 const std::string_view optional_prefix,
710 const std::string_view optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000711 if (archive == NULL || archive->hash_table == NULL) {
712 ALOGW("Zip: Invalid ZipArchiveHandle");
713 return kInvalidHandle;
714 }
715
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700716 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
717 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
718 ALOGW("Zip: prefix/suffix too long");
719 return kInvalidEntryName;
720 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000721
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700722 *cookie_ptr = new IterationHandle(archive, optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000723 return 0;
724}
725
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100726void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100727 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100728}
729
Elliott Hughesb17bf522019-05-03 22:38:44 -0700730int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
731 ZipEntry* data) {
732 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
733 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
734 return kInvalidEntryName;
735 }
736
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700737 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
738 archive->central_directory.GetBasePtr());
Elliott Hughesb17bf522019-05-03 22:38:44 -0700739 if (ent < 0) {
740 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
741 return static_cast<int32_t>(ent); // kEntryNotFound is safe to truncate.
742 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700743 // We know there are at most hash_table_size entries, safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700744 return FindEntry(archive, static_cast<uint32_t>(ent), data);
745}
746
Elliott Hughese06a8082019-05-22 18:56:41 -0700747int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700748 std::string_view sv;
749 int32_t result = Next(cookie, data, &sv);
750 if (result == 0 && name) {
751 *name = std::string(sv);
752 }
753 return result;
754}
755
756int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800757 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000758 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100759 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000760 return kInvalidHandle;
761 }
762
763 ZipArchive* archive = handle->archive;
764 if (archive == NULL || archive->hash_table == NULL) {
765 ALOGW("Zip: Invalid ZipArchiveHandle");
766 return kInvalidHandle;
767 }
768
769 const uint32_t currentOffset = handle->position;
770 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100771 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000772 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700773 const std::string_view entry_name =
774 hash_table[i].ToStringView(archive->central_directory.GetBasePtr());
775 if (hash_table[i].name_offset != 0 && (android::base::StartsWith(entry_name, handle->prefix) &&
776 android::base::EndsWith(entry_name, handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000777 handle->position = (i + 1);
778 const int error = FindEntry(archive, i, data);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700779 if (!error && name) {
780 *name = entry_name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000781 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000782 return error;
783 }
784 }
785
786 handle->position = 0;
787 return kIterationEnd;
788}
789
Narayan Kamathf899bd52015-04-17 11:53:14 +0100790// A Writer that writes data to a fixed size memory region.
791// The size of the memory region must be equal to the total size of
792// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100793class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100794 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900795 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100796
797 virtual bool Append(uint8_t* buf, size_t buf_size) override {
798 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700799 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900800 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100801 return false;
802 }
803
804 memcpy(buf_ + bytes_written_, buf, buf_size);
805 bytes_written_ += buf_size;
806 return true;
807 }
808
809 private:
810 uint8_t* const buf_;
811 const size_t size_;
812 size_t bytes_written_;
813};
814
815// A Writer that appends data to a file |fd| at its current position.
816// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100817class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100818 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100819 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
820 // guaranteeing that the file descriptor is valid and that there's enough
821 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800822 // is truncated to the correct length (no truncation if |fd| references a
823 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100824 //
825 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800826 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100827 const uint32_t declared_length = entry->uncompressed_length;
828 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
829 if (current_offset == -1) {
830 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800831 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100832 }
833
Narayan Kamathf899bd52015-04-17 11:53:14 +0100834#if defined(__linux__)
835 if (declared_length > 0) {
836 // Make sure we have enough space on the volume to extract the compressed
837 // entry. Note that the call to ftruncate below will change the file size but
838 // will not allocate space on disk and this call to fallocate will not
839 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700840 // Note: fallocate is only supported by the following filesystems -
841 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
842 // EOPNOTSUPP error when issued in other filesystems.
843 // Hence, check for the return error code before concluding that the
844 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700845 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700846 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700847 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100848 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
849 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800850 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100851 }
852 }
853#endif // __linux__
854
Tao Baoa456c212016-11-15 10:08:07 -0800855 struct stat sb;
856 if (fstat(fd, &sb) == -1) {
857 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800858 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100859 }
860
Tao Baoa456c212016-11-15 10:08:07 -0800861 // Block device doesn't support ftruncate(2).
862 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700863 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -0800864 if (result == -1) {
865 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
866 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800867 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800868 }
869 }
870
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800871 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100872 }
873
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700874 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800875 : fd_(other.fd_),
876 declared_length_(other.declared_length_),
877 total_bytes_written_(other.total_bytes_written_) {
878 other.fd_ = -1;
879 }
880
881 bool IsValid() const { return fd_ != -1; }
882
Narayan Kamathf899bd52015-04-17 11:53:14 +0100883 virtual bool Append(uint8_t* buf, size_t buf_size) override {
884 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700885 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900886 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100887 return false;
888 }
889
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100890 const bool result = android::base::WriteFully(fd_, buf, buf_size);
891 if (result) {
892 total_bytes_written_ += buf_size;
893 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700894 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100895 }
896
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100897 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100898 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900899
Narayan Kamathf899bd52015-04-17 11:53:14 +0100900 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800901 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900902 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100903
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800904 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100905 const size_t declared_length_;
906 size_t total_bytes_written_;
907};
908
Narayan Kamath485b3642017-10-26 14:42:39 +0100909class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100910 public:
911 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
912 : Reader(), zip_file_(zip_file), entry_(entry) {}
913
914 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
915 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
916 }
917
918 virtual ~EntryReader() {}
919
920 private:
921 const MappedZipFile& zip_file_;
922 const ZipEntry* entry_;
923};
924
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800925// This method is using libz macros with old-style-casts
926#pragma GCC diagnostic push
927#pragma GCC diagnostic ignored "-Wold-style-cast"
928static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
929 return inflateInit2(stream, window_bits);
930}
931#pragma GCC diagnostic pop
932
Narayan Kamath485b3642017-10-26 14:42:39 +0100933namespace zip_archive {
934
935// Moved out of line to avoid -Wweak-vtables.
936Reader::~Reader() {}
937Writer::~Writer() {}
938
939int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
940 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700941 const size_t kBufSize = 32768;
942 std::vector<uint8_t> read_buf(kBufSize);
943 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000944 z_stream zstream;
945 int zerr;
946
947 /*
948 * Initialize the zlib stream struct.
949 */
950 memset(&zstream, 0, sizeof(zstream));
951 zstream.zalloc = Z_NULL;
952 zstream.zfree = Z_NULL;
953 zstream.opaque = Z_NULL;
954 zstream.next_in = NULL;
955 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700956 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000957 zstream.avail_out = kBufSize;
958 zstream.data_type = Z_UNKNOWN;
959
960 /*
961 * Use the undocumented "negative window bits" feature to tell zlib
962 * that there's no zlib header waiting for it.
963 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800964 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000965 if (zerr != Z_OK) {
966 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900967 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000968 } else {
969 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
970 }
971
972 return kZlibError;
973 }
974
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800975 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900976 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800977 };
978
979 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
980
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000981 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700982 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100983 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000984 do {
985 /* read as much as we can */
986 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700987 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100988 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700989 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100990 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700991 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800992 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000993 }
994
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100995 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000996
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700997 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100998 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000999 }
1000
1001 /* uncompress the data */
1002 zerr = inflate(&zstream, Z_NO_FLUSH);
1003 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001004 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1005 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001006 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001007 }
1008
1009 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001010 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001011 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001012 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001013 return kIoError;
1014 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001015 DCHECK_LE(write_size, kBufSize);
1016 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +00001017 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001018
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001019 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001020 zstream.avail_out = kBufSize;
1021 }
1022 } while (zerr == Z_OK);
1023
Elliott Hughese8f4b142018-10-19 16:09:39 -07001024 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001025
Narayan Kamath162b7052017-06-05 13:21:12 +01001026 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1027 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1028 // doesn't bother calculating the checksum in that scenario. We just do
1029 // it ourselves above because there are no additional gains to be made by
1030 // having zlib calculate it for us, since they do it by calling crc32 in
1031 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001032 if (compute_crc) {
1033 *crc_out = crc;
1034 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001035
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001036 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001037 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1038 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001039 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001040 }
1041
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001042 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001043}
Narayan Kamath485b3642017-10-26 14:42:39 +01001044} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001045
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001046static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001047 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001048 const EntryReader reader(mapped_zip, entry);
1049
Narayan Kamath485b3642017-10-26 14:42:39 +01001050 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1051 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001052}
1053
Narayan Kamath485b3642017-10-26 14:42:39 +01001054static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1055 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001056 static const uint32_t kBufSize = 32768;
1057 std::vector<uint8_t> buf(kBufSize);
1058
1059 const uint32_t length = entry->uncompressed_length;
1060 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -07001061 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001062 while (count < length) {
1063 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001064 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001065
Adam Lesinskide117e42017-06-19 10:27:38 -07001066 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001067 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001068
1069 // Make sure to read at offset to ensure concurrent access to the fd.
1070 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001071 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -07001072 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001073 return kIoError;
1074 }
1075
1076 if (!writer->Append(&buf[0], block_size)) {
1077 return kIoError;
1078 }
1079 crc = crc32(crc, &buf[0], block_size);
1080 count += block_size;
1081 }
1082
1083 *crc_out = crc;
1084
1085 return 0;
1086}
1087
Ryan Prichard3673f992018-10-10 22:41:14 -07001088int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001089 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001090
1091 // this should default to kUnknownCompressionMethod.
1092 int32_t return_value = -1;
1093 uint64_t crc = 0;
1094 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001095 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001096 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001097 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001098 }
1099
1100 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001101 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001102 if (return_value) {
1103 return return_value;
1104 }
1105 }
1106
Narayan Kamath162b7052017-06-05 13:21:12 +01001107 // Validate that the CRC matches the calculated value.
1108 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001109 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001110 return kInconsistentInformation;
1111 }
1112
1113 return return_value;
1114}
1115
Ryan Prichard3673f992018-10-10 22:41:14 -07001116int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001117 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001118 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001119}
1120
Ryan Prichard3673f992018-10-10 22:41:14 -07001121int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001122 auto writer = FileWriter::Create(fd, entry);
1123 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001124 return kIoError;
1125 }
1126
Ryan Prichard3673f992018-10-10 22:41:14 -07001127 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001128}
1129
1130const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001131 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1132 // match.
1133 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1134 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1135
1136 const uint32_t idx = -error_code;
1137 if (idx < arraysize(kErrorMessages)) {
1138 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001139 }
1140
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001141 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001142}
1143
Ryan Prichard3673f992018-10-10 22:41:14 -07001144int GetFileDescriptor(const ZipArchiveHandle archive) {
1145 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001146}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001147
Ryan Mitchellc7335762020-03-09 09:33:46 -07001148off64_t GetFileDescriptorOffset(const ZipArchiveHandle archive) {
1149 return archive->mapped_zip.GetFileOffset();
1150}
1151
Tianjie Xu18c25922016-09-29 15:27:41 -07001152#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001153class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001154 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001155 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1156 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001157
1158 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1159 return proc_function_(buf, buf_size, cookie_);
1160 }
1161
1162 private:
1163 ProcessZipEntryFunction proc_function_;
1164 void* cookie_;
1165};
1166
Ryan Prichard3673f992018-10-10 22:41:14 -07001167int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001168 ProcessZipEntryFunction func, void* cookie) {
1169 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001170 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001171}
1172
Jiyong Parkcd997e62017-06-30 17:23:33 +09001173#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001174
1175int MappedZipFile::GetFileDescriptor() const {
1176 if (!has_fd_) {
1177 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1178 return -1;
1179 }
1180 return fd_;
1181}
1182
Elliott Hughesf66460b2019-10-22 11:44:50 -07001183const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001184 if (has_fd_) {
1185 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1186 return nullptr;
1187 }
1188 return base_ptr_;
1189}
1190
Ryan Mitchellc7335762020-03-09 09:33:46 -07001191off64_t MappedZipFile::GetFileOffset() const {
1192 return fd_offset_;
1193}
1194
Tianjie Xu18c25922016-09-29 15:27:41 -07001195off64_t MappedZipFile::GetFileLength() const {
1196 if (has_fd_) {
Ryan Mitchellc7335762020-03-09 09:33:46 -07001197 if (data_length_ != -1) {
1198 return data_length_;
1199 }
1200 data_length_ = lseek64(fd_, 0, SEEK_END);
1201 if (data_length_ == -1) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001202 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1203 }
Ryan Mitchellc7335762020-03-09 09:33:46 -07001204 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001205 } else {
1206 if (base_ptr_ == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001207 ALOGE("Zip: invalid file map");
Tianjie Xu18c25922016-09-29 15:27:41 -07001208 return -1;
1209 }
Ryan Mitchellc7335762020-03-09 09:33:46 -07001210 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001211 }
1212}
1213
Tianjie Xu18c25922016-09-29 15:27:41 -07001214// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001215bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001216 if (has_fd_) {
Ryan Mitchellc7335762020-03-09 09:33:46 -07001217 if (off < 0) {
1218 ALOGE("Zip: invalid offset %" PRId64, off);
1219 return false;
1220 }
1221
1222 off64_t read_offset;
1223 if (__builtin_add_overflow(fd_offset_, off, &read_offset)) {
1224 ALOGE("Zip: invalid read offset %" PRId64 " overflows, fd offset %" PRId64, off, fd_offset_);
1225 return false;
1226 }
1227
1228 if (data_length_ != -1) {
1229 off64_t read_end;
1230 if (len > std::numeric_limits<off64_t>::max() ||
1231 __builtin_add_overflow(off, static_cast<off64_t>(len), &read_end)) {
1232 ALOGE("Zip: invalid read length %" PRId64 " overflows, offset %" PRId64,
1233 static_cast<off64_t>(len), off);
1234 return false;
1235 }
1236
1237 if (read_end > data_length_) {
1238 ALOGE("Zip: invalid read length %" PRId64 " exceeds data length %" PRId64 ", offset %"
1239 PRId64, static_cast<off64_t>(len), data_length_, off);
1240 return false;
1241 }
1242 }
1243
1244 if (!android::base::ReadFullyAtOffset(fd_, buf, len, read_offset)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001245 ALOGE("Zip: failed to read at offset %" PRId64, off);
Tianjie Xu18c25922016-09-29 15:27:41 -07001246 return false;
1247 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001248 } else {
Ryan Mitchellc7335762020-03-09 09:33:46 -07001249 if (off < 0 || off > data_length_) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001250 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64, off, data_length_);
Adam Lesinskide117e42017-06-19 10:27:38 -07001251 return false;
1252 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001253 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001254 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001255 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001256}
1257
Elliott Hughesf66460b2019-10-22 11:44:50 -07001258void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1259 size_t cd_size) {
1260 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001261 length_ = cd_size;
1262}
1263
Elliott Hughese8f4b142018-10-19 16:09:39 -07001264bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001265 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001266 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
Ryan Mitchellc7335762020-03-09 09:33:46 -07001267 mapped_zip.GetFileOffset() + cd_start_offset,
1268 cd_size, PROT_READ);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001269 if (!directory_map) {
1270 ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1271 cd_start_offset, cd_size, strerror(errno));
1272 return false;
1273 }
Tianjie Xu18c25922016-09-29 15:27:41 -07001274
Elliott Hughese8f4b142018-10-19 16:09:39 -07001275 CHECK_EQ(directory_map->size(), cd_size);
1276 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001277 } else {
1278 if (mapped_zip.GetBasePtr() == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001279 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
Tianjie Xu18c25922016-09-29 15:27:41 -07001280 return false;
1281 }
1282 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1283 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001284 ALOGE(
1285 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1286 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1287 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001288 return false;
1289 }
1290
1291 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1292 }
1293 return true;
1294}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001295
1296tm ZipEntry::GetModificationTime() const {
1297 tm t = {};
1298
1299 t.tm_hour = (mod_time >> 11) & 0x1f;
1300 t.tm_min = (mod_time >> 5) & 0x3f;
1301 t.tm_sec = (mod_time & 0x1f) << 1;
1302
1303 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1304 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1305 t.tm_mday = (mod_time >> 16) & 0x1f;
1306
1307 return t;
1308}