blob: 0710d0addb46eb735745e620fc864fd2961a4ec3 [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));
Narayan Kamath7462f022013-11-21 13:05:04 +0000281 return kInvalidOffset;
282 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100283 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000284#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000285 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000286#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000287 return kEmptyArchive;
288 }
289
Jiyong Parkcd997e62017-06-30 17:23:33 +0900290 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
291 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000292
293 /*
294 * It all looks good. Create a mapping for the CD, and set the fields
295 * in archive.
296 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700297
Elliott Hughese8f4b142018-10-19 16:09:39 -0700298 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700299 static_cast<size_t>(eocd->cd_size))) {
300 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000301 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000302 }
303
Narayan Kamath926973e2014-06-09 14:18:14 +0100304 archive->num_entries = eocd->num_records;
305 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000306
307 return 0;
308}
309
310/*
311 * Find the zip Central Directory and memory-map it.
312 *
313 * On success, returns 0 after populating fields from the EOCD area:
314 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700315 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000316 * num_entries
317 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700318static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000319 // Test file length. We use lseek64 to make sure the file
320 // is small enough to be a zip file (Its size must be less than
321 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700322 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000323 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000324 return kInvalidFile;
325 }
326
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800327 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100328 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000329 return kInvalidFile;
330 }
331
Narayan Kamath926973e2014-06-09 14:18:14 +0100332 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
333 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000334 return kInvalidFile;
335 }
336
337 /*
338 * Perform the traditional EOCD snipe hunt.
339 *
340 * We're searching for the End of Central Directory magic number,
341 * which appears at the start of the EOCD block. It's followed by
342 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
343 * need to read the last part of the file into a buffer, dig through
344 * it to find the magic number, parse some values out, and use those
345 * to determine the extent of the CD.
346 *
347 * We start by pulling in the last part of the file.
348 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100349 off64_t read_amount = kMaxEOCDSearch;
350 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000351 read_amount = file_length;
352 }
353
Tianjie Xu18c25922016-09-29 15:27:41 -0700354 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900355 int32_t result =
356 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000357 return result;
358}
359
360/*
361 * Parses the Zip archive's Central Directory. Allocates and populates the
362 * hash table.
363 *
364 * Returns 0 on success.
365 */
366static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700367 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
368 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100369 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000370
371 /*
372 * Create hash table. We have a minimum 75% load factor, possibly as
373 * low as 50% after we round off to a power of 2. There must be at
374 * least one unused entry to avoid an infinite loop during creation.
375 */
376 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900377 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100378 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700379 if (archive->hash_table == nullptr) {
380 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
381 archive->hash_table_size, sizeof(ZipString));
382 return -1;
383 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000384
385 /*
386 * Walk through the central directory, adding entries to the hash
387 * table and verifying values.
388 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100389 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000390 const uint8_t* ptr = cd_ptr;
391 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700392 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
393 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
394#if defined(__ANDROID__)
395 android_errorWriteLog(0x534e4554, "36392138");
396#endif
397 return -1;
398 }
399
Jiyong Parkcd997e62017-06-30 17:23:33 +0900400 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100401 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700402 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800403 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000404 }
405
Narayan Kamath926973e2014-06-09 14:18:14 +0100406 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000407 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800408 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900409 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800410 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000411 }
412
Narayan Kamath926973e2014-06-09 14:18:14 +0100413 const uint16_t file_name_length = cdr->file_name_length;
414 const uint16_t extra_length = cdr->extra_field_length;
415 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100416 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
417
Tianjie Xu9e020e22016-10-10 12:11:30 -0700418 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900419 ALOGW(
420 "Zip: file name boundary exceeds the central directory range, file_name_length: "
421 "%" PRIx16 ", cd_length: %zu",
422 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700423 return -1;
424 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000425 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
426 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800427 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100428 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000429
430 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700431 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100432 entry_name.name = file_name;
433 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100434 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
435 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800436 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000437 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800438 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000439 }
440
Narayan Kamath926973e2014-06-09 14:18:14 +0100441 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
442 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900443 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800444 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000445 }
446 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100447
448 uint32_t lfh_start_bytes;
449 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
450 sizeof(uint32_t), 0)) {
451 ALOGW("Zip: Unable to read header for entry at offset == 0.");
452 return -1;
453 }
454
455 if (lfh_start_bytes != LocalFileHeader::kSignature) {
456 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
457#if defined(__ANDROID__)
458 android_errorWriteLog(0x534e4554, "64211847");
459#endif
460 return -1;
461 }
462
Mark Salyzyn088bf902014-05-08 16:02:20 -0700463 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000464
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800465 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000466}
467
Jiyong Parkcd997e62017-06-30 17:23:33 +0900468static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000469 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700470 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000471 return result;
472 }
473
474 if ((result = ParseZipArchive(archive))) {
475 return result;
476 }
477
478 return 0;
479}
480
Jiyong Parkcd997e62017-06-30 17:23:33 +0900481int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
482 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700483 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000484 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000485 return OpenArchiveInternal(archive, debug_file_name);
486}
487
488int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800489 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700490 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000491 *handle = archive;
492
Narayan Kamath7462f022013-11-21 13:05:04 +0000493 if (fd < 0) {
494 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
495 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000496 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700497
Narayan Kamath7462f022013-11-21 13:05:04 +0000498 return OpenArchiveInternal(archive, fileName);
499}
500
Tianjie Xu18c25922016-09-29 15:27:41 -0700501int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900502 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700503 ZipArchive* archive = new ZipArchive(address, length);
504 *handle = archive;
505 return OpenArchiveInternal(archive, debug_file_name);
506}
507
Narayan Kamath7462f022013-11-21 13:05:04 +0000508/*
509 * Close a ZipArchive, closing the file and freeing the contents.
510 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700511void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000512 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100513 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000514}
515
Narayan Kamath162b7052017-06-05 13:21:12 +0100516static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100517 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700518 off64_t offset = entry->offset;
519 if (entry->method != kCompressStored) {
520 offset += entry->compressed_length;
521 } else {
522 offset += entry->uncompressed_length;
523 }
524
525 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000526 return kIoError;
527 }
528
Narayan Kamath926973e2014-06-09 14:18:14 +0100529 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700530 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
531 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000532
Narayan Kamath162b7052017-06-05 13:21:12 +0100533 // Validate that the values in the data descriptor match those in the central
534 // directory.
535 if (entry->compressed_length != descriptor->compressed_size ||
536 entry->uncompressed_length != descriptor->uncompressed_size ||
537 entry->crc32 != descriptor->crc32) {
538 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
539 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
540 entry->compressed_length, entry->uncompressed_length, entry->crc32,
541 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
542 return kInconsistentInformation;
543 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000544
545 return 0;
546}
547
Jiyong Parkcd997e62017-06-30 17:23:33 +0900548static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000549 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000550
551 // Recover the start of the central directory entry from the filename
552 // pointer. The filename is the first entry past the fixed-size data,
553 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100554 const ZipString from_offset =
555 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
556 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100557 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000558
559 // This is the base of our mmapped region, we have to sanity check that
560 // the name that's in the hash table is a pointer to a location within
561 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700562 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
563 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000564 ALOGW("Zip: Invalid entry pointer");
565 return kInvalidOffset;
566 }
567
Jiyong Parkcd997e62017-06-30 17:23:33 +0900568 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100569
Narayan Kamath7462f022013-11-21 13:05:04 +0000570 // The offset of the start of the central directory in the zipfile.
571 // We keep this lying around so that we can sanity check all our lengths
572 // and our per-file structures.
573 const off64_t cd_offset = archive->directory_offset;
574
575 // Fill out the compression method, modification time, crc32
576 // and other interesting attributes from the central directory. These
577 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100578 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900579 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100580 data->crc32 = cdr->crc32;
581 data->compressed_length = cdr->compressed_size;
582 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000583
584 // Figure out the local header offset from the central directory. The
585 // actual file data will begin after the local header and the name /
586 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100587 const off64_t local_header_offset = cdr->local_file_header_offset;
588 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000589 ALOGW("Zip: bad local hdr offset in zip");
590 return kInvalidOffset;
591 }
592
Narayan Kamath926973e2014-06-09 14:18:14 +0100593 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700594 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800595 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900596 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000597 return kIoError;
598 }
599
Jiyong Parkcd997e62017-06-30 17:23:33 +0900600 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100601
602 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700603 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900604 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000605 return kInvalidOffset;
606 }
607
608 // Paranoia: Match the values specified in the local file header
609 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700610
Narayan Kamath162b7052017-06-05 13:21:12 +0100611 // Warn if central directory and local file header don't agree on the use
612 // of a trailing Data Descriptor. The reference implementation is inconsistent
613 // and appears to use the LFH value during extraction (unzip) but the CD value
614 // while displayng information about archives (zipinfo). The spec remains
615 // silent on this inconsistency as well.
616 //
617 // For now, always use the version from the LFH but make sure that the values
618 // specified in the central directory match those in the data descriptor.
619 //
620 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
621 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
622 // encoded using UTF-8). This implementation does not check for the presence of
623 // that flag and always enforces that entry names are valid UTF-8.
624 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
625 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700626 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700627 }
628
629 // If there is no trailing data descriptor, verify that the central directory and local file
630 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100631 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000632 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900633 if (data->compressed_length != lfh->compressed_size ||
634 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
635 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
636 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
637 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
638 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000639 return kInconsistentInformation;
640 }
641 } else {
642 data->has_data_descriptor = 1;
643 }
644
Elliott Hughes55fd2932017-05-28 22:59:04 -0700645 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
646 if ((cdr->version_made_by >> 8) == 3) {
647 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
648 } else {
649 data->unix_mode = 0777;
650 }
651
Narayan Kamath7462f022013-11-21 13:05:04 +0000652 // Check that the local file header name matches the declared
653 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100654 if (lfh->file_name_length == nameLen) {
655 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200656 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000657 ALOGW("Zip: Invalid declared length");
658 return kInvalidOffset;
659 }
660
Tianjie Xu18c25922016-09-29 15:27:41 -0700661 std::vector<uint8_t> name_buf(nameLen);
662 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800663 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000664 return kIoError;
665 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100666 const ZipString from_offset =
667 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
668 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000669 return kInconsistentInformation;
670 }
671
Narayan Kamath7462f022013-11-21 13:05:04 +0000672 } else {
673 ALOGW("Zip: lfh name did not match central directory.");
674 return kInconsistentInformation;
675 }
676
Jiyong Parkcd997e62017-06-30 17:23:33 +0900677 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
678 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000679 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800680 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000681 return kInvalidOffset;
682 }
683
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800684 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700685 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900686 static_cast<int64_t>(data_offset), data->compressed_length,
687 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000688 return kInvalidOffset;
689 }
690
691 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900692 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
693 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
694 static_cast<int64_t>(data_offset), data->uncompressed_length,
695 static_cast<int64_t>(cd_offset));
696 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000697 }
698
699 data->offset = data_offset;
700 return 0;
701}
702
703struct IterationHandle {
704 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100705 // We're not using vector here because this code is used in the Windows SDK
706 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700707 ZipString prefix;
708 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000709 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100710
Jiyong Parkcd997e62017-06-30 17:23:33 +0900711 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700712 if (in_prefix) {
713 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
714 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
715 prefix.name = name_copy;
716 prefix.name_length = in_prefix->name_length;
717 } else {
718 prefix.name = NULL;
719 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700720 }
Yusuke Sato07447542015-06-25 14:39:19 -0700721 if (in_suffix) {
722 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
723 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
724 suffix.name = name_copy;
725 suffix.name_length = in_suffix->name_length;
726 } else {
727 suffix.name = NULL;
728 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700729 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100730 }
731
732 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700733 delete[] prefix.name;
734 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100735 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000736};
737
Ryan Prichard3673f992018-10-10 22:41:14 -0700738int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
739 const ZipString* optional_prefix, const ZipString* optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000740 if (archive == NULL || archive->hash_table == NULL) {
741 ALOGW("Zip: Invalid ZipArchiveHandle");
742 return kInvalidHandle;
743 }
744
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700745 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000746 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000747 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000748
Jiyong Parkcd997e62017-06-30 17:23:33 +0900749 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000750 return 0;
751}
752
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100753void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100754 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100755}
756
Ryan Prichard3673f992018-10-10 22:41:14 -0700757int32_t FindEntry(const ZipArchiveHandle archive, const ZipString& entryName, ZipEntry* data) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100758 if (entryName.name_length == 0) {
759 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000760 return kInvalidEntryName;
761 }
762
Zimuzo5a503ef2018-09-17 19:49:55 +0100763 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
764 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000765 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100766 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000767 return ent;
768 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000769 return FindEntry(archive, ent, data);
770}
771
Yusuke Sato07447542015-06-25 14:39:19 -0700772int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800773 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000774 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100775 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000776 return kInvalidHandle;
777 }
778
779 ZipArchive* archive = handle->archive;
780 if (archive == NULL || archive->hash_table == NULL) {
781 ALOGW("Zip: Invalid ZipArchiveHandle");
782 return kInvalidHandle;
783 }
784
785 const uint32_t currentOffset = handle->position;
786 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100787 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000788 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100789 const ZipString from_offset =
790 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
791 if (hash_table[i].name_offset != 0 &&
792 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
793 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000794 handle->position = (i + 1);
795 const int error = FindEntry(archive, i, data);
796 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100797 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000798 name->name_length = hash_table[i].name_length;
799 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000800 return error;
801 }
802 }
803
804 handle->position = 0;
805 return kIterationEnd;
806}
807
Narayan Kamathf899bd52015-04-17 11:53:14 +0100808// A Writer that writes data to a fixed size memory region.
809// The size of the memory region must be equal to the total size of
810// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100811class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100812 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900813 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100814
815 virtual bool Append(uint8_t* buf, size_t buf_size) override {
816 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700817 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900818 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100819 return false;
820 }
821
822 memcpy(buf_ + bytes_written_, buf, buf_size);
823 bytes_written_ += buf_size;
824 return true;
825 }
826
827 private:
828 uint8_t* const buf_;
829 const size_t size_;
830 size_t bytes_written_;
831};
832
833// A Writer that appends data to a file |fd| at its current position.
834// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100835class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100836 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100837 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
838 // guaranteeing that the file descriptor is valid and that there's enough
839 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800840 // is truncated to the correct length (no truncation if |fd| references a
841 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100842 //
843 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800844 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100845 const uint32_t declared_length = entry->uncompressed_length;
846 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
847 if (current_offset == -1) {
848 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800849 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100850 }
851
852 int result = 0;
853#if defined(__linux__)
854 if (declared_length > 0) {
855 // Make sure we have enough space on the volume to extract the compressed
856 // entry. Note that the call to ftruncate below will change the file size but
857 // will not allocate space on disk and this call to fallocate will not
858 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700859 // Note: fallocate is only supported by the following filesystems -
860 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
861 // EOPNOTSUPP error when issued in other filesystems.
862 // Hence, check for the return error code before concluding that the
863 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100864 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700865 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700866 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100867 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
868 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800869 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100870 }
871 }
872#endif // __linux__
873
Tao Baoa456c212016-11-15 10:08:07 -0800874 struct stat sb;
875 if (fstat(fd, &sb) == -1) {
876 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800877 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100878 }
879
Tao Baoa456c212016-11-15 10:08:07 -0800880 // Block device doesn't support ftruncate(2).
881 if (!S_ISBLK(sb.st_mode)) {
882 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
883 if (result == -1) {
884 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
885 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800886 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800887 }
888 }
889
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800890 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100891 }
892
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700893 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800894 : fd_(other.fd_),
895 declared_length_(other.declared_length_),
896 total_bytes_written_(other.total_bytes_written_) {
897 other.fd_ = -1;
898 }
899
900 bool IsValid() const { return fd_ != -1; }
901
Narayan Kamathf899bd52015-04-17 11:53:14 +0100902 virtual bool Append(uint8_t* buf, size_t buf_size) override {
903 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700904 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900905 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100906 return false;
907 }
908
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100909 const bool result = android::base::WriteFully(fd_, buf, buf_size);
910 if (result) {
911 total_bytes_written_ += buf_size;
912 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700913 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100914 }
915
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100916 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100917 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900918
Narayan Kamathf899bd52015-04-17 11:53:14 +0100919 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800920 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900921 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100922
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800923 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100924 const size_t declared_length_;
925 size_t total_bytes_written_;
926};
927
Narayan Kamath485b3642017-10-26 14:42:39 +0100928class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100929 public:
930 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
931 : Reader(), zip_file_(zip_file), entry_(entry) {}
932
933 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
934 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
935 }
936
937 virtual ~EntryReader() {}
938
939 private:
940 const MappedZipFile& zip_file_;
941 const ZipEntry* entry_;
942};
943
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800944// This method is using libz macros with old-style-casts
945#pragma GCC diagnostic push
946#pragma GCC diagnostic ignored "-Wold-style-cast"
947static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
948 return inflateInit2(stream, window_bits);
949}
950#pragma GCC diagnostic pop
951
Narayan Kamath485b3642017-10-26 14:42:39 +0100952namespace zip_archive {
953
954// Moved out of line to avoid -Wweak-vtables.
955Reader::~Reader() {}
956Writer::~Writer() {}
957
958int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
959 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700960 const size_t kBufSize = 32768;
961 std::vector<uint8_t> read_buf(kBufSize);
962 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000963 z_stream zstream;
964 int zerr;
965
966 /*
967 * Initialize the zlib stream struct.
968 */
969 memset(&zstream, 0, sizeof(zstream));
970 zstream.zalloc = Z_NULL;
971 zstream.zfree = Z_NULL;
972 zstream.opaque = Z_NULL;
973 zstream.next_in = NULL;
974 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700975 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000976 zstream.avail_out = kBufSize;
977 zstream.data_type = Z_UNKNOWN;
978
979 /*
980 * Use the undocumented "negative window bits" feature to tell zlib
981 * that there's no zlib header waiting for it.
982 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800983 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000984 if (zerr != Z_OK) {
985 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900986 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000987 } else {
988 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
989 }
990
991 return kZlibError;
992 }
993
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800994 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900995 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800996 };
997
998 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
999
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001000 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +01001001 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001002 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +00001003 do {
1004 /* read as much as we can */
1005 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001006 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
1007 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001008 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001009 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1010 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001011 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001012 }
1013
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001014 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001015
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001016 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001017 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001018 }
1019
1020 /* uncompress the data */
1021 zerr = inflate(&zstream, Z_NO_FLUSH);
1022 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001023 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1024 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001025 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001026 }
1027
1028 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001029 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001030 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001031 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001032 return kIoError;
1033 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001034 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001035 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001036
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001037 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001038 zstream.avail_out = kBufSize;
1039 }
1040 } while (zerr == Z_OK);
1041
Elliott Hughese8f4b142018-10-19 16:09:39 -07001042 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001043
Narayan Kamath162b7052017-06-05 13:21:12 +01001044 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1045 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1046 // doesn't bother calculating the checksum in that scenario. We just do
1047 // it ourselves above because there are no additional gains to be made by
1048 // having zlib calculate it for us, since they do it by calling crc32 in
1049 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001050 if (compute_crc) {
1051 *crc_out = crc;
1052 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001053
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001054 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001055 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1056 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001057 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001058 }
1059
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001060 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001061}
Narayan Kamath485b3642017-10-26 14:42:39 +01001062} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001063
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001064static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001065 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001066 const EntryReader reader(mapped_zip, entry);
1067
Narayan Kamath485b3642017-10-26 14:42:39 +01001068 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1069 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001070}
1071
Narayan Kamath485b3642017-10-26 14:42:39 +01001072static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1073 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001074 static const uint32_t kBufSize = 32768;
1075 std::vector<uint8_t> buf(kBufSize);
1076
1077 const uint32_t length = entry->uncompressed_length;
1078 uint32_t count = 0;
1079 uint64_t crc = 0;
1080 while (count < length) {
1081 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001082 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001083
Adam Lesinskide117e42017-06-19 10:27:38 -07001084 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001085 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001086
1087 // Make sure to read at offset to ensure concurrent access to the fd.
1088 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1089 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1090 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001091 return kIoError;
1092 }
1093
1094 if (!writer->Append(&buf[0], block_size)) {
1095 return kIoError;
1096 }
1097 crc = crc32(crc, &buf[0], block_size);
1098 count += block_size;
1099 }
1100
1101 *crc_out = crc;
1102
1103 return 0;
1104}
1105
Ryan Prichard3673f992018-10-10 22:41:14 -07001106int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001107 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001108
1109 // this should default to kUnknownCompressionMethod.
1110 int32_t return_value = -1;
1111 uint64_t crc = 0;
1112 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001113 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001114 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001115 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001116 }
1117
1118 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001119 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001120 if (return_value) {
1121 return return_value;
1122 }
1123 }
1124
Narayan Kamath162b7052017-06-05 13:21:12 +01001125 // Validate that the CRC matches the calculated value.
1126 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001127 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001128 return kInconsistentInformation;
1129 }
1130
1131 return return_value;
1132}
1133
Ryan Prichard3673f992018-10-10 22:41:14 -07001134int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001135 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001136 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001137}
1138
Ryan Prichard3673f992018-10-10 22:41:14 -07001139int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001140 auto writer = FileWriter::Create(fd, entry);
1141 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001142 return kIoError;
1143 }
1144
Ryan Prichard3673f992018-10-10 22:41:14 -07001145 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001146}
1147
1148const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001149 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1150 // match.
1151 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1152 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1153
1154 const uint32_t idx = -error_code;
1155 if (idx < arraysize(kErrorMessages)) {
1156 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001157 }
1158
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001159 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001160}
1161
Ryan Prichard3673f992018-10-10 22:41:14 -07001162int GetFileDescriptor(const ZipArchiveHandle archive) {
1163 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001164}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001165
Jiyong Parkcd997e62017-06-30 17:23:33 +09001166ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001167 size_t len = strlen(entry_name);
1168 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1169 name_length = static_cast<uint16_t>(len);
1170}
Tianjie Xu18c25922016-09-29 15:27:41 -07001171
1172#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001173class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001174 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001175 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1176 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001177
1178 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1179 return proc_function_(buf, buf_size, cookie_);
1180 }
1181
1182 private:
1183 ProcessZipEntryFunction proc_function_;
1184 void* cookie_;
1185};
1186
Ryan Prichard3673f992018-10-10 22:41:14 -07001187int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001188 ProcessZipEntryFunction func, void* cookie) {
1189 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001190 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001191}
1192
Jiyong Parkcd997e62017-06-30 17:23:33 +09001193#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001194
1195int MappedZipFile::GetFileDescriptor() const {
1196 if (!has_fd_) {
1197 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1198 return -1;
1199 }
1200 return fd_;
1201}
1202
1203void* MappedZipFile::GetBasePtr() const {
1204 if (has_fd_) {
1205 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1206 return nullptr;
1207 }
1208 return base_ptr_;
1209}
1210
1211off64_t MappedZipFile::GetFileLength() const {
1212 if (has_fd_) {
1213 off64_t result = lseek64(fd_, 0, SEEK_END);
1214 if (result == -1) {
1215 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1216 }
1217 return result;
1218 } else {
1219 if (base_ptr_ == nullptr) {
1220 ALOGE("Zip: invalid file map\n");
1221 return -1;
1222 }
1223 return static_cast<off64_t>(data_length_);
1224 }
1225}
1226
Tianjie Xu18c25922016-09-29 15:27:41 -07001227// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001228bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001229 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001230 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001231 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1232 return false;
1233 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001234 } else {
1235 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1236 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1237 return false;
1238 }
1239 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001240 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001241 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001242}
1243
1244void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1245 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1246 length_ = cd_size;
1247}
1248
Elliott Hughese8f4b142018-10-19 16:09:39 -07001249bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001250 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001251 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1252 cd_start_offset, cd_size, PROT_READ);
1253 if (!directory_map) return false;
Tianjie Xu18c25922016-09-29 15:27:41 -07001254
Elliott Hughese8f4b142018-10-19 16:09:39 -07001255 CHECK_EQ(directory_map->size(), cd_size);
1256 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001257 } else {
1258 if (mapped_zip.GetBasePtr() == nullptr) {
1259 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1260 return false;
1261 }
1262 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1263 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001264 ALOGE(
1265 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1266 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1267 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001268 return false;
1269 }
1270
1271 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1272 }
1273 return true;
1274}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001275
1276tm ZipEntry::GetModificationTime() const {
1277 tm t = {};
1278
1279 t.tm_hour = (mod_time >> 11) & 0x1f;
1280 t.tm_min = (mod_time >> 5) & 0x3f;
1281 t.tm_sec = (mod_time & 0x1f) << 1;
1282
1283 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1284 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1285 t.tm_mday = (mod_time >> 16) & 0x1f;
1286
1287 return t;
1288}