blob: 4221ee7d52698da31b89ba89855f13452bd7ec94 [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
Narayan Kamath7462f022013-11-21 13:05:04 +000023#include <assert.h>
24#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070025#include <fcntl.h>
26#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000027#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <stdlib.h>
29#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070030#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000031#include <unistd.h>
32
Dan Albert1ae07642015-04-09 14:11:18 -070033#include <memory>
34#include <vector>
35
Josh Gao1b496342018-07-17 11:08:48 -070036#if defined(__BIONIC__)
37#include <android/fdsan.h>
38#endif
39
Mark Salyzynff2dcd92016-09-28 15:54:45 -070040#include <android-base/file.h>
41#include <android-base/logging.h>
42#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
43#include <android-base/memory.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070044#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070045#include <log/log.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070046#include <utils/Compat.h>
47#include <utils/FileMap.h>
Christopher Ferrise6884ce2015-11-10 14:55:12 -080048#include "ziparchive/zip_archive.h"
Dan Albert1ae07642015-04-09 14:11:18 -070049#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000050
Narayan Kamath044bc8e2014-12-03 18:22:53 +000051#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070052#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080053#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070054
Dan Albert1ae07642015-04-09 14:11:18 -070055using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000056
Narayan Kamath162b7052017-06-05 13:21:12 +010057// Used to turn on crc checks - verify that the content CRC matches the values
58// specified in the local file header and the central directory.
59static const bool kCrcChecksEnabled = false;
60
Narayan Kamath926973e2014-06-09 14:18:14 +010061// This is for windows. If we don't open a file in binary mode, weird
Narayan Kamath7462f022013-11-21 13:05:04 +000062// things will happen.
63#ifndef O_BINARY
64#define O_BINARY 0
65#endif
66
Narayan Kamath926973e2014-06-09 14:18:14 +010067// The maximum number of bytes to scan backwards for the EOCD start.
68static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
69
Narayan Kamath7462f022013-11-21 13:05:04 +000070/*
71 * A Read-only Zip archive.
72 *
73 * We want "open" and "find entry by name" to be fast operations, and
74 * we want to use as little memory as possible. We memory-map the zip
75 * central directory, and load a hash table with pointers to the filenames
76 * (which aren't null-terminated). The other fields are at a fixed offset
77 * from the filename, so we don't need to extract those (but we do need
78 * to byte-read and endian-swap them every time we want them).
79 *
80 * It's possible that somebody has handed us a massive (~1GB) zip archive,
81 * so we can't expect to mmap the entire file.
82 *
83 * To speed comparisons when doing a lookup by name, we could make the mapping
84 * "private" (copy-on-write) and null-terminate the filenames after verifying
85 * the record structure. However, this requires a private mapping of
86 * every page that the Central Directory touches. Easier to tuck a copy
87 * of the string length into the hash table entry.
88 */
Narayan Kamath7462f022013-11-21 13:05:04 +000089
Narayan Kamath7462f022013-11-21 13:05:04 +000090/*
91 * Round up to the next highest power of 2.
92 *
93 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
94 */
95static uint32_t RoundUpPower2(uint32_t val) {
96 val--;
97 val |= val >> 1;
98 val |= val >> 2;
99 val |= val >> 4;
100 val |= val >> 8;
101 val |= val >> 16;
102 val++;
103
104 return val;
105}
106
Yusuke Sato07447542015-06-25 14:39:19 -0700107static uint32_t ComputeHash(const ZipString& name) {
Sebastian Pop1f93d712017-11-28 16:36:48 -0600108#if !defined(_WIN32)
109 return std::hash<std::string_view>{}(
110 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length));
111#else
112 // Remove this code path once the windows compiler knows how to compile the above statement.
Narayan Kamath7462f022013-11-21 13:05:04 +0000113 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100114 uint16_t len = name.name_length;
115 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000116
117 while (len--) {
118 hash = hash * 31 + *str++;
119 }
120
121 return hash;
Sebastian Pop1f93d712017-11-28 16:36:48 -0600122#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000123}
124
Zimuzo5a503ef2018-09-17 19:49:55 +0100125static bool isZipStringEqual(const uint8_t* start, const ZipString& zip_string,
126 const ZipStringOffset& zip_string_offset) {
127 const ZipString from_offset = zip_string_offset.GetZipString(start);
128 return from_offset == zip_string;
129}
130
131/**
132 * Returns offset of ZipString#name from the start of the central directory in the memory map.
133 * For valid ZipStrings contained in the zip archive mmap, 0 < offset < 0xffffff.
134 */
135static inline uint32_t GetOffset(const uint8_t* name, const uint8_t* start) {
136 CHECK_GT(name, start);
137 CHECK_LT(name, start + 0xffffff);
138 return static_cast<uint32_t>(name - start);
139}
140
Narayan Kamath7462f022013-11-21 13:05:04 +0000141/*
142 * Convert a ZipEntry to a hash table index, verifying that it's in a
143 * valid range.
144 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100145static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
146 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100147 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000148
149 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
150 uint32_t ent = hash & (hash_table_size - 1);
Zimuzo5a503ef2018-09-17 19:49:55 +0100151 while (hash_table[ent].name_offset != 0) {
152 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000153 return ent;
154 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000155 ent = (ent + 1) & (hash_table_size - 1);
156 }
157
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100158 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000159 return kEntryNotFound;
160}
161
162/*
163 * Add a new entry to the hash table.
164 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100165static int32_t AddToHash(ZipStringOffset* hash_table, const uint64_t hash_table_size,
166 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100167 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000168 uint32_t ent = hash & (hash_table_size - 1);
169
170 /*
171 * We over-allocated the table, so we're guaranteed to find an empty slot.
172 * Further, we guarantee that the hashtable size is not 0.
173 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100174 while (hash_table[ent].name_offset != 0) {
175 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000176 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100177 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000178 return kDuplicateEntry;
179 }
180 ent = (ent + 1) & (hash_table_size - 1);
181 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100182 hash_table[ent].name_offset = GetOffset(name.name, start);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100183 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000184 return 0;
185}
186
Josh Gaoabdfc242018-09-07 12:44:40 -0700187#if defined(__BIONIC__)
188uint64_t GetOwnerTag(const ZipArchive* archive) {
189 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
190 reinterpret_cast<uint64_t>(archive));
191}
192#endif
193
Josh Gao1b496342018-07-17 11:08:48 -0700194ZipArchive::ZipArchive(const int fd, bool assume_ownership)
195 : mapped_zip(fd),
196 close_file(assume_ownership),
197 directory_offset(0),
198 central_directory(),
199 directory_map(new android::FileMap()),
200 num_entries(0),
201 hash_table_size(0),
202 hash_table(nullptr) {
203#if defined(__BIONIC__)
204 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700205 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700206 }
207#endif
208}
209
210ZipArchive::ZipArchive(void* address, size_t length)
211 : mapped_zip(address, length),
212 close_file(false),
213 directory_offset(0),
214 central_directory(),
215 directory_map(new android::FileMap()),
216 num_entries(0),
217 hash_table_size(0),
218 hash_table(nullptr) {}
219
220ZipArchive::~ZipArchive() {
221 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
222#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700223 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700224#else
225 close(mapped_zip.GetFileDescriptor());
226#endif
227 }
228
229 free(hash_table);
230}
231
Tianjie Xu18c25922016-09-29 15:27:41 -0700232static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Zimuzo5a503ef2018-09-17 19:49:55 +0100233 off64_t file_length, off64_t read_amount,
234 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000235 const off64_t search_start = file_length - read_amount;
236
Jiyong Parkcd997e62017-06-30 17:23:33 +0900237 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
238 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
239 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000240 return kIoError;
241 }
242
243 /*
244 * Scan backward for the EOCD magic. In an archive without a trailing
245 * comment, we'll find it on the first try. (We may want to consider
246 * doing an initial minimal read; if we don't find it, retry with a
247 * second read as above.)
248 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100249 int i = read_amount - sizeof(EocdRecord);
250 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700251 if (scan_buffer[i] == 0x50) {
252 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
253 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
254 ALOGV("+++ Found EOCD at buf+%d", i);
255 break;
256 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000257 }
258 }
259 if (i < 0) {
260 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
261 return kInvalidFile;
262 }
263
264 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100265 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000266 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100267 * Verify that there's no trailing space at the end of the central directory
268 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000269 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900270 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100271 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100272 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100273 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100274 return kInvalidFile;
275 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000276
Narayan Kamath926973e2014-06-09 14:18:14 +0100277 /*
278 * Grab the CD offset and size, and the number of entries in the
279 * archive and verify that they look reasonable.
280 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700281 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100282 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900283 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700284#if defined(__ANDROID__)
285 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
286 android_errorWriteLog(0x534e4554, "31251826");
287 }
288#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000289 return kInvalidOffset;
290 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100291 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000292#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000293 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000294#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000295 return kEmptyArchive;
296 }
297
Jiyong Parkcd997e62017-06-30 17:23:33 +0900298 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
299 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000300
301 /*
302 * It all looks good. Create a mapping for the CD, and set the fields
303 * in archive.
304 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700305
306 if (!archive->InitializeCentralDirectory(debug_file_name,
307 static_cast<off64_t>(eocd->cd_start_offset),
308 static_cast<size_t>(eocd->cd_size))) {
309 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000310 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000311 }
312
Narayan Kamath926973e2014-06-09 14:18:14 +0100313 archive->num_entries = eocd->num_records;
314 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000315
316 return 0;
317}
318
319/*
320 * Find the zip Central Directory and memory-map it.
321 *
322 * On success, returns 0 after populating fields from the EOCD area:
323 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700324 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000325 * num_entries
326 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700327static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000328 // Test file length. We use lseek64 to make sure the file
329 // is small enough to be a zip file (Its size must be less than
330 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700331 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000332 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000333 return kInvalidFile;
334 }
335
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800336 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100337 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000338 return kInvalidFile;
339 }
340
Narayan Kamath926973e2014-06-09 14:18:14 +0100341 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
342 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000343 return kInvalidFile;
344 }
345
346 /*
347 * Perform the traditional EOCD snipe hunt.
348 *
349 * We're searching for the End of Central Directory magic number,
350 * which appears at the start of the EOCD block. It's followed by
351 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
352 * need to read the last part of the file into a buffer, dig through
353 * it to find the magic number, parse some values out, and use those
354 * to determine the extent of the CD.
355 *
356 * We start by pulling in the last part of the file.
357 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100358 off64_t read_amount = kMaxEOCDSearch;
359 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000360 read_amount = file_length;
361 }
362
Tianjie Xu18c25922016-09-29 15:27:41 -0700363 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900364 int32_t result =
365 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000366 return result;
367}
368
369/*
370 * Parses the Zip archive's Central Directory. Allocates and populates the
371 * hash table.
372 *
373 * Returns 0 on success.
374 */
375static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700376 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
377 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100378 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000379
380 /*
381 * Create hash table. We have a minimum 75% load factor, possibly as
382 * low as 50% after we round off to a power of 2. There must be at
383 * least one unused entry to avoid an infinite loop during creation.
384 */
385 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900386 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100387 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700388 if (archive->hash_table == nullptr) {
389 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
390 archive->hash_table_size, sizeof(ZipString));
391 return -1;
392 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000393
394 /*
395 * Walk through the central directory, adding entries to the hash
396 * table and verifying values.
397 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100398 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000399 const uint8_t* ptr = cd_ptr;
400 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700401 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
402 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
403#if defined(__ANDROID__)
404 android_errorWriteLog(0x534e4554, "36392138");
405#endif
406 return -1;
407 }
408
Jiyong Parkcd997e62017-06-30 17:23:33 +0900409 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100410 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700411 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800412 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000413 }
414
Narayan Kamath926973e2014-06-09 14:18:14 +0100415 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000416 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800417 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900418 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800419 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000420 }
421
Narayan Kamath926973e2014-06-09 14:18:14 +0100422 const uint16_t file_name_length = cdr->file_name_length;
423 const uint16_t extra_length = cdr->extra_field_length;
424 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100425 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
426
Tianjie Xu9e020e22016-10-10 12:11:30 -0700427 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900428 ALOGW(
429 "Zip: file name boundary exceeds the central directory range, file_name_length: "
430 "%" PRIx16 ", cd_length: %zu",
431 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700432 return -1;
433 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000434 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
435 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800436 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100437 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000438
439 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700440 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100441 entry_name.name = file_name;
442 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100443 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
444 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800445 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000446 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800447 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000448 }
449
Narayan Kamath926973e2014-06-09 14:18:14 +0100450 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
451 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900452 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800453 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000454 }
455 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100456
457 uint32_t lfh_start_bytes;
458 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
459 sizeof(uint32_t), 0)) {
460 ALOGW("Zip: Unable to read header for entry at offset == 0.");
461 return -1;
462 }
463
464 if (lfh_start_bytes != LocalFileHeader::kSignature) {
465 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
466#if defined(__ANDROID__)
467 android_errorWriteLog(0x534e4554, "64211847");
468#endif
469 return -1;
470 }
471
Mark Salyzyn088bf902014-05-08 16:02:20 -0700472 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000473
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800474 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000475}
476
Jiyong Parkcd997e62017-06-30 17:23:33 +0900477static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000478 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700479 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000480 return result;
481 }
482
483 if ((result = ParseZipArchive(archive))) {
484 return result;
485 }
486
487 return 0;
488}
489
Jiyong Parkcd997e62017-06-30 17:23:33 +0900490int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
491 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700492 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000493 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000494 return OpenArchiveInternal(archive, debug_file_name);
495}
496
497int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Ryan Mitchellc77f9d32018-08-25 14:06:29 -0700498 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700499 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000500 *handle = archive;
501
Narayan Kamath7462f022013-11-21 13:05:04 +0000502 if (fd < 0) {
503 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
504 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000505 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700506
Narayan Kamath7462f022013-11-21 13:05:04 +0000507 return OpenArchiveInternal(archive, fileName);
508}
509
Tianjie Xu18c25922016-09-29 15:27:41 -0700510int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900511 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700512 ZipArchive* archive = new ZipArchive(address, length);
513 *handle = archive;
514 return OpenArchiveInternal(archive, debug_file_name);
515}
516
Narayan Kamath7462f022013-11-21 13:05:04 +0000517/*
518 * Close a ZipArchive, closing the file and freeing the contents.
519 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700520void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000521 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100522 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000523}
524
Narayan Kamath162b7052017-06-05 13:21:12 +0100525static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100526 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700527 off64_t offset = entry->offset;
528 if (entry->method != kCompressStored) {
529 offset += entry->compressed_length;
530 } else {
531 offset += entry->uncompressed_length;
532 }
533
534 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000535 return kIoError;
536 }
537
Narayan Kamath926973e2014-06-09 14:18:14 +0100538 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700539 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
540 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000541
Narayan Kamath162b7052017-06-05 13:21:12 +0100542 // Validate that the values in the data descriptor match those in the central
543 // directory.
544 if (entry->compressed_length != descriptor->compressed_size ||
545 entry->uncompressed_length != descriptor->uncompressed_size ||
546 entry->crc32 != descriptor->crc32) {
547 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
548 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
549 entry->compressed_length, entry->uncompressed_length, entry->crc32,
550 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
551 return kInconsistentInformation;
552 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000553
554 return 0;
555}
556
Jiyong Parkcd997e62017-06-30 17:23:33 +0900557static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000558 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000559
560 // Recover the start of the central directory entry from the filename
561 // pointer. The filename is the first entry past the fixed-size data,
562 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100563 const ZipString from_offset =
564 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
565 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100566 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000567
568 // This is the base of our mmapped region, we have to sanity check that
569 // the name that's in the hash table is a pointer to a location within
570 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700571 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
572 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000573 ALOGW("Zip: Invalid entry pointer");
574 return kInvalidOffset;
575 }
576
Jiyong Parkcd997e62017-06-30 17:23:33 +0900577 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100578
Narayan Kamath7462f022013-11-21 13:05:04 +0000579 // The offset of the start of the central directory in the zipfile.
580 // We keep this lying around so that we can sanity check all our lengths
581 // and our per-file structures.
582 const off64_t cd_offset = archive->directory_offset;
583
584 // Fill out the compression method, modification time, crc32
585 // and other interesting attributes from the central directory. These
586 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100587 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900588 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100589 data->crc32 = cdr->crc32;
590 data->compressed_length = cdr->compressed_size;
591 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000592
593 // Figure out the local header offset from the central directory. The
594 // actual file data will begin after the local header and the name /
595 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100596 const off64_t local_header_offset = cdr->local_file_header_offset;
597 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000598 ALOGW("Zip: bad local hdr offset in zip");
599 return kInvalidOffset;
600 }
601
Narayan Kamath926973e2014-06-09 14:18:14 +0100602 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700603 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800604 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900605 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000606 return kIoError;
607 }
608
Jiyong Parkcd997e62017-06-30 17:23:33 +0900609 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100610
611 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700612 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900613 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000614 return kInvalidOffset;
615 }
616
617 // Paranoia: Match the values specified in the local file header
618 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700619
Narayan Kamath162b7052017-06-05 13:21:12 +0100620 // Warn if central directory and local file header don't agree on the use
621 // of a trailing Data Descriptor. The reference implementation is inconsistent
622 // and appears to use the LFH value during extraction (unzip) but the CD value
623 // while displayng information about archives (zipinfo). The spec remains
624 // silent on this inconsistency as well.
625 //
626 // For now, always use the version from the LFH but make sure that the values
627 // specified in the central directory match those in the data descriptor.
628 //
629 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
630 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
631 // encoded using UTF-8). This implementation does not check for the presence of
632 // that flag and always enforces that entry names are valid UTF-8.
633 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
634 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700635 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700636 }
637
638 // If there is no trailing data descriptor, verify that the central directory and local file
639 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100640 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000641 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900642 if (data->compressed_length != lfh->compressed_size ||
643 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
644 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
645 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
646 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
647 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000648 return kInconsistentInformation;
649 }
650 } else {
651 data->has_data_descriptor = 1;
652 }
653
Elliott Hughes55fd2932017-05-28 22:59:04 -0700654 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
655 if ((cdr->version_made_by >> 8) == 3) {
656 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
657 } else {
658 data->unix_mode = 0777;
659 }
660
Narayan Kamath7462f022013-11-21 13:05:04 +0000661 // Check that the local file header name matches the declared
662 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100663 if (lfh->file_name_length == nameLen) {
664 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200665 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000666 ALOGW("Zip: Invalid declared length");
667 return kInvalidOffset;
668 }
669
Tianjie Xu18c25922016-09-29 15:27:41 -0700670 std::vector<uint8_t> name_buf(nameLen);
671 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800672 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000673 return kIoError;
674 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100675 const ZipString from_offset =
676 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
677 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000678 return kInconsistentInformation;
679 }
680
Narayan Kamath7462f022013-11-21 13:05:04 +0000681 } else {
682 ALOGW("Zip: lfh name did not match central directory.");
683 return kInconsistentInformation;
684 }
685
Jiyong Parkcd997e62017-06-30 17:23:33 +0900686 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
687 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000688 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800689 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000690 return kInvalidOffset;
691 }
692
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800693 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700694 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900695 static_cast<int64_t>(data_offset), data->compressed_length,
696 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000697 return kInvalidOffset;
698 }
699
700 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900701 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
702 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
703 static_cast<int64_t>(data_offset), data->uncompressed_length,
704 static_cast<int64_t>(cd_offset));
705 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000706 }
707
708 data->offset = data_offset;
709 return 0;
710}
711
712struct IterationHandle {
713 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100714 // We're not using vector here because this code is used in the Windows SDK
715 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700716 ZipString prefix;
717 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000718 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100719
Jiyong Parkcd997e62017-06-30 17:23:33 +0900720 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700721 if (in_prefix) {
722 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
723 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
724 prefix.name = name_copy;
725 prefix.name_length = in_prefix->name_length;
726 } else {
727 prefix.name = NULL;
728 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700729 }
Yusuke Sato07447542015-06-25 14:39:19 -0700730 if (in_suffix) {
731 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
732 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
733 suffix.name = name_copy;
734 suffix.name_length = in_suffix->name_length;
735 } else {
736 suffix.name = NULL;
737 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700738 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100739 }
740
741 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700742 delete[] prefix.name;
743 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100744 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000745};
746
Ryan Prichard3673f992018-10-10 22:41:14 -0700747int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
748 const ZipString* optional_prefix, const ZipString* optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000749 if (archive == NULL || archive->hash_table == NULL) {
750 ALOGW("Zip: Invalid ZipArchiveHandle");
751 return kInvalidHandle;
752 }
753
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700754 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000755 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000756 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000757
Jiyong Parkcd997e62017-06-30 17:23:33 +0900758 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000759 return 0;
760}
761
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100762void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100763 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100764}
765
Ryan Prichard3673f992018-10-10 22:41:14 -0700766int32_t FindEntry(const ZipArchiveHandle archive, const ZipString& entryName, ZipEntry* data) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100767 if (entryName.name_length == 0) {
768 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000769 return kInvalidEntryName;
770 }
771
Zimuzo5a503ef2018-09-17 19:49:55 +0100772 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
773 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000774 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100775 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000776 return ent;
777 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000778 return FindEntry(archive, ent, data);
779}
780
Yusuke Sato07447542015-06-25 14:39:19 -0700781int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800782 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000783 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100784 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000785 return kInvalidHandle;
786 }
787
788 ZipArchive* archive = handle->archive;
789 if (archive == NULL || archive->hash_table == NULL) {
790 ALOGW("Zip: Invalid ZipArchiveHandle");
791 return kInvalidHandle;
792 }
793
794 const uint32_t currentOffset = handle->position;
795 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100796 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000797 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100798 const ZipString from_offset =
799 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
800 if (hash_table[i].name_offset != 0 &&
801 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
802 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000803 handle->position = (i + 1);
804 const int error = FindEntry(archive, i, data);
805 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100806 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000807 name->name_length = hash_table[i].name_length;
808 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000809 return error;
810 }
811 }
812
813 handle->position = 0;
814 return kIterationEnd;
815}
816
Narayan Kamathf899bd52015-04-17 11:53:14 +0100817// A Writer that writes data to a fixed size memory region.
818// The size of the memory region must be equal to the total size of
819// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100820class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100821 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900822 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100823
824 virtual bool Append(uint8_t* buf, size_t buf_size) override {
825 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900826 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
827 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100828 return false;
829 }
830
831 memcpy(buf_ + bytes_written_, buf, buf_size);
832 bytes_written_ += buf_size;
833 return true;
834 }
835
836 private:
837 uint8_t* const buf_;
838 const size_t size_;
839 size_t bytes_written_;
840};
841
842// A Writer that appends data to a file |fd| at its current position.
843// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100844class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100845 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100846 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
847 // guaranteeing that the file descriptor is valid and that there's enough
848 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800849 // is truncated to the correct length (no truncation if |fd| references a
850 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100851 //
852 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800853 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100854 const uint32_t declared_length = entry->uncompressed_length;
855 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
856 if (current_offset == -1) {
857 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800858 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100859 }
860
861 int result = 0;
862#if defined(__linux__)
863 if (declared_length > 0) {
864 // Make sure we have enough space on the volume to extract the compressed
865 // entry. Note that the call to ftruncate below will change the file size but
866 // will not allocate space on disk and this call to fallocate will not
867 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700868 // Note: fallocate is only supported by the following filesystems -
869 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
870 // EOPNOTSUPP error when issued in other filesystems.
871 // Hence, check for the return error code before concluding that the
872 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100873 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700874 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700875 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100876 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
877 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800878 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100879 }
880 }
881#endif // __linux__
882
Tao Baoa456c212016-11-15 10:08:07 -0800883 struct stat sb;
884 if (fstat(fd, &sb) == -1) {
885 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800886 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100887 }
888
Tao Baoa456c212016-11-15 10:08:07 -0800889 // Block device doesn't support ftruncate(2).
890 if (!S_ISBLK(sb.st_mode)) {
891 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
892 if (result == -1) {
893 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
894 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800895 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800896 }
897 }
898
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800899 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100900 }
901
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700902 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800903 : fd_(other.fd_),
904 declared_length_(other.declared_length_),
905 total_bytes_written_(other.total_bytes_written_) {
906 other.fd_ = -1;
907 }
908
909 bool IsValid() const { return fd_ != -1; }
910
Narayan Kamathf899bd52015-04-17 11:53:14 +0100911 virtual bool Append(uint8_t* buf, size_t buf_size) override {
912 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900913 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
914 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100915 return false;
916 }
917
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100918 const bool result = android::base::WriteFully(fd_, buf, buf_size);
919 if (result) {
920 total_bytes_written_ += buf_size;
921 } else {
922 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100923 }
924
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100925 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100926 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900927
Narayan Kamathf899bd52015-04-17 11:53:14 +0100928 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800929 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900930 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100931
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800932 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100933 const size_t declared_length_;
934 size_t total_bytes_written_;
935};
936
Narayan Kamath485b3642017-10-26 14:42:39 +0100937class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100938 public:
939 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
940 : Reader(), zip_file_(zip_file), entry_(entry) {}
941
942 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
943 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
944 }
945
946 virtual ~EntryReader() {}
947
948 private:
949 const MappedZipFile& zip_file_;
950 const ZipEntry* entry_;
951};
952
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800953// This method is using libz macros with old-style-casts
954#pragma GCC diagnostic push
955#pragma GCC diagnostic ignored "-Wold-style-cast"
956static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
957 return inflateInit2(stream, window_bits);
958}
959#pragma GCC diagnostic pop
960
Narayan Kamath485b3642017-10-26 14:42:39 +0100961namespace zip_archive {
962
963// Moved out of line to avoid -Wweak-vtables.
964Reader::~Reader() {}
965Writer::~Writer() {}
966
967int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
968 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700969 const size_t kBufSize = 32768;
970 std::vector<uint8_t> read_buf(kBufSize);
971 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000972 z_stream zstream;
973 int zerr;
974
975 /*
976 * Initialize the zlib stream struct.
977 */
978 memset(&zstream, 0, sizeof(zstream));
979 zstream.zalloc = Z_NULL;
980 zstream.zfree = Z_NULL;
981 zstream.opaque = Z_NULL;
982 zstream.next_in = NULL;
983 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700984 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000985 zstream.avail_out = kBufSize;
986 zstream.data_type = Z_UNKNOWN;
987
988 /*
989 * Use the undocumented "negative window bits" feature to tell zlib
990 * that there's no zlib header waiting for it.
991 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800992 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000993 if (zerr != Z_OK) {
994 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900995 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000996 } else {
997 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
998 }
999
1000 return kZlibError;
1001 }
1002
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001003 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001004 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001005 };
1006
1007 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1008
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001009 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +01001010 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001011 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +00001012 do {
1013 /* read as much as we can */
1014 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001015 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
1016 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001017 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001018 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1019 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001020 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001021 }
1022
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001023 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001024
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001025 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001026 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001027 }
1028
1029 /* uncompress the data */
1030 zerr = inflate(&zstream, Z_NO_FLUSH);
1031 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001032 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1033 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001034 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001035 }
1036
1037 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001038 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001039 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001040 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001041 return kIoError;
1042 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001043 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001044 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001045
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001046 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001047 zstream.avail_out = kBufSize;
1048 }
1049 } while (zerr == Z_OK);
1050
Jiyong Parkcd997e62017-06-30 17:23:33 +09001051 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001052
Narayan Kamath162b7052017-06-05 13:21:12 +01001053 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1054 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1055 // doesn't bother calculating the checksum in that scenario. We just do
1056 // it ourselves above because there are no additional gains to be made by
1057 // having zlib calculate it for us, since they do it by calling crc32 in
1058 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001059 if (compute_crc) {
1060 *crc_out = crc;
1061 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001062
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001063 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001064 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1065 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001066 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001067 }
1068
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001069 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001070}
Narayan Kamath485b3642017-10-26 14:42:39 +01001071} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001072
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001073static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001074 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001075 const EntryReader reader(mapped_zip, entry);
1076
Narayan Kamath485b3642017-10-26 14:42:39 +01001077 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1078 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001079}
1080
Narayan Kamath485b3642017-10-26 14:42:39 +01001081static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1082 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001083 static const uint32_t kBufSize = 32768;
1084 std::vector<uint8_t> buf(kBufSize);
1085
1086 const uint32_t length = entry->uncompressed_length;
1087 uint32_t count = 0;
1088 uint64_t crc = 0;
1089 while (count < length) {
1090 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001091 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001092
Adam Lesinskide117e42017-06-19 10:27:38 -07001093 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001094 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001095
1096 // Make sure to read at offset to ensure concurrent access to the fd.
1097 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1098 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1099 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001100 return kIoError;
1101 }
1102
1103 if (!writer->Append(&buf[0], block_size)) {
1104 return kIoError;
1105 }
1106 crc = crc32(crc, &buf[0], block_size);
1107 count += block_size;
1108 }
1109
1110 *crc_out = crc;
1111
1112 return 0;
1113}
1114
Ryan Prichard3673f992018-10-10 22:41:14 -07001115int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001116 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001117
1118 // this should default to kUnknownCompressionMethod.
1119 int32_t return_value = -1;
1120 uint64_t crc = 0;
1121 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001122 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001123 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001124 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001125 }
1126
1127 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001128 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001129 if (return_value) {
1130 return return_value;
1131 }
1132 }
1133
Narayan Kamath162b7052017-06-05 13:21:12 +01001134 // Validate that the CRC matches the calculated value.
1135 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001136 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001137 return kInconsistentInformation;
1138 }
1139
1140 return return_value;
1141}
1142
Ryan Prichard3673f992018-10-10 22:41:14 -07001143int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001144 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001145 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001146}
1147
Ryan Prichard3673f992018-10-10 22:41:14 -07001148int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001149 auto writer = FileWriter::Create(fd, entry);
1150 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001151 return kIoError;
1152 }
1153
Ryan Prichard3673f992018-10-10 22:41:14 -07001154 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001155}
1156
1157const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001158 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1159 // match.
1160 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1161 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1162
1163 const uint32_t idx = -error_code;
1164 if (idx < arraysize(kErrorMessages)) {
1165 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001166 }
1167
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001168 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001169}
1170
Ryan Prichard3673f992018-10-10 22:41:14 -07001171int GetFileDescriptor(const ZipArchiveHandle archive) {
1172 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001173}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001174
Jiyong Parkcd997e62017-06-30 17:23:33 +09001175ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001176 size_t len = strlen(entry_name);
1177 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1178 name_length = static_cast<uint16_t>(len);
1179}
Tianjie Xu18c25922016-09-29 15:27:41 -07001180
1181#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001182class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001183 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001184 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1185 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001186
1187 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1188 return proc_function_(buf, buf_size, cookie_);
1189 }
1190
1191 private:
1192 ProcessZipEntryFunction proc_function_;
1193 void* cookie_;
1194};
1195
Ryan Prichard3673f992018-10-10 22:41:14 -07001196int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001197 ProcessZipEntryFunction func, void* cookie) {
1198 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001199 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001200}
1201
Jiyong Parkcd997e62017-06-30 17:23:33 +09001202#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001203
1204int MappedZipFile::GetFileDescriptor() const {
1205 if (!has_fd_) {
1206 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1207 return -1;
1208 }
1209 return fd_;
1210}
1211
1212void* MappedZipFile::GetBasePtr() const {
1213 if (has_fd_) {
1214 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1215 return nullptr;
1216 }
1217 return base_ptr_;
1218}
1219
1220off64_t MappedZipFile::GetFileLength() const {
1221 if (has_fd_) {
1222 off64_t result = lseek64(fd_, 0, SEEK_END);
1223 if (result == -1) {
1224 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1225 }
1226 return result;
1227 } else {
1228 if (base_ptr_ == nullptr) {
1229 ALOGE("Zip: invalid file map\n");
1230 return -1;
1231 }
1232 return static_cast<off64_t>(data_length_);
1233 }
1234}
1235
Tianjie Xu18c25922016-09-29 15:27:41 -07001236// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001237bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001238 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001239 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001240 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1241 return false;
1242 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001243 } else {
1244 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1245 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1246 return false;
1247 }
1248 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001249 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001250 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001251}
1252
1253void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1254 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1255 length_ = cd_size;
1256}
1257
1258bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1259 size_t cd_size) {
1260 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001261 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1262 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001263 return false;
1264 }
1265
1266 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001267 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001268 } else {
1269 if (mapped_zip.GetBasePtr() == nullptr) {
1270 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1271 return false;
1272 }
1273 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1274 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001275 ALOGE(
1276 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1277 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1278 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001279 return false;
1280 }
1281
1282 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1283 }
1284 return true;
1285}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001286
1287tm ZipEntry::GetModificationTime() const {
1288 tm t = {};
1289
1290 t.tm_hour = (mod_time >> 11) & 0x1f;
1291 t.tm_min = (mod_time >> 5) & 0x3f;
1292 t.tm_sec = (mod_time & 0x1f) << 1;
1293
1294 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1295 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1296 t.tm_mday = (mod_time >> 16) & 0x1f;
1297
1298 return t;
1299}