blob: 6b9f6e165fa734552e71b2538c63e2a1bbfb758a [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#if !defined(_WIN32)
106 return std::hash<std::string_view>{}(
107 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length));
108#else
109 // Remove this code path once the windows compiler knows how to compile the above statement.
Narayan Kamath7462f022013-11-21 13:05:04 +0000110 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100111 uint16_t len = name.name_length;
112 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000113
114 while (len--) {
115 hash = hash * 31 + *str++;
116 }
117
118 return hash;
Sebastian Pop1f93d712017-11-28 16:36:48 -0600119#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000120}
121
Zimuzo5a503ef2018-09-17 19:49:55 +0100122static bool isZipStringEqual(const uint8_t* start, const ZipString& zip_string,
123 const ZipStringOffset& zip_string_offset) {
124 const ZipString from_offset = zip_string_offset.GetZipString(start);
125 return from_offset == zip_string;
126}
127
128/**
129 * Returns offset of ZipString#name from the start of the central directory in the memory map.
130 * For valid ZipStrings contained in the zip archive mmap, 0 < offset < 0xffffff.
131 */
132static inline uint32_t GetOffset(const uint8_t* name, const uint8_t* start) {
133 CHECK_GT(name, start);
134 CHECK_LT(name, start + 0xffffff);
135 return static_cast<uint32_t>(name - start);
136}
137
Narayan Kamath7462f022013-11-21 13:05:04 +0000138/*
139 * Convert a ZipEntry to a hash table index, verifying that it's in a
140 * valid range.
141 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100142static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
143 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100144 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000145
146 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
147 uint32_t ent = hash & (hash_table_size - 1);
Zimuzo5a503ef2018-09-17 19:49:55 +0100148 while (hash_table[ent].name_offset != 0) {
149 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000150 return ent;
151 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000152 ent = (ent + 1) & (hash_table_size - 1);
153 }
154
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100155 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000156 return kEntryNotFound;
157}
158
159/*
160 * Add a new entry to the hash table.
161 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100162static int32_t AddToHash(ZipStringOffset* hash_table, const uint64_t hash_table_size,
163 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100164 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000165 uint32_t ent = hash & (hash_table_size - 1);
166
167 /*
168 * We over-allocated the table, so we're guaranteed to find an empty slot.
169 * Further, we guarantee that the hashtable size is not 0.
170 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100171 while (hash_table[ent].name_offset != 0) {
172 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000173 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100174 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000175 return kDuplicateEntry;
176 }
177 ent = (ent + 1) & (hash_table_size - 1);
178 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100179 hash_table[ent].name_offset = GetOffset(name.name, start);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100180 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000181 return 0;
182}
183
Josh Gaoabdfc242018-09-07 12:44:40 -0700184#if defined(__BIONIC__)
185uint64_t GetOwnerTag(const ZipArchive* archive) {
186 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
187 reinterpret_cast<uint64_t>(archive));
188}
189#endif
190
Josh Gao1b496342018-07-17 11:08:48 -0700191ZipArchive::ZipArchive(const int fd, bool assume_ownership)
192 : mapped_zip(fd),
193 close_file(assume_ownership),
194 directory_offset(0),
195 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700196 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700197 num_entries(0),
198 hash_table_size(0),
199 hash_table(nullptr) {
200#if defined(__BIONIC__)
201 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700202 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700203 }
204#endif
205}
206
207ZipArchive::ZipArchive(void* address, size_t length)
208 : mapped_zip(address, length),
209 close_file(false),
210 directory_offset(0),
211 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700212 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700213 num_entries(0),
214 hash_table_size(0),
215 hash_table(nullptr) {}
216
217ZipArchive::~ZipArchive() {
218 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
219#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700220 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700221#else
222 close(mapped_zip.GetFileDescriptor());
223#endif
224 }
225
226 free(hash_table);
227}
228
Tianjie Xu18c25922016-09-29 15:27:41 -0700229static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Zimuzo5a503ef2018-09-17 19:49:55 +0100230 off64_t file_length, off64_t read_amount,
231 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000232 const off64_t search_start = file_length - read_amount;
233
Jiyong Parkcd997e62017-06-30 17:23:33 +0900234 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
235 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
236 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000237 return kIoError;
238 }
239
240 /*
241 * Scan backward for the EOCD magic. In an archive without a trailing
242 * comment, we'll find it on the first try. (We may want to consider
243 * doing an initial minimal read; if we don't find it, retry with a
244 * second read as above.)
245 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100246 int i = read_amount - sizeof(EocdRecord);
247 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700248 if (scan_buffer[i] == 0x50) {
249 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
250 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
251 ALOGV("+++ Found EOCD at buf+%d", i);
252 break;
253 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000254 }
255 }
256 if (i < 0) {
257 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
258 return kInvalidFile;
259 }
260
261 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100262 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000263 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100264 * Verify that there's no trailing space at the end of the central directory
265 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000266 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900267 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100268 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100269 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100270 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100271 return kInvalidFile;
272 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000273
Narayan Kamath926973e2014-06-09 14:18:14 +0100274 /*
275 * Grab the CD offset and size, and the number of entries in the
276 * archive and verify that they look reasonable.
277 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700278 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100279 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900280 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700281#if defined(__ANDROID__)
282 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
283 android_errorWriteLog(0x534e4554, "31251826");
284 }
285#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000286 return kInvalidOffset;
287 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100288 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000289#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000290 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000291#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000292 return kEmptyArchive;
293 }
294
Jiyong Parkcd997e62017-06-30 17:23:33 +0900295 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
296 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000297
298 /*
299 * It all looks good. Create a mapping for the CD, and set the fields
300 * in archive.
301 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700302
Elliott Hughese8f4b142018-10-19 16:09:39 -0700303 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700304 static_cast<size_t>(eocd->cd_size))) {
305 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000306 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000307 }
308
Narayan Kamath926973e2014-06-09 14:18:14 +0100309 archive->num_entries = eocd->num_records;
310 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000311
312 return 0;
313}
314
315/*
316 * Find the zip Central Directory and memory-map it.
317 *
318 * On success, returns 0 after populating fields from the EOCD area:
319 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700320 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000321 * num_entries
322 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700323static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000324 // Test file length. We use lseek64 to make sure the file
325 // is small enough to be a zip file (Its size must be less than
326 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700327 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000328 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000329 return kInvalidFile;
330 }
331
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800332 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100333 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000334 return kInvalidFile;
335 }
336
Narayan Kamath926973e2014-06-09 14:18:14 +0100337 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
338 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000339 return kInvalidFile;
340 }
341
342 /*
343 * Perform the traditional EOCD snipe hunt.
344 *
345 * We're searching for the End of Central Directory magic number,
346 * which appears at the start of the EOCD block. It's followed by
347 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
348 * need to read the last part of the file into a buffer, dig through
349 * it to find the magic number, parse some values out, and use those
350 * to determine the extent of the CD.
351 *
352 * We start by pulling in the last part of the file.
353 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100354 off64_t read_amount = kMaxEOCDSearch;
355 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000356 read_amount = file_length;
357 }
358
Tianjie Xu18c25922016-09-29 15:27:41 -0700359 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900360 int32_t result =
361 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000362 return result;
363}
364
365/*
366 * Parses the Zip archive's Central Directory. Allocates and populates the
367 * hash table.
368 *
369 * Returns 0 on success.
370 */
371static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700372 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
373 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100374 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000375
376 /*
377 * Create hash table. We have a minimum 75% load factor, possibly as
378 * low as 50% after we round off to a power of 2. There must be at
379 * least one unused entry to avoid an infinite loop during creation.
380 */
381 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900382 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100383 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700384 if (archive->hash_table == nullptr) {
385 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
386 archive->hash_table_size, sizeof(ZipString));
387 return -1;
388 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000389
390 /*
391 * Walk through the central directory, adding entries to the hash
392 * table and verifying values.
393 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100394 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000395 const uint8_t* ptr = cd_ptr;
396 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700397 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
398 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
399#if defined(__ANDROID__)
400 android_errorWriteLog(0x534e4554, "36392138");
401#endif
402 return -1;
403 }
404
Jiyong Parkcd997e62017-06-30 17:23:33 +0900405 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100406 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700407 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800408 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000409 }
410
Narayan Kamath926973e2014-06-09 14:18:14 +0100411 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000412 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800413 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900414 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800415 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000416 }
417
Narayan Kamath926973e2014-06-09 14:18:14 +0100418 const uint16_t file_name_length = cdr->file_name_length;
419 const uint16_t extra_length = cdr->extra_field_length;
420 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100421 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
422
Tianjie Xu9e020e22016-10-10 12:11:30 -0700423 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900424 ALOGW(
425 "Zip: file name boundary exceeds the central directory range, file_name_length: "
426 "%" PRIx16 ", cd_length: %zu",
427 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700428 return -1;
429 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000430 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
431 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800432 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100433 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000434
435 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700436 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100437 entry_name.name = file_name;
438 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100439 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
440 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800441 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000442 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800443 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000444 }
445
Narayan Kamath926973e2014-06-09 14:18:14 +0100446 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
447 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900448 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800449 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000450 }
451 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100452
453 uint32_t lfh_start_bytes;
454 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
455 sizeof(uint32_t), 0)) {
456 ALOGW("Zip: Unable to read header for entry at offset == 0.");
457 return -1;
458 }
459
460 if (lfh_start_bytes != LocalFileHeader::kSignature) {
461 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
462#if defined(__ANDROID__)
463 android_errorWriteLog(0x534e4554, "64211847");
464#endif
465 return -1;
466 }
467
Mark Salyzyn088bf902014-05-08 16:02:20 -0700468 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000469
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800470 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000471}
472
Jiyong Parkcd997e62017-06-30 17:23:33 +0900473static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000474 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700475 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000476 return result;
477 }
478
479 if ((result = ParseZipArchive(archive))) {
480 return result;
481 }
482
483 return 0;
484}
485
Jiyong Parkcd997e62017-06-30 17:23:33 +0900486int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
487 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700488 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000489 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000490 return OpenArchiveInternal(archive, debug_file_name);
491}
492
493int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800494 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700495 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000496 *handle = archive;
497
Narayan Kamath7462f022013-11-21 13:05:04 +0000498 if (fd < 0) {
499 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
500 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000501 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700502
Narayan Kamath7462f022013-11-21 13:05:04 +0000503 return OpenArchiveInternal(archive, fileName);
504}
505
Tianjie Xu18c25922016-09-29 15:27:41 -0700506int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900507 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700508 ZipArchive* archive = new ZipArchive(address, length);
509 *handle = archive;
510 return OpenArchiveInternal(archive, debug_file_name);
511}
512
Narayan Kamath7462f022013-11-21 13:05:04 +0000513/*
514 * Close a ZipArchive, closing the file and freeing the contents.
515 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700516void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000517 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100518 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000519}
520
Narayan Kamath162b7052017-06-05 13:21:12 +0100521static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100522 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700523 off64_t offset = entry->offset;
524 if (entry->method != kCompressStored) {
525 offset += entry->compressed_length;
526 } else {
527 offset += entry->uncompressed_length;
528 }
529
530 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000531 return kIoError;
532 }
533
Narayan Kamath926973e2014-06-09 14:18:14 +0100534 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700535 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
536 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000537
Narayan Kamath162b7052017-06-05 13:21:12 +0100538 // Validate that the values in the data descriptor match those in the central
539 // directory.
540 if (entry->compressed_length != descriptor->compressed_size ||
541 entry->uncompressed_length != descriptor->uncompressed_size ||
542 entry->crc32 != descriptor->crc32) {
543 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
544 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
545 entry->compressed_length, entry->uncompressed_length, entry->crc32,
546 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
547 return kInconsistentInformation;
548 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000549
550 return 0;
551}
552
Jiyong Parkcd997e62017-06-30 17:23:33 +0900553static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000554 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000555
556 // Recover the start of the central directory entry from the filename
557 // pointer. The filename is the first entry past the fixed-size data,
558 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100559 const ZipString from_offset =
560 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
561 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100562 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000563
564 // This is the base of our mmapped region, we have to sanity check that
565 // the name that's in the hash table is a pointer to a location within
566 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700567 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
568 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000569 ALOGW("Zip: Invalid entry pointer");
570 return kInvalidOffset;
571 }
572
Jiyong Parkcd997e62017-06-30 17:23:33 +0900573 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100574
Narayan Kamath7462f022013-11-21 13:05:04 +0000575 // The offset of the start of the central directory in the zipfile.
576 // We keep this lying around so that we can sanity check all our lengths
577 // and our per-file structures.
578 const off64_t cd_offset = archive->directory_offset;
579
580 // Fill out the compression method, modification time, crc32
581 // and other interesting attributes from the central directory. These
582 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100583 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900584 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100585 data->crc32 = cdr->crc32;
586 data->compressed_length = cdr->compressed_size;
587 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000588
589 // Figure out the local header offset from the central directory. The
590 // actual file data will begin after the local header and the name /
591 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100592 const off64_t local_header_offset = cdr->local_file_header_offset;
593 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000594 ALOGW("Zip: bad local hdr offset in zip");
595 return kInvalidOffset;
596 }
597
Narayan Kamath926973e2014-06-09 14:18:14 +0100598 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700599 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800600 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900601 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000602 return kIoError;
603 }
604
Jiyong Parkcd997e62017-06-30 17:23:33 +0900605 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100606
607 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700608 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900609 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000610 return kInvalidOffset;
611 }
612
613 // Paranoia: Match the values specified in the local file header
614 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700615
Narayan Kamath162b7052017-06-05 13:21:12 +0100616 // Warn if central directory and local file header don't agree on the use
617 // of a trailing Data Descriptor. The reference implementation is inconsistent
618 // and appears to use the LFH value during extraction (unzip) but the CD value
619 // while displayng information about archives (zipinfo). The spec remains
620 // silent on this inconsistency as well.
621 //
622 // For now, always use the version from the LFH but make sure that the values
623 // specified in the central directory match those in the data descriptor.
624 //
625 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
626 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
627 // encoded using UTF-8). This implementation does not check for the presence of
628 // that flag and always enforces that entry names are valid UTF-8.
629 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
630 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700631 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700632 }
633
634 // If there is no trailing data descriptor, verify that the central directory and local file
635 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100636 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000637 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900638 if (data->compressed_length != lfh->compressed_size ||
639 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
640 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
641 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
642 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
643 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000644 return kInconsistentInformation;
645 }
646 } else {
647 data->has_data_descriptor = 1;
648 }
649
Elliott Hughes55fd2932017-05-28 22:59:04 -0700650 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
651 if ((cdr->version_made_by >> 8) == 3) {
652 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
653 } else {
654 data->unix_mode = 0777;
655 }
656
Narayan Kamath7462f022013-11-21 13:05:04 +0000657 // Check that the local file header name matches the declared
658 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100659 if (lfh->file_name_length == nameLen) {
660 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200661 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000662 ALOGW("Zip: Invalid declared length");
663 return kInvalidOffset;
664 }
665
Tianjie Xu18c25922016-09-29 15:27:41 -0700666 std::vector<uint8_t> name_buf(nameLen);
667 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800668 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000669 return kIoError;
670 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100671 const ZipString from_offset =
672 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
673 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000674 return kInconsistentInformation;
675 }
676
Narayan Kamath7462f022013-11-21 13:05:04 +0000677 } else {
678 ALOGW("Zip: lfh name did not match central directory.");
679 return kInconsistentInformation;
680 }
681
Jiyong Parkcd997e62017-06-30 17:23:33 +0900682 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
683 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000684 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800685 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000686 return kInvalidOffset;
687 }
688
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800689 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700690 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900691 static_cast<int64_t>(data_offset), data->compressed_length,
692 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000693 return kInvalidOffset;
694 }
695
696 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900697 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
698 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
699 static_cast<int64_t>(data_offset), data->uncompressed_length,
700 static_cast<int64_t>(cd_offset));
701 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000702 }
703
704 data->offset = data_offset;
705 return 0;
706}
707
708struct IterationHandle {
709 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100710 // We're not using vector here because this code is used in the Windows SDK
711 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700712 ZipString prefix;
713 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000714 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100715
Jiyong Parkcd997e62017-06-30 17:23:33 +0900716 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700717 if (in_prefix) {
718 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
719 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
720 prefix.name = name_copy;
721 prefix.name_length = in_prefix->name_length;
722 } else {
723 prefix.name = NULL;
724 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700725 }
Yusuke Sato07447542015-06-25 14:39:19 -0700726 if (in_suffix) {
727 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
728 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
729 suffix.name = name_copy;
730 suffix.name_length = in_suffix->name_length;
731 } else {
732 suffix.name = NULL;
733 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700734 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100735 }
736
737 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700738 delete[] prefix.name;
739 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100740 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000741};
742
Ryan Prichard3673f992018-10-10 22:41:14 -0700743int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
744 const ZipString* optional_prefix, const ZipString* optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000745 if (archive == NULL || archive->hash_table == NULL) {
746 ALOGW("Zip: Invalid ZipArchiveHandle");
747 return kInvalidHandle;
748 }
749
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700750 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000751 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000752 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000753
Jiyong Parkcd997e62017-06-30 17:23:33 +0900754 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000755 return 0;
756}
757
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100758void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100759 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100760}
761
Ryan Prichard3673f992018-10-10 22:41:14 -0700762int32_t FindEntry(const ZipArchiveHandle archive, const ZipString& entryName, ZipEntry* data) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100763 if (entryName.name_length == 0) {
764 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000765 return kInvalidEntryName;
766 }
767
Zimuzo5a503ef2018-09-17 19:49:55 +0100768 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
769 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000770 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100771 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000772 return ent;
773 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000774 return FindEntry(archive, ent, data);
775}
776
Yusuke Sato07447542015-06-25 14:39:19 -0700777int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800778 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000779 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100780 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000781 return kInvalidHandle;
782 }
783
784 ZipArchive* archive = handle->archive;
785 if (archive == NULL || archive->hash_table == NULL) {
786 ALOGW("Zip: Invalid ZipArchiveHandle");
787 return kInvalidHandle;
788 }
789
790 const uint32_t currentOffset = handle->position;
791 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100792 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000793 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100794 const ZipString from_offset =
795 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
796 if (hash_table[i].name_offset != 0 &&
797 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
798 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000799 handle->position = (i + 1);
800 const int error = FindEntry(archive, i, data);
801 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100802 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000803 name->name_length = hash_table[i].name_length;
804 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000805 return error;
806 }
807 }
808
809 handle->position = 0;
810 return kIterationEnd;
811}
812
Narayan Kamathf899bd52015-04-17 11:53:14 +0100813// A Writer that writes data to a fixed size memory region.
814// The size of the memory region must be equal to the total size of
815// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100816class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100817 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900818 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100819
820 virtual bool Append(uint8_t* buf, size_t buf_size) override {
821 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700822 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900823 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100824 return false;
825 }
826
827 memcpy(buf_ + bytes_written_, buf, buf_size);
828 bytes_written_ += buf_size;
829 return true;
830 }
831
832 private:
833 uint8_t* const buf_;
834 const size_t size_;
835 size_t bytes_written_;
836};
837
838// A Writer that appends data to a file |fd| at its current position.
839// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100840class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100841 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100842 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
843 // guaranteeing that the file descriptor is valid and that there's enough
844 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800845 // is truncated to the correct length (no truncation if |fd| references a
846 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100847 //
848 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800849 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100850 const uint32_t declared_length = entry->uncompressed_length;
851 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
852 if (current_offset == -1) {
853 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800854 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100855 }
856
857 int result = 0;
858#if defined(__linux__)
859 if (declared_length > 0) {
860 // Make sure we have enough space on the volume to extract the compressed
861 // entry. Note that the call to ftruncate below will change the file size but
862 // will not allocate space on disk and this call to fallocate will not
863 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700864 // Note: fallocate is only supported by the following filesystems -
865 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
866 // EOPNOTSUPP error when issued in other filesystems.
867 // Hence, check for the return error code before concluding that the
868 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100869 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700870 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700871 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100872 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
873 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800874 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100875 }
876 }
877#endif // __linux__
878
Tao Baoa456c212016-11-15 10:08:07 -0800879 struct stat sb;
880 if (fstat(fd, &sb) == -1) {
881 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800882 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100883 }
884
Tao Baoa456c212016-11-15 10:08:07 -0800885 // Block device doesn't support ftruncate(2).
886 if (!S_ISBLK(sb.st_mode)) {
887 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
888 if (result == -1) {
889 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
890 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800891 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800892 }
893 }
894
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800895 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100896 }
897
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700898 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800899 : fd_(other.fd_),
900 declared_length_(other.declared_length_),
901 total_bytes_written_(other.total_bytes_written_) {
902 other.fd_ = -1;
903 }
904
905 bool IsValid() const { return fd_ != -1; }
906
Narayan Kamathf899bd52015-04-17 11:53:14 +0100907 virtual bool Append(uint8_t* buf, size_t buf_size) override {
908 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700909 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900910 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100911 return false;
912 }
913
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100914 const bool result = android::base::WriteFully(fd_, buf, buf_size);
915 if (result) {
916 total_bytes_written_ += buf_size;
917 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700918 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100919 }
920
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100921 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100922 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900923
Narayan Kamathf899bd52015-04-17 11:53:14 +0100924 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800925 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900926 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100927
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800928 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100929 const size_t declared_length_;
930 size_t total_bytes_written_;
931};
932
Narayan Kamath485b3642017-10-26 14:42:39 +0100933class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100934 public:
935 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
936 : Reader(), zip_file_(zip_file), entry_(entry) {}
937
938 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
939 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
940 }
941
942 virtual ~EntryReader() {}
943
944 private:
945 const MappedZipFile& zip_file_;
946 const ZipEntry* entry_;
947};
948
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800949// This method is using libz macros with old-style-casts
950#pragma GCC diagnostic push
951#pragma GCC diagnostic ignored "-Wold-style-cast"
952static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
953 return inflateInit2(stream, window_bits);
954}
955#pragma GCC diagnostic pop
956
Narayan Kamath485b3642017-10-26 14:42:39 +0100957namespace zip_archive {
958
959// Moved out of line to avoid -Wweak-vtables.
960Reader::~Reader() {}
961Writer::~Writer() {}
962
963int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
964 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700965 const size_t kBufSize = 32768;
966 std::vector<uint8_t> read_buf(kBufSize);
967 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000968 z_stream zstream;
969 int zerr;
970
971 /*
972 * Initialize the zlib stream struct.
973 */
974 memset(&zstream, 0, sizeof(zstream));
975 zstream.zalloc = Z_NULL;
976 zstream.zfree = Z_NULL;
977 zstream.opaque = Z_NULL;
978 zstream.next_in = NULL;
979 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700980 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000981 zstream.avail_out = kBufSize;
982 zstream.data_type = Z_UNKNOWN;
983
984 /*
985 * Use the undocumented "negative window bits" feature to tell zlib
986 * that there's no zlib header waiting for it.
987 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800988 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000989 if (zerr != Z_OK) {
990 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900991 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000992 } else {
993 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
994 }
995
996 return kZlibError;
997 }
998
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800999 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001000 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001001 };
1002
1003 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1004
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001005 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +01001006 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001007 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +00001008 do {
1009 /* read as much as we can */
1010 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001011 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
1012 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001013 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001014 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1015 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001016 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001017 }
1018
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001019 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001020
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001021 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001022 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001023 }
1024
1025 /* uncompress the data */
1026 zerr = inflate(&zstream, Z_NO_FLUSH);
1027 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001028 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1029 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001030 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001031 }
1032
1033 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001034 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001035 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001036 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001037 return kIoError;
1038 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001039 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001040 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001041
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001042 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001043 zstream.avail_out = kBufSize;
1044 }
1045 } while (zerr == Z_OK);
1046
Elliott Hughese8f4b142018-10-19 16:09:39 -07001047 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001048
Narayan Kamath162b7052017-06-05 13:21:12 +01001049 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1050 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1051 // doesn't bother calculating the checksum in that scenario. We just do
1052 // it ourselves above because there are no additional gains to be made by
1053 // having zlib calculate it for us, since they do it by calling crc32 in
1054 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001055 if (compute_crc) {
1056 *crc_out = crc;
1057 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001058
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001059 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001060 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1061 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001062 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001063 }
1064
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001065 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001066}
Narayan Kamath485b3642017-10-26 14:42:39 +01001067} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001068
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001069static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001070 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001071 const EntryReader reader(mapped_zip, entry);
1072
Narayan Kamath485b3642017-10-26 14:42:39 +01001073 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1074 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001075}
1076
Narayan Kamath485b3642017-10-26 14:42:39 +01001077static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1078 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001079 static const uint32_t kBufSize = 32768;
1080 std::vector<uint8_t> buf(kBufSize);
1081
1082 const uint32_t length = entry->uncompressed_length;
1083 uint32_t count = 0;
1084 uint64_t crc = 0;
1085 while (count < length) {
1086 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001087 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001088
Adam Lesinskide117e42017-06-19 10:27:38 -07001089 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001090 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001091
1092 // Make sure to read at offset to ensure concurrent access to the fd.
1093 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1094 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1095 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001096 return kIoError;
1097 }
1098
1099 if (!writer->Append(&buf[0], block_size)) {
1100 return kIoError;
1101 }
1102 crc = crc32(crc, &buf[0], block_size);
1103 count += block_size;
1104 }
1105
1106 *crc_out = crc;
1107
1108 return 0;
1109}
1110
Ryan Prichard3673f992018-10-10 22:41:14 -07001111int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001112 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001113
1114 // this should default to kUnknownCompressionMethod.
1115 int32_t return_value = -1;
1116 uint64_t crc = 0;
1117 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001118 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001119 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001120 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001121 }
1122
1123 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001124 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001125 if (return_value) {
1126 return return_value;
1127 }
1128 }
1129
Narayan Kamath162b7052017-06-05 13:21:12 +01001130 // Validate that the CRC matches the calculated value.
1131 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001132 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001133 return kInconsistentInformation;
1134 }
1135
1136 return return_value;
1137}
1138
Ryan Prichard3673f992018-10-10 22:41:14 -07001139int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001140 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001141 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001142}
1143
Ryan Prichard3673f992018-10-10 22:41:14 -07001144int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001145 auto writer = FileWriter::Create(fd, entry);
1146 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001147 return kIoError;
1148 }
1149
Ryan Prichard3673f992018-10-10 22:41:14 -07001150 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001151}
1152
1153const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001154 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1155 // match.
1156 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1157 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1158
1159 const uint32_t idx = -error_code;
1160 if (idx < arraysize(kErrorMessages)) {
1161 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001162 }
1163
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001164 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001165}
1166
Ryan Prichard3673f992018-10-10 22:41:14 -07001167int GetFileDescriptor(const ZipArchiveHandle archive) {
1168 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001169}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001170
Jiyong Parkcd997e62017-06-30 17:23:33 +09001171ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001172 size_t len = strlen(entry_name);
1173 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1174 name_length = static_cast<uint16_t>(len);
1175}
Tianjie Xu18c25922016-09-29 15:27:41 -07001176
1177#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001178class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001179 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001180 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1181 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001182
1183 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1184 return proc_function_(buf, buf_size, cookie_);
1185 }
1186
1187 private:
1188 ProcessZipEntryFunction proc_function_;
1189 void* cookie_;
1190};
1191
Ryan Prichard3673f992018-10-10 22:41:14 -07001192int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001193 ProcessZipEntryFunction func, void* cookie) {
1194 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001195 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001196}
1197
Jiyong Parkcd997e62017-06-30 17:23:33 +09001198#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001199
1200int MappedZipFile::GetFileDescriptor() const {
1201 if (!has_fd_) {
1202 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1203 return -1;
1204 }
1205 return fd_;
1206}
1207
1208void* MappedZipFile::GetBasePtr() const {
1209 if (has_fd_) {
1210 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1211 return nullptr;
1212 }
1213 return base_ptr_;
1214}
1215
1216off64_t MappedZipFile::GetFileLength() const {
1217 if (has_fd_) {
1218 off64_t result = lseek64(fd_, 0, SEEK_END);
1219 if (result == -1) {
1220 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1221 }
1222 return result;
1223 } else {
1224 if (base_ptr_ == nullptr) {
1225 ALOGE("Zip: invalid file map\n");
1226 return -1;
1227 }
1228 return static_cast<off64_t>(data_length_);
1229 }
1230}
1231
Tianjie Xu18c25922016-09-29 15:27:41 -07001232// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001233bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001234 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001235 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001236 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1237 return false;
1238 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001239 } else {
1240 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1241 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1242 return false;
1243 }
1244 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001245 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001246 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001247}
1248
1249void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1250 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1251 length_ = cd_size;
1252}
1253
Elliott Hughese8f4b142018-10-19 16:09:39 -07001254bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001255 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001256 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1257 cd_start_offset, cd_size, PROT_READ);
1258 if (!directory_map) return false;
Tianjie Xu18c25922016-09-29 15:27:41 -07001259
Elliott Hughese8f4b142018-10-19 16:09:39 -07001260 CHECK_EQ(directory_map->size(), cd_size);
1261 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001262 } else {
1263 if (mapped_zip.GetBasePtr() == nullptr) {
1264 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1265 return false;
1266 }
1267 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1268 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001269 ALOGE(
1270 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1271 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1272 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001273 return false;
1274 }
1275
1276 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1277 }
1278 return true;
1279}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001280
1281tm ZipEntry::GetModificationTime() const {
1282 tm t = {};
1283
1284 t.tm_hour = (mod_time >> 11) & 0x1f;
1285 t.tm_min = (mod_time >> 5) & 0x3f;
1286 t.tm_sec = (mod_time & 0x1f) << 1;
1287
1288 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1289 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1290 t.tm_mday = (mod_time >> 16) & 0x1f;
1291
1292 return t;
1293}