blob: e1ec47aef3d21dbe526e9c3646bd60f79a179f75 [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
Elliott Hughes9c8bd662018-10-26 16:14:21 -070037#if defined(__APPLE__)
38#define lseek64 lseek
39#endif
40
Josh Gao1b496342018-07-17 11:08:48 -070041#if defined(__BIONIC__)
42#include <android/fdsan.h>
43#endif
44
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045#include <android-base/file.h>
46#include <android-base/logging.h>
47#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
Elliott Hughese8f4b142018-10-19 16:09:39 -070048#include <android-base/mapped_file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070049#include <android-base/memory.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070050#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070051#include <log/log.h>
Dan Albert1ae07642015-04-09 14:11:18 -070052#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000053
Narayan Kamath044bc8e2014-12-03 18:22:53 +000054#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070055#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080056#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070057
Dan Albert1ae07642015-04-09 14:11:18 -070058using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000059
Narayan Kamath162b7052017-06-05 13:21:12 +010060// Used to turn on crc checks - verify that the content CRC matches the values
61// specified in the local file header and the central directory.
62static const bool kCrcChecksEnabled = false;
63
Narayan Kamath926973e2014-06-09 14:18:14 +010064// The maximum number of bytes to scan backwards for the EOCD start.
65static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
66
Narayan Kamath7462f022013-11-21 13:05:04 +000067/*
68 * A Read-only Zip archive.
69 *
70 * We want "open" and "find entry by name" to be fast operations, and
71 * we want to use as little memory as possible. We memory-map the zip
72 * central directory, and load a hash table with pointers to the filenames
73 * (which aren't null-terminated). The other fields are at a fixed offset
74 * from the filename, so we don't need to extract those (but we do need
75 * to byte-read and endian-swap them every time we want them).
76 *
77 * It's possible that somebody has handed us a massive (~1GB) zip archive,
78 * so we can't expect to mmap the entire file.
79 *
80 * To speed comparisons when doing a lookup by name, we could make the mapping
81 * "private" (copy-on-write) and null-terminate the filenames after verifying
82 * the record structure. However, this requires a private mapping of
83 * every page that the Central Directory touches. Easier to tuck a copy
84 * of the string length into the hash table entry.
85 */
Narayan Kamath7462f022013-11-21 13:05:04 +000086
Narayan Kamath7462f022013-11-21 13:05:04 +000087/*
88 * Round up to the next highest power of 2.
89 *
90 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
91 */
92static uint32_t RoundUpPower2(uint32_t val) {
93 val--;
94 val |= val >> 1;
95 val |= val >> 2;
96 val |= val >> 4;
97 val |= val >> 8;
98 val |= val >> 16;
99 val++;
100
101 return val;
102}
103
Yusuke Sato07447542015-06-25 14:39:19 -0700104static uint32_t ComputeHash(const ZipString& name) {
Nick Kralevichc0bf3662019-04-05 09:10:34 -0700105 return static_cast<uint32_t>(std::hash<std::string_view>{}(
106 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length)));
Narayan Kamath7462f022013-11-21 13:05:04 +0000107}
108
Zimuzo5a503ef2018-09-17 19:49:55 +0100109static bool isZipStringEqual(const uint8_t* start, const ZipString& zip_string,
110 const ZipStringOffset& zip_string_offset) {
111 const ZipString from_offset = zip_string_offset.GetZipString(start);
112 return from_offset == zip_string;
113}
114
115/**
116 * Returns offset of ZipString#name from the start of the central directory in the memory map.
117 * For valid ZipStrings contained in the zip archive mmap, 0 < offset < 0xffffff.
118 */
119static inline uint32_t GetOffset(const uint8_t* name, const uint8_t* start) {
120 CHECK_GT(name, start);
121 CHECK_LT(name, start + 0xffffff);
122 return static_cast<uint32_t>(name - start);
123}
124
Narayan Kamath7462f022013-11-21 13:05:04 +0000125/*
126 * Convert a ZipEntry to a hash table index, verifying that it's in a
127 * valid range.
128 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100129static int64_t EntryToIndex(const ZipStringOffset* hash_table, const uint32_t hash_table_size,
130 const ZipString& name, const uint8_t* start) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100131 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000132
133 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
134 uint32_t ent = hash & (hash_table_size - 1);
Zimuzo5a503ef2018-09-17 19:49:55 +0100135 while (hash_table[ent].name_offset != 0) {
136 if (isZipStringEqual(start, name, hash_table[ent])) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000137 return ent;
138 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000139 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 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100149static int32_t AddToHash(ZipStringOffset* hash_table, const uint64_t hash_table_size,
150 const ZipString& name, const uint8_t* start) {
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 */
Zimuzo5a503ef2018-09-17 19:49:55 +0100158 while (hash_table[ent].name_offset != 0) {
159 if (isZipStringEqual(start, name, hash_table[ent])) {
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 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100166 hash_table[ent].name_offset = GetOffset(name.name, start);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100167 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000168 return 0;
169}
170
Josh Gaoabdfc242018-09-07 12:44:40 -0700171#if defined(__BIONIC__)
172uint64_t GetOwnerTag(const ZipArchive* archive) {
173 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
174 reinterpret_cast<uint64_t>(archive));
175}
176#endif
177
Josh Gao1b496342018-07-17 11:08:48 -0700178ZipArchive::ZipArchive(const int fd, bool assume_ownership)
179 : mapped_zip(fd),
180 close_file(assume_ownership),
181 directory_offset(0),
182 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700183 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700184 num_entries(0),
185 hash_table_size(0),
186 hash_table(nullptr) {
187#if defined(__BIONIC__)
188 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700189 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700190 }
191#endif
192}
193
194ZipArchive::ZipArchive(void* address, size_t length)
195 : mapped_zip(address, length),
196 close_file(false),
197 directory_offset(0),
198 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700199 directory_map(),
Josh Gao1b496342018-07-17 11:08:48 -0700200 num_entries(0),
201 hash_table_size(0),
202 hash_table(nullptr) {}
203
204ZipArchive::~ZipArchive() {
205 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
206#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700207 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700208#else
209 close(mapped_zip.GetFileDescriptor());
210#endif
211 }
212
213 free(hash_table);
214}
215
Tianjie Xu18c25922016-09-29 15:27:41 -0700216static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Zimuzo5a503ef2018-09-17 19:49:55 +0100217 off64_t file_length, off64_t read_amount,
218 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000219 const off64_t search_start = file_length - read_amount;
220
Jiyong Parkcd997e62017-06-30 17:23:33 +0900221 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
222 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
223 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000224 return kIoError;
225 }
226
227 /*
228 * Scan backward for the EOCD magic. In an archive without a trailing
229 * comment, we'll find it on the first try. (We may want to consider
230 * doing an initial minimal read; if we don't find it, retry with a
231 * second read as above.)
232 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100233 int i = read_amount - sizeof(EocdRecord);
234 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700235 if (scan_buffer[i] == 0x50) {
236 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
237 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
238 ALOGV("+++ Found EOCD at buf+%d", i);
239 break;
240 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000241 }
242 }
243 if (i < 0) {
244 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
245 return kInvalidFile;
246 }
247
248 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100249 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000250 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100251 * Verify that there's no trailing space at the end of the central directory
252 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000253 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900254 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100255 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100256 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100257 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100258 return kInvalidFile;
259 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000260
Narayan Kamath926973e2014-06-09 14:18:14 +0100261 /*
262 * Grab the CD offset and size, and the number of entries in the
263 * archive and verify that they look reasonable.
264 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700265 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100266 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900267 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000268 return kInvalidOffset;
269 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100270 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000271#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000272 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000273#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000274 return kEmptyArchive;
275 }
276
Jiyong Parkcd997e62017-06-30 17:23:33 +0900277 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
278 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000279
280 /*
281 * It all looks good. Create a mapping for the CD, and set the fields
282 * in archive.
283 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700284
Elliott Hughese8f4b142018-10-19 16:09:39 -0700285 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700286 static_cast<size_t>(eocd->cd_size))) {
287 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000288 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000289 }
290
Narayan Kamath926973e2014-06-09 14:18:14 +0100291 archive->num_entries = eocd->num_records;
292 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000293
294 return 0;
295}
296
297/*
298 * Find the zip Central Directory and memory-map it.
299 *
300 * On success, returns 0 after populating fields from the EOCD area:
301 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700302 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000303 * num_entries
304 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700305static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000306 // Test file length. We use lseek64 to make sure the file
307 // is small enough to be a zip file (Its size must be less than
308 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700309 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000310 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000311 return kInvalidFile;
312 }
313
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800314 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100315 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000316 return kInvalidFile;
317 }
318
Narayan Kamath926973e2014-06-09 14:18:14 +0100319 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
320 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000321 return kInvalidFile;
322 }
323
324 /*
325 * Perform the traditional EOCD snipe hunt.
326 *
327 * We're searching for the End of Central Directory magic number,
328 * which appears at the start of the EOCD block. It's followed by
329 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
330 * need to read the last part of the file into a buffer, dig through
331 * it to find the magic number, parse some values out, and use those
332 * to determine the extent of the CD.
333 *
334 * We start by pulling in the last part of the file.
335 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100336 off64_t read_amount = kMaxEOCDSearch;
337 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000338 read_amount = file_length;
339 }
340
Tianjie Xu18c25922016-09-29 15:27:41 -0700341 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900342 int32_t result =
343 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000344 return result;
345}
346
347/*
348 * Parses the Zip archive's Central Directory. Allocates and populates the
349 * hash table.
350 *
351 * Returns 0 on success.
352 */
353static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700354 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
355 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100356 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000357
358 /*
359 * Create hash table. We have a minimum 75% load factor, possibly as
360 * low as 50% after we round off to a power of 2. There must be at
361 * least one unused entry to avoid an infinite loop during creation.
362 */
363 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900364 archive->hash_table =
Zimuzo5a503ef2018-09-17 19:49:55 +0100365 reinterpret_cast<ZipStringOffset*>(calloc(archive->hash_table_size, sizeof(ZipStringOffset)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700366 if (archive->hash_table == nullptr) {
367 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
368 archive->hash_table_size, sizeof(ZipString));
369 return -1;
370 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000371
372 /*
373 * Walk through the central directory, adding entries to the hash
374 * table and verifying values.
375 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100376 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000377 const uint8_t* ptr = cd_ptr;
378 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700379 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
380 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
381#if defined(__ANDROID__)
382 android_errorWriteLog(0x534e4554, "36392138");
383#endif
384 return -1;
385 }
386
Jiyong Parkcd997e62017-06-30 17:23:33 +0900387 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100388 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700389 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800390 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000391 }
392
Narayan Kamath926973e2014-06-09 14:18:14 +0100393 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000394 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800395 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900396 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800397 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000398 }
399
Narayan Kamath926973e2014-06-09 14:18:14 +0100400 const uint16_t file_name_length = cdr->file_name_length;
401 const uint16_t extra_length = cdr->extra_field_length;
402 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100403 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
404
Tianjie Xu9e020e22016-10-10 12:11:30 -0700405 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900406 ALOGW(
407 "Zip: file name boundary exceeds the central directory range, file_name_length: "
408 "%" PRIx16 ", cd_length: %zu",
409 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700410 return -1;
411 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000412 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
413 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800414 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100415 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000416
417 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700418 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100419 entry_name.name = file_name;
420 entry_name.name_length = file_name_length;
Zimuzo5a503ef2018-09-17 19:49:55 +0100421 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name,
422 archive->central_directory.GetBasePtr());
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800423 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000424 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800425 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000426 }
427
Narayan Kamath926973e2014-06-09 14:18:14 +0100428 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
429 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900430 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800431 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000432 }
433 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100434
435 uint32_t lfh_start_bytes;
436 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
437 sizeof(uint32_t), 0)) {
438 ALOGW("Zip: Unable to read header for entry at offset == 0.");
439 return -1;
440 }
441
442 if (lfh_start_bytes != LocalFileHeader::kSignature) {
443 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
444#if defined(__ANDROID__)
445 android_errorWriteLog(0x534e4554, "64211847");
446#endif
447 return -1;
448 }
449
Mark Salyzyn088bf902014-05-08 16:02:20 -0700450 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000451
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800452 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000453}
454
Jiyong Parkcd997e62017-06-30 17:23:33 +0900455static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000456 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700457 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000458 return result;
459 }
460
461 if ((result = ParseZipArchive(archive))) {
462 return result;
463 }
464
465 return 0;
466}
467
Jiyong Parkcd997e62017-06-30 17:23:33 +0900468int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
469 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700470 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000471 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000472 return OpenArchiveInternal(archive, debug_file_name);
473}
474
475int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800476 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700477 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000478 *handle = archive;
479
Narayan Kamath7462f022013-11-21 13:05:04 +0000480 if (fd < 0) {
481 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
482 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000483 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700484
Narayan Kamath7462f022013-11-21 13:05:04 +0000485 return OpenArchiveInternal(archive, fileName);
486}
487
Tianjie Xu18c25922016-09-29 15:27:41 -0700488int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900489 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700490 ZipArchive* archive = new ZipArchive(address, length);
491 *handle = archive;
492 return OpenArchiveInternal(archive, debug_file_name);
493}
494
Narayan Kamath7462f022013-11-21 13:05:04 +0000495/*
496 * Close a ZipArchive, closing the file and freeing the contents.
497 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700498void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000499 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100500 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000501}
502
Narayan Kamath162b7052017-06-05 13:21:12 +0100503static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100504 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700505 off64_t offset = entry->offset;
506 if (entry->method != kCompressStored) {
507 offset += entry->compressed_length;
508 } else {
509 offset += entry->uncompressed_length;
510 }
511
512 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000513 return kIoError;
514 }
515
Narayan Kamath926973e2014-06-09 14:18:14 +0100516 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700517 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
518 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000519
Narayan Kamath162b7052017-06-05 13:21:12 +0100520 // Validate that the values in the data descriptor match those in the central
521 // directory.
522 if (entry->compressed_length != descriptor->compressed_size ||
523 entry->uncompressed_length != descriptor->uncompressed_size ||
524 entry->crc32 != descriptor->crc32) {
525 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
526 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
527 entry->compressed_length, entry->uncompressed_length, entry->crc32,
528 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
529 return kInconsistentInformation;
530 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000531
532 return 0;
533}
534
Jiyong Parkcd997e62017-06-30 17:23:33 +0900535static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000536 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000537
538 // Recover the start of the central directory entry from the filename
539 // pointer. The filename is the first entry past the fixed-size data,
540 // so we can just subtract back from that.
Zimuzo5a503ef2018-09-17 19:49:55 +0100541 const ZipString from_offset =
542 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
543 const uint8_t* ptr = from_offset.name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100544 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000545
546 // This is the base of our mmapped region, we have to sanity check that
547 // the name that's in the hash table is a pointer to a location within
548 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700549 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
550 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000551 ALOGW("Zip: Invalid entry pointer");
552 return kInvalidOffset;
553 }
554
Jiyong Parkcd997e62017-06-30 17:23:33 +0900555 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100556
Narayan Kamath7462f022013-11-21 13:05:04 +0000557 // The offset of the start of the central directory in the zipfile.
558 // We keep this lying around so that we can sanity check all our lengths
559 // and our per-file structures.
560 const off64_t cd_offset = archive->directory_offset;
561
562 // Fill out the compression method, modification time, crc32
563 // and other interesting attributes from the central directory. These
564 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100565 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900566 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100567 data->crc32 = cdr->crc32;
568 data->compressed_length = cdr->compressed_size;
569 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000570
571 // Figure out the local header offset from the central directory. The
572 // actual file data will begin after the local header and the name /
573 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100574 const off64_t local_header_offset = cdr->local_file_header_offset;
575 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000576 ALOGW("Zip: bad local hdr offset in zip");
577 return kInvalidOffset;
578 }
579
Narayan Kamath926973e2014-06-09 14:18:14 +0100580 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700581 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800582 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900583 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000584 return kIoError;
585 }
586
Jiyong Parkcd997e62017-06-30 17:23:33 +0900587 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100588
589 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700590 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900591 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000592 return kInvalidOffset;
593 }
594
595 // Paranoia: Match the values specified in the local file header
596 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700597
Narayan Kamath162b7052017-06-05 13:21:12 +0100598 // Warn if central directory and local file header don't agree on the use
599 // of a trailing Data Descriptor. The reference implementation is inconsistent
600 // and appears to use the LFH value during extraction (unzip) but the CD value
601 // while displayng information about archives (zipinfo). The spec remains
602 // silent on this inconsistency as well.
603 //
604 // For now, always use the version from the LFH but make sure that the values
605 // specified in the central directory match those in the data descriptor.
606 //
607 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
608 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
609 // encoded using UTF-8). This implementation does not check for the presence of
610 // that flag and always enforces that entry names are valid UTF-8.
611 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
612 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700613 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700614 }
615
616 // If there is no trailing data descriptor, verify that the central directory and local file
617 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100618 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000619 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900620 if (data->compressed_length != lfh->compressed_size ||
621 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
622 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
623 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
624 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
625 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000626 return kInconsistentInformation;
627 }
628 } else {
629 data->has_data_descriptor = 1;
630 }
631
Elliott Hughes55fd2932017-05-28 22:59:04 -0700632 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
633 if ((cdr->version_made_by >> 8) == 3) {
634 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
635 } else {
636 data->unix_mode = 0777;
637 }
638
Narayan Kamath7462f022013-11-21 13:05:04 +0000639 // Check that the local file header name matches the declared
640 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100641 if (lfh->file_name_length == nameLen) {
642 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200643 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000644 ALOGW("Zip: Invalid declared length");
645 return kInvalidOffset;
646 }
647
Tianjie Xu18c25922016-09-29 15:27:41 -0700648 std::vector<uint8_t> name_buf(nameLen);
649 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800650 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000651 return kIoError;
652 }
Zimuzo5a503ef2018-09-17 19:49:55 +0100653 const ZipString from_offset =
654 archive->hash_table[ent].GetZipString(archive->central_directory.GetBasePtr());
655 if (memcmp(from_offset.name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000656 return kInconsistentInformation;
657 }
658
Narayan Kamath7462f022013-11-21 13:05:04 +0000659 } else {
660 ALOGW("Zip: lfh name did not match central directory.");
661 return kInconsistentInformation;
662 }
663
Jiyong Parkcd997e62017-06-30 17:23:33 +0900664 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
665 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000666 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800667 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000668 return kInvalidOffset;
669 }
670
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800671 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700672 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900673 static_cast<int64_t>(data_offset), data->compressed_length,
674 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000675 return kInvalidOffset;
676 }
677
678 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900679 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
680 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
681 static_cast<int64_t>(data_offset), data->uncompressed_length,
682 static_cast<int64_t>(cd_offset));
683 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000684 }
685
686 data->offset = data_offset;
687 return 0;
688}
689
690struct IterationHandle {
691 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100692 // We're not using vector here because this code is used in the Windows SDK
693 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700694 ZipString prefix;
695 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000696 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100697
Jiyong Parkcd997e62017-06-30 17:23:33 +0900698 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700699 if (in_prefix) {
700 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
701 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
702 prefix.name = name_copy;
703 prefix.name_length = in_prefix->name_length;
704 } else {
705 prefix.name = NULL;
706 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700707 }
Yusuke Sato07447542015-06-25 14:39:19 -0700708 if (in_suffix) {
709 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
710 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
711 suffix.name = name_copy;
712 suffix.name_length = in_suffix->name_length;
713 } else {
714 suffix.name = NULL;
715 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700716 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100717 }
718
719 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700720 delete[] prefix.name;
721 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100722 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000723};
724
Ryan Prichard3673f992018-10-10 22:41:14 -0700725int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
726 const ZipString* optional_prefix, const ZipString* optional_suffix) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000727 if (archive == NULL || archive->hash_table == NULL) {
728 ALOGW("Zip: Invalid ZipArchiveHandle");
729 return kInvalidHandle;
730 }
731
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700732 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000733 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000734 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000735
Jiyong Parkcd997e62017-06-30 17:23:33 +0900736 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000737 return 0;
738}
739
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100740void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100741 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100742}
743
Ryan Prichard3673f992018-10-10 22:41:14 -0700744int32_t FindEntry(const ZipArchiveHandle archive, const ZipString& entryName, ZipEntry* data) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100745 if (entryName.name_length == 0) {
746 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000747 return kInvalidEntryName;
748 }
749
Zimuzo5a503ef2018-09-17 19:49:55 +0100750 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName,
751 archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000752 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100753 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000754 return ent;
755 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000756 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) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100762 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000763 return kInvalidHandle;
764 }
765
766 ZipArchive* archive = handle->archive;
767 if (archive == NULL || archive->hash_table == NULL) {
768 ALOGW("Zip: Invalid ZipArchiveHandle");
769 return kInvalidHandle;
770 }
771
772 const uint32_t currentOffset = handle->position;
773 const uint32_t hash_table_length = archive->hash_table_size;
Zimuzo5a503ef2018-09-17 19:49:55 +0100774 const ZipStringOffset* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000775 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100776 const ZipString from_offset =
777 hash_table[i].GetZipString(archive->central_directory.GetBasePtr());
778 if (hash_table[i].name_offset != 0 &&
779 (handle->prefix.name_length == 0 || from_offset.StartsWith(handle->prefix)) &&
780 (handle->suffix.name_length == 0 || from_offset.EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000781 handle->position = (i + 1);
782 const int error = FindEntry(archive, i, data);
783 if (!error) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100784 name->name = from_offset.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000785 name->name_length = hash_table[i].name_length;
786 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000787 return error;
788 }
789 }
790
791 handle->position = 0;
792 return kIterationEnd;
793}
794
Narayan Kamathf899bd52015-04-17 11:53:14 +0100795// A Writer that writes data to a fixed size memory region.
796// The size of the memory region must be equal to the total size of
797// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100798class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100799 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900800 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100801
802 virtual bool Append(uint8_t* buf, size_t buf_size) override {
803 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700804 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900805 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100806 return false;
807 }
808
809 memcpy(buf_ + bytes_written_, buf, buf_size);
810 bytes_written_ += buf_size;
811 return true;
812 }
813
814 private:
815 uint8_t* const buf_;
816 const size_t size_;
817 size_t bytes_written_;
818};
819
820// A Writer that appends data to a file |fd| at its current position.
821// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100822class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100823 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100824 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
825 // guaranteeing that the file descriptor is valid and that there's enough
826 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800827 // is truncated to the correct length (no truncation if |fd| references a
828 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100829 //
830 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800831 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100832 const uint32_t declared_length = entry->uncompressed_length;
833 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
834 if (current_offset == -1) {
835 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800836 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100837 }
838
839 int result = 0;
840#if defined(__linux__)
841 if (declared_length > 0) {
842 // Make sure we have enough space on the volume to extract the compressed
843 // entry. Note that the call to ftruncate below will change the file size but
844 // will not allocate space on disk and this call to fallocate will not
845 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700846 // Note: fallocate is only supported by the following filesystems -
847 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
848 // EOPNOTSUPP error when issued in other filesystems.
849 // Hence, check for the return error code before concluding that the
850 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100851 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700852 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700853 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100854 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
855 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800856 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100857 }
858 }
859#endif // __linux__
860
Tao Baoa456c212016-11-15 10:08:07 -0800861 struct stat sb;
862 if (fstat(fd, &sb) == -1) {
863 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800864 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100865 }
866
Tao Baoa456c212016-11-15 10:08:07 -0800867 // Block device doesn't support ftruncate(2).
868 if (!S_ISBLK(sb.st_mode)) {
869 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
870 if (result == -1) {
871 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
872 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800873 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800874 }
875 }
876
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800877 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100878 }
879
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700880 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800881 : fd_(other.fd_),
882 declared_length_(other.declared_length_),
883 total_bytes_written_(other.total_bytes_written_) {
884 other.fd_ = -1;
885 }
886
887 bool IsValid() const { return fd_ != -1; }
888
Narayan Kamathf899bd52015-04-17 11:53:14 +0100889 virtual bool Append(uint8_t* buf, size_t buf_size) override {
890 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700891 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900892 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100893 return false;
894 }
895
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100896 const bool result = android::base::WriteFully(fd_, buf, buf_size);
897 if (result) {
898 total_bytes_written_ += buf_size;
899 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700900 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100901 }
902
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100903 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100904 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900905
Narayan Kamathf899bd52015-04-17 11:53:14 +0100906 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800907 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900908 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100909
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800910 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100911 const size_t declared_length_;
912 size_t total_bytes_written_;
913};
914
Narayan Kamath485b3642017-10-26 14:42:39 +0100915class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100916 public:
917 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
918 : Reader(), zip_file_(zip_file), entry_(entry) {}
919
920 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
921 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
922 }
923
924 virtual ~EntryReader() {}
925
926 private:
927 const MappedZipFile& zip_file_;
928 const ZipEntry* entry_;
929};
930
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800931// This method is using libz macros with old-style-casts
932#pragma GCC diagnostic push
933#pragma GCC diagnostic ignored "-Wold-style-cast"
934static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
935 return inflateInit2(stream, window_bits);
936}
937#pragma GCC diagnostic pop
938
Narayan Kamath485b3642017-10-26 14:42:39 +0100939namespace zip_archive {
940
941// Moved out of line to avoid -Wweak-vtables.
942Reader::~Reader() {}
943Writer::~Writer() {}
944
945int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
946 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700947 const size_t kBufSize = 32768;
948 std::vector<uint8_t> read_buf(kBufSize);
949 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000950 z_stream zstream;
951 int zerr;
952
953 /*
954 * Initialize the zlib stream struct.
955 */
956 memset(&zstream, 0, sizeof(zstream));
957 zstream.zalloc = Z_NULL;
958 zstream.zfree = Z_NULL;
959 zstream.opaque = Z_NULL;
960 zstream.next_in = NULL;
961 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700962 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000963 zstream.avail_out = kBufSize;
964 zstream.data_type = Z_UNKNOWN;
965
966 /*
967 * Use the undocumented "negative window bits" feature to tell zlib
968 * that there's no zlib header waiting for it.
969 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800970 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000971 if (zerr != Z_OK) {
972 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900973 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000974 } else {
975 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
976 }
977
978 return kZlibError;
979 }
980
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800981 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900982 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800983 };
984
985 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
986
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000987 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100988 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100989 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000990 do {
991 /* read as much as we can */
992 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100993 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
994 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700995 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100996 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
997 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800998 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000999 }
1000
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001001 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001002
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001003 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001004 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001005 }
1006
1007 /* uncompress the data */
1008 zerr = inflate(&zstream, Z_NO_FLUSH);
1009 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001010 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1011 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001012 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001013 }
1014
1015 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001016 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001017 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001018 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001019 return kIoError;
1020 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001021 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +00001022 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001023
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001024 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001025 zstream.avail_out = kBufSize;
1026 }
1027 } while (zerr == Z_OK);
1028
Elliott Hughese8f4b142018-10-19 16:09:39 -07001029 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001030
Narayan Kamath162b7052017-06-05 13:21:12 +01001031 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1032 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1033 // doesn't bother calculating the checksum in that scenario. We just do
1034 // it ourselves above because there are no additional gains to be made by
1035 // having zlib calculate it for us, since they do it by calling crc32 in
1036 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001037 if (compute_crc) {
1038 *crc_out = crc;
1039 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001040
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001041 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001042 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1043 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001044 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001045 }
1046
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001047 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001048}
Narayan Kamath485b3642017-10-26 14:42:39 +01001049} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001050
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001051static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001052 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001053 const EntryReader reader(mapped_zip, entry);
1054
Narayan Kamath485b3642017-10-26 14:42:39 +01001055 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1056 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001057}
1058
Narayan Kamath485b3642017-10-26 14:42:39 +01001059static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1060 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001061 static const uint32_t kBufSize = 32768;
1062 std::vector<uint8_t> buf(kBufSize);
1063
1064 const uint32_t length = entry->uncompressed_length;
1065 uint32_t count = 0;
1066 uint64_t crc = 0;
1067 while (count < length) {
1068 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001069 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001070
Adam Lesinskide117e42017-06-19 10:27:38 -07001071 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001072 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001073
1074 // Make sure to read at offset to ensure concurrent access to the fd.
1075 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1076 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1077 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001078 return kIoError;
1079 }
1080
1081 if (!writer->Append(&buf[0], block_size)) {
1082 return kIoError;
1083 }
1084 crc = crc32(crc, &buf[0], block_size);
1085 count += block_size;
1086 }
1087
1088 *crc_out = crc;
1089
1090 return 0;
1091}
1092
Ryan Prichard3673f992018-10-10 22:41:14 -07001093int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
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
Ryan Prichard3673f992018-10-10 22:41:14 -07001121int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001122 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001123 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001124}
1125
Ryan Prichard3673f992018-10-10 22:41:14 -07001126int32_t ExtractEntryToFile(ZipArchiveHandle archive, 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
Ryan Prichard3673f992018-10-10 22:41:14 -07001132 return ExtractToWriter(archive, 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
Ryan Prichard3673f992018-10-10 22:41:14 -07001149int GetFileDescriptor(const ZipArchiveHandle archive) {
1150 return archive->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
Ryan Prichard3673f992018-10-10 22:41:14 -07001174int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001175 ProcessZipEntryFunction func, void* cookie) {
1176 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001177 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001178}
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
Elliott Hughese8f4b142018-10-19 16:09:39 -07001236bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001237 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001238 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1239 cd_start_offset, cd_size, PROT_READ);
1240 if (!directory_map) return false;
Tianjie Xu18c25922016-09-29 15:27:41 -07001241
Elliott Hughese8f4b142018-10-19 16:09:39 -07001242 CHECK_EQ(directory_map->size(), cd_size);
1243 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001244 } else {
1245 if (mapped_zip.GetBasePtr() == nullptr) {
1246 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1247 return false;
1248 }
1249 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1250 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001251 ALOGE(
1252 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1253 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1254 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001255 return false;
1256 }
1257
1258 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1259 }
1260 return true;
1261}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001262
1263tm ZipEntry::GetModificationTime() const {
1264 tm t = {};
1265
1266 t.tm_hour = (mod_time >> 11) & 0x1f;
1267 t.tm_min = (mod_time >> 5) & 0x3f;
1268 t.tm_sec = (mod_time & 0x1f) << 1;
1269
1270 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1271 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1272 t.tm_mday = (mod_time >> 16) & 0x1f;
1273
1274 return t;
1275}