blob: 9d6d919b15f899cab4dbdcd00469f4331d09233e [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
Elliott Hughese8f4b142018-10-19 16:09:39 -070023#include "ziparchive/zip_archive.h"
24
Narayan Kamath7462f022013-11-21 13:05:04 +000025#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070026#include <fcntl.h>
27#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000029#include <stdlib.h>
30#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070031#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000032#include <unistd.h>
33
Dan Albert1ae07642015-04-09 14:11:18 -070034#include <memory>
35#include <vector>
36
Josh Gao1b496342018-07-17 11:08:48 -070037#if defined(__BIONIC__)
38#include <android/fdsan.h>
39#endif
40
Mark Salyzynff2dcd92016-09-28 15:54:45 -070041#include <android-base/file.h>
42#include <android-base/logging.h>
43#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
Elliott Hughese8f4b142018-10-19 16:09:39 -070044#include <android-base/mapped_file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045#include <android-base/memory.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070046#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070047#include <log/log.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// The maximum number of bytes to scan backwards for the EOCD start.
61static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
62
Narayan Kamath7462f022013-11-21 13:05:04 +000063/*
64 * A Read-only Zip archive.
65 *
66 * We want "open" and "find entry by name" to be fast operations, and
67 * we want to use as little memory as possible. We memory-map the zip
68 * central directory, and load a hash table with pointers to the filenames
69 * (which aren't null-terminated). The other fields are at a fixed offset
70 * from the filename, so we don't need to extract those (but we do need
71 * to byte-read and endian-swap them every time we want them).
72 *
73 * It's possible that somebody has handed us a massive (~1GB) zip archive,
74 * so we can't expect to mmap the entire file.
75 *
76 * To speed comparisons when doing a lookup by name, we could make the mapping
77 * "private" (copy-on-write) and null-terminate the filenames after verifying
78 * the record structure. However, this requires a private mapping of
79 * every page that the Central Directory touches. Easier to tuck a copy
80 * of the string length into the hash table entry.
81 */
Narayan Kamath7462f022013-11-21 13:05:04 +000082
Narayan Kamath7462f022013-11-21 13:05:04 +000083/*
84 * Round up to the next highest power of 2.
85 *
86 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
87 */
88static uint32_t RoundUpPower2(uint32_t val) {
89 val--;
90 val |= val >> 1;
91 val |= val >> 2;
92 val |= val >> 4;
93 val |= val >> 8;
94 val |= val >> 16;
95 val++;
96
97 return val;
98}
99
Yusuke Sato07447542015-06-25 14:39:19 -0700100static uint32_t ComputeHash(const ZipString& name) {
Sebastian Pop1f93d712017-11-28 16:36:48 -0600101#if !defined(_WIN32)
102 return std::hash<std::string_view>{}(
103 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length));
104#else
105 // Remove this code path once the windows compiler knows how to compile the above statement.
Narayan Kamath7462f022013-11-21 13:05:04 +0000106 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100107 uint16_t len = name.name_length;
108 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000109
110 while (len--) {
111 hash = hash * 31 + *str++;
112 }
113
114 return hash;
Sebastian Pop1f93d712017-11-28 16:36:48 -0600115#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000116}
117
Zimuzo5a503ef2018-09-17 19:49:55 +0100118static bool isZipStringEqual(const uint8_t* start, const ZipString& zip_string,
119 const ZipStringOffset& zip_string_offset) {
120 const ZipString from_offset = zip_string_offset.GetZipString(start);
121 return from_offset == zip_string;
122}
123
124/**
125 * Returns offset of ZipString#name from the start of the central directory in the memory map.
126 * For valid ZipStrings contained in the zip archive mmap, 0 < offset < 0xffffff.
127 */
128static inline uint32_t GetOffset(const uint8_t* name, const uint8_t* start) {
129 CHECK_GT(name, start);
130 CHECK_LT(name, start + 0xffffff);
131 return static_cast<uint32_t>(name - start);
132}
133
Narayan Kamath7462f022013-11-21 13:05:04 +0000134/*
135 * Convert a ZipEntry to a hash table index, verifying that it's in a
136 * valid range.
137 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100138static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
139 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100140 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000141
142 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
143 uint32_t ent = hash & (hash_table_size - 1);
Zimuzo5a503ef2018-09-17 19:49:55 +0100144 while (hash_table[ent].name_offset != 0) {
145 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000146 return ent;
147 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000148 ent = (ent + 1) & (hash_table_size - 1);
149 }
150
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100151 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000152 return kEntryNotFound;
153}
154
155/*
156 * Add a new entry to the hash table.
157 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100158static int32_t AddToHash(ZipStringOffset* hash_table, const uint64_t hash_table_size,
159 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100160 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000161 uint32_t ent = hash & (hash_table_size - 1);
162
163 /*
164 * We over-allocated the table, so we're guaranteed to find an empty slot.
165 * Further, we guarantee that the hashtable size is not 0.
166 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100167 while (hash_table[ent].name_offset != 0) {
168 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000169 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100170 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000171 return kDuplicateEntry;
172 }
173 ent = (ent + 1) & (hash_table_size - 1);
174 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100175 hash_table[ent].name_offset = GetOffset(name.name, start);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100176 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000177 return 0;
178}
179
Josh Gaoabdfc242018-09-07 12:44:40 -0700180#if defined(__BIONIC__)
181uint64_t GetOwnerTag(const ZipArchive* archive) {
182 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
183 reinterpret_cast<uint64_t>(archive));
184}
185#endif
186
Josh Gao1b496342018-07-17 11:08:48 -0700187ZipArchive::ZipArchive(const int fd, bool assume_ownership)
188 : mapped_zip(fd),
189 close_file(assume_ownership),
190 directory_offset(0),
191 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700192 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700193 num_entries(0),
194 hash_table_size(0),
195 hash_table(nullptr) {
196#if defined(__BIONIC__)
197 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700198 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700199 }
200#endif
201}
202
203ZipArchive::ZipArchive(void* address, size_t length)
204 : mapped_zip(address, length),
205 close_file(false),
206 directory_offset(0),
207 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700208 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700209 num_entries(0),
210 hash_table_size(0),
211 hash_table(nullptr) {}
212
213ZipArchive::~ZipArchive() {
214 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
215#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700216 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700217#else
218 close(mapped_zip.GetFileDescriptor());
219#endif
220 }
221
222 free(hash_table);
223}
224
Tianjie Xu18c25922016-09-29 15:27:41 -0700225static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Zimuzo5a503ef2018-09-17 19:49:55 +0100226 off64_t file_length, off64_t read_amount,
227 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000228 const off64_t search_start = file_length - read_amount;
229
Jiyong Parkcd997e62017-06-30 17:23:33 +0900230 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
231 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
232 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000233 return kIoError;
234 }
235
236 /*
237 * Scan backward for the EOCD magic. In an archive without a trailing
238 * comment, we'll find it on the first try. (We may want to consider
239 * doing an initial minimal read; if we don't find it, retry with a
240 * second read as above.)
241 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100242 int i = read_amount - sizeof(EocdRecord);
243 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700244 if (scan_buffer[i] == 0x50) {
245 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
246 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
247 ALOGV("+++ Found EOCD at buf+%d", i);
248 break;
249 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000250 }
251 }
252 if (i < 0) {
253 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
254 return kInvalidFile;
255 }
256
257 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100258 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000259 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100260 * Verify that there's no trailing space at the end of the central directory
261 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000262 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900263 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100264 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100265 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100266 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100267 return kInvalidFile;
268 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000269
Narayan Kamath926973e2014-06-09 14:18:14 +0100270 /*
271 * Grab the CD offset and size, and the number of entries in the
272 * archive and verify that they look reasonable.
273 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700274 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100275 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900276 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700277#if defined(__ANDROID__)
278 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
279 android_errorWriteLog(0x534e4554, "31251826");
280 }
281#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000282 return kInvalidOffset;
283 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100284 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000285#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000286 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000287#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000288 return kEmptyArchive;
289 }
290
Jiyong Parkcd997e62017-06-30 17:23:33 +0900291 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
292 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000293
294 /*
295 * It all looks good. Create a mapping for the CD, and set the fields
296 * in archive.
297 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700298
Elliott Hughese8f4b142018-10-19 16:09:39 -0700299 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700300 static_cast<size_t>(eocd->cd_size))) {
301 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000302 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000303 }
304
Narayan Kamath926973e2014-06-09 14:18:14 +0100305 archive->num_entries = eocd->num_records;
306 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000307
308 return 0;
309}
310
311/*
312 * Find the zip Central Directory and memory-map it.
313 *
314 * On success, returns 0 after populating fields from the EOCD area:
315 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700316 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000317 * num_entries
318 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700319static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000320 // Test file length. We use lseek64 to make sure the file
321 // is small enough to be a zip file (Its size must be less than
322 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700323 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000324 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000325 return kInvalidFile;
326 }
327
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800328 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100329 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000330 return kInvalidFile;
331 }
332
Narayan Kamath926973e2014-06-09 14:18:14 +0100333 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
334 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000335 return kInvalidFile;
336 }
337
338 /*
339 * Perform the traditional EOCD snipe hunt.
340 *
341 * We're searching for the End of Central Directory magic number,
342 * which appears at the start of the EOCD block. It's followed by
343 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
344 * need to read the last part of the file into a buffer, dig through
345 * it to find the magic number, parse some values out, and use those
346 * to determine the extent of the CD.
347 *
348 * We start by pulling in the last part of the file.
349 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100350 off64_t read_amount = kMaxEOCDSearch;
351 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000352 read_amount = file_length;
353 }
354
Tianjie Xu18c25922016-09-29 15:27:41 -0700355 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900356 int32_t result =
357 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000358 return result;
359}
360
361/*
362 * Parses the Zip archive's Central Directory. Allocates and populates the
363 * hash table.
364 *
365 * Returns 0 on success.
366 */
367static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700368 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
369 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100370 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000371
372 /*
373 * Create hash table. We have a minimum 75% load factor, possibly as
374 * low as 50% after we round off to a power of 2. There must be at
375 * least one unused entry to avoid an infinite loop during creation.
376 */
377 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900378 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100379 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700380 if (archive->hash_table == nullptr) {
381 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
382 archive->hash_table_size, sizeof(ZipString));
383 return -1;
384 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000385
386 /*
387 * Walk through the central directory, adding entries to the hash
388 * table and verifying values.
389 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100390 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000391 const uint8_t* ptr = cd_ptr;
392 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700393 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
394 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
395#if defined(__ANDROID__)
396 android_errorWriteLog(0x534e4554, "36392138");
397#endif
398 return -1;
399 }
400
Jiyong Parkcd997e62017-06-30 17:23:33 +0900401 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100402 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700403 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800404 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000405 }
406
Narayan Kamath926973e2014-06-09 14:18:14 +0100407 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000408 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800409 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900410 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800411 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000412 }
413
Narayan Kamath926973e2014-06-09 14:18:14 +0100414 const uint16_t file_name_length = cdr->file_name_length;
415 const uint16_t extra_length = cdr->extra_field_length;
416 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100417 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
418
Tianjie Xu9e020e22016-10-10 12:11:30 -0700419 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900420 ALOGW(
421 "Zip: file name boundary exceeds the central directory range, file_name_length: "
422 "%" PRIx16 ", cd_length: %zu",
423 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700424 return -1;
425 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000426 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
427 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800428 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100429 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000430
431 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700432 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100433 entry_name.name = file_name;
434 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100435 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
436 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800437 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000438 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800439 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000440 }
441
Narayan Kamath926973e2014-06-09 14:18:14 +0100442 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
443 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900444 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800445 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000446 }
447 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100448
449 uint32_t lfh_start_bytes;
450 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
451 sizeof(uint32_t), 0)) {
452 ALOGW("Zip: Unable to read header for entry at offset == 0.");
453 return -1;
454 }
455
456 if (lfh_start_bytes != LocalFileHeader::kSignature) {
457 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
458#if defined(__ANDROID__)
459 android_errorWriteLog(0x534e4554, "64211847");
460#endif
461 return -1;
462 }
463
Mark Salyzyn088bf902014-05-08 16:02:20 -0700464 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000465
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800466 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000467}
468
Jiyong Parkcd997e62017-06-30 17:23:33 +0900469static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000470 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700471 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000472 return result;
473 }
474
475 if ((result = ParseZipArchive(archive))) {
476 return result;
477 }
478
479 return 0;
480}
481
Jiyong Parkcd997e62017-06-30 17:23:33 +0900482int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
483 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700484 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000485 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000486 return OpenArchiveInternal(archive, debug_file_name);
487}
488
489int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Ryan Mitchellc77f9d32018-08-25 14:06:29 -0700490 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700491 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000492 *handle = archive;
493
Narayan Kamath7462f022013-11-21 13:05:04 +0000494 if (fd < 0) {
495 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
496 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000497 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700498
Narayan Kamath7462f022013-11-21 13:05:04 +0000499 return OpenArchiveInternal(archive, fileName);
500}
501
Tianjie Xu18c25922016-09-29 15:27:41 -0700502int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900503 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700504 ZipArchive* archive = new ZipArchive(address, length);
505 *handle = archive;
506 return OpenArchiveInternal(archive, debug_file_name);
507}
508
Narayan Kamath7462f022013-11-21 13:05:04 +0000509/*
510 * Close a ZipArchive, closing the file and freeing the contents.
511 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700512void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000513 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100514 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000515}
516
Narayan Kamath162b7052017-06-05 13:21:12 +0100517static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100518 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700519 off64_t offset = entry->offset;
520 if (entry->method != kCompressStored) {
521 offset += entry->compressed_length;
522 } else {
523 offset += entry->uncompressed_length;
524 }
525
526 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000527 return kIoError;
528 }
529
Narayan Kamath926973e2014-06-09 14:18:14 +0100530 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700531 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
532 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000533
Narayan Kamath162b7052017-06-05 13:21:12 +0100534 // Validate that the values in the data descriptor match those in the central
535 // directory.
536 if (entry->compressed_length != descriptor->compressed_size ||
537 entry->uncompressed_length != descriptor->uncompressed_size ||
538 entry->crc32 != descriptor->crc32) {
539 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
540 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
541 entry->compressed_length, entry->uncompressed_length, entry->crc32,
542 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
543 return kInconsistentInformation;
544 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000545
546 return 0;
547}
548
Jiyong Parkcd997e62017-06-30 17:23:33 +0900549static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000550 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000551
552 // Recover the start of the central directory entry from the filename
553 // pointer. The filename is the first entry past the fixed-size data,
554 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100555 const ZipString from_offset =
556 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
557 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100558 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000559
560 // This is the base of our mmapped region, we have to sanity check that
561 // the name that's in the hash table is a pointer to a location within
562 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700563 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
564 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000565 ALOGW("Zip: Invalid entry pointer");
566 return kInvalidOffset;
567 }
568
Jiyong Parkcd997e62017-06-30 17:23:33 +0900569 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100570
Narayan Kamath7462f022013-11-21 13:05:04 +0000571 // The offset of the start of the central directory in the zipfile.
572 // We keep this lying around so that we can sanity check all our lengths
573 // and our per-file structures.
574 const off64_t cd_offset = archive->directory_offset;
575
576 // Fill out the compression method, modification time, crc32
577 // and other interesting attributes from the central directory. These
578 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100579 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900580 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100581 data->crc32 = cdr->crc32;
582 data->compressed_length = cdr->compressed_size;
583 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000584
585 // Figure out the local header offset from the central directory. The
586 // actual file data will begin after the local header and the name /
587 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100588 const off64_t local_header_offset = cdr->local_file_header_offset;
589 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000590 ALOGW("Zip: bad local hdr offset in zip");
591 return kInvalidOffset;
592 }
593
Narayan Kamath926973e2014-06-09 14:18:14 +0100594 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700595 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800596 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900597 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000598 return kIoError;
599 }
600
Jiyong Parkcd997e62017-06-30 17:23:33 +0900601 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100602
603 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700604 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900605 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000606 return kInvalidOffset;
607 }
608
609 // Paranoia: Match the values specified in the local file header
610 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700611
Narayan Kamath162b7052017-06-05 13:21:12 +0100612 // Warn if central directory and local file header don't agree on the use
613 // of a trailing Data Descriptor. The reference implementation is inconsistent
614 // and appears to use the LFH value during extraction (unzip) but the CD value
615 // while displayng information about archives (zipinfo). The spec remains
616 // silent on this inconsistency as well.
617 //
618 // For now, always use the version from the LFH but make sure that the values
619 // specified in the central directory match those in the data descriptor.
620 //
621 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
622 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
623 // encoded using UTF-8). This implementation does not check for the presence of
624 // that flag and always enforces that entry names are valid UTF-8.
625 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
626 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700627 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700628 }
629
630 // If there is no trailing data descriptor, verify that the central directory and local file
631 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100632 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000633 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900634 if (data->compressed_length != lfh->compressed_size ||
635 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
636 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
637 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
638 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
639 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000640 return kInconsistentInformation;
641 }
642 } else {
643 data->has_data_descriptor = 1;
644 }
645
Elliott Hughes55fd2932017-05-28 22:59:04 -0700646 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
647 if ((cdr->version_made_by >> 8) == 3) {
648 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
649 } else {
650 data->unix_mode = 0777;
651 }
652
Narayan Kamath7462f022013-11-21 13:05:04 +0000653 // Check that the local file header name matches the declared
654 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100655 if (lfh->file_name_length == nameLen) {
656 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200657 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000658 ALOGW("Zip: Invalid declared length");
659 return kInvalidOffset;
660 }
661
Tianjie Xu18c25922016-09-29 15:27:41 -0700662 std::vector<uint8_t> name_buf(nameLen);
663 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800664 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000665 return kIoError;
666 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100667 const ZipString from_offset =
668 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
669 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000670 return kInconsistentInformation;
671 }
672
Narayan Kamath7462f022013-11-21 13:05:04 +0000673 } else {
674 ALOGW("Zip: lfh name did not match central directory.");
675 return kInconsistentInformation;
676 }
677
Jiyong Parkcd997e62017-06-30 17:23:33 +0900678 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
679 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000680 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800681 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000682 return kInvalidOffset;
683 }
684
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800685 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700686 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900687 static_cast<int64_t>(data_offset), data->compressed_length,
688 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000689 return kInvalidOffset;
690 }
691
692 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900693 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
694 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
695 static_cast<int64_t>(data_offset), data->uncompressed_length,
696 static_cast<int64_t>(cd_offset));
697 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000698 }
699
700 data->offset = data_offset;
701 return 0;
702}
703
704struct IterationHandle {
705 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100706 // We're not using vector here because this code is used in the Windows SDK
707 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700708 ZipString prefix;
709 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000710 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100711
Jiyong Parkcd997e62017-06-30 17:23:33 +0900712 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700713 if (in_prefix) {
714 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
715 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
716 prefix.name = name_copy;
717 prefix.name_length = in_prefix->name_length;
718 } else {
719 prefix.name = NULL;
720 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700721 }
Yusuke Sato07447542015-06-25 14:39:19 -0700722 if (in_suffix) {
723 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
724 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
725 suffix.name = name_copy;
726 suffix.name_length = in_suffix->name_length;
727 } else {
728 suffix.name = NULL;
729 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700730 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100731 }
732
733 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700734 delete[] prefix.name;
735 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100736 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000737};
738
Ryan Prichard3673f992018-10-10 22:41:14 -0700739int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
740 const ZipString* optional_prefix, const ZipString* optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000741 if (archive == NULL || archive->hash_table == NULL) {
742 ALOGW("Zip: Invalid ZipArchiveHandle");
743 return kInvalidHandle;
744 }
745
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700746 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000747 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000748 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000749
Jiyong Parkcd997e62017-06-30 17:23:33 +0900750 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000751 return 0;
752}
753
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100754void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100755 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100756}
757
Ryan Prichard3673f992018-10-10 22:41:14 -0700758int32_t FindEntry(const ZipArchiveHandle archive, const ZipString& entryName, ZipEntry* data) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100759 if (entryName.name_length == 0) {
760 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000761 return kInvalidEntryName;
762 }
763
Zimuzo5a503ef2018-09-17 19:49:55 +0100764 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
765 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000766 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100767 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000768 return ent;
769 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000770 return FindEntry(archive, ent, data);
771}
772
Yusuke Sato07447542015-06-25 14:39:19 -0700773int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800774 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000775 if (handle == NULL) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100776 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000777 return kInvalidHandle;
778 }
779
780 ZipArchive* archive = handle->archive;
781 if (archive == NULL || archive->hash_table == NULL) {
782 ALOGW("Zip: Invalid ZipArchiveHandle");
783 return kInvalidHandle;
784 }
785
786 const uint32_t currentOffset = handle->position;
787 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100788 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000789 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100790 const ZipString from_offset =
791 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
792 if (hash_table[i].name_offset != 0 &&
793 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
794 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000795 handle->position = (i + 1);
796 const int error = FindEntry(archive, i, data);
797 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100798 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000799 name->name_length = hash_table[i].name_length;
800 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000801 return error;
802 }
803 }
804
805 handle->position = 0;
806 return kIterationEnd;
807}
808
Narayan Kamathf899bd52015-04-17 11:53:14 +0100809// A Writer that writes data to a fixed size memory region.
810// The size of the memory region must be equal to the total size of
811// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100812class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100813 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900814 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100815
816 virtual bool Append(uint8_t* buf, size_t buf_size) override {
817 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700818 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900819 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100820 return false;
821 }
822
823 memcpy(buf_ + bytes_written_, buf, buf_size);
824 bytes_written_ += buf_size;
825 return true;
826 }
827
828 private:
829 uint8_t* const buf_;
830 const size_t size_;
831 size_t bytes_written_;
832};
833
834// A Writer that appends data to a file |fd| at its current position.
835// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100836class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100837 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100838 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
839 // guaranteeing that the file descriptor is valid and that there's enough
840 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800841 // is truncated to the correct length (no truncation if |fd| references a
842 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100843 //
844 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800845 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100846 const uint32_t declared_length = entry->uncompressed_length;
847 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
848 if (current_offset == -1) {
849 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800850 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100851 }
852
853 int result = 0;
854#if defined(__linux__)
855 if (declared_length > 0) {
856 // Make sure we have enough space on the volume to extract the compressed
857 // entry. Note that the call to ftruncate below will change the file size but
858 // will not allocate space on disk and this call to fallocate will not
859 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700860 // Note: fallocate is only supported by the following filesystems -
861 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
862 // EOPNOTSUPP error when issued in other filesystems.
863 // Hence, check for the return error code before concluding that the
864 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100865 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700866 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700867 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100868 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
869 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800870 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100871 }
872 }
873#endif // __linux__
874
Tao Baoa456c212016-11-15 10:08:07 -0800875 struct stat sb;
876 if (fstat(fd, &sb) == -1) {
877 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800878 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100879 }
880
Tao Baoa456c212016-11-15 10:08:07 -0800881 // Block device doesn't support ftruncate(2).
882 if (!S_ISBLK(sb.st_mode)) {
883 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
884 if (result == -1) {
885 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
886 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800887 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800888 }
889 }
890
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800891 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100892 }
893
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700894 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800895 : fd_(other.fd_),
896 declared_length_(other.declared_length_),
897 total_bytes_written_(other.total_bytes_written_) {
898 other.fd_ = -1;
899 }
900
901 bool IsValid() const { return fd_ != -1; }
902
Narayan Kamathf899bd52015-04-17 11:53:14 +0100903 virtual bool Append(uint8_t* buf, size_t buf_size) override {
904 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700905 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900906 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100907 return false;
908 }
909
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100910 const bool result = android::base::WriteFully(fd_, buf, buf_size);
911 if (result) {
912 total_bytes_written_ += buf_size;
913 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700914 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100915 }
916
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100917 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100918 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900919
Narayan Kamathf899bd52015-04-17 11:53:14 +0100920 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800921 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900922 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100923
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800924 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100925 const size_t declared_length_;
926 size_t total_bytes_written_;
927};
928
Narayan Kamath485b3642017-10-26 14:42:39 +0100929class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100930 public:
931 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
932 : Reader(), zip_file_(zip_file), entry_(entry) {}
933
934 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
935 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
936 }
937
938 virtual ~EntryReader() {}
939
940 private:
941 const MappedZipFile& zip_file_;
942 const ZipEntry* entry_;
943};
944
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800945// This method is using libz macros with old-style-casts
946#pragma GCC diagnostic push
947#pragma GCC diagnostic ignored "-Wold-style-cast"
948static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
949 return inflateInit2(stream, window_bits);
950}
951#pragma GCC diagnostic pop
952
Narayan Kamath485b3642017-10-26 14:42:39 +0100953namespace zip_archive {
954
955// Moved out of line to avoid -Wweak-vtables.
956Reader::~Reader() {}
957Writer::~Writer() {}
958
959int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
960 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700961 const size_t kBufSize = 32768;
962 std::vector<uint8_t> read_buf(kBufSize);
963 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000964 z_stream zstream;
965 int zerr;
966
967 /*
968 * Initialize the zlib stream struct.
969 */
970 memset(&zstream, 0, sizeof(zstream));
971 zstream.zalloc = Z_NULL;
972 zstream.zfree = Z_NULL;
973 zstream.opaque = Z_NULL;
974 zstream.next_in = NULL;
975 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700976 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000977 zstream.avail_out = kBufSize;
978 zstream.data_type = Z_UNKNOWN;
979
980 /*
981 * Use the undocumented "negative window bits" feature to tell zlib
982 * that there's no zlib header waiting for it.
983 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800984 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000985 if (zerr != Z_OK) {
986 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900987 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000988 } else {
989 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
990 }
991
992 return kZlibError;
993 }
994
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800995 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900996 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800997 };
998
999 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1000
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001001 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +01001002 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001003 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +00001004 do {
1005 /* read as much as we can */
1006 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001007 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
1008 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001009 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001010 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1011 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001012 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001013 }
1014
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001015 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001016
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001017 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001018 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001019 }
1020
1021 /* uncompress the data */
1022 zerr = inflate(&zstream, Z_NO_FLUSH);
1023 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001024 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1025 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001026 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001027 }
1028
1029 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001030 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001031 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001032 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001033 return kIoError;
1034 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001035 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001036 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001037
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001038 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001039 zstream.avail_out = kBufSize;
1040 }
1041 } while (zerr == Z_OK);
1042
Elliott Hughese8f4b142018-10-19 16:09:39 -07001043 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001044
Narayan Kamath162b7052017-06-05 13:21:12 +01001045 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1046 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1047 // doesn't bother calculating the checksum in that scenario. We just do
1048 // it ourselves above because there are no additional gains to be made by
1049 // having zlib calculate it for us, since they do it by calling crc32 in
1050 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001051 if (compute_crc) {
1052 *crc_out = crc;
1053 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001054
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001055 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001056 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1057 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001058 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001059 }
1060
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001061 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001062}
Narayan Kamath485b3642017-10-26 14:42:39 +01001063} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001064
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001065static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001066 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001067 const EntryReader reader(mapped_zip, entry);
1068
Narayan Kamath485b3642017-10-26 14:42:39 +01001069 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1070 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001071}
1072
Narayan Kamath485b3642017-10-26 14:42:39 +01001073static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1074 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001075 static const uint32_t kBufSize = 32768;
1076 std::vector<uint8_t> buf(kBufSize);
1077
1078 const uint32_t length = entry->uncompressed_length;
1079 uint32_t count = 0;
1080 uint64_t crc = 0;
1081 while (count < length) {
1082 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001083 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001084
Adam Lesinskide117e42017-06-19 10:27:38 -07001085 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001086 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001087
1088 // Make sure to read at offset to ensure concurrent access to the fd.
1089 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1090 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1091 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001092 return kIoError;
1093 }
1094
1095 if (!writer->Append(&buf[0], block_size)) {
1096 return kIoError;
1097 }
1098 crc = crc32(crc, &buf[0], block_size);
1099 count += block_size;
1100 }
1101
1102 *crc_out = crc;
1103
1104 return 0;
1105}
1106
Ryan Prichard3673f992018-10-10 22:41:14 -07001107int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001108 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001109
1110 // this should default to kUnknownCompressionMethod.
1111 int32_t return_value = -1;
1112 uint64_t crc = 0;
1113 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001114 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001115 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001116 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001117 }
1118
1119 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001120 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001121 if (return_value) {
1122 return return_value;
1123 }
1124 }
1125
Narayan Kamath162b7052017-06-05 13:21:12 +01001126 // Validate that the CRC matches the calculated value.
1127 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001128 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001129 return kInconsistentInformation;
1130 }
1131
1132 return return_value;
1133}
1134
Ryan Prichard3673f992018-10-10 22:41:14 -07001135int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001136 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001137 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001138}
1139
Ryan Prichard3673f992018-10-10 22:41:14 -07001140int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001141 auto writer = FileWriter::Create(fd, entry);
1142 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001143 return kIoError;
1144 }
1145
Ryan Prichard3673f992018-10-10 22:41:14 -07001146 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001147}
1148
1149const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001150 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1151 // match.
1152 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1153 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1154
1155 const uint32_t idx = -error_code;
1156 if (idx < arraysize(kErrorMessages)) {
1157 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001158 }
1159
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001160 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001161}
1162
Ryan Prichard3673f992018-10-10 22:41:14 -07001163int GetFileDescriptor(const ZipArchiveHandle archive) {
1164 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001165}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001166
Jiyong Parkcd997e62017-06-30 17:23:33 +09001167ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001168 size_t len = strlen(entry_name);
1169 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1170 name_length = static_cast<uint16_t>(len);
1171}
Tianjie Xu18c25922016-09-29 15:27:41 -07001172
1173#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001174class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001175 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001176 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1177 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001178
1179 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1180 return proc_function_(buf, buf_size, cookie_);
1181 }
1182
1183 private:
1184 ProcessZipEntryFunction proc_function_;
1185 void* cookie_;
1186};
1187
Ryan Prichard3673f992018-10-10 22:41:14 -07001188int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001189 ProcessZipEntryFunction func, void* cookie) {
1190 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001191 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001192}
1193
Jiyong Parkcd997e62017-06-30 17:23:33 +09001194#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001195
1196int MappedZipFile::GetFileDescriptor() const {
1197 if (!has_fd_) {
1198 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1199 return -1;
1200 }
1201 return fd_;
1202}
1203
1204void* MappedZipFile::GetBasePtr() const {
1205 if (has_fd_) {
1206 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1207 return nullptr;
1208 }
1209 return base_ptr_;
1210}
1211
1212off64_t MappedZipFile::GetFileLength() const {
1213 if (has_fd_) {
1214 off64_t result = lseek64(fd_, 0, SEEK_END);
1215 if (result == -1) {
1216 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1217 }
1218 return result;
1219 } else {
1220 if (base_ptr_ == nullptr) {
1221 ALOGE("Zip: invalid file map\n");
1222 return -1;
1223 }
1224 return static_cast<off64_t>(data_length_);
1225 }
1226}
1227
Tianjie Xu18c25922016-09-29 15:27:41 -07001228// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001229bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001230 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001231 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001232 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1233 return false;
1234 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001235 } else {
1236 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1237 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1238 return false;
1239 }
1240 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001241 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001242 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001243}
1244
1245void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1246 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1247 length_ = cd_size;
1248}
1249
Elliott Hughese8f4b142018-10-19 16:09:39 -07001250bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001251 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001252 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1253 cd_start_offset, cd_size, PROT_READ);
1254 if (!directory_map) return false;
Tianjie Xu18c25922016-09-29 15:27:41 -07001255
Elliott Hughese8f4b142018-10-19 16:09:39 -07001256 CHECK_EQ(directory_map->size(), cd_size);
1257 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001258 } else {
1259 if (mapped_zip.GetBasePtr() == nullptr) {
1260 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1261 return false;
1262 }
1263 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1264 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001265 ALOGE(
1266 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1267 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1268 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001269 return false;
1270 }
1271
1272 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1273 }
1274 return true;
1275}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001276
1277tm ZipEntry::GetModificationTime() const {
1278 tm t = {};
1279
1280 t.tm_hour = (mod_time >> 11) & 0x1f;
1281 t.tm_min = (mod_time >> 5) & 0x3f;
1282 t.tm_sec = (mod_time & 0x1f) << 1;
1283
1284 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1285 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1286 t.tm_mday = (mod_time >> 16) & 0x1f;
1287
1288 return t;
1289}