blob: 9536fc7aea68c08fd3ebd841b65799a52b3fc9ef [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>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070044#include <log/log.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045#include <utils/Compat.h>
46#include <utils/FileMap.h>
Christopher Ferrise6884ce2015-11-10 14:55:12 -080047#include "ziparchive/zip_archive.h"
Dan Albert1ae07642015-04-09 14:11:18 -070048#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000049
Narayan Kamath044bc8e2014-12-03 18:22:53 +000050#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070051#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080052#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070053
Dan Albert1ae07642015-04-09 14:11:18 -070054using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000055
Narayan Kamath162b7052017-06-05 13:21:12 +010056// Used to turn on crc checks - verify that the content CRC matches the values
57// specified in the local file header and the central directory.
58static const bool kCrcChecksEnabled = false;
59
Narayan Kamath926973e2014-06-09 14:18:14 +010060// This is for windows. If we don't open a file in binary mode, weird
Narayan Kamath7462f022013-11-21 13:05:04 +000061// things will happen.
62#ifndef O_BINARY
63#define O_BINARY 0
64#endif
65
Narayan Kamath926973e2014-06-09 14:18:14 +010066// The maximum number of bytes to scan backwards for the EOCD start.
67static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
68
Narayan Kamath7462f022013-11-21 13:05:04 +000069/*
70 * A Read-only Zip archive.
71 *
72 * We want "open" and "find entry by name" to be fast operations, and
73 * we want to use as little memory as possible. We memory-map the zip
74 * central directory, and load a hash table with pointers to the filenames
75 * (which aren't null-terminated). The other fields are at a fixed offset
76 * from the filename, so we don't need to extract those (but we do need
77 * to byte-read and endian-swap them every time we want them).
78 *
79 * It's possible that somebody has handed us a massive (~1GB) zip archive,
80 * so we can't expect to mmap the entire file.
81 *
82 * To speed comparisons when doing a lookup by name, we could make the mapping
83 * "private" (copy-on-write) and null-terminate the filenames after verifying
84 * the record structure. However, this requires a private mapping of
85 * every page that the Central Directory touches. Easier to tuck a copy
86 * of the string length into the hash table entry.
87 */
Narayan Kamath7462f022013-11-21 13:05:04 +000088
Narayan Kamath7462f022013-11-21 13:05:04 +000089/*
90 * Round up to the next highest power of 2.
91 *
92 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
93 */
94static uint32_t RoundUpPower2(uint32_t val) {
95 val--;
96 val |= val >> 1;
97 val |= val >> 2;
98 val |= val >> 4;
99 val |= val >> 8;
100 val |= val >> 16;
101 val++;
102
103 return val;
104}
105
Yusuke Sato07447542015-06-25 14:39:19 -0700106static uint32_t ComputeHash(const ZipString& name) {
Sebastian Pop1f93d712017-11-28 16:36:48 -0600107#if !defined(_WIN32)
108 return std::hash<std::string_view>{}(
109 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length));
110#else
111 // Remove this code path once the windows compiler knows how to compile the above statement.
Narayan Kamath7462f022013-11-21 13:05:04 +0000112 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100113 uint16_t len = name.name_length;
114 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000115
116 while (len--) {
117 hash = hash * 31 + *str++;
118 }
119
120 return hash;
Sebastian Pop1f93d712017-11-28 16:36:48 -0600121#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000122}
123
124/*
125 * Convert a ZipEntry to a hash table index, verifying that it's in a
126 * valid range.
127 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900128static int64_t EntryToIndex(const ZipString* hash_table, const uint32_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700129 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100130 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000131
132 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
133 uint32_t ent = hash & (hash_table_size - 1);
134 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700135 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000136 return ent;
137 }
138
139 ent = (ent + 1) & (hash_table_size - 1);
140 }
141
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100142 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000143 return kEntryNotFound;
144}
145
146/*
147 * Add a new entry to the hash table.
148 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900149static int32_t AddToHash(ZipString* hash_table, const uint64_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700150 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100151 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000152 uint32_t ent = hash & (hash_table_size - 1);
153
154 /*
155 * We over-allocated the table, so we're guaranteed to find an empty slot.
156 * Further, we guarantee that the hashtable size is not 0.
157 */
158 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700159 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000160 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100161 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000162 return kDuplicateEntry;
163 }
164 ent = (ent + 1) & (hash_table_size - 1);
165 }
166
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100167 hash_table[ent].name = name.name;
168 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000169 return 0;
170}
171
Josh Gao1b496342018-07-17 11:08:48 -0700172ZipArchive::ZipArchive(const int fd, bool assume_ownership)
173 : mapped_zip(fd),
174 close_file(assume_ownership),
175 directory_offset(0),
176 central_directory(),
177 directory_map(new android::FileMap()),
178 num_entries(0),
179 hash_table_size(0),
180 hash_table(nullptr) {
181#if defined(__BIONIC__)
182 if (assume_ownership) {
183 android_fdsan_exchange_owner_tag(fd, 0, reinterpret_cast<uint64_t>(this));
184 }
185#endif
186}
187
188ZipArchive::ZipArchive(void* address, size_t length)
189 : mapped_zip(address, length),
190 close_file(false),
191 directory_offset(0),
192 central_directory(),
193 directory_map(new android::FileMap()),
194 num_entries(0),
195 hash_table_size(0),
196 hash_table(nullptr) {}
197
198ZipArchive::~ZipArchive() {
199 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
200#if defined(__BIONIC__)
201 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), reinterpret_cast<uint64_t>(this));
202#else
203 close(mapped_zip.GetFileDescriptor());
204#endif
205 }
206
207 free(hash_table);
208}
209
Tianjie Xu18c25922016-09-29 15:27:41 -0700210static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900211 off64_t file_length, off64_t read_amount, uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000212 const off64_t search_start = file_length - read_amount;
213
Jiyong Parkcd997e62017-06-30 17:23:33 +0900214 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
215 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
216 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000217 return kIoError;
218 }
219
220 /*
221 * Scan backward for the EOCD magic. In an archive without a trailing
222 * comment, we'll find it on the first try. (We may want to consider
223 * doing an initial minimal read; if we don't find it, retry with a
224 * second read as above.)
225 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100226 int i = read_amount - sizeof(EocdRecord);
227 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700228 if (scan_buffer[i] == 0x50) {
229 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
230 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
231 ALOGV("+++ Found EOCD at buf+%d", i);
232 break;
233 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000234 }
235 }
236 if (i < 0) {
237 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
238 return kInvalidFile;
239 }
240
241 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100242 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000243 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100244 * Verify that there's no trailing space at the end of the central directory
245 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000246 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900247 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100248 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100249 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100250 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100251 return kInvalidFile;
252 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000253
Narayan Kamath926973e2014-06-09 14:18:14 +0100254 /*
255 * Grab the CD offset and size, and the number of entries in the
256 * archive and verify that they look reasonable.
257 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700258 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100259 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900260 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700261#if defined(__ANDROID__)
262 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
263 android_errorWriteLog(0x534e4554, "31251826");
264 }
265#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000266 return kInvalidOffset;
267 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100268 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000269#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000270 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000271#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000272 return kEmptyArchive;
273 }
274
Jiyong Parkcd997e62017-06-30 17:23:33 +0900275 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
276 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000277
278 /*
279 * It all looks good. Create a mapping for the CD, and set the fields
280 * in archive.
281 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700282
283 if (!archive->InitializeCentralDirectory(debug_file_name,
284 static_cast<off64_t>(eocd->cd_start_offset),
285 static_cast<size_t>(eocd->cd_size))) {
286 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000287 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000288 }
289
Narayan Kamath926973e2014-06-09 14:18:14 +0100290 archive->num_entries = eocd->num_records;
291 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000292
293 return 0;
294}
295
296/*
297 * Find the zip Central Directory and memory-map it.
298 *
299 * On success, returns 0 after populating fields from the EOCD area:
300 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700301 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000302 * num_entries
303 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700304static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000305 // Test file length. We use lseek64 to make sure the file
306 // is small enough to be a zip file (Its size must be less than
307 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700308 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000309 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000310 return kInvalidFile;
311 }
312
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800313 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100314 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000315 return kInvalidFile;
316 }
317
Narayan Kamath926973e2014-06-09 14:18:14 +0100318 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
319 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000320 return kInvalidFile;
321 }
322
323 /*
324 * Perform the traditional EOCD snipe hunt.
325 *
326 * We're searching for the End of Central Directory magic number,
327 * which appears at the start of the EOCD block. It's followed by
328 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
329 * need to read the last part of the file into a buffer, dig through
330 * it to find the magic number, parse some values out, and use those
331 * to determine the extent of the CD.
332 *
333 * We start by pulling in the last part of the file.
334 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100335 off64_t read_amount = kMaxEOCDSearch;
336 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000337 read_amount = file_length;
338 }
339
Tianjie Xu18c25922016-09-29 15:27:41 -0700340 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900341 int32_t result =
342 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000343 return result;
344}
345
346/*
347 * Parses the Zip archive's Central Directory. Allocates and populates the
348 * hash table.
349 *
350 * Returns 0 on success.
351 */
352static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700353 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
354 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100355 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000356
357 /*
358 * Create hash table. We have a minimum 75% load factor, possibly as
359 * low as 50% after we round off to a power of 2. There must be at
360 * least one unused entry to avoid an infinite loop during creation.
361 */
362 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900363 archive->hash_table =
364 reinterpret_cast<ZipString*>(calloc(archive->hash_table_size, sizeof(ZipString)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700365 if (archive->hash_table == nullptr) {
366 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
367 archive->hash_table_size, sizeof(ZipString));
368 return -1;
369 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000370
371 /*
372 * Walk through the central directory, adding entries to the hash
373 * table and verifying values.
374 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100375 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000376 const uint8_t* ptr = cd_ptr;
377 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700378 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
379 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
380#if defined(__ANDROID__)
381 android_errorWriteLog(0x534e4554, "36392138");
382#endif
383 return -1;
384 }
385
Jiyong Parkcd997e62017-06-30 17:23:33 +0900386 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100387 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700388 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800389 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000390 }
391
Narayan Kamath926973e2014-06-09 14:18:14 +0100392 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000393 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800394 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900395 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800396 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000397 }
398
Narayan Kamath926973e2014-06-09 14:18:14 +0100399 const uint16_t file_name_length = cdr->file_name_length;
400 const uint16_t extra_length = cdr->extra_field_length;
401 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100402 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
403
Tianjie Xu9e020e22016-10-10 12:11:30 -0700404 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900405 ALOGW(
406 "Zip: file name boundary exceeds the central directory range, file_name_length: "
407 "%" PRIx16 ", cd_length: %zu",
408 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700409 return -1;
410 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000411 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
412 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800413 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100414 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000415
416 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700417 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100418 entry_name.name = file_name;
419 entry_name.name_length = file_name_length;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900420 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800421 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000422 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800423 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000424 }
425
Narayan Kamath926973e2014-06-09 14:18:14 +0100426 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
427 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900428 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800429 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000430 }
431 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100432
433 uint32_t lfh_start_bytes;
434 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
435 sizeof(uint32_t), 0)) {
436 ALOGW("Zip: Unable to read header for entry at offset == 0.");
437 return -1;
438 }
439
440 if (lfh_start_bytes != LocalFileHeader::kSignature) {
441 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
442#if defined(__ANDROID__)
443 android_errorWriteLog(0x534e4554, "64211847");
444#endif
445 return -1;
446 }
447
Mark Salyzyn088bf902014-05-08 16:02:20 -0700448 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000449
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800450 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000451}
452
Jiyong Parkcd997e62017-06-30 17:23:33 +0900453static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000454 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700455 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000456 return result;
457 }
458
459 if ((result = ParseZipArchive(archive))) {
460 return result;
461 }
462
463 return 0;
464}
465
Jiyong Parkcd997e62017-06-30 17:23:33 +0900466int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
467 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700468 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000469 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000470 return OpenArchiveInternal(archive, debug_file_name);
471}
472
473int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100474 const int fd = open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700475 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000476 *handle = archive;
477
Narayan Kamath7462f022013-11-21 13:05:04 +0000478 if (fd < 0) {
479 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
480 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000481 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700482
Narayan Kamath7462f022013-11-21 13:05:04 +0000483 return OpenArchiveInternal(archive, fileName);
484}
485
Tianjie Xu18c25922016-09-29 15:27:41 -0700486int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900487 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700488 ZipArchive* archive = new ZipArchive(address, length);
489 *handle = archive;
490 return OpenArchiveInternal(archive, debug_file_name);
491}
492
Narayan Kamath7462f022013-11-21 13:05:04 +0000493/*
494 * Close a ZipArchive, closing the file and freeing the contents.
495 */
496void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800497 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000498 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100499 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000500}
501
Narayan Kamath162b7052017-06-05 13:21:12 +0100502static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100503 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700504 off64_t offset = entry->offset;
505 if (entry->method != kCompressStored) {
506 offset += entry->compressed_length;
507 } else {
508 offset += entry->uncompressed_length;
509 }
510
511 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000512 return kIoError;
513 }
514
Narayan Kamath926973e2014-06-09 14:18:14 +0100515 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700516 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
517 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000518
Narayan Kamath162b7052017-06-05 13:21:12 +0100519 // Validate that the values in the data descriptor match those in the central
520 // directory.
521 if (entry->compressed_length != descriptor->compressed_size ||
522 entry->uncompressed_length != descriptor->uncompressed_size ||
523 entry->crc32 != descriptor->crc32) {
524 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
525 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
526 entry->compressed_length, entry->uncompressed_length, entry->crc32,
527 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
528 return kInconsistentInformation;
529 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000530
531 return 0;
532}
533
Jiyong Parkcd997e62017-06-30 17:23:33 +0900534static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000535 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000536
537 // Recover the start of the central directory entry from the filename
538 // pointer. The filename is the first entry past the fixed-size data,
539 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100540 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100541 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000542
543 // This is the base of our mmapped region, we have to sanity check that
544 // the name that's in the hash table is a pointer to a location within
545 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700546 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
547 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000548 ALOGW("Zip: Invalid entry pointer");
549 return kInvalidOffset;
550 }
551
Jiyong Parkcd997e62017-06-30 17:23:33 +0900552 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100553
Narayan Kamath7462f022013-11-21 13:05:04 +0000554 // The offset of the start of the central directory in the zipfile.
555 // We keep this lying around so that we can sanity check all our lengths
556 // and our per-file structures.
557 const off64_t cd_offset = archive->directory_offset;
558
559 // Fill out the compression method, modification time, crc32
560 // and other interesting attributes from the central directory. These
561 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100562 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900563 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100564 data->crc32 = cdr->crc32;
565 data->compressed_length = cdr->compressed_size;
566 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000567
568 // Figure out the local header offset from the central directory. The
569 // actual file data will begin after the local header and the name /
570 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100571 const off64_t local_header_offset = cdr->local_file_header_offset;
572 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000573 ALOGW("Zip: bad local hdr offset in zip");
574 return kInvalidOffset;
575 }
576
Narayan Kamath926973e2014-06-09 14:18:14 +0100577 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700578 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800579 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900580 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000581 return kIoError;
582 }
583
Jiyong Parkcd997e62017-06-30 17:23:33 +0900584 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100585
586 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700587 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900588 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000589 return kInvalidOffset;
590 }
591
592 // Paranoia: Match the values specified in the local file header
593 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700594
Narayan Kamath162b7052017-06-05 13:21:12 +0100595 // Warn if central directory and local file header don't agree on the use
596 // of a trailing Data Descriptor. The reference implementation is inconsistent
597 // and appears to use the LFH value during extraction (unzip) but the CD value
598 // while displayng information about archives (zipinfo). The spec remains
599 // silent on this inconsistency as well.
600 //
601 // For now, always use the version from the LFH but make sure that the values
602 // specified in the central directory match those in the data descriptor.
603 //
604 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
605 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
606 // encoded using UTF-8). This implementation does not check for the presence of
607 // that flag and always enforces that entry names are valid UTF-8.
608 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
609 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700610 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700611 }
612
613 // If there is no trailing data descriptor, verify that the central directory and local file
614 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100615 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000616 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900617 if (data->compressed_length != lfh->compressed_size ||
618 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
619 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
620 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
621 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
622 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000623 return kInconsistentInformation;
624 }
625 } else {
626 data->has_data_descriptor = 1;
627 }
628
Elliott Hughes55fd2932017-05-28 22:59:04 -0700629 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
630 if ((cdr->version_made_by >> 8) == 3) {
631 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
632 } else {
633 data->unix_mode = 0777;
634 }
635
Narayan Kamath7462f022013-11-21 13:05:04 +0000636 // Check that the local file header name matches the declared
637 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100638 if (lfh->file_name_length == nameLen) {
639 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200640 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000641 ALOGW("Zip: Invalid declared length");
642 return kInvalidOffset;
643 }
644
Tianjie Xu18c25922016-09-29 15:27:41 -0700645 std::vector<uint8_t> name_buf(nameLen);
646 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800647 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000648 return kIoError;
649 }
650
Tianjie Xu18c25922016-09-29 15:27:41 -0700651 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000652 return kInconsistentInformation;
653 }
654
Narayan Kamath7462f022013-11-21 13:05:04 +0000655 } else {
656 ALOGW("Zip: lfh name did not match central directory.");
657 return kInconsistentInformation;
658 }
659
Jiyong Parkcd997e62017-06-30 17:23:33 +0900660 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
661 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000662 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800663 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000664 return kInvalidOffset;
665 }
666
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800667 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700668 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900669 static_cast<int64_t>(data_offset), data->compressed_length,
670 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000671 return kInvalidOffset;
672 }
673
674 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900675 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
676 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
677 static_cast<int64_t>(data_offset), data->uncompressed_length,
678 static_cast<int64_t>(cd_offset));
679 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000680 }
681
682 data->offset = data_offset;
683 return 0;
684}
685
686struct IterationHandle {
687 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100688 // We're not using vector here because this code is used in the Windows SDK
689 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700690 ZipString prefix;
691 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000692 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100693
Jiyong Parkcd997e62017-06-30 17:23:33 +0900694 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700695 if (in_prefix) {
696 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
697 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
698 prefix.name = name_copy;
699 prefix.name_length = in_prefix->name_length;
700 } else {
701 prefix.name = NULL;
702 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700703 }
Yusuke Sato07447542015-06-25 14:39:19 -0700704 if (in_suffix) {
705 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
706 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
707 suffix.name = name_copy;
708 suffix.name_length = in_suffix->name_length;
709 } else {
710 suffix.name = NULL;
711 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700712 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100713 }
714
715 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700716 delete[] prefix.name;
717 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100718 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000719};
720
Jiyong Parkcd997e62017-06-30 17:23:33 +0900721int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700722 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800723 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000724
725 if (archive == NULL || archive->hash_table == NULL) {
726 ALOGW("Zip: Invalid ZipArchiveHandle");
727 return kInvalidHandle;
728 }
729
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700730 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000731 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000732 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000733
Jiyong Parkcd997e62017-06-30 17:23:33 +0900734 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000735 return 0;
736}
737
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100738void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100739 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100740}
741
Jiyong Parkcd997e62017-06-30 17:23:33 +0900742int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800743 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100744 if (entryName.name_length == 0) {
745 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000746 return kInvalidEntryName;
747 }
748
Jiyong Parkcd997e62017-06-30 17:23:33 +0900749 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000750
751 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100752 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000753 return ent;
754 }
755
756 return FindEntry(archive, ent, data);
757}
758
Yusuke Sato07447542015-06-25 14:39:19 -0700759int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800760 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000761 if (handle == NULL) {
762 return kInvalidHandle;
763 }
764
765 ZipArchive* archive = handle->archive;
766 if (archive == NULL || archive->hash_table == NULL) {
767 ALOGW("Zip: Invalid ZipArchiveHandle");
768 return kInvalidHandle;
769 }
770
771 const uint32_t currentOffset = handle->position;
772 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700773 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000774
775 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
776 if (hash_table[i].name != NULL &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900777 (handle->prefix.name_length == 0 || hash_table[i].StartsWith(handle->prefix)) &&
778 (handle->suffix.name_length == 0 || hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000779 handle->position = (i + 1);
780 const int error = FindEntry(archive, i, data);
781 if (!error) {
782 name->name = hash_table[i].name;
783 name->name_length = hash_table[i].name_length;
784 }
785
786 return error;
787 }
788 }
789
790 handle->position = 0;
791 return kIterationEnd;
792}
793
Narayan Kamathf899bd52015-04-17 11:53:14 +0100794// A Writer that writes data to a fixed size memory region.
795// The size of the memory region must be equal to the total size of
796// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100797class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100798 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900799 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100800
801 virtual bool Append(uint8_t* buf, size_t buf_size) override {
802 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900803 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
804 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100805 return false;
806 }
807
808 memcpy(buf_ + bytes_written_, buf, buf_size);
809 bytes_written_ += buf_size;
810 return true;
811 }
812
813 private:
814 uint8_t* const buf_;
815 const size_t size_;
816 size_t bytes_written_;
817};
818
819// A Writer that appends data to a file |fd| at its current position.
820// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100821class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100822 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100823 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
824 // guaranteeing that the file descriptor is valid and that there's enough
825 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800826 // is truncated to the correct length (no truncation if |fd| references a
827 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100828 //
829 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800830 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100831 const uint32_t declared_length = entry->uncompressed_length;
832 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
833 if (current_offset == -1) {
834 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800835 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100836 }
837
838 int result = 0;
839#if defined(__linux__)
840 if (declared_length > 0) {
841 // Make sure we have enough space on the volume to extract the compressed
842 // entry. Note that the call to ftruncate below will change the file size but
843 // will not allocate space on disk and this call to fallocate will not
844 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700845 // Note: fallocate is only supported by the following filesystems -
846 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
847 // EOPNOTSUPP error when issued in other filesystems.
848 // Hence, check for the return error code before concluding that the
849 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100850 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700851 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700852 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100853 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
854 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800855 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100856 }
857 }
858#endif // __linux__
859
Tao Baoa456c212016-11-15 10:08:07 -0800860 struct stat sb;
861 if (fstat(fd, &sb) == -1) {
862 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800863 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100864 }
865
Tao Baoa456c212016-11-15 10:08:07 -0800866 // Block device doesn't support ftruncate(2).
867 if (!S_ISBLK(sb.st_mode)) {
868 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
869 if (result == -1) {
870 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
871 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800872 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800873 }
874 }
875
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800876 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100877 }
878
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800879 FileWriter(FileWriter&& other)
880 : fd_(other.fd_),
881 declared_length_(other.declared_length_),
882 total_bytes_written_(other.total_bytes_written_) {
883 other.fd_ = -1;
884 }
885
886 bool IsValid() const { return fd_ != -1; }
887
Narayan Kamathf899bd52015-04-17 11:53:14 +0100888 virtual bool Append(uint8_t* buf, size_t buf_size) override {
889 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900890 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
891 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100892 return false;
893 }
894
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100895 const bool result = android::base::WriteFully(fd_, buf, buf_size);
896 if (result) {
897 total_bytes_written_ += buf_size;
898 } else {
899 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100900 }
901
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100902 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100903 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900904
Narayan Kamathf899bd52015-04-17 11:53:14 +0100905 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800906 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900907 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100908
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800909 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100910 const size_t declared_length_;
911 size_t total_bytes_written_;
912};
913
Narayan Kamath485b3642017-10-26 14:42:39 +0100914class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100915 public:
916 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
917 : Reader(), zip_file_(zip_file), entry_(entry) {}
918
919 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
920 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
921 }
922
923 virtual ~EntryReader() {}
924
925 private:
926 const MappedZipFile& zip_file_;
927 const ZipEntry* entry_;
928};
929
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800930// This method is using libz macros with old-style-casts
931#pragma GCC diagnostic push
932#pragma GCC diagnostic ignored "-Wold-style-cast"
933static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
934 return inflateInit2(stream, window_bits);
935}
936#pragma GCC diagnostic pop
937
Narayan Kamath485b3642017-10-26 14:42:39 +0100938namespace zip_archive {
939
940// Moved out of line to avoid -Wweak-vtables.
941Reader::~Reader() {}
942Writer::~Writer() {}
943
944int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
945 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700946 const size_t kBufSize = 32768;
947 std::vector<uint8_t> read_buf(kBufSize);
948 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000949 z_stream zstream;
950 int zerr;
951
952 /*
953 * Initialize the zlib stream struct.
954 */
955 memset(&zstream, 0, sizeof(zstream));
956 zstream.zalloc = Z_NULL;
957 zstream.zfree = Z_NULL;
958 zstream.opaque = Z_NULL;
959 zstream.next_in = NULL;
960 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700961 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000962 zstream.avail_out = kBufSize;
963 zstream.data_type = Z_UNKNOWN;
964
965 /*
966 * Use the undocumented "negative window bits" feature to tell zlib
967 * that there's no zlib header waiting for it.
968 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800969 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000970 if (zerr != Z_OK) {
971 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900972 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000973 } else {
974 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
975 }
976
977 return kZlibError;
978 }
979
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800980 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900981 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800982 };
983
984 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
985
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000986 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100987 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100988 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000989 do {
990 /* read as much as we can */
991 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100992 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
993 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700994 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100995 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
996 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800997 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000998 }
999
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001000 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001001
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001002 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001003 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001004 }
1005
1006 /* uncompress the data */
1007 zerr = inflate(&zstream, Z_NO_FLUSH);
1008 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001009 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1010 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001011 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001012 }
1013
1014 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001015 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001016 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001017 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001018 return kIoError;
1019 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001020 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001021 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001022
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001023 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001024 zstream.avail_out = kBufSize;
1025 }
1026 } while (zerr == Z_OK);
1027
Jiyong Parkcd997e62017-06-30 17:23:33 +09001028 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001029
Narayan Kamath162b7052017-06-05 13:21:12 +01001030 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1031 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1032 // doesn't bother calculating the checksum in that scenario. We just do
1033 // it ourselves above because there are no additional gains to be made by
1034 // having zlib calculate it for us, since they do it by calling crc32 in
1035 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001036 if (compute_crc) {
1037 *crc_out = crc;
1038 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001039
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001040 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001041 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1042 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001043 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001044 }
1045
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001046 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001047}
Narayan Kamath485b3642017-10-26 14:42:39 +01001048} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001049
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001050static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001051 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001052 const EntryReader reader(mapped_zip, entry);
1053
Narayan Kamath485b3642017-10-26 14:42:39 +01001054 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1055 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001056}
1057
Narayan Kamath485b3642017-10-26 14:42:39 +01001058static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1059 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001060 static const uint32_t kBufSize = 32768;
1061 std::vector<uint8_t> buf(kBufSize);
1062
1063 const uint32_t length = entry->uncompressed_length;
1064 uint32_t count = 0;
1065 uint64_t crc = 0;
1066 while (count < length) {
1067 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001068 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001069
Adam Lesinskide117e42017-06-19 10:27:38 -07001070 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001071 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001072
1073 // Make sure to read at offset to ensure concurrent access to the fd.
1074 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1075 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1076 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001077 return kIoError;
1078 }
1079
1080 if (!writer->Append(&buf[0], block_size)) {
1081 return kIoError;
1082 }
1083 crc = crc32(crc, &buf[0], block_size);
1084 count += block_size;
1085 }
1086
1087 *crc_out = crc;
1088
1089 return 0;
1090}
1091
Narayan Kamath485b3642017-10-26 14:42:39 +01001092int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001093 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001094 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001095
1096 // this should default to kUnknownCompressionMethod.
1097 int32_t return_value = -1;
1098 uint64_t crc = 0;
1099 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001100 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001101 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001102 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001103 }
1104
1105 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001106 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001107 if (return_value) {
1108 return return_value;
1109 }
1110 }
1111
Narayan Kamath162b7052017-06-05 13:21:12 +01001112 // Validate that the CRC matches the calculated value.
1113 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001114 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001115 return kInconsistentInformation;
1116 }
1117
1118 return return_value;
1119}
1120
Jiyong Parkcd997e62017-06-30 17:23:33 +09001121int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001122 MemoryWriter writer(begin, size);
1123 return ExtractToWriter(handle, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001124}
1125
Jiyong Parkcd997e62017-06-30 17:23:33 +09001126int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001127 auto writer = FileWriter::Create(fd, entry);
1128 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001129 return kIoError;
1130 }
1131
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001132 return ExtractToWriter(handle, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001133}
1134
1135const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001136 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1137 // match.
1138 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1139 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1140
1141 const uint32_t idx = -error_code;
1142 if (idx < arraysize(kErrorMessages)) {
1143 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001144 }
1145
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001146 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001147}
1148
1149int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001150 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001151}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001152
Jiyong Parkcd997e62017-06-30 17:23:33 +09001153ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001154 size_t len = strlen(entry_name);
1155 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1156 name_length = static_cast<uint16_t>(len);
1157}
Tianjie Xu18c25922016-09-29 15:27:41 -07001158
1159#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001160class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001161 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001162 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1163 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001164
1165 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1166 return proc_function_(buf, buf_size, cookie_);
1167 }
1168
1169 private:
1170 ProcessZipEntryFunction proc_function_;
1171 void* cookie_;
1172};
1173
1174int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1175 ProcessZipEntryFunction func, void* cookie) {
1176 ProcessWriter writer(func, cookie);
1177 return ExtractToWriter(handle, entry, &writer);
1178}
1179
Jiyong Parkcd997e62017-06-30 17:23:33 +09001180#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001181
1182int MappedZipFile::GetFileDescriptor() const {
1183 if (!has_fd_) {
1184 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1185 return -1;
1186 }
1187 return fd_;
1188}
1189
1190void* MappedZipFile::GetBasePtr() const {
1191 if (has_fd_) {
1192 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1193 return nullptr;
1194 }
1195 return base_ptr_;
1196}
1197
1198off64_t MappedZipFile::GetFileLength() const {
1199 if (has_fd_) {
1200 off64_t result = lseek64(fd_, 0, SEEK_END);
1201 if (result == -1) {
1202 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1203 }
1204 return result;
1205 } else {
1206 if (base_ptr_ == nullptr) {
1207 ALOGE("Zip: invalid file map\n");
1208 return -1;
1209 }
1210 return static_cast<off64_t>(data_length_);
1211 }
1212}
1213
Tianjie Xu18c25922016-09-29 15:27:41 -07001214// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001215bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001216 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001217 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001218 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1219 return false;
1220 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001221 } else {
1222 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1223 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1224 return false;
1225 }
1226 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001227 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001228 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001229}
1230
1231void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1232 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1233 length_ = cd_size;
1234}
1235
1236bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1237 size_t cd_size) {
1238 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001239 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1240 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001241 return false;
1242 }
1243
1244 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001245 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001246 } else {
1247 if (mapped_zip.GetBasePtr() == nullptr) {
1248 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1249 return false;
1250 }
1251 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1252 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001253 ALOGE(
1254 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1255 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1256 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001257 return false;
1258 }
1259
1260 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1261 }
1262 return true;
1263}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001264
1265tm ZipEntry::GetModificationTime() const {
1266 tm t = {};
1267
1268 t.tm_hour = (mod_time >> 11) & 0x1f;
1269 t.tm_min = (mod_time >> 5) & 0x3f;
1270 t.tm_sec = (mod_time & 0x1f) << 1;
1271
1272 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1273 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1274 t.tm_mday = (mod_time >> 16) & 0x1f;
1275
1276 return t;
1277}