blob: add6e14cb96cb180664da771e52febaec55a107b [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 Gao1b496342018-07-17 11:08:48 -0700173ZipArchive::ZipArchive(const int fd, bool assume_ownership)
174 : mapped_zip(fd),
175 close_file(assume_ownership),
176 directory_offset(0),
177 central_directory(),
178 directory_map(new android::FileMap()),
179 num_entries(0),
180 hash_table_size(0),
181 hash_table(nullptr) {
182#if defined(__BIONIC__)
183 if (assume_ownership) {
184 android_fdsan_exchange_owner_tag(fd, 0, reinterpret_cast<uint64_t>(this));
185 }
186#endif
187}
188
189ZipArchive::ZipArchive(void* address, size_t length)
190 : mapped_zip(address, length),
191 close_file(false),
192 directory_offset(0),
193 central_directory(),
194 directory_map(new android::FileMap()),
195 num_entries(0),
196 hash_table_size(0),
197 hash_table(nullptr) {}
198
199ZipArchive::~ZipArchive() {
200 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
201#if defined(__BIONIC__)
202 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), reinterpret_cast<uint64_t>(this));
203#else
204 close(mapped_zip.GetFileDescriptor());
205#endif
206 }
207
208 free(hash_table);
209}
210
Tianjie Xu18c25922016-09-29 15:27:41 -0700211static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900212 off64_t file_length, off64_t read_amount, uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000213 const off64_t search_start = file_length - read_amount;
214
Jiyong Parkcd997e62017-06-30 17:23:33 +0900215 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
216 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
217 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000218 return kIoError;
219 }
220
221 /*
222 * Scan backward for the EOCD magic. In an archive without a trailing
223 * comment, we'll find it on the first try. (We may want to consider
224 * doing an initial minimal read; if we don't find it, retry with a
225 * second read as above.)
226 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100227 int i = read_amount - sizeof(EocdRecord);
228 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700229 if (scan_buffer[i] == 0x50) {
230 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
231 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
232 ALOGV("+++ Found EOCD at buf+%d", i);
233 break;
234 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000235 }
236 }
237 if (i < 0) {
238 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
239 return kInvalidFile;
240 }
241
242 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100243 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000244 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100245 * Verify that there's no trailing space at the end of the central directory
246 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000247 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900248 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100249 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100250 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100251 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100252 return kInvalidFile;
253 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000254
Narayan Kamath926973e2014-06-09 14:18:14 +0100255 /*
256 * Grab the CD offset and size, and the number of entries in the
257 * archive and verify that they look reasonable.
258 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700259 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100260 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900261 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700262#if defined(__ANDROID__)
263 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
264 android_errorWriteLog(0x534e4554, "31251826");
265 }
266#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000267 return kInvalidOffset;
268 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100269 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000270#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000271 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000272#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000273 return kEmptyArchive;
274 }
275
Jiyong Parkcd997e62017-06-30 17:23:33 +0900276 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
277 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000278
279 /*
280 * It all looks good. Create a mapping for the CD, and set the fields
281 * in archive.
282 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700283
284 if (!archive->InitializeCentralDirectory(debug_file_name,
285 static_cast<off64_t>(eocd->cd_start_offset),
286 static_cast<size_t>(eocd->cd_size))) {
287 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000288 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000289 }
290
Narayan Kamath926973e2014-06-09 14:18:14 +0100291 archive->num_entries = eocd->num_records;
292 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000293
294 return 0;
295}
296
297/*
298 * Find the zip Central Directory and memory-map it.
299 *
300 * On success, returns 0 after populating fields from the EOCD area:
301 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700302 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000303 * num_entries
304 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700305static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000306 // Test file length. We use lseek64 to make sure the file
307 // is small enough to be a zip file (Its size must be less than
308 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700309 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000310 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000311 return kInvalidFile;
312 }
313
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800314 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100315 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000316 return kInvalidFile;
317 }
318
Narayan Kamath926973e2014-06-09 14:18:14 +0100319 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
320 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000321 return kInvalidFile;
322 }
323
324 /*
325 * Perform the traditional EOCD snipe hunt.
326 *
327 * We're searching for the End of Central Directory magic number,
328 * which appears at the start of the EOCD block. It's followed by
329 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
330 * need to read the last part of the file into a buffer, dig through
331 * it to find the magic number, parse some values out, and use those
332 * to determine the extent of the CD.
333 *
334 * We start by pulling in the last part of the file.
335 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100336 off64_t read_amount = kMaxEOCDSearch;
337 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000338 read_amount = file_length;
339 }
340
Tianjie Xu18c25922016-09-29 15:27:41 -0700341 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900342 int32_t result =
343 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000344 return result;
345}
346
347/*
348 * Parses the Zip archive's Central Directory. Allocates and populates the
349 * hash table.
350 *
351 * Returns 0 on success.
352 */
353static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700354 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
355 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100356 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000357
358 /*
359 * Create hash table. We have a minimum 75% load factor, possibly as
360 * low as 50% after we round off to a power of 2. There must be at
361 * least one unused entry to avoid an infinite loop during creation.
362 */
363 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900364 archive->hash_table =
365 reinterpret_cast<ZipString*>(calloc(archive->hash_table_size, sizeof(ZipString)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700366 if (archive->hash_table == nullptr) {
367 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
368 archive->hash_table_size, sizeof(ZipString));
369 return -1;
370 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000371
372 /*
373 * Walk through the central directory, adding entries to the hash
374 * table and verifying values.
375 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100376 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000377 const uint8_t* ptr = cd_ptr;
378 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700379 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
380 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
381#if defined(__ANDROID__)
382 android_errorWriteLog(0x534e4554, "36392138");
383#endif
384 return -1;
385 }
386
Jiyong Parkcd997e62017-06-30 17:23:33 +0900387 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100388 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700389 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800390 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000391 }
392
Narayan Kamath926973e2014-06-09 14:18:14 +0100393 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000394 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800395 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900396 static_cast<int64_t>(local_header_offset), 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 uint16_t file_name_length = cdr->file_name_length;
401 const uint16_t extra_length = cdr->extra_field_length;
402 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100403 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
404
Tianjie Xu9e020e22016-10-10 12:11:30 -0700405 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900406 ALOGW(
407 "Zip: file name boundary exceeds the central directory range, file_name_length: "
408 "%" PRIx16 ", cd_length: %zu",
409 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700410 return -1;
411 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000412 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
413 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800414 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100415 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000416
417 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700418 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100419 entry_name.name = file_name;
420 entry_name.name_length = file_name_length;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900421 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800422 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000423 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800424 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000425 }
426
Narayan Kamath926973e2014-06-09 14:18:14 +0100427 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
428 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900429 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800430 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000431 }
432 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100433
434 uint32_t lfh_start_bytes;
435 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
436 sizeof(uint32_t), 0)) {
437 ALOGW("Zip: Unable to read header for entry at offset == 0.");
438 return -1;
439 }
440
441 if (lfh_start_bytes != LocalFileHeader::kSignature) {
442 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
443#if defined(__ANDROID__)
444 android_errorWriteLog(0x534e4554, "64211847");
445#endif
446 return -1;
447 }
448
Mark Salyzyn088bf902014-05-08 16:02:20 -0700449 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000450
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800451 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000452}
453
Jiyong Parkcd997e62017-06-30 17:23:33 +0900454static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000455 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700456 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000457 return result;
458 }
459
460 if ((result = ParseZipArchive(archive))) {
461 return result;
462 }
463
464 return 0;
465}
466
Jiyong Parkcd997e62017-06-30 17:23:33 +0900467int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
468 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700469 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000470 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000471 return OpenArchiveInternal(archive, debug_file_name);
472}
473
474int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Ryan Mitchellc77f9d32018-08-25 14:06:29 -0700475 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700476 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000477 *handle = archive;
478
Narayan Kamath7462f022013-11-21 13:05:04 +0000479 if (fd < 0) {
480 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
481 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000482 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700483
Narayan Kamath7462f022013-11-21 13:05:04 +0000484 return OpenArchiveInternal(archive, fileName);
485}
486
Tianjie Xu18c25922016-09-29 15:27:41 -0700487int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900488 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700489 ZipArchive* archive = new ZipArchive(address, length);
490 *handle = archive;
491 return OpenArchiveInternal(archive, debug_file_name);
492}
493
Narayan Kamath7462f022013-11-21 13:05:04 +0000494/*
495 * Close a ZipArchive, closing the file and freeing the contents.
496 */
497void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800498 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000499 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100500 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000501}
502
Narayan Kamath162b7052017-06-05 13:21:12 +0100503static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100504 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700505 off64_t offset = entry->offset;
506 if (entry->method != kCompressStored) {
507 offset += entry->compressed_length;
508 } else {
509 offset += entry->uncompressed_length;
510 }
511
512 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000513 return kIoError;
514 }
515
Narayan Kamath926973e2014-06-09 14:18:14 +0100516 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700517 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
518 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000519
Narayan Kamath162b7052017-06-05 13:21:12 +0100520 // Validate that the values in the data descriptor match those in the central
521 // directory.
522 if (entry->compressed_length != descriptor->compressed_size ||
523 entry->uncompressed_length != descriptor->uncompressed_size ||
524 entry->crc32 != descriptor->crc32) {
525 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
526 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
527 entry->compressed_length, entry->uncompressed_length, entry->crc32,
528 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
529 return kInconsistentInformation;
530 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000531
532 return 0;
533}
534
Jiyong Parkcd997e62017-06-30 17:23:33 +0900535static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000536 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000537
538 // Recover the start of the central directory entry from the filename
539 // pointer. The filename is the first entry past the fixed-size data,
540 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100541 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100542 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000543
544 // This is the base of our mmapped region, we have to sanity check that
545 // the name that's in the hash table is a pointer to a location within
546 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700547 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
548 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000549 ALOGW("Zip: Invalid entry pointer");
550 return kInvalidOffset;
551 }
552
Jiyong Parkcd997e62017-06-30 17:23:33 +0900553 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100554
Narayan Kamath7462f022013-11-21 13:05:04 +0000555 // The offset of the start of the central directory in the zipfile.
556 // We keep this lying around so that we can sanity check all our lengths
557 // and our per-file structures.
558 const off64_t cd_offset = archive->directory_offset;
559
560 // Fill out the compression method, modification time, crc32
561 // and other interesting attributes from the central directory. These
562 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100563 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900564 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100565 data->crc32 = cdr->crc32;
566 data->compressed_length = cdr->compressed_size;
567 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000568
569 // Figure out the local header offset from the central directory. The
570 // actual file data will begin after the local header and the name /
571 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100572 const off64_t local_header_offset = cdr->local_file_header_offset;
573 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000574 ALOGW("Zip: bad local hdr offset in zip");
575 return kInvalidOffset;
576 }
577
Narayan Kamath926973e2014-06-09 14:18:14 +0100578 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700579 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800580 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900581 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000582 return kIoError;
583 }
584
Jiyong Parkcd997e62017-06-30 17:23:33 +0900585 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100586
587 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700588 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900589 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000590 return kInvalidOffset;
591 }
592
593 // Paranoia: Match the values specified in the local file header
594 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700595
Narayan Kamath162b7052017-06-05 13:21:12 +0100596 // Warn if central directory and local file header don't agree on the use
597 // of a trailing Data Descriptor. The reference implementation is inconsistent
598 // and appears to use the LFH value during extraction (unzip) but the CD value
599 // while displayng information about archives (zipinfo). The spec remains
600 // silent on this inconsistency as well.
601 //
602 // For now, always use the version from the LFH but make sure that the values
603 // specified in the central directory match those in the data descriptor.
604 //
605 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
606 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
607 // encoded using UTF-8). This implementation does not check for the presence of
608 // that flag and always enforces that entry names are valid UTF-8.
609 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
610 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700611 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700612 }
613
614 // If there is no trailing data descriptor, verify that the central directory and local file
615 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100616 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000617 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900618 if (data->compressed_length != lfh->compressed_size ||
619 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
620 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
621 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
622 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
623 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000624 return kInconsistentInformation;
625 }
626 } else {
627 data->has_data_descriptor = 1;
628 }
629
Elliott Hughes55fd2932017-05-28 22:59:04 -0700630 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
631 if ((cdr->version_made_by >> 8) == 3) {
632 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
633 } else {
634 data->unix_mode = 0777;
635 }
636
Narayan Kamath7462f022013-11-21 13:05:04 +0000637 // Check that the local file header name matches the declared
638 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100639 if (lfh->file_name_length == nameLen) {
640 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200641 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000642 ALOGW("Zip: Invalid declared length");
643 return kInvalidOffset;
644 }
645
Tianjie Xu18c25922016-09-29 15:27:41 -0700646 std::vector<uint8_t> name_buf(nameLen);
647 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800648 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000649 return kIoError;
650 }
651
Tianjie Xu18c25922016-09-29 15:27:41 -0700652 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000653 return kInconsistentInformation;
654 }
655
Narayan Kamath7462f022013-11-21 13:05:04 +0000656 } else {
657 ALOGW("Zip: lfh name did not match central directory.");
658 return kInconsistentInformation;
659 }
660
Jiyong Parkcd997e62017-06-30 17:23:33 +0900661 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
662 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000663 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800664 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000665 return kInvalidOffset;
666 }
667
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800668 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700669 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900670 static_cast<int64_t>(data_offset), data->compressed_length,
671 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000672 return kInvalidOffset;
673 }
674
675 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900676 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
677 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
678 static_cast<int64_t>(data_offset), data->uncompressed_length,
679 static_cast<int64_t>(cd_offset));
680 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000681 }
682
683 data->offset = data_offset;
684 return 0;
685}
686
687struct IterationHandle {
688 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100689 // We're not using vector here because this code is used in the Windows SDK
690 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700691 ZipString prefix;
692 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000693 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100694
Jiyong Parkcd997e62017-06-30 17:23:33 +0900695 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700696 if (in_prefix) {
697 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
698 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
699 prefix.name = name_copy;
700 prefix.name_length = in_prefix->name_length;
701 } else {
702 prefix.name = NULL;
703 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700704 }
Yusuke Sato07447542015-06-25 14:39:19 -0700705 if (in_suffix) {
706 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
707 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
708 suffix.name = name_copy;
709 suffix.name_length = in_suffix->name_length;
710 } else {
711 suffix.name = NULL;
712 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700713 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100714 }
715
716 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700717 delete[] prefix.name;
718 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100719 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000720};
721
Jiyong Parkcd997e62017-06-30 17:23:33 +0900722int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700723 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800724 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000725
726 if (archive == NULL || archive->hash_table == NULL) {
727 ALOGW("Zip: Invalid ZipArchiveHandle");
728 return kInvalidHandle;
729 }
730
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700731 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000732 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000733 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000734
Jiyong Parkcd997e62017-06-30 17:23:33 +0900735 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000736 return 0;
737}
738
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100739void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100740 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100741}
742
Jiyong Parkcd997e62017-06-30 17:23:33 +0900743int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800744 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100745 if (entryName.name_length == 0) {
746 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000747 return kInvalidEntryName;
748 }
749
Jiyong Parkcd997e62017-06-30 17:23:33 +0900750 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000751
752 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100753 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000754 return ent;
755 }
756
757 return FindEntry(archive, ent, data);
758}
759
Yusuke Sato07447542015-06-25 14:39:19 -0700760int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800761 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000762 if (handle == NULL) {
763 return kInvalidHandle;
764 }
765
766 ZipArchive* archive = handle->archive;
767 if (archive == NULL || archive->hash_table == NULL) {
768 ALOGW("Zip: Invalid ZipArchiveHandle");
769 return kInvalidHandle;
770 }
771
772 const uint32_t currentOffset = handle->position;
773 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700774 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000775
776 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
777 if (hash_table[i].name != NULL &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900778 (handle->prefix.name_length == 0 || hash_table[i].StartsWith(handle->prefix)) &&
779 (handle->suffix.name_length == 0 || hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000780 handle->position = (i + 1);
781 const int error = FindEntry(archive, i, data);
782 if (!error) {
783 name->name = hash_table[i].name;
784 name->name_length = hash_table[i].name_length;
785 }
786
787 return error;
788 }
789 }
790
791 handle->position = 0;
792 return kIterationEnd;
793}
794
Narayan Kamathf899bd52015-04-17 11:53:14 +0100795// A Writer that writes data to a fixed size memory region.
796// The size of the memory region must be equal to the total size of
797// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100798class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100799 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900800 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100801
802 virtual bool Append(uint8_t* buf, size_t buf_size) override {
803 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900804 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
805 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100806 return false;
807 }
808
809 memcpy(buf_ + bytes_written_, buf, buf_size);
810 bytes_written_ += buf_size;
811 return true;
812 }
813
814 private:
815 uint8_t* const buf_;
816 const size_t size_;
817 size_t bytes_written_;
818};
819
820// A Writer that appends data to a file |fd| at its current position.
821// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100822class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100823 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100824 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
825 // guaranteeing that the file descriptor is valid and that there's enough
826 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800827 // is truncated to the correct length (no truncation if |fd| references a
828 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100829 //
830 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800831 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100832 const uint32_t declared_length = entry->uncompressed_length;
833 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
834 if (current_offset == -1) {
835 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800836 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100837 }
838
839 int result = 0;
840#if defined(__linux__)
841 if (declared_length > 0) {
842 // Make sure we have enough space on the volume to extract the compressed
843 // entry. Note that the call to ftruncate below will change the file size but
844 // will not allocate space on disk and this call to fallocate will not
845 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700846 // Note: fallocate is only supported by the following filesystems -
847 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
848 // EOPNOTSUPP error when issued in other filesystems.
849 // Hence, check for the return error code before concluding that the
850 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100851 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700852 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700853 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100854 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
855 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800856 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100857 }
858 }
859#endif // __linux__
860
Tao Baoa456c212016-11-15 10:08:07 -0800861 struct stat sb;
862 if (fstat(fd, &sb) == -1) {
863 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800864 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100865 }
866
Tao Baoa456c212016-11-15 10:08:07 -0800867 // Block device doesn't support ftruncate(2).
868 if (!S_ISBLK(sb.st_mode)) {
869 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
870 if (result == -1) {
871 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
872 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800873 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800874 }
875 }
876
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800877 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100878 }
879
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800880 FileWriter(FileWriter&& other)
881 : fd_(other.fd_),
882 declared_length_(other.declared_length_),
883 total_bytes_written_(other.total_bytes_written_) {
884 other.fd_ = -1;
885 }
886
887 bool IsValid() const { return fd_ != -1; }
888
Narayan Kamathf899bd52015-04-17 11:53:14 +0100889 virtual bool Append(uint8_t* buf, size_t buf_size) override {
890 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900891 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
892 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100893 return false;
894 }
895
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100896 const bool result = android::base::WriteFully(fd_, buf, buf_size);
897 if (result) {
898 total_bytes_written_ += buf_size;
899 } else {
900 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100901 }
902
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100903 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100904 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900905
Narayan Kamathf899bd52015-04-17 11:53:14 +0100906 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800907 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900908 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100909
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800910 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100911 const size_t declared_length_;
912 size_t total_bytes_written_;
913};
914
Narayan Kamath485b3642017-10-26 14:42:39 +0100915class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100916 public:
917 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
918 : Reader(), zip_file_(zip_file), entry_(entry) {}
919
920 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
921 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
922 }
923
924 virtual ~EntryReader() {}
925
926 private:
927 const MappedZipFile& zip_file_;
928 const ZipEntry* entry_;
929};
930
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800931// This method is using libz macros with old-style-casts
932#pragma GCC diagnostic push
933#pragma GCC diagnostic ignored "-Wold-style-cast"
934static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
935 return inflateInit2(stream, window_bits);
936}
937#pragma GCC diagnostic pop
938
Narayan Kamath485b3642017-10-26 14:42:39 +0100939namespace zip_archive {
940
941// Moved out of line to avoid -Wweak-vtables.
942Reader::~Reader() {}
943Writer::~Writer() {}
944
945int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
946 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700947 const size_t kBufSize = 32768;
948 std::vector<uint8_t> read_buf(kBufSize);
949 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000950 z_stream zstream;
951 int zerr;
952
953 /*
954 * Initialize the zlib stream struct.
955 */
956 memset(&zstream, 0, sizeof(zstream));
957 zstream.zalloc = Z_NULL;
958 zstream.zfree = Z_NULL;
959 zstream.opaque = Z_NULL;
960 zstream.next_in = NULL;
961 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700962 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000963 zstream.avail_out = kBufSize;
964 zstream.data_type = Z_UNKNOWN;
965
966 /*
967 * Use the undocumented "negative window bits" feature to tell zlib
968 * that there's no zlib header waiting for it.
969 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800970 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000971 if (zerr != Z_OK) {
972 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900973 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000974 } else {
975 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
976 }
977
978 return kZlibError;
979 }
980
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800981 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900982 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800983 };
984
985 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
986
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000987 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100988 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100989 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000990 do {
991 /* read as much as we can */
992 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100993 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
994 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700995 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100996 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
997 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800998 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000999 }
1000
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001001 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001002
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001003 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001004 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001005 }
1006
1007 /* uncompress the data */
1008 zerr = inflate(&zstream, Z_NO_FLUSH);
1009 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001010 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1011 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001012 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001013 }
1014
1015 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001016 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001017 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001018 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001019 return kIoError;
1020 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001021 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001022 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001023
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001024 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001025 zstream.avail_out = kBufSize;
1026 }
1027 } while (zerr == Z_OK);
1028
Jiyong Parkcd997e62017-06-30 17:23:33 +09001029 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001030
Narayan Kamath162b7052017-06-05 13:21:12 +01001031 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1032 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1033 // doesn't bother calculating the checksum in that scenario. We just do
1034 // it ourselves above because there are no additional gains to be made by
1035 // having zlib calculate it for us, since they do it by calling crc32 in
1036 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001037 if (compute_crc) {
1038 *crc_out = crc;
1039 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001040
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001041 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001042 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1043 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001044 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001045 }
1046
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001047 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001048}
Narayan Kamath485b3642017-10-26 14:42:39 +01001049} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001050
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001051static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001052 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001053 const EntryReader reader(mapped_zip, entry);
1054
Narayan Kamath485b3642017-10-26 14:42:39 +01001055 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1056 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001057}
1058
Narayan Kamath485b3642017-10-26 14:42:39 +01001059static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1060 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001061 static const uint32_t kBufSize = 32768;
1062 std::vector<uint8_t> buf(kBufSize);
1063
1064 const uint32_t length = entry->uncompressed_length;
1065 uint32_t count = 0;
1066 uint64_t crc = 0;
1067 while (count < length) {
1068 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001069 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001070
Adam Lesinskide117e42017-06-19 10:27:38 -07001071 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001072 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001073
1074 // Make sure to read at offset to ensure concurrent access to the fd.
1075 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1076 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1077 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001078 return kIoError;
1079 }
1080
1081 if (!writer->Append(&buf[0], block_size)) {
1082 return kIoError;
1083 }
1084 crc = crc32(crc, &buf[0], block_size);
1085 count += block_size;
1086 }
1087
1088 *crc_out = crc;
1089
1090 return 0;
1091}
1092
Narayan Kamath485b3642017-10-26 14:42:39 +01001093int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001094 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001095 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001096
1097 // this should default to kUnknownCompressionMethod.
1098 int32_t return_value = -1;
1099 uint64_t crc = 0;
1100 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001101 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001102 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001103 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001104 }
1105
1106 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001107 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001108 if (return_value) {
1109 return return_value;
1110 }
1111 }
1112
Narayan Kamath162b7052017-06-05 13:21:12 +01001113 // Validate that the CRC matches the calculated value.
1114 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001115 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001116 return kInconsistentInformation;
1117 }
1118
1119 return return_value;
1120}
1121
Jiyong Parkcd997e62017-06-30 17:23:33 +09001122int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001123 MemoryWriter writer(begin, size);
1124 return ExtractToWriter(handle, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001125}
1126
Jiyong Parkcd997e62017-06-30 17:23:33 +09001127int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001128 auto writer = FileWriter::Create(fd, entry);
1129 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001130 return kIoError;
1131 }
1132
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001133 return ExtractToWriter(handle, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001134}
1135
1136const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001137 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1138 // match.
1139 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1140 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1141
1142 const uint32_t idx = -error_code;
1143 if (idx < arraysize(kErrorMessages)) {
1144 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001145 }
1146
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001147 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001148}
1149
1150int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001151 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001152}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001153
Jiyong Parkcd997e62017-06-30 17:23:33 +09001154ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001155 size_t len = strlen(entry_name);
1156 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1157 name_length = static_cast<uint16_t>(len);
1158}
Tianjie Xu18c25922016-09-29 15:27:41 -07001159
1160#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001161class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001162 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001163 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1164 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001165
1166 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1167 return proc_function_(buf, buf_size, cookie_);
1168 }
1169
1170 private:
1171 ProcessZipEntryFunction proc_function_;
1172 void* cookie_;
1173};
1174
1175int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1176 ProcessZipEntryFunction func, void* cookie) {
1177 ProcessWriter writer(func, cookie);
1178 return ExtractToWriter(handle, entry, &writer);
1179}
1180
Jiyong Parkcd997e62017-06-30 17:23:33 +09001181#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001182
1183int MappedZipFile::GetFileDescriptor() const {
1184 if (!has_fd_) {
1185 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1186 return -1;
1187 }
1188 return fd_;
1189}
1190
1191void* MappedZipFile::GetBasePtr() const {
1192 if (has_fd_) {
1193 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1194 return nullptr;
1195 }
1196 return base_ptr_;
1197}
1198
1199off64_t MappedZipFile::GetFileLength() const {
1200 if (has_fd_) {
1201 off64_t result = lseek64(fd_, 0, SEEK_END);
1202 if (result == -1) {
1203 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1204 }
1205 return result;
1206 } else {
1207 if (base_ptr_ == nullptr) {
1208 ALOGE("Zip: invalid file map\n");
1209 return -1;
1210 }
1211 return static_cast<off64_t>(data_length_);
1212 }
1213}
1214
Tianjie Xu18c25922016-09-29 15:27:41 -07001215// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001216bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001217 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001218 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001219 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1220 return false;
1221 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001222 } else {
1223 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1224 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1225 return false;
1226 }
1227 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001228 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001229 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001230}
1231
1232void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1233 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1234 length_ = cd_size;
1235}
1236
1237bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1238 size_t cd_size) {
1239 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001240 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1241 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001242 return false;
1243 }
1244
1245 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001246 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001247 } else {
1248 if (mapped_zip.GetBasePtr() == nullptr) {
1249 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1250 return false;
1251 }
1252 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1253 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001254 ALOGE(
1255 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1256 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1257 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001258 return false;
1259 }
1260
1261 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1262 }
1263 return true;
1264}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001265
1266tm ZipEntry::GetModificationTime() const {
1267 tm t = {};
1268
1269 t.tm_hour = (mod_time >> 11) & 0x1f;
1270 t.tm_min = (mod_time >> 5) & 0x3f;
1271 t.tm_sec = (mod_time & 0x1f) << 1;
1272
1273 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1274 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1275 t.tm_mday = (mod_time >> 16) & 0x1f;
1276
1277 return t;
1278}