blob: fb3313be1fec8b1f3e378d88d0fc11864d8605bf [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
125/*
126 * Convert a ZipEntry to a hash table index, verifying that it's in a
127 * valid range.
128 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900129static int64_t EntryToIndex(const ZipString* hash_table, const uint32_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700130 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100131 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000132
133 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
134 uint32_t ent = hash & (hash_table_size - 1);
135 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700136 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000137 return ent;
138 }
139
140 ent = (ent + 1) & (hash_table_size - 1);
141 }
142
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100143 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000144 return kEntryNotFound;
145}
146
147/*
148 * Add a new entry to the hash table.
149 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900150static int32_t AddToHash(ZipString* hash_table, const uint64_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700151 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100152 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000153 uint32_t ent = hash & (hash_table_size - 1);
154
155 /*
156 * We over-allocated the table, so we're guaranteed to find an empty slot.
157 * Further, we guarantee that the hashtable size is not 0.
158 */
159 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700160 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000161 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100162 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000163 return kDuplicateEntry;
164 }
165 ent = (ent + 1) & (hash_table_size - 1);
166 }
167
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100168 hash_table[ent].name = name.name;
169 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000170 return 0;
171}
172
Josh Gaoabdfc242018-09-07 12:44:40 -0700173#if defined(__BIONIC__)
174uint64_t GetOwnerTag(const ZipArchive* archive) {
175 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
176 reinterpret_cast<uint64_t>(archive));
177}
178#endif
179
Josh Gao1b496342018-07-17 11:08:48 -0700180ZipArchive::ZipArchive(const int fd, bool assume_ownership)
181 : mapped_zip(fd),
182 close_file(assume_ownership),
183 directory_offset(0),
184 central_directory(),
185 directory_map(new android::FileMap()),
186 num_entries(0),
187 hash_table_size(0),
188 hash_table(nullptr) {
189#if defined(__BIONIC__)
190 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700191 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700192 }
193#endif
194}
195
196ZipArchive::ZipArchive(void* address, size_t length)
197 : mapped_zip(address, length),
198 close_file(false),
199 directory_offset(0),
200 central_directory(),
201 directory_map(new android::FileMap()),
202 num_entries(0),
203 hash_table_size(0),
204 hash_table(nullptr) {}
205
206ZipArchive::~ZipArchive() {
207 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
208#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700209 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700210#else
211 close(mapped_zip.GetFileDescriptor());
212#endif
213 }
214
215 free(hash_table);
216}
217
Tianjie Xu18c25922016-09-29 15:27:41 -0700218static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900219 off64_t file_length, off64_t read_amount, uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000220 const off64_t search_start = file_length - read_amount;
221
Jiyong Parkcd997e62017-06-30 17:23:33 +0900222 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
223 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
224 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000225 return kIoError;
226 }
227
228 /*
229 * Scan backward for the EOCD magic. In an archive without a trailing
230 * comment, we'll find it on the first try. (We may want to consider
231 * doing an initial minimal read; if we don't find it, retry with a
232 * second read as above.)
233 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100234 int i = read_amount - sizeof(EocdRecord);
235 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700236 if (scan_buffer[i] == 0x50) {
237 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
238 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
239 ALOGV("+++ Found EOCD at buf+%d", i);
240 break;
241 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000242 }
243 }
244 if (i < 0) {
245 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
246 return kInvalidFile;
247 }
248
249 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100250 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000251 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100252 * Verify that there's no trailing space at the end of the central directory
253 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000254 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900255 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100256 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100257 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100258 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100259 return kInvalidFile;
260 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000261
Narayan Kamath926973e2014-06-09 14:18:14 +0100262 /*
263 * Grab the CD offset and size, and the number of entries in the
264 * archive and verify that they look reasonable.
265 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700266 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100267 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900268 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700269#if defined(__ANDROID__)
270 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
271 android_errorWriteLog(0x534e4554, "31251826");
272 }
273#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000274 return kInvalidOffset;
275 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100276 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000277#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000278 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000279#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000280 return kEmptyArchive;
281 }
282
Jiyong Parkcd997e62017-06-30 17:23:33 +0900283 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
284 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000285
286 /*
287 * It all looks good. Create a mapping for the CD, and set the fields
288 * in archive.
289 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700290
291 if (!archive->InitializeCentralDirectory(debug_file_name,
292 static_cast<off64_t>(eocd->cd_start_offset),
293 static_cast<size_t>(eocd->cd_size))) {
294 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000295 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000296 }
297
Narayan Kamath926973e2014-06-09 14:18:14 +0100298 archive->num_entries = eocd->num_records;
299 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000300
301 return 0;
302}
303
304/*
305 * Find the zip Central Directory and memory-map it.
306 *
307 * On success, returns 0 after populating fields from the EOCD area:
308 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700309 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000310 * num_entries
311 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700312static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000313 // Test file length. We use lseek64 to make sure the file
314 // is small enough to be a zip file (Its size must be less than
315 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700316 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000317 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000318 return kInvalidFile;
319 }
320
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800321 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100322 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000323 return kInvalidFile;
324 }
325
Narayan Kamath926973e2014-06-09 14:18:14 +0100326 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
327 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000328 return kInvalidFile;
329 }
330
331 /*
332 * Perform the traditional EOCD snipe hunt.
333 *
334 * We're searching for the End of Central Directory magic number,
335 * which appears at the start of the EOCD block. It's followed by
336 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
337 * need to read the last part of the file into a buffer, dig through
338 * it to find the magic number, parse some values out, and use those
339 * to determine the extent of the CD.
340 *
341 * We start by pulling in the last part of the file.
342 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100343 off64_t read_amount = kMaxEOCDSearch;
344 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000345 read_amount = file_length;
346 }
347
Tianjie Xu18c25922016-09-29 15:27:41 -0700348 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900349 int32_t result =
350 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000351 return result;
352}
353
354/*
355 * Parses the Zip archive's Central Directory. Allocates and populates the
356 * hash table.
357 *
358 * Returns 0 on success.
359 */
360static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700361 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
362 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100363 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000364
365 /*
366 * Create hash table. We have a minimum 75% load factor, possibly as
367 * low as 50% after we round off to a power of 2. There must be at
368 * least one unused entry to avoid an infinite loop during creation.
369 */
370 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900371 archive->hash_table =
372 reinterpret_cast<ZipString*>(calloc(archive->hash_table_size, sizeof(ZipString)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700373 if (archive->hash_table == nullptr) {
374 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
375 archive->hash_table_size, sizeof(ZipString));
376 return -1;
377 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000378
379 /*
380 * Walk through the central directory, adding entries to the hash
381 * table and verifying values.
382 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100383 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000384 const uint8_t* ptr = cd_ptr;
385 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700386 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
387 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
388#if defined(__ANDROID__)
389 android_errorWriteLog(0x534e4554, "36392138");
390#endif
391 return -1;
392 }
393
Jiyong Parkcd997e62017-06-30 17:23:33 +0900394 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100395 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700396 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800397 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000398 }
399
Narayan Kamath926973e2014-06-09 14:18:14 +0100400 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000401 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800402 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900403 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800404 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000405 }
406
Narayan Kamath926973e2014-06-09 14:18:14 +0100407 const uint16_t file_name_length = cdr->file_name_length;
408 const uint16_t extra_length = cdr->extra_field_length;
409 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100410 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
411
Tianjie Xu9e020e22016-10-10 12:11:30 -0700412 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900413 ALOGW(
414 "Zip: file name boundary exceeds the central directory range, file_name_length: "
415 "%" PRIx16 ", cd_length: %zu",
416 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700417 return -1;
418 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000419 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
420 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800421 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100422 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000423
424 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700425 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100426 entry_name.name = file_name;
427 entry_name.name_length = file_name_length;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900428 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800429 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000430 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800431 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000432 }
433
Narayan Kamath926973e2014-06-09 14:18:14 +0100434 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
435 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900436 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800437 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000438 }
439 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100440
441 uint32_t lfh_start_bytes;
442 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
443 sizeof(uint32_t), 0)) {
444 ALOGW("Zip: Unable to read header for entry at offset == 0.");
445 return -1;
446 }
447
448 if (lfh_start_bytes != LocalFileHeader::kSignature) {
449 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
450#if defined(__ANDROID__)
451 android_errorWriteLog(0x534e4554, "64211847");
452#endif
453 return -1;
454 }
455
Mark Salyzyn088bf902014-05-08 16:02:20 -0700456 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000457
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800458 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000459}
460
Jiyong Parkcd997e62017-06-30 17:23:33 +0900461static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000462 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700463 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000464 return result;
465 }
466
467 if ((result = ParseZipArchive(archive))) {
468 return result;
469 }
470
471 return 0;
472}
473
Jiyong Parkcd997e62017-06-30 17:23:33 +0900474int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
475 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700476 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000477 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000478 return OpenArchiveInternal(archive, debug_file_name);
479}
480
481int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Ryan Mitchellc77f9d32018-08-25 14:06:29 -0700482 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700483 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000484 *handle = archive;
485
Narayan Kamath7462f022013-11-21 13:05:04 +0000486 if (fd < 0) {
487 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
488 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000489 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700490
Narayan Kamath7462f022013-11-21 13:05:04 +0000491 return OpenArchiveInternal(archive, fileName);
492}
493
Tianjie Xu18c25922016-09-29 15:27:41 -0700494int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900495 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700496 ZipArchive* archive = new ZipArchive(address, length);
497 *handle = archive;
498 return OpenArchiveInternal(archive, debug_file_name);
499}
500
Narayan Kamath7462f022013-11-21 13:05:04 +0000501/*
502 * Close a ZipArchive, closing the file and freeing the contents.
503 */
504void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800505 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000506 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100507 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000508}
509
Narayan Kamath162b7052017-06-05 13:21:12 +0100510static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100511 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700512 off64_t offset = entry->offset;
513 if (entry->method != kCompressStored) {
514 offset += entry->compressed_length;
515 } else {
516 offset += entry->uncompressed_length;
517 }
518
519 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000520 return kIoError;
521 }
522
Narayan Kamath926973e2014-06-09 14:18:14 +0100523 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700524 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
525 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000526
Narayan Kamath162b7052017-06-05 13:21:12 +0100527 // Validate that the values in the data descriptor match those in the central
528 // directory.
529 if (entry->compressed_length != descriptor->compressed_size ||
530 entry->uncompressed_length != descriptor->uncompressed_size ||
531 entry->crc32 != descriptor->crc32) {
532 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
533 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
534 entry->compressed_length, entry->uncompressed_length, entry->crc32,
535 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
536 return kInconsistentInformation;
537 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000538
539 return 0;
540}
541
Jiyong Parkcd997e62017-06-30 17:23:33 +0900542static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000543 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000544
545 // Recover the start of the central directory entry from the filename
546 // pointer. The filename is the first entry past the fixed-size data,
547 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100548 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100549 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000550
551 // This is the base of our mmapped region, we have to sanity check that
552 // the name that's in the hash table is a pointer to a location within
553 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700554 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
555 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000556 ALOGW("Zip: Invalid entry pointer");
557 return kInvalidOffset;
558 }
559
Jiyong Parkcd997e62017-06-30 17:23:33 +0900560 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100561
Narayan Kamath7462f022013-11-21 13:05:04 +0000562 // The offset of the start of the central directory in the zipfile.
563 // We keep this lying around so that we can sanity check all our lengths
564 // and our per-file structures.
565 const off64_t cd_offset = archive->directory_offset;
566
567 // Fill out the compression method, modification time, crc32
568 // and other interesting attributes from the central directory. These
569 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100570 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900571 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100572 data->crc32 = cdr->crc32;
573 data->compressed_length = cdr->compressed_size;
574 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000575
576 // Figure out the local header offset from the central directory. The
577 // actual file data will begin after the local header and the name /
578 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100579 const off64_t local_header_offset = cdr->local_file_header_offset;
580 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000581 ALOGW("Zip: bad local hdr offset in zip");
582 return kInvalidOffset;
583 }
584
Narayan Kamath926973e2014-06-09 14:18:14 +0100585 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700586 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800587 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900588 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000589 return kIoError;
590 }
591
Jiyong Parkcd997e62017-06-30 17:23:33 +0900592 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100593
594 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700595 ALOGW("Zip: didn't find signature at start of lfh, 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 kInvalidOffset;
598 }
599
600 // Paranoia: Match the values specified in the local file header
601 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700602
Narayan Kamath162b7052017-06-05 13:21:12 +0100603 // Warn if central directory and local file header don't agree on the use
604 // of a trailing Data Descriptor. The reference implementation is inconsistent
605 // and appears to use the LFH value during extraction (unzip) but the CD value
606 // while displayng information about archives (zipinfo). The spec remains
607 // silent on this inconsistency as well.
608 //
609 // For now, always use the version from the LFH but make sure that the values
610 // specified in the central directory match those in the data descriptor.
611 //
612 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
613 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
614 // encoded using UTF-8). This implementation does not check for the presence of
615 // that flag and always enforces that entry names are valid UTF-8.
616 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
617 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700618 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700619 }
620
621 // If there is no trailing data descriptor, verify that the central directory and local file
622 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100623 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000624 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900625 if (data->compressed_length != lfh->compressed_size ||
626 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
627 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
628 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
629 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
630 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000631 return kInconsistentInformation;
632 }
633 } else {
634 data->has_data_descriptor = 1;
635 }
636
Elliott Hughes55fd2932017-05-28 22:59:04 -0700637 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
638 if ((cdr->version_made_by >> 8) == 3) {
639 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
640 } else {
641 data->unix_mode = 0777;
642 }
643
Narayan Kamath7462f022013-11-21 13:05:04 +0000644 // Check that the local file header name matches the declared
645 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100646 if (lfh->file_name_length == nameLen) {
647 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200648 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000649 ALOGW("Zip: Invalid declared length");
650 return kInvalidOffset;
651 }
652
Tianjie Xu18c25922016-09-29 15:27:41 -0700653 std::vector<uint8_t> name_buf(nameLen);
654 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800655 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000656 return kIoError;
657 }
658
Tianjie Xu18c25922016-09-29 15:27:41 -0700659 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000660 return kInconsistentInformation;
661 }
662
Narayan Kamath7462f022013-11-21 13:05:04 +0000663 } else {
664 ALOGW("Zip: lfh name did not match central directory.");
665 return kInconsistentInformation;
666 }
667
Jiyong Parkcd997e62017-06-30 17:23:33 +0900668 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
669 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000670 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800671 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000672 return kInvalidOffset;
673 }
674
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800675 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700676 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900677 static_cast<int64_t>(data_offset), data->compressed_length,
678 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000679 return kInvalidOffset;
680 }
681
682 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900683 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
684 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
685 static_cast<int64_t>(data_offset), data->uncompressed_length,
686 static_cast<int64_t>(cd_offset));
687 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000688 }
689
690 data->offset = data_offset;
691 return 0;
692}
693
694struct IterationHandle {
695 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100696 // We're not using vector here because this code is used in the Windows SDK
697 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700698 ZipString prefix;
699 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000700 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100701
Jiyong Parkcd997e62017-06-30 17:23:33 +0900702 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700703 if (in_prefix) {
704 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
705 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
706 prefix.name = name_copy;
707 prefix.name_length = in_prefix->name_length;
708 } else {
709 prefix.name = NULL;
710 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700711 }
Yusuke Sato07447542015-06-25 14:39:19 -0700712 if (in_suffix) {
713 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
714 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
715 suffix.name = name_copy;
716 suffix.name_length = in_suffix->name_length;
717 } else {
718 suffix.name = NULL;
719 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700720 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100721 }
722
723 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700724 delete[] prefix.name;
725 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100726 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000727};
728
Jiyong Parkcd997e62017-06-30 17:23:33 +0900729int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700730 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800731 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000732
733 if (archive == NULL || archive->hash_table == NULL) {
734 ALOGW("Zip: Invalid ZipArchiveHandle");
735 return kInvalidHandle;
736 }
737
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700738 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000739 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000740 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000741
Jiyong Parkcd997e62017-06-30 17:23:33 +0900742 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000743 return 0;
744}
745
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100746void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100747 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100748}
749
Jiyong Parkcd997e62017-06-30 17:23:33 +0900750int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800751 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100752 if (entryName.name_length == 0) {
753 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000754 return kInvalidEntryName;
755 }
756
Jiyong Parkcd997e62017-06-30 17:23:33 +0900757 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000758
759 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100760 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000761 return ent;
762 }
763
764 return FindEntry(archive, ent, data);
765}
766
Yusuke Sato07447542015-06-25 14:39:19 -0700767int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800768 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000769 if (handle == NULL) {
770 return kInvalidHandle;
771 }
772
773 ZipArchive* archive = handle->archive;
774 if (archive == NULL || archive->hash_table == NULL) {
775 ALOGW("Zip: Invalid ZipArchiveHandle");
776 return kInvalidHandle;
777 }
778
779 const uint32_t currentOffset = handle->position;
780 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700781 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000782
783 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
784 if (hash_table[i].name != NULL &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900785 (handle->prefix.name_length == 0 || hash_table[i].StartsWith(handle->prefix)) &&
786 (handle->suffix.name_length == 0 || hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000787 handle->position = (i + 1);
788 const int error = FindEntry(archive, i, data);
789 if (!error) {
790 name->name = hash_table[i].name;
791 name->name_length = hash_table[i].name_length;
792 }
793
794 return error;
795 }
796 }
797
798 handle->position = 0;
799 return kIterationEnd;
800}
801
Narayan Kamathf899bd52015-04-17 11:53:14 +0100802// A Writer that writes data to a fixed size memory region.
803// The size of the memory region must be equal to the total size of
804// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100805class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100806 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900807 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100808
809 virtual bool Append(uint8_t* buf, size_t buf_size) override {
810 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900811 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
812 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100813 return false;
814 }
815
816 memcpy(buf_ + bytes_written_, buf, buf_size);
817 bytes_written_ += buf_size;
818 return true;
819 }
820
821 private:
822 uint8_t* const buf_;
823 const size_t size_;
824 size_t bytes_written_;
825};
826
827// A Writer that appends data to a file |fd| at its current position.
828// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100829class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100830 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100831 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
832 // guaranteeing that the file descriptor is valid and that there's enough
833 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800834 // is truncated to the correct length (no truncation if |fd| references a
835 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100836 //
837 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800838 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100839 const uint32_t declared_length = entry->uncompressed_length;
840 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
841 if (current_offset == -1) {
842 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800843 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100844 }
845
846 int result = 0;
847#if defined(__linux__)
848 if (declared_length > 0) {
849 // Make sure we have enough space on the volume to extract the compressed
850 // entry. Note that the call to ftruncate below will change the file size but
851 // will not allocate space on disk and this call to fallocate will not
852 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700853 // Note: fallocate is only supported by the following filesystems -
854 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
855 // EOPNOTSUPP error when issued in other filesystems.
856 // Hence, check for the return error code before concluding that the
857 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100858 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700859 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700860 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100861 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
862 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800863 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100864 }
865 }
866#endif // __linux__
867
Tao Baoa456c212016-11-15 10:08:07 -0800868 struct stat sb;
869 if (fstat(fd, &sb) == -1) {
870 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800871 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100872 }
873
Tao Baoa456c212016-11-15 10:08:07 -0800874 // Block device doesn't support ftruncate(2).
875 if (!S_ISBLK(sb.st_mode)) {
876 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
877 if (result == -1) {
878 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
879 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800880 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800881 }
882 }
883
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800884 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100885 }
886
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800887 FileWriter(FileWriter&& other)
888 : fd_(other.fd_),
889 declared_length_(other.declared_length_),
890 total_bytes_written_(other.total_bytes_written_) {
891 other.fd_ = -1;
892 }
893
894 bool IsValid() const { return fd_ != -1; }
895
Narayan Kamathf899bd52015-04-17 11:53:14 +0100896 virtual bool Append(uint8_t* buf, size_t buf_size) override {
897 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900898 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
899 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100900 return false;
901 }
902
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100903 const bool result = android::base::WriteFully(fd_, buf, buf_size);
904 if (result) {
905 total_bytes_written_ += buf_size;
906 } else {
907 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100908 }
909
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100910 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100911 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900912
Narayan Kamathf899bd52015-04-17 11:53:14 +0100913 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800914 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900915 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100916
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800917 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100918 const size_t declared_length_;
919 size_t total_bytes_written_;
920};
921
Narayan Kamath485b3642017-10-26 14:42:39 +0100922class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100923 public:
924 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
925 : Reader(), zip_file_(zip_file), entry_(entry) {}
926
927 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
928 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
929 }
930
931 virtual ~EntryReader() {}
932
933 private:
934 const MappedZipFile& zip_file_;
935 const ZipEntry* entry_;
936};
937
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800938// This method is using libz macros with old-style-casts
939#pragma GCC diagnostic push
940#pragma GCC diagnostic ignored "-Wold-style-cast"
941static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
942 return inflateInit2(stream, window_bits);
943}
944#pragma GCC diagnostic pop
945
Narayan Kamath485b3642017-10-26 14:42:39 +0100946namespace zip_archive {
947
948// Moved out of line to avoid -Wweak-vtables.
949Reader::~Reader() {}
950Writer::~Writer() {}
951
952int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
953 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700954 const size_t kBufSize = 32768;
955 std::vector<uint8_t> read_buf(kBufSize);
956 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000957 z_stream zstream;
958 int zerr;
959
960 /*
961 * Initialize the zlib stream struct.
962 */
963 memset(&zstream, 0, sizeof(zstream));
964 zstream.zalloc = Z_NULL;
965 zstream.zfree = Z_NULL;
966 zstream.opaque = Z_NULL;
967 zstream.next_in = NULL;
968 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700969 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000970 zstream.avail_out = kBufSize;
971 zstream.data_type = Z_UNKNOWN;
972
973 /*
974 * Use the undocumented "negative window bits" feature to tell zlib
975 * that there's no zlib header waiting for it.
976 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800977 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000978 if (zerr != Z_OK) {
979 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900980 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000981 } else {
982 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
983 }
984
985 return kZlibError;
986 }
987
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800988 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900989 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800990 };
991
992 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
993
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000994 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100995 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100996 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000997 do {
998 /* read as much as we can */
999 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001000 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
1001 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001002 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001003 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1004 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001005 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001006 }
1007
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001008 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001009
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001010 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001011 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001012 }
1013
1014 /* uncompress the data */
1015 zerr = inflate(&zstream, Z_NO_FLUSH);
1016 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001017 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1018 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001019 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001020 }
1021
1022 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001023 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001024 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001025 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001026 return kIoError;
1027 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001028 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001029 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001030
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001031 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001032 zstream.avail_out = kBufSize;
1033 }
1034 } while (zerr == Z_OK);
1035
Jiyong Parkcd997e62017-06-30 17:23:33 +09001036 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001037
Narayan Kamath162b7052017-06-05 13:21:12 +01001038 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1039 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1040 // doesn't bother calculating the checksum in that scenario. We just do
1041 // it ourselves above because there are no additional gains to be made by
1042 // having zlib calculate it for us, since they do it by calling crc32 in
1043 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001044 if (compute_crc) {
1045 *crc_out = crc;
1046 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001047
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001048 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001049 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1050 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001051 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001052 }
1053
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001054 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001055}
Narayan Kamath485b3642017-10-26 14:42:39 +01001056} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001057
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001058static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001059 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001060 const EntryReader reader(mapped_zip, entry);
1061
Narayan Kamath485b3642017-10-26 14:42:39 +01001062 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1063 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001064}
1065
Narayan Kamath485b3642017-10-26 14:42:39 +01001066static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1067 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001068 static const uint32_t kBufSize = 32768;
1069 std::vector<uint8_t> buf(kBufSize);
1070
1071 const uint32_t length = entry->uncompressed_length;
1072 uint32_t count = 0;
1073 uint64_t crc = 0;
1074 while (count < length) {
1075 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001076 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001077
Adam Lesinskide117e42017-06-19 10:27:38 -07001078 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001079 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001080
1081 // Make sure to read at offset to ensure concurrent access to the fd.
1082 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1083 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1084 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001085 return kIoError;
1086 }
1087
1088 if (!writer->Append(&buf[0], block_size)) {
1089 return kIoError;
1090 }
1091 crc = crc32(crc, &buf[0], block_size);
1092 count += block_size;
1093 }
1094
1095 *crc_out = crc;
1096
1097 return 0;
1098}
1099
Narayan Kamath485b3642017-10-26 14:42:39 +01001100int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001101 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001102 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001103
1104 // this should default to kUnknownCompressionMethod.
1105 int32_t return_value = -1;
1106 uint64_t crc = 0;
1107 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001108 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001109 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001110 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001111 }
1112
1113 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001114 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001115 if (return_value) {
1116 return return_value;
1117 }
1118 }
1119
Narayan Kamath162b7052017-06-05 13:21:12 +01001120 // Validate that the CRC matches the calculated value.
1121 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001122 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001123 return kInconsistentInformation;
1124 }
1125
1126 return return_value;
1127}
1128
Jiyong Parkcd997e62017-06-30 17:23:33 +09001129int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001130 MemoryWriter writer(begin, size);
1131 return ExtractToWriter(handle, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001132}
1133
Jiyong Parkcd997e62017-06-30 17:23:33 +09001134int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001135 auto writer = FileWriter::Create(fd, entry);
1136 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001137 return kIoError;
1138 }
1139
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001140 return ExtractToWriter(handle, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001141}
1142
1143const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001144 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1145 // match.
1146 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1147 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1148
1149 const uint32_t idx = -error_code;
1150 if (idx < arraysize(kErrorMessages)) {
1151 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001152 }
1153
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001154 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001155}
1156
1157int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001158 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001159}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001160
Jiyong Parkcd997e62017-06-30 17:23:33 +09001161ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001162 size_t len = strlen(entry_name);
1163 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1164 name_length = static_cast<uint16_t>(len);
1165}
Tianjie Xu18c25922016-09-29 15:27:41 -07001166
1167#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001168class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001169 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001170 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1171 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001172
1173 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1174 return proc_function_(buf, buf_size, cookie_);
1175 }
1176
1177 private:
1178 ProcessZipEntryFunction proc_function_;
1179 void* cookie_;
1180};
1181
1182int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1183 ProcessZipEntryFunction func, void* cookie) {
1184 ProcessWriter writer(func, cookie);
1185 return ExtractToWriter(handle, entry, &writer);
1186}
1187
Jiyong Parkcd997e62017-06-30 17:23:33 +09001188#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001189
1190int MappedZipFile::GetFileDescriptor() const {
1191 if (!has_fd_) {
1192 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1193 return -1;
1194 }
1195 return fd_;
1196}
1197
1198void* MappedZipFile::GetBasePtr() const {
1199 if (has_fd_) {
1200 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1201 return nullptr;
1202 }
1203 return base_ptr_;
1204}
1205
1206off64_t MappedZipFile::GetFileLength() const {
1207 if (has_fd_) {
1208 off64_t result = lseek64(fd_, 0, SEEK_END);
1209 if (result == -1) {
1210 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1211 }
1212 return result;
1213 } else {
1214 if (base_ptr_ == nullptr) {
1215 ALOGE("Zip: invalid file map\n");
1216 return -1;
1217 }
1218 return static_cast<off64_t>(data_length_);
1219 }
1220}
1221
Tianjie Xu18c25922016-09-29 15:27:41 -07001222// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001223bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001224 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001225 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001226 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1227 return false;
1228 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001229 } else {
1230 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1231 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1232 return false;
1233 }
1234 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001235 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001236 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001237}
1238
1239void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1240 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1241 length_ = cd_size;
1242}
1243
1244bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1245 size_t cd_size) {
1246 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001247 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1248 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001249 return false;
1250 }
1251
1252 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001253 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001254 } else {
1255 if (mapped_zip.GetBasePtr() == nullptr) {
1256 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1257 return false;
1258 }
1259 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1260 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001261 ALOGE(
1262 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1263 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1264 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001265 return false;
1266 }
1267
1268 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1269 }
1270 return true;
1271}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001272
1273tm ZipEntry::GetModificationTime() const {
1274 tm t = {};
1275
1276 t.tm_hour = (mod_time >> 11) & 0x1f;
1277 t.tm_min = (mod_time >> 5) & 0x3f;
1278 t.tm_sec = (mod_time & 0x1f) << 1;
1279
1280 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1281 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1282 t.tm_mday = (mod_time >> 16) & 0x1f;
1283
1284 return t;
1285}