blob: fb300a7be160be71c61aa87fb66bc38c8f6b341c [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 Gao1b496342018-07-17 11:08:48 -0700187ZipArchive::ZipArchive(const int fd, bool assume_ownership)
188 : mapped_zip(fd),
189 close_file(assume_ownership),
190 directory_offset(0),
191 central_directory(),
192 directory_map(new android::FileMap()),
193 num_entries(0),
194 hash_table_size(0),
195 hash_table(nullptr) {
196#if defined(__BIONIC__)
197 if (assume_ownership) {
198 android_fdsan_exchange_owner_tag(fd, 0, reinterpret_cast<uint64_t>(this));
199 }
200#endif
201}
202
203ZipArchive::ZipArchive(void* address, size_t length)
204 : mapped_zip(address, length),
205 close_file(false),
206 directory_offset(0),
207 central_directory(),
208 directory_map(new android::FileMap()),
209 num_entries(0),
210 hash_table_size(0),
211 hash_table(nullptr) {}
212
213ZipArchive::~ZipArchive() {
214 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
215#if defined(__BIONIC__)
216 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), reinterpret_cast<uint64_t>(this));
217#else
218 close(mapped_zip.GetFileDescriptor());
219#endif
220 }
221
222 free(hash_table);
223}
224
Tianjie Xu18c25922016-09-29 15:27:41 -0700225static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Zimuzo5a503ef2018-09-17 19:49:55 +0100226 off64_t file_length, off64_t read_amount,
227 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000228 const off64_t search_start = file_length - read_amount;
229
Jiyong Parkcd997e62017-06-30 17:23:33 +0900230 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
231 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
232 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000233 return kIoError;
234 }
235
236 /*
237 * Scan backward for the EOCD magic. In an archive without a trailing
238 * comment, we'll find it on the first try. (We may want to consider
239 * doing an initial minimal read; if we don't find it, retry with a
240 * second read as above.)
241 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100242 int i = read_amount - sizeof(EocdRecord);
243 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700244 if (scan_buffer[i] == 0x50) {
245 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
246 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
247 ALOGV("+++ Found EOCD at buf+%d", i);
248 break;
249 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000250 }
251 }
252 if (i < 0) {
253 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
254 return kInvalidFile;
255 }
256
257 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100258 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000259 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100260 * Verify that there's no trailing space at the end of the central directory
261 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000262 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900263 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100264 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100265 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100266 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100267 return kInvalidFile;
268 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000269
Narayan Kamath926973e2014-06-09 14:18:14 +0100270 /*
271 * Grab the CD offset and size, and the number of entries in the
272 * archive and verify that they look reasonable.
273 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700274 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100275 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900276 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700277#if defined(__ANDROID__)
278 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
279 android_errorWriteLog(0x534e4554, "31251826");
280 }
281#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000282 return kInvalidOffset;
283 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100284 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000285#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000286 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000287#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000288 return kEmptyArchive;
289 }
290
Jiyong Parkcd997e62017-06-30 17:23:33 +0900291 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
292 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000293
294 /*
295 * It all looks good. Create a mapping for the CD, and set the fields
296 * in archive.
297 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700298
299 if (!archive->InitializeCentralDirectory(debug_file_name,
300 static_cast<off64_t>(eocd->cd_start_offset),
301 static_cast<size_t>(eocd->cd_size))) {
302 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000303 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000304 }
305
Narayan Kamath926973e2014-06-09 14:18:14 +0100306 archive->num_entries = eocd->num_records;
307 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000308
309 return 0;
310}
311
312/*
313 * Find the zip Central Directory and memory-map it.
314 *
315 * On success, returns 0 after populating fields from the EOCD area:
316 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700317 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000318 * num_entries
319 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700320static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000321 // Test file length. We use lseek64 to make sure the file
322 // is small enough to be a zip file (Its size must be less than
323 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700324 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000325 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000326 return kInvalidFile;
327 }
328
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800329 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100330 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000331 return kInvalidFile;
332 }
333
Narayan Kamath926973e2014-06-09 14:18:14 +0100334 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
335 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000336 return kInvalidFile;
337 }
338
339 /*
340 * Perform the traditional EOCD snipe hunt.
341 *
342 * We're searching for the End of Central Directory magic number,
343 * which appears at the start of the EOCD block. It's followed by
344 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
345 * need to read the last part of the file into a buffer, dig through
346 * it to find the magic number, parse some values out, and use those
347 * to determine the extent of the CD.
348 *
349 * We start by pulling in the last part of the file.
350 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100351 off64_t read_amount = kMaxEOCDSearch;
352 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000353 read_amount = file_length;
354 }
355
Tianjie Xu18c25922016-09-29 15:27:41 -0700356 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900357 int32_t result =
358 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000359 return result;
360}
361
362/*
363 * Parses the Zip archive's Central Directory. Allocates and populates the
364 * hash table.
365 *
366 * Returns 0 on success.
367 */
368static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700369 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
370 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100371 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000372
373 /*
374 * Create hash table. We have a minimum 75% load factor, possibly as
375 * low as 50% after we round off to a power of 2. There must be at
376 * least one unused entry to avoid an infinite loop during creation.
377 */
378 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900379 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100380 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700381 if (archive->hash_table == nullptr) {
382 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
383 archive->hash_table_size, sizeof(ZipString));
384 return -1;
385 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000386
387 /*
388 * Walk through the central directory, adding entries to the hash
389 * table and verifying values.
390 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100391 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000392 const uint8_t* ptr = cd_ptr;
393 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700394 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
395 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
396#if defined(__ANDROID__)
397 android_errorWriteLog(0x534e4554, "36392138");
398#endif
399 return -1;
400 }
401
Jiyong Parkcd997e62017-06-30 17:23:33 +0900402 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100403 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700404 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800405 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000406 }
407
Narayan Kamath926973e2014-06-09 14:18:14 +0100408 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000409 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800410 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900411 static_cast<int64_t>(local_header_offset), 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 uint16_t file_name_length = cdr->file_name_length;
416 const uint16_t extra_length = cdr->extra_field_length;
417 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100418 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
419
Tianjie Xu9e020e22016-10-10 12:11:30 -0700420 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900421 ALOGW(
422 "Zip: file name boundary exceeds the central directory range, file_name_length: "
423 "%" PRIx16 ", cd_length: %zu",
424 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700425 return -1;
426 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000427 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
428 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800429 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100430 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000431
432 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700433 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100434 entry_name.name = file_name;
435 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100436 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
437 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800438 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000439 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800440 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000441 }
442
Narayan Kamath926973e2014-06-09 14:18:14 +0100443 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
444 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900445 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800446 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000447 }
448 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100449
450 uint32_t lfh_start_bytes;
451 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
452 sizeof(uint32_t), 0)) {
453 ALOGW("Zip: Unable to read header for entry at offset == 0.");
454 return -1;
455 }
456
457 if (lfh_start_bytes != LocalFileHeader::kSignature) {
458 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
459#if defined(__ANDROID__)
460 android_errorWriteLog(0x534e4554, "64211847");
461#endif
462 return -1;
463 }
464
Mark Salyzyn088bf902014-05-08 16:02:20 -0700465 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000466
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800467 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000468}
469
Jiyong Parkcd997e62017-06-30 17:23:33 +0900470static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000471 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700472 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000473 return result;
474 }
475
476 if ((result = ParseZipArchive(archive))) {
477 return result;
478 }
479
480 return 0;
481}
482
Jiyong Parkcd997e62017-06-30 17:23:33 +0900483int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
484 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700485 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000486 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000487 return OpenArchiveInternal(archive, debug_file_name);
488}
489
490int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Ryan Mitchellc77f9d32018-08-25 14:06:29 -0700491 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700492 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000493 *handle = archive;
494
Narayan Kamath7462f022013-11-21 13:05:04 +0000495 if (fd < 0) {
496 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
497 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000498 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700499
Narayan Kamath7462f022013-11-21 13:05:04 +0000500 return OpenArchiveInternal(archive, fileName);
501}
502
Tianjie Xu18c25922016-09-29 15:27:41 -0700503int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900504 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700505 ZipArchive* archive = new ZipArchive(address, length);
506 *handle = archive;
507 return OpenArchiveInternal(archive, debug_file_name);
508}
509
Narayan Kamath7462f022013-11-21 13:05:04 +0000510/*
511 * Close a ZipArchive, closing the file and freeing the contents.
512 */
513void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800514 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000515 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100516 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000517}
518
Narayan Kamath162b7052017-06-05 13:21:12 +0100519static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100520 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700521 off64_t offset = entry->offset;
522 if (entry->method != kCompressStored) {
523 offset += entry->compressed_length;
524 } else {
525 offset += entry->uncompressed_length;
526 }
527
528 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000529 return kIoError;
530 }
531
Narayan Kamath926973e2014-06-09 14:18:14 +0100532 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700533 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
534 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000535
Narayan Kamath162b7052017-06-05 13:21:12 +0100536 // Validate that the values in the data descriptor match those in the central
537 // directory.
538 if (entry->compressed_length != descriptor->compressed_size ||
539 entry->uncompressed_length != descriptor->uncompressed_size ||
540 entry->crc32 != descriptor->crc32) {
541 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
542 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
543 entry->compressed_length, entry->uncompressed_length, entry->crc32,
544 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
545 return kInconsistentInformation;
546 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000547
548 return 0;
549}
550
Jiyong Parkcd997e62017-06-30 17:23:33 +0900551static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000552 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000553
554 // Recover the start of the central directory entry from the filename
555 // pointer. The filename is the first entry past the fixed-size data,
556 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100557 const ZipString from_offset =
558 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
559 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100560 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000561
562 // This is the base of our mmapped region, we have to sanity check that
563 // the name that's in the hash table is a pointer to a location within
564 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700565 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
566 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000567 ALOGW("Zip: Invalid entry pointer");
568 return kInvalidOffset;
569 }
570
Jiyong Parkcd997e62017-06-30 17:23:33 +0900571 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100572
Narayan Kamath7462f022013-11-21 13:05:04 +0000573 // The offset of the start of the central directory in the zipfile.
574 // We keep this lying around so that we can sanity check all our lengths
575 // and our per-file structures.
576 const off64_t cd_offset = archive->directory_offset;
577
578 // Fill out the compression method, modification time, crc32
579 // and other interesting attributes from the central directory. These
580 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100581 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900582 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100583 data->crc32 = cdr->crc32;
584 data->compressed_length = cdr->compressed_size;
585 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000586
587 // Figure out the local header offset from the central directory. The
588 // actual file data will begin after the local header and the name /
589 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100590 const off64_t local_header_offset = cdr->local_file_header_offset;
591 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000592 ALOGW("Zip: bad local hdr offset in zip");
593 return kInvalidOffset;
594 }
595
Narayan Kamath926973e2014-06-09 14:18:14 +0100596 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700597 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800598 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900599 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000600 return kIoError;
601 }
602
Jiyong Parkcd997e62017-06-30 17:23:33 +0900603 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100604
605 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700606 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900607 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000608 return kInvalidOffset;
609 }
610
611 // Paranoia: Match the values specified in the local file header
612 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700613
Narayan Kamath162b7052017-06-05 13:21:12 +0100614 // Warn if central directory and local file header don't agree on the use
615 // of a trailing Data Descriptor. The reference implementation is inconsistent
616 // and appears to use the LFH value during extraction (unzip) but the CD value
617 // while displayng information about archives (zipinfo). The spec remains
618 // silent on this inconsistency as well.
619 //
620 // For now, always use the version from the LFH but make sure that the values
621 // specified in the central directory match those in the data descriptor.
622 //
623 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
624 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
625 // encoded using UTF-8). This implementation does not check for the presence of
626 // that flag and always enforces that entry names are valid UTF-8.
627 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
628 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700629 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700630 }
631
632 // If there is no trailing data descriptor, verify that the central directory and local file
633 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100634 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000635 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900636 if (data->compressed_length != lfh->compressed_size ||
637 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
638 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
639 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
640 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
641 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000642 return kInconsistentInformation;
643 }
644 } else {
645 data->has_data_descriptor = 1;
646 }
647
Elliott Hughes55fd2932017-05-28 22:59:04 -0700648 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
649 if ((cdr->version_made_by >> 8) == 3) {
650 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
651 } else {
652 data->unix_mode = 0777;
653 }
654
Narayan Kamath7462f022013-11-21 13:05:04 +0000655 // Check that the local file header name matches the declared
656 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100657 if (lfh->file_name_length == nameLen) {
658 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200659 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000660 ALOGW("Zip: Invalid declared length");
661 return kInvalidOffset;
662 }
663
Tianjie Xu18c25922016-09-29 15:27:41 -0700664 std::vector<uint8_t> name_buf(nameLen);
665 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800666 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000667 return kIoError;
668 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100669 const ZipString from_offset =
670 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
671 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000672 return kInconsistentInformation;
673 }
674
Narayan Kamath7462f022013-11-21 13:05:04 +0000675 } else {
676 ALOGW("Zip: lfh name did not match central directory.");
677 return kInconsistentInformation;
678 }
679
Jiyong Parkcd997e62017-06-30 17:23:33 +0900680 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
681 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000682 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800683 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000684 return kInvalidOffset;
685 }
686
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800687 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700688 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900689 static_cast<int64_t>(data_offset), data->compressed_length,
690 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000691 return kInvalidOffset;
692 }
693
694 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900695 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
696 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
697 static_cast<int64_t>(data_offset), data->uncompressed_length,
698 static_cast<int64_t>(cd_offset));
699 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000700 }
701
702 data->offset = data_offset;
703 return 0;
704}
705
706struct IterationHandle {
707 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100708 // We're not using vector here because this code is used in the Windows SDK
709 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700710 ZipString prefix;
711 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000712 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100713
Jiyong Parkcd997e62017-06-30 17:23:33 +0900714 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700715 if (in_prefix) {
716 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
717 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
718 prefix.name = name_copy;
719 prefix.name_length = in_prefix->name_length;
720 } else {
721 prefix.name = NULL;
722 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700723 }
Yusuke Sato07447542015-06-25 14:39:19 -0700724 if (in_suffix) {
725 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
726 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
727 suffix.name = name_copy;
728 suffix.name_length = in_suffix->name_length;
729 } else {
730 suffix.name = NULL;
731 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700732 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100733 }
734
735 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700736 delete[] prefix.name;
737 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100738 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000739};
740
Jiyong Parkcd997e62017-06-30 17:23:33 +0900741int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700742 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800743 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000744
745 if (archive == NULL || archive->hash_table == NULL) {
746 ALOGW("Zip: Invalid ZipArchiveHandle");
747 return kInvalidHandle;
748 }
749
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700750 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000751 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000752 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000753
Jiyong Parkcd997e62017-06-30 17:23:33 +0900754 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000755 return 0;
756}
757
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100758void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100759 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100760}
761
Jiyong Parkcd997e62017-06-30 17:23:33 +0900762int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800763 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100764 if (entryName.name_length == 0) {
765 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000766 return kInvalidEntryName;
767 }
768
Zimuzo5a503ef2018-09-17 19:49:55 +0100769 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
770 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000771 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100772 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000773 return ent;
774 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000775 return FindEntry(archive, ent, data);
776}
777
Yusuke Sato07447542015-06-25 14:39:19 -0700778int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800779 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000780 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100781 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000782 return kInvalidHandle;
783 }
784
785 ZipArchive* archive = handle->archive;
786 if (archive == NULL || archive->hash_table == NULL) {
787 ALOGW("Zip: Invalid ZipArchiveHandle");
788 return kInvalidHandle;
789 }
790
791 const uint32_t currentOffset = handle->position;
792 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100793 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000794 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100795 const ZipString from_offset =
796 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
797 if (hash_table[i].name_offset != 0 &&
798 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
799 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000800 handle->position = (i + 1);
801 const int error = FindEntry(archive, i, data);
802 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100803 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000804 name->name_length = hash_table[i].name_length;
805 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000806 return error;
807 }
808 }
809
810 handle->position = 0;
811 return kIterationEnd;
812}
813
Narayan Kamathf899bd52015-04-17 11:53:14 +0100814// A Writer that writes data to a fixed size memory region.
815// The size of the memory region must be equal to the total size of
816// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100817class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100818 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900819 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100820
821 virtual bool Append(uint8_t* buf, size_t buf_size) override {
822 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900823 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
824 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100825 return false;
826 }
827
828 memcpy(buf_ + bytes_written_, buf, buf_size);
829 bytes_written_ += buf_size;
830 return true;
831 }
832
833 private:
834 uint8_t* const buf_;
835 const size_t size_;
836 size_t bytes_written_;
837};
838
839// A Writer that appends data to a file |fd| at its current position.
840// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100841class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100842 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100843 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
844 // guaranteeing that the file descriptor is valid and that there's enough
845 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800846 // is truncated to the correct length (no truncation if |fd| references a
847 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100848 //
849 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800850 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100851 const uint32_t declared_length = entry->uncompressed_length;
852 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
853 if (current_offset == -1) {
854 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800855 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100856 }
857
858 int result = 0;
859#if defined(__linux__)
860 if (declared_length > 0) {
861 // Make sure we have enough space on the volume to extract the compressed
862 // entry. Note that the call to ftruncate below will change the file size but
863 // will not allocate space on disk and this call to fallocate will not
864 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700865 // Note: fallocate is only supported by the following filesystems -
866 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
867 // EOPNOTSUPP error when issued in other filesystems.
868 // Hence, check for the return error code before concluding that the
869 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100870 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700871 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700872 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100873 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
874 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800875 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100876 }
877 }
878#endif // __linux__
879
Tao Baoa456c212016-11-15 10:08:07 -0800880 struct stat sb;
881 if (fstat(fd, &sb) == -1) {
882 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800883 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100884 }
885
Tao Baoa456c212016-11-15 10:08:07 -0800886 // Block device doesn't support ftruncate(2).
887 if (!S_ISBLK(sb.st_mode)) {
888 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
889 if (result == -1) {
890 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
891 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800892 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800893 }
894 }
895
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800896 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100897 }
898
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800899 FileWriter(FileWriter&& other)
900 : fd_(other.fd_),
901 declared_length_(other.declared_length_),
902 total_bytes_written_(other.total_bytes_written_) {
903 other.fd_ = -1;
904 }
905
906 bool IsValid() const { return fd_ != -1; }
907
Narayan Kamathf899bd52015-04-17 11:53:14 +0100908 virtual bool Append(uint8_t* buf, size_t buf_size) override {
909 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900910 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
911 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100912 return false;
913 }
914
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100915 const bool result = android::base::WriteFully(fd_, buf, buf_size);
916 if (result) {
917 total_bytes_written_ += buf_size;
918 } else {
919 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100920 }
921
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100922 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100923 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900924
Narayan Kamathf899bd52015-04-17 11:53:14 +0100925 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800926 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900927 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100928
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800929 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100930 const size_t declared_length_;
931 size_t total_bytes_written_;
932};
933
Narayan Kamath485b3642017-10-26 14:42:39 +0100934class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100935 public:
936 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
937 : Reader(), zip_file_(zip_file), entry_(entry) {}
938
939 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
940 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
941 }
942
943 virtual ~EntryReader() {}
944
945 private:
946 const MappedZipFile& zip_file_;
947 const ZipEntry* entry_;
948};
949
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800950// This method is using libz macros with old-style-casts
951#pragma GCC diagnostic push
952#pragma GCC diagnostic ignored "-Wold-style-cast"
953static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
954 return inflateInit2(stream, window_bits);
955}
956#pragma GCC diagnostic pop
957
Narayan Kamath485b3642017-10-26 14:42:39 +0100958namespace zip_archive {
959
960// Moved out of line to avoid -Wweak-vtables.
961Reader::~Reader() {}
962Writer::~Writer() {}
963
964int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
965 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700966 const size_t kBufSize = 32768;
967 std::vector<uint8_t> read_buf(kBufSize);
968 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000969 z_stream zstream;
970 int zerr;
971
972 /*
973 * Initialize the zlib stream struct.
974 */
975 memset(&zstream, 0, sizeof(zstream));
976 zstream.zalloc = Z_NULL;
977 zstream.zfree = Z_NULL;
978 zstream.opaque = Z_NULL;
979 zstream.next_in = NULL;
980 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700981 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000982 zstream.avail_out = kBufSize;
983 zstream.data_type = Z_UNKNOWN;
984
985 /*
986 * Use the undocumented "negative window bits" feature to tell zlib
987 * that there's no zlib header waiting for it.
988 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800989 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000990 if (zerr != Z_OK) {
991 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900992 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000993 } else {
994 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
995 }
996
997 return kZlibError;
998 }
999
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001000 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001001 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001002 };
1003
1004 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1005
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001006 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +01001007 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001008 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +00001009 do {
1010 /* read as much as we can */
1011 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001012 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
1013 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001014 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001015 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1016 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001017 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001018 }
1019
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001020 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001021
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001022 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001023 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001024 }
1025
1026 /* uncompress the data */
1027 zerr = inflate(&zstream, Z_NO_FLUSH);
1028 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001029 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1030 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001031 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001032 }
1033
1034 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001035 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001036 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001037 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001038 return kIoError;
1039 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001040 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001041 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001042
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001043 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001044 zstream.avail_out = kBufSize;
1045 }
1046 } while (zerr == Z_OK);
1047
Jiyong Parkcd997e62017-06-30 17:23:33 +09001048 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001049
Narayan Kamath162b7052017-06-05 13:21:12 +01001050 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1051 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1052 // doesn't bother calculating the checksum in that scenario. We just do
1053 // it ourselves above because there are no additional gains to be made by
1054 // having zlib calculate it for us, since they do it by calling crc32 in
1055 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001056 if (compute_crc) {
1057 *crc_out = crc;
1058 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001059
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001060 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001061 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1062 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001063 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001064 }
1065
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001066 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001067}
Narayan Kamath485b3642017-10-26 14:42:39 +01001068} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001069
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001070static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001071 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001072 const EntryReader reader(mapped_zip, entry);
1073
Narayan Kamath485b3642017-10-26 14:42:39 +01001074 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1075 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001076}
1077
Narayan Kamath485b3642017-10-26 14:42:39 +01001078static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1079 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001080 static const uint32_t kBufSize = 32768;
1081 std::vector<uint8_t> buf(kBufSize);
1082
1083 const uint32_t length = entry->uncompressed_length;
1084 uint32_t count = 0;
1085 uint64_t crc = 0;
1086 while (count < length) {
1087 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001088 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001089
Adam Lesinskide117e42017-06-19 10:27:38 -07001090 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001091 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001092
1093 // Make sure to read at offset to ensure concurrent access to the fd.
1094 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1095 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1096 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001097 return kIoError;
1098 }
1099
1100 if (!writer->Append(&buf[0], block_size)) {
1101 return kIoError;
1102 }
1103 crc = crc32(crc, &buf[0], block_size);
1104 count += block_size;
1105 }
1106
1107 *crc_out = crc;
1108
1109 return 0;
1110}
1111
Narayan Kamath485b3642017-10-26 14:42:39 +01001112int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001113 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001114 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001115
1116 // this should default to kUnknownCompressionMethod.
1117 int32_t return_value = -1;
1118 uint64_t crc = 0;
1119 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001120 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001121 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001122 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001123 }
1124
1125 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001126 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001127 if (return_value) {
1128 return return_value;
1129 }
1130 }
1131
Narayan Kamath162b7052017-06-05 13:21:12 +01001132 // Validate that the CRC matches the calculated value.
1133 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001134 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001135 return kInconsistentInformation;
1136 }
1137
1138 return return_value;
1139}
1140
Jiyong Parkcd997e62017-06-30 17:23:33 +09001141int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001142 MemoryWriter writer(begin, size);
1143 return ExtractToWriter(handle, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001144}
1145
Jiyong Parkcd997e62017-06-30 17:23:33 +09001146int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001147 auto writer = FileWriter::Create(fd, entry);
1148 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001149 return kIoError;
1150 }
1151
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001152 return ExtractToWriter(handle, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001153}
1154
1155const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001156 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1157 // match.
1158 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1159 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1160
1161 const uint32_t idx = -error_code;
1162 if (idx < arraysize(kErrorMessages)) {
1163 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001164 }
1165
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001166 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001167}
1168
1169int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001170 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001171}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001172
Jiyong Parkcd997e62017-06-30 17:23:33 +09001173ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001174 size_t len = strlen(entry_name);
1175 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1176 name_length = static_cast<uint16_t>(len);
1177}
Tianjie Xu18c25922016-09-29 15:27:41 -07001178
1179#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001180class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001181 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001182 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1183 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001184
1185 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1186 return proc_function_(buf, buf_size, cookie_);
1187 }
1188
1189 private:
1190 ProcessZipEntryFunction proc_function_;
1191 void* cookie_;
1192};
1193
1194int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1195 ProcessZipEntryFunction func, void* cookie) {
1196 ProcessWriter writer(func, cookie);
1197 return ExtractToWriter(handle, entry, &writer);
1198}
1199
Jiyong Parkcd997e62017-06-30 17:23:33 +09001200#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001201
1202int MappedZipFile::GetFileDescriptor() const {
1203 if (!has_fd_) {
1204 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1205 return -1;
1206 }
1207 return fd_;
1208}
1209
1210void* MappedZipFile::GetBasePtr() const {
1211 if (has_fd_) {
1212 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1213 return nullptr;
1214 }
1215 return base_ptr_;
1216}
1217
1218off64_t MappedZipFile::GetFileLength() const {
1219 if (has_fd_) {
1220 off64_t result = lseek64(fd_, 0, SEEK_END);
1221 if (result == -1) {
1222 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1223 }
1224 return result;
1225 } else {
1226 if (base_ptr_ == nullptr) {
1227 ALOGE("Zip: invalid file map\n");
1228 return -1;
1229 }
1230 return static_cast<off64_t>(data_length_);
1231 }
1232}
1233
Tianjie Xu18c25922016-09-29 15:27:41 -07001234// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001235bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001236 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001237 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001238 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1239 return false;
1240 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001241 } else {
1242 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1243 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1244 return false;
1245 }
1246 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001247 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001248 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001249}
1250
1251void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1252 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1253 length_ = cd_size;
1254}
1255
1256bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1257 size_t cd_size) {
1258 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001259 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1260 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001261 return false;
1262 }
1263
1264 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001265 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001266 } else {
1267 if (mapped_zip.GetBasePtr() == nullptr) {
1268 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1269 return false;
1270 }
1271 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1272 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001273 ALOGE(
1274 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1275 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1276 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001277 return false;
1278 }
1279
1280 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1281 }
1282 return true;
1283}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001284
1285tm ZipEntry::GetModificationTime() const {
1286 tm t = {};
1287
1288 t.tm_hour = (mod_time >> 11) & 0x1f;
1289 t.tm_min = (mod_time >> 5) & 0x3f;
1290 t.tm_sec = (mod_time & 0x1f) << 1;
1291
1292 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1293 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1294 t.tm_mday = (mod_time >> 16) & 0x1f;
1295
1296 return t;
1297}