blob: 6458585711101ed14c607cabc63e84bbf2e7e260 [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>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070050#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070051#include <log/log.h>
Dan Albert1ae07642015-04-09 14:11:18 -070052#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000053
Narayan Kamath044bc8e2014-12-03 18:22:53 +000054#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070055#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080056#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070057
Dan Albert1ae07642015-04-09 14:11:18 -070058using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000059
Narayan Kamath162b7052017-06-05 13:21:12 +010060// Used to turn on crc checks - verify that the content CRC matches the values
61// specified in the local file header and the central directory.
62static const bool kCrcChecksEnabled = false;
63
Narayan Kamath926973e2014-06-09 14:18:14 +010064// The maximum number of bytes to scan backwards for the EOCD start.
65static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
66
Narayan Kamath7462f022013-11-21 13:05:04 +000067/*
68 * A Read-only Zip archive.
69 *
70 * We want "open" and "find entry by name" to be fast operations, and
71 * we want to use as little memory as possible. We memory-map the zip
72 * central directory, and load a hash table with pointers to the filenames
73 * (which aren't null-terminated). The other fields are at a fixed offset
74 * from the filename, so we don't need to extract those (but we do need
75 * to byte-read and endian-swap them every time we want them).
76 *
77 * It's possible that somebody has handed us a massive (~1GB) zip archive,
78 * so we can't expect to mmap the entire file.
79 *
80 * To speed comparisons when doing a lookup by name, we could make the mapping
81 * "private" (copy-on-write) and null-terminate the filenames after verifying
82 * the record structure. However, this requires a private mapping of
83 * every page that the Central Directory touches. Easier to tuck a copy
84 * of the string length into the hash table entry.
85 */
Narayan Kamath7462f022013-11-21 13:05:04 +000086
Narayan Kamath7462f022013-11-21 13:05:04 +000087/*
88 * Round up to the next highest power of 2.
89 *
90 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
91 */
92static uint32_t RoundUpPower2(uint32_t val) {
93 val--;
94 val |= val >> 1;
95 val |= val >> 2;
96 val |= val >> 4;
97 val |= val >> 8;
98 val |= val >> 16;
99 val++;
100
101 return val;
102}
103
Yusuke Sato07447542015-06-25 14:39:19 -0700104static uint32_t ComputeHash(const ZipString& name) {
Sebastian Pop1f93d712017-11-28 16:36:48 -0600105 return std::hash<std::string_view>{}(
Nick Kralevicha4e54332019-04-04 14:19:43 -0700106 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length)) &
107 UINT32_MAX;
Narayan Kamath7462f022013-11-21 13:05:04 +0000108}
109
Zimuzo5a503ef2018-09-17 19:49:55 +0100110static bool isZipStringEqual(const uint8_t* start, const ZipString& zip_string,
111 const ZipStringOffset& zip_string_offset) {
112 const ZipString from_offset = zip_string_offset.GetZipString(start);
113 return from_offset == zip_string;
114}
115
116/**
117 * Returns offset of ZipString#name from the start of the central directory in the memory map.
118 * For valid ZipStrings contained in the zip archive mmap, 0 < offset < 0xffffff.
119 */
120static inline uint32_t GetOffset(const uint8_t* name, const uint8_t* start) {
121 CHECK_GT(name, start);
122 CHECK_LT(name, start + 0xffffff);
123 return static_cast<uint32_t>(name - start);
124}
125
Narayan Kamath7462f022013-11-21 13:05:04 +0000126/*
127 * Convert a ZipEntry to a hash table index, verifying that it's in a
128 * valid range.
129 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100130static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
131 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100132 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000133
134 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
135 uint32_t ent = hash & (hash_table_size - 1);
Zimuzo5a503ef2018-09-17 19:49:55 +0100136 while (hash_table[ent].name_offset != 0) {
137 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000138 return ent;
139 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000140 ent = (ent + 1) & (hash_table_size - 1);
141 }
142
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100143 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000144 return kEntryNotFound;
145}
146
147/*
148 * Add a new entry to the hash table.
149 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700150static int32_t AddToHash(ZipStringOffset* hash_table, const uint32_t hash_table_size,
Zimuzo5a503ef2018-09-17 19:49:55 +0100151 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100152 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000153 uint32_t ent = hash & (hash_table_size - 1);
154
155 /*
156 * We over-allocated the table, so we're guaranteed to find an empty slot.
157 * Further, we guarantee that the hashtable size is not 0.
158 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100159 while (hash_table[ent].name_offset != 0) {
160 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000161 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100162 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000163 return kDuplicateEntry;
164 }
165 ent = (ent + 1) & (hash_table_size - 1);
166 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100167 hash_table[ent].name_offset = GetOffset(name.name, start);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100168 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000169 return 0;
170}
171
Josh Gaoabdfc242018-09-07 12:44:40 -0700172#if defined(__BIONIC__)
173uint64_t GetOwnerTag(const ZipArchive* archive) {
174 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
175 reinterpret_cast<uint64_t>(archive));
176}
177#endif
178
Josh Gao1b496342018-07-17 11:08:48 -0700179ZipArchive::ZipArchive(const int fd, bool assume_ownership)
180 : mapped_zip(fd),
181 close_file(assume_ownership),
182 directory_offset(0),
183 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700184 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700185 num_entries(0),
186 hash_table_size(0),
187 hash_table(nullptr) {
188#if defined(__BIONIC__)
189 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700190 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700191 }
192#endif
193}
194
195ZipArchive::ZipArchive(void* address, size_t length)
196 : mapped_zip(address, length),
197 close_file(false),
198 directory_offset(0),
199 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700200 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700201 num_entries(0),
202 hash_table_size(0),
203 hash_table(nullptr) {}
204
205ZipArchive::~ZipArchive() {
206 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
207#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700208 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700209#else
210 close(mapped_zip.GetFileDescriptor());
211#endif
212 }
213
214 free(hash_table);
215}
216
Tianjie Xu18c25922016-09-29 15:27:41 -0700217static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Andreas Gampe964b95c2019-04-05 13:48:02 -0700218 off64_t file_length, uint32_t read_amount,
Zimuzo5a503ef2018-09-17 19:49:55 +0100219 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000220 const off64_t search_start = file_length - read_amount;
221
Jiyong Parkcd997e62017-06-30 17:23:33 +0900222 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
223 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
224 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000225 return kIoError;
226 }
227
228 /*
229 * Scan backward for the EOCD magic. In an archive without a trailing
230 * comment, we'll find it on the first try. (We may want to consider
231 * doing an initial minimal read; if we don't find it, retry with a
232 * second read as above.)
233 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700234 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
235 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100236 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700237 if (scan_buffer[i] == 0x50) {
238 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
239 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
240 ALOGV("+++ Found EOCD at buf+%d", i);
241 break;
242 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000243 }
244 }
245 if (i < 0) {
246 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
247 return kInvalidFile;
248 }
249
250 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100251 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000252 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100253 * Verify that there's no trailing space at the end of the central directory
254 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000255 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900256 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100257 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100258 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100259 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100260 return kInvalidFile;
261 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000262
Narayan Kamath926973e2014-06-09 14:18:14 +0100263 /*
264 * Grab the CD offset and size, and the number of entries in the
265 * archive and verify that they look reasonable.
266 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700267 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100268 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900269 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000270 return kInvalidOffset;
271 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100272 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000273#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000274 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000275#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000276 return kEmptyArchive;
277 }
278
Jiyong Parkcd997e62017-06-30 17:23:33 +0900279 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
280 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000281
282 /*
283 * It all looks good. Create a mapping for the CD, and set the fields
284 * in archive.
285 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700286
Elliott Hughese8f4b142018-10-19 16:09:39 -0700287 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700288 static_cast<size_t>(eocd->cd_size))) {
289 ALOGE("Zip: failed to intialize central directory.\n");
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 */
365 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900366 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100367 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700368 if (archive->hash_table == nullptr) {
369 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
370 archive->hash_table_size, sizeof(ZipString));
371 return -1;
372 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000373
374 /*
375 * Walk through the central directory, adding entries to the hash
376 * table and verifying values.
377 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100378 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000379 const uint8_t* ptr = cd_ptr;
380 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700381 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
382 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
383#if defined(__ANDROID__)
384 android_errorWriteLog(0x534e4554, "36392138");
385#endif
386 return -1;
387 }
388
Jiyong Parkcd997e62017-06-30 17:23:33 +0900389 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100390 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700391 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800392 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000393 }
394
Narayan Kamath926973e2014-06-09 14:18:14 +0100395 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000396 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800397 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900398 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800399 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000400 }
401
Narayan Kamath926973e2014-06-09 14:18:14 +0100402 const uint16_t file_name_length = cdr->file_name_length;
403 const uint16_t extra_length = cdr->extra_field_length;
404 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100405 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
406
Tianjie Xu9e020e22016-10-10 12:11:30 -0700407 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900408 ALOGW(
409 "Zip: file name boundary exceeds the central directory range, file_name_length: "
410 "%" PRIx16 ", cd_length: %zu",
411 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700412 return -1;
413 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000414 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
415 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800416 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100417 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000418
419 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700420 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100421 entry_name.name = file_name;
422 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100423 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
424 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800425 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000426 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800427 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000428 }
429
Narayan Kamath926973e2014-06-09 14:18:14 +0100430 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
431 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900432 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800433 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000434 }
435 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100436
437 uint32_t lfh_start_bytes;
438 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
439 sizeof(uint32_t), 0)) {
440 ALOGW("Zip: Unable to read header for entry at offset == 0.");
441 return -1;
442 }
443
444 if (lfh_start_bytes != LocalFileHeader::kSignature) {
445 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
446#if defined(__ANDROID__)
447 android_errorWriteLog(0x534e4554, "64211847");
448#endif
449 return -1;
450 }
451
Mark Salyzyn088bf902014-05-08 16:02:20 -0700452 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000453
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800454 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000455}
456
Jiyong Parkcd997e62017-06-30 17:23:33 +0900457static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000458 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700459 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000460 return result;
461 }
462
463 if ((result = ParseZipArchive(archive))) {
464 return result;
465 }
466
467 return 0;
468}
469
Jiyong Parkcd997e62017-06-30 17:23:33 +0900470int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
471 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700472 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000473 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000474 return OpenArchiveInternal(archive, debug_file_name);
475}
476
477int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800478 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700479 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000480 *handle = archive;
481
Narayan Kamath7462f022013-11-21 13:05:04 +0000482 if (fd < 0) {
483 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
484 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000485 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700486
Narayan Kamath7462f022013-11-21 13:05:04 +0000487 return OpenArchiveInternal(archive, fileName);
488}
489
Tianjie Xu18c25922016-09-29 15:27:41 -0700490int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900491 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700492 ZipArchive* archive = new ZipArchive(address, length);
493 *handle = archive;
494 return OpenArchiveInternal(archive, debug_file_name);
495}
496
Narayan Kamath7462f022013-11-21 13:05:04 +0000497/*
498 * Close a ZipArchive, closing the file and freeing the contents.
499 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700500void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000501 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100502 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000503}
504
Narayan Kamath162b7052017-06-05 13:21:12 +0100505static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100506 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700507 off64_t offset = entry->offset;
508 if (entry->method != kCompressStored) {
509 offset += entry->compressed_length;
510 } else {
511 offset += entry->uncompressed_length;
512 }
513
514 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000515 return kIoError;
516 }
517
Narayan Kamath926973e2014-06-09 14:18:14 +0100518 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700519 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
520 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000521
Narayan Kamath162b7052017-06-05 13:21:12 +0100522 // Validate that the values in the data descriptor match those in the central
523 // directory.
524 if (entry->compressed_length != descriptor->compressed_size ||
525 entry->uncompressed_length != descriptor->uncompressed_size ||
526 entry->crc32 != descriptor->crc32) {
527 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
528 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
529 entry->compressed_length, entry->uncompressed_length, entry->crc32,
530 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
531 return kInconsistentInformation;
532 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000533
534 return 0;
535}
536
Andreas Gampe964b95c2019-04-05 13:48:02 -0700537static int32_t FindEntry(const ZipArchive* archive, const int32_t ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000538 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000539
540 // Recover the start of the central directory entry from the filename
541 // pointer. The filename is the first entry past the fixed-size data,
542 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100543 const ZipString from_offset =
544 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
545 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100546 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000547
548 // This is the base of our mmapped region, we have to sanity check that
549 // the name that's in the hash table is a pointer to a location within
550 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700551 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
552 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000553 ALOGW("Zip: Invalid entry pointer");
554 return kInvalidOffset;
555 }
556
Jiyong Parkcd997e62017-06-30 17:23:33 +0900557 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100558
Narayan Kamath7462f022013-11-21 13:05:04 +0000559 // The offset of the start of the central directory in the zipfile.
560 // We keep this lying around so that we can sanity check all our lengths
561 // and our per-file structures.
562 const off64_t cd_offset = archive->directory_offset;
563
564 // Fill out the compression method, modification time, crc32
565 // and other interesting attributes from the central directory. These
566 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100567 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900568 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100569 data->crc32 = cdr->crc32;
570 data->compressed_length = cdr->compressed_size;
571 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000572
573 // Figure out the local header offset from the central directory. The
574 // actual file data will begin after the local header and the name /
575 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100576 const off64_t local_header_offset = cdr->local_file_header_offset;
577 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000578 ALOGW("Zip: bad local hdr offset in zip");
579 return kInvalidOffset;
580 }
581
Narayan Kamath926973e2014-06-09 14:18:14 +0100582 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700583 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800584 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900585 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000586 return kIoError;
587 }
588
Jiyong Parkcd997e62017-06-30 17:23:33 +0900589 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100590
591 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700592 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900593 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000594 return kInvalidOffset;
595 }
596
597 // Paranoia: Match the values specified in the local file header
598 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700599
Narayan Kamath162b7052017-06-05 13:21:12 +0100600 // Warn if central directory and local file header don't agree on the use
601 // of a trailing Data Descriptor. The reference implementation is inconsistent
602 // and appears to use the LFH value during extraction (unzip) but the CD value
603 // while displayng information about archives (zipinfo). The spec remains
604 // silent on this inconsistency as well.
605 //
606 // For now, always use the version from the LFH but make sure that the values
607 // specified in the central directory match those in the data descriptor.
608 //
609 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
610 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
611 // encoded using UTF-8). This implementation does not check for the presence of
612 // that flag and always enforces that entry names are valid UTF-8.
613 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
614 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700615 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700616 }
617
618 // If there is no trailing data descriptor, verify that the central directory and local file
619 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100620 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000621 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900622 if (data->compressed_length != lfh->compressed_size ||
623 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
624 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
625 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
626 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
627 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000628 return kInconsistentInformation;
629 }
630 } else {
631 data->has_data_descriptor = 1;
632 }
633
Elliott Hughes55fd2932017-05-28 22:59:04 -0700634 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
635 if ((cdr->version_made_by >> 8) == 3) {
636 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
637 } else {
638 data->unix_mode = 0777;
639 }
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.
Narayan Kamath926973e2014-06-09 14:18:14 +0100643 if (lfh->file_name_length == nameLen) {
644 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200645 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000646 ALOGW("Zip: Invalid declared length");
647 return kInvalidOffset;
648 }
649
Tianjie Xu18c25922016-09-29 15:27:41 -0700650 std::vector<uint8_t> name_buf(nameLen);
651 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800652 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000653 return kIoError;
654 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100655 const ZipString from_offset =
656 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
657 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000658 return kInconsistentInformation;
659 }
660
Narayan Kamath7462f022013-11-21 13:05:04 +0000661 } else {
662 ALOGW("Zip: lfh name did not match central directory.");
663 return kInconsistentInformation;
664 }
665
Jiyong Parkcd997e62017-06-30 17:23:33 +0900666 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
667 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000668 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800669 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000670 return kInvalidOffset;
671 }
672
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800673 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700674 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900675 static_cast<int64_t>(data_offset), data->compressed_length,
676 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000677 return kInvalidOffset;
678 }
679
680 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900681 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
682 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
683 static_cast<int64_t>(data_offset), data->uncompressed_length,
684 static_cast<int64_t>(cd_offset));
685 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000686 }
687
688 data->offset = data_offset;
689 return 0;
690}
691
692struct IterationHandle {
693 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100694 // We're not using vector here because this code is used in the Windows SDK
695 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700696 ZipString prefix;
697 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000698 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100699
Jiyong Parkcd997e62017-06-30 17:23:33 +0900700 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700701 if (in_prefix) {
702 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
703 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
704 prefix.name = name_copy;
705 prefix.name_length = in_prefix->name_length;
706 } else {
707 prefix.name = NULL;
708 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700709 }
Yusuke Sato07447542015-06-25 14:39:19 -0700710 if (in_suffix) {
711 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
712 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
713 suffix.name = name_copy;
714 suffix.name_length = in_suffix->name_length;
715 } else {
716 suffix.name = NULL;
717 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700718 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100719 }
720
721 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700722 delete[] prefix.name;
723 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100724 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000725};
726
Ryan Prichard3673f992018-10-10 22:41:14 -0700727int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
728 const ZipString* optional_prefix, const ZipString* optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000729 if (archive == NULL || archive->hash_table == NULL) {
730 ALOGW("Zip: Invalid ZipArchiveHandle");
731 return kInvalidHandle;
732 }
733
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700734 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000735 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000736 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000737
Jiyong Parkcd997e62017-06-30 17:23:33 +0900738 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000739 return 0;
740}
741
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100742void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100743 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100744}
745
Ryan Prichard3673f992018-10-10 22:41:14 -0700746int32_t FindEntry(const ZipArchiveHandle archive, const ZipString& entryName, ZipEntry* data) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100747 if (entryName.name_length == 0) {
748 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000749 return kInvalidEntryName;
750 }
751
Zimuzo5a503ef2018-09-17 19:49:55 +0100752 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
753 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000754 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100755 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700756 return static_cast<int32_t>(ent); // kEntryNotFound is safe to truncate.
Narayan Kamath7462f022013-11-21 13:05:04 +0000757 }
Andreas Gampe964b95c2019-04-05 13:48:02 -0700758 // We know there are at most hast_table_size entries, safe to truncate.
759 return FindEntry(archive, static_cast<uint32_t>(ent), data);
Narayan Kamath7462f022013-11-21 13:05:04 +0000760}
761
Yusuke Sato07447542015-06-25 14:39:19 -0700762int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800763 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000764 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100765 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000766 return kInvalidHandle;
767 }
768
769 ZipArchive* archive = handle->archive;
770 if (archive == NULL || archive->hash_table == NULL) {
771 ALOGW("Zip: Invalid ZipArchiveHandle");
772 return kInvalidHandle;
773 }
774
775 const uint32_t currentOffset = handle->position;
776 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100777 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000778 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100779 const ZipString from_offset =
780 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
781 if (hash_table[i].name_offset != 0 &&
782 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
783 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000784 handle->position = (i + 1);
785 const int error = FindEntry(archive, i, data);
786 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100787 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000788 name->name_length = hash_table[i].name_length;
789 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000790 return error;
791 }
792 }
793
794 handle->position = 0;
795 return kIterationEnd;
796}
797
Narayan Kamathf899bd52015-04-17 11:53:14 +0100798// A Writer that writes data to a fixed size memory region.
799// The size of the memory region must be equal to the total size of
800// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100801class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100802 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900803 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100804
805 virtual bool Append(uint8_t* buf, size_t buf_size) override {
806 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700807 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900808 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100809 return false;
810 }
811
812 memcpy(buf_ + bytes_written_, buf, buf_size);
813 bytes_written_ += buf_size;
814 return true;
815 }
816
817 private:
818 uint8_t* const buf_;
819 const size_t size_;
820 size_t bytes_written_;
821};
822
823// A Writer that appends data to a file |fd| at its current position.
824// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100825class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100826 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100827 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
828 // guaranteeing that the file descriptor is valid and that there's enough
829 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800830 // is truncated to the correct length (no truncation if |fd| references a
831 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100832 //
833 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800834 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100835 const uint32_t declared_length = entry->uncompressed_length;
836 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
837 if (current_offset == -1) {
838 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800839 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100840 }
841
Narayan Kamathf899bd52015-04-17 11:53:14 +0100842#if defined(__linux__)
843 if (declared_length > 0) {
844 // Make sure we have enough space on the volume to extract the compressed
845 // entry. Note that the call to ftruncate below will change the file size but
846 // will not allocate space on disk and this call to fallocate will not
847 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700848 // Note: fallocate is only supported by the following filesystems -
849 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
850 // EOPNOTSUPP error when issued in other filesystems.
851 // Hence, check for the return error code before concluding that the
852 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700853 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700854 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700855 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100856 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
857 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800858 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100859 }
860 }
861#endif // __linux__
862
Tao Baoa456c212016-11-15 10:08:07 -0800863 struct stat sb;
864 if (fstat(fd, &sb) == -1) {
865 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800866 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100867 }
868
Tao Baoa456c212016-11-15 10:08:07 -0800869 // Block device doesn't support ftruncate(2).
870 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700871 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -0800872 if (result == -1) {
873 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
874 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800875 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800876 }
877 }
878
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800879 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100880 }
881
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700882 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800883 : fd_(other.fd_),
884 declared_length_(other.declared_length_),
885 total_bytes_written_(other.total_bytes_written_) {
886 other.fd_ = -1;
887 }
888
889 bool IsValid() const { return fd_ != -1; }
890
Narayan Kamathf899bd52015-04-17 11:53:14 +0100891 virtual bool Append(uint8_t* buf, size_t buf_size) override {
892 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700893 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900894 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100895 return false;
896 }
897
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100898 const bool result = android::base::WriteFully(fd_, buf, buf_size);
899 if (result) {
900 total_bytes_written_ += buf_size;
901 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700902 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100903 }
904
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100905 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100906 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900907
Narayan Kamathf899bd52015-04-17 11:53:14 +0100908 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800909 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900910 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100911
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800912 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100913 const size_t declared_length_;
914 size_t total_bytes_written_;
915};
916
Narayan Kamath485b3642017-10-26 14:42:39 +0100917class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100918 public:
919 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
920 : Reader(), zip_file_(zip_file), entry_(entry) {}
921
922 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
923 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
924 }
925
926 virtual ~EntryReader() {}
927
928 private:
929 const MappedZipFile& zip_file_;
930 const ZipEntry* entry_;
931};
932
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800933// This method is using libz macros with old-style-casts
934#pragma GCC diagnostic push
935#pragma GCC diagnostic ignored "-Wold-style-cast"
936static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
937 return inflateInit2(stream, window_bits);
938}
939#pragma GCC diagnostic pop
940
Narayan Kamath485b3642017-10-26 14:42:39 +0100941namespace zip_archive {
942
943// Moved out of line to avoid -Wweak-vtables.
944Reader::~Reader() {}
945Writer::~Writer() {}
946
947int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
948 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700949 const size_t kBufSize = 32768;
950 std::vector<uint8_t> read_buf(kBufSize);
951 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000952 z_stream zstream;
953 int zerr;
954
955 /*
956 * Initialize the zlib stream struct.
957 */
958 memset(&zstream, 0, sizeof(zstream));
959 zstream.zalloc = Z_NULL;
960 zstream.zfree = Z_NULL;
961 zstream.opaque = Z_NULL;
962 zstream.next_in = NULL;
963 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700964 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000965 zstream.avail_out = kBufSize;
966 zstream.data_type = Z_UNKNOWN;
967
968 /*
969 * Use the undocumented "negative window bits" feature to tell zlib
970 * that there's no zlib header waiting for it.
971 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800972 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000973 if (zerr != Z_OK) {
974 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900975 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000976 } else {
977 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
978 }
979
980 return kZlibError;
981 }
982
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800983 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900984 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800985 };
986
987 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
988
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000989 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700990 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100991 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000992 do {
993 /* read as much as we can */
994 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700995 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100996 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700997 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100998 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700999 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001000 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001001 }
1002
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001003 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001004
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001005 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001006 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001007 }
1008
1009 /* uncompress the data */
1010 zerr = inflate(&zstream, Z_NO_FLUSH);
1011 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001012 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1013 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001014 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001015 }
1016
1017 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001018 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001019 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001020 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001021 return kIoError;
1022 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001023 DCHECK_LE(write_size, kBufSize);
1024 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +00001025 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001026
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001027 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001028 zstream.avail_out = kBufSize;
1029 }
1030 } while (zerr == Z_OK);
1031
Elliott Hughese8f4b142018-10-19 16:09:39 -07001032 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001033
Narayan Kamath162b7052017-06-05 13:21:12 +01001034 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1035 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1036 // doesn't bother calculating the checksum in that scenario. We just do
1037 // it ourselves above because there are no additional gains to be made by
1038 // having zlib calculate it for us, since they do it by calling crc32 in
1039 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001040 if (compute_crc) {
1041 *crc_out = crc;
1042 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001043
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001044 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001045 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1046 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001047 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001048 }
1049
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001050 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001051}
Narayan Kamath485b3642017-10-26 14:42:39 +01001052} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001053
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001054static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001055 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001056 const EntryReader reader(mapped_zip, entry);
1057
Narayan Kamath485b3642017-10-26 14:42:39 +01001058 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1059 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001060}
1061
Narayan Kamath485b3642017-10-26 14:42:39 +01001062static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1063 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001064 static const uint32_t kBufSize = 32768;
1065 std::vector<uint8_t> buf(kBufSize);
1066
1067 const uint32_t length = entry->uncompressed_length;
1068 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -07001069 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001070 while (count < length) {
1071 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001072 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001073
Adam Lesinskide117e42017-06-19 10:27:38 -07001074 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001075 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001076
1077 // Make sure to read at offset to ensure concurrent access to the fd.
1078 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001079 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -07001080 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001081 return kIoError;
1082 }
1083
1084 if (!writer->Append(&buf[0], block_size)) {
1085 return kIoError;
1086 }
1087 crc = crc32(crc, &buf[0], block_size);
1088 count += block_size;
1089 }
1090
1091 *crc_out = crc;
1092
1093 return 0;
1094}
1095
Ryan Prichard3673f992018-10-10 22:41:14 -07001096int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001097 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001098
1099 // this should default to kUnknownCompressionMethod.
1100 int32_t return_value = -1;
1101 uint64_t crc = 0;
1102 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001103 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001104 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001105 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001106 }
1107
1108 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001109 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001110 if (return_value) {
1111 return return_value;
1112 }
1113 }
1114
Narayan Kamath162b7052017-06-05 13:21:12 +01001115 // Validate that the CRC matches the calculated value.
1116 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001117 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001118 return kInconsistentInformation;
1119 }
1120
1121 return return_value;
1122}
1123
Ryan Prichard3673f992018-10-10 22:41:14 -07001124int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001125 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001126 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001127}
1128
Ryan Prichard3673f992018-10-10 22:41:14 -07001129int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001130 auto writer = FileWriter::Create(fd, entry);
1131 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001132 return kIoError;
1133 }
1134
Ryan Prichard3673f992018-10-10 22:41:14 -07001135 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001136}
1137
1138const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001139 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1140 // match.
1141 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1142 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1143
1144 const uint32_t idx = -error_code;
1145 if (idx < arraysize(kErrorMessages)) {
1146 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001147 }
1148
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001149 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001150}
1151
Ryan Prichard3673f992018-10-10 22:41:14 -07001152int GetFileDescriptor(const ZipArchiveHandle archive) {
1153 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001154}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001155
Jiyong Parkcd997e62017-06-30 17:23:33 +09001156ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001157 size_t len = strlen(entry_name);
1158 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1159 name_length = static_cast<uint16_t>(len);
1160}
Tianjie Xu18c25922016-09-29 15:27:41 -07001161
1162#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001163class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001164 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001165 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1166 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001167
1168 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1169 return proc_function_(buf, buf_size, cookie_);
1170 }
1171
1172 private:
1173 ProcessZipEntryFunction proc_function_;
1174 void* cookie_;
1175};
1176
Ryan Prichard3673f992018-10-10 22:41:14 -07001177int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001178 ProcessZipEntryFunction func, void* cookie) {
1179 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001180 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001181}
1182
Jiyong Parkcd997e62017-06-30 17:23:33 +09001183#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001184
1185int MappedZipFile::GetFileDescriptor() const {
1186 if (!has_fd_) {
1187 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1188 return -1;
1189 }
1190 return fd_;
1191}
1192
1193void* MappedZipFile::GetBasePtr() const {
1194 if (has_fd_) {
1195 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1196 return nullptr;
1197 }
1198 return base_ptr_;
1199}
1200
1201off64_t MappedZipFile::GetFileLength() const {
1202 if (has_fd_) {
1203 off64_t result = lseek64(fd_, 0, SEEK_END);
1204 if (result == -1) {
1205 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1206 }
1207 return result;
1208 } else {
1209 if (base_ptr_ == nullptr) {
1210 ALOGE("Zip: invalid file map\n");
1211 return -1;
1212 }
1213 return static_cast<off64_t>(data_length_);
1214 }
1215}
1216
Tianjie Xu18c25922016-09-29 15:27:41 -07001217// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001218bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001219 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001220 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001221 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1222 return false;
1223 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001224 } else {
1225 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1226 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1227 return false;
1228 }
1229 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001230 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001231 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001232}
1233
1234void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1235 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1236 length_ = cd_size;
1237}
1238
Elliott Hughese8f4b142018-10-19 16:09:39 -07001239bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001240 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001241 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1242 cd_start_offset, cd_size, PROT_READ);
1243 if (!directory_map) return false;
Tianjie Xu18c25922016-09-29 15:27:41 -07001244
Elliott Hughese8f4b142018-10-19 16:09:39 -07001245 CHECK_EQ(directory_map->size(), cd_size);
1246 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001247 } else {
1248 if (mapped_zip.GetBasePtr() == nullptr) {
1249 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1250 return false;
1251 }
1252 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1253 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001254 ALOGE(
1255 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1256 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1257 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001258 return false;
1259 }
1260
1261 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1262 }
1263 return true;
1264}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001265
1266tm ZipEntry::GetModificationTime() const {
1267 tm t = {};
1268
1269 t.tm_hour = (mod_time >> 11) & 0x1f;
1270 t.tm_min = (mod_time >> 5) & 0x3f;
1271 t.tm_sec = (mod_time & 0x1f) << 1;
1272
1273 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1274 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1275 t.tm_mday = (mod_time >> 16) & 0x1f;
1276
1277 return t;
1278}