blob: 6b6502ba4965dbfce20d607cd247c616ccd8f652 [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>
Songchun Fanc33f5262020-03-24 09:15:51 -070035#include <optional>
Dan Albert1ae07642015-04-09 14:11:18 -070036#include <vector>
37
Elliott Hughes9c8bd662018-10-26 16:14:21 -070038#if defined(__APPLE__)
39#define lseek64 lseek
40#endif
41
Josh Gao1b496342018-07-17 11:08:48 -070042#if defined(__BIONIC__)
43#include <android/fdsan.h>
44#endif
45
Mark Salyzynff2dcd92016-09-28 15:54:45 -070046#include <android-base/file.h>
47#include <android-base/logging.h>
48#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
Elliott Hughese8f4b142018-10-19 16:09:39 -070049#include <android-base/mapped_file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070050#include <android-base/memory.h>
Elliott Hughes50ef29a2019-06-18 18:23:59 -070051#include <android-base/strings.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070052#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070053#include <log/log.h>
Dan Albert1ae07642015-04-09 14:11:18 -070054#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000055
Narayan Kamath044bc8e2014-12-03 18:22:53 +000056#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070057#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080058#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070059
Dan Albert1ae07642015-04-09 14:11:18 -070060using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000061
Narayan Kamath162b7052017-06-05 13:21:12 +010062// Used to turn on crc checks - verify that the content CRC matches the values
63// specified in the local file header and the central directory.
64static const bool kCrcChecksEnabled = false;
65
Narayan Kamath926973e2014-06-09 14:18:14 +010066// The maximum number of bytes to scan backwards for the EOCD start.
67static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
68
Tianjie Xu69ee4b72020-03-11 11:59:10 -070069// Set a reasonable cap (256 GiB) for the zip file size. So the data is always valid when
70// we parse the fields in cd or local headers as 64 bits signed integers.
71static constexpr uint64_t kMaxFileLength = 256 * static_cast<uint64_t>(1u << 30u);
72
Narayan Kamath7462f022013-11-21 13:05:04 +000073/*
74 * A Read-only Zip archive.
75 *
76 * We want "open" and "find entry by name" to be fast operations, and
77 * we want to use as little memory as possible. We memory-map the zip
78 * central directory, and load a hash table with pointers to the filenames
79 * (which aren't null-terminated). The other fields are at a fixed offset
80 * from the filename, so we don't need to extract those (but we do need
81 * to byte-read and endian-swap them every time we want them).
82 *
83 * It's possible that somebody has handed us a massive (~1GB) zip archive,
84 * so we can't expect to mmap the entire file.
85 *
86 * To speed comparisons when doing a lookup by name, we could make the mapping
87 * "private" (copy-on-write) and null-terminate the filenames after verifying
88 * the record structure. However, this requires a private mapping of
89 * every page that the Central Directory touches. Easier to tuck a copy
90 * of the string length into the hash table entry.
91 */
Narayan Kamath7462f022013-11-21 13:05:04 +000092
Josh Gaoabdfc242018-09-07 12:44:40 -070093#if defined(__BIONIC__)
94uint64_t GetOwnerTag(const ZipArchive* archive) {
95 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
96 reinterpret_cast<uint64_t>(archive));
97}
98#endif
99
Ryan Mitchell23150e42020-03-09 09:33:46 -0700100ZipArchive::ZipArchive(MappedZipFile&& map, bool assume_ownership)
101 : mapped_zip(map),
Josh Gao1b496342018-07-17 11:08:48 -0700102 close_file(assume_ownership),
103 directory_offset(0),
104 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700105 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800106 num_entries(0) {
Josh Gao1b496342018-07-17 11:08:48 -0700107#if defined(__BIONIC__)
108 if (assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700109 CHECK(mapped_zip.HasFd());
110 android_fdsan_exchange_owner_tag(mapped_zip.GetFileDescriptor(), 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700111 }
112#endif
113}
114
Elliott Hughesf66460b2019-10-22 11:44:50 -0700115ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700116 : mapped_zip(address, length),
117 close_file(false),
118 directory_offset(0),
119 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700120 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800121 num_entries(0) {}
Josh Gao1b496342018-07-17 11:08:48 -0700122
123ZipArchive::~ZipArchive() {
124 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
125#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700126 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700127#else
128 close(mapped_zip.GetFileDescriptor());
129#endif
130 }
Josh Gao1b496342018-07-17 11:08:48 -0700131}
132
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700133struct CentralDirectoryInfo {
134 uint64_t num_records;
135 // The size of the central directory (in bytes).
136 uint64_t cd_size;
137 // The offset of the start of the central directory, relative
138 // to the start of the file.
139 uint64_t cd_start_offset;
140};
141
142static ZipError FindCentralDirectoryInfoForZip64(CentralDirectoryInfo* /* cdInfo */) {
143 ALOGW("Zip: Parsing zip64 EOCD isn't supported yet.");
144 return kInvalidFile;
145}
146
147static ZipError FindCentralDirectoryInfo(const char* debug_file_name, ZipArchive* archive,
148 off64_t file_length, uint32_t read_amount,
149 CentralDirectoryInfo* cdInfo) {
150 std::vector<uint8_t> scan_buffer(read_amount);
Narayan Kamath7462f022013-11-21 13:05:04 +0000151 const off64_t search_start = file_length - read_amount;
152
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700153 if (!archive->mapped_zip.ReadAtOffset(scan_buffer.data(), read_amount, search_start)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900154 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
155 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000156 return kIoError;
157 }
158
159 /*
160 * Scan backward for the EOCD magic. In an archive without a trailing
161 * comment, we'll find it on the first try. (We may want to consider
162 * doing an initial minimal read; if we don't find it, retry with a
163 * second read as above.)
164 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700165 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
166 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100167 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700168 if (scan_buffer[i] == 0x50) {
169 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
170 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
171 ALOGV("+++ Found EOCD at buf+%d", i);
172 break;
173 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000174 }
175 }
176 if (i < 0) {
177 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
178 return kInvalidFile;
179 }
180
181 const off64_t eocd_offset = search_start + i;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700182 auto eocd = reinterpret_cast<const EocdRecord*>(scan_buffer.data() + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000183 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100184 * Verify that there's no trailing space at the end of the central directory
185 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000186 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900187 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100188 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100189 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100190 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100191 return kInvalidFile;
192 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000193
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700194 // One of the field is 0xFFFFFFFF, look for the zip64 EOCD instead.
195 if (eocd->cd_size == UINT32_MAX || eocd->cd_start_offset == UINT32_MAX) {
196 ALOGV("Looking for the zip64 EOCD, cd_size: %" PRIu32 "cd_start_offset: %" PRId32,
197 eocd->cd_size, eocd->cd_start_offset);
198 return FindCentralDirectoryInfoForZip64(cdInfo);
199 }
200
Narayan Kamath926973e2014-06-09 14:18:14 +0100201 /*
202 * Grab the CD offset and size, and the number of entries in the
203 * archive and verify that they look reasonable.
204 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700205 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100206 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900207 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000208 return kInvalidOffset;
209 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000210
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700211 *cdInfo = {.num_records = eocd->num_records,
212 .cd_size = eocd->cd_size,
213 .cd_start_offset = eocd->cd_start_offset};
214 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000215}
216
217/*
218 * Find the zip Central Directory and memory-map it.
219 *
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700220 * On success, returns kSuccess after populating fields from the EOCD area:
Narayan Kamath7462f022013-11-21 13:05:04 +0000221 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700222 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000223 * num_entries
224 */
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700225static ZipError MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
226 // Test file length. We use lseek64 to make sure the file is small enough to be a zip file.
Tianjie Xu18c25922016-09-29 15:27:41 -0700227 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000228 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000229 return kInvalidFile;
230 }
231
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700232 if (file_length > kMaxFileLength) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100233 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000234 return kInvalidFile;
235 }
236
Narayan Kamath926973e2014-06-09 14:18:14 +0100237 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
238 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000239 return kInvalidFile;
240 }
241
242 /*
243 * Perform the traditional EOCD snipe hunt.
244 *
245 * We're searching for the End of Central Directory magic number,
246 * which appears at the start of the EOCD block. It's followed by
247 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
248 * need to read the last part of the file into a buffer, dig through
249 * it to find the magic number, parse some values out, and use those
250 * to determine the extent of the CD.
251 *
252 * We start by pulling in the last part of the file.
253 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700254 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100255 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700256 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000257 }
258
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700259 CentralDirectoryInfo cdInfo = {};
260 if (auto result =
261 FindCentralDirectoryInfo(debug_file_name, archive, file_length, read_amount, &cdInfo);
262 result != kSuccess) {
263 return result;
264 }
265
266 if (cdInfo.num_records == 0) {
267#if defined(__ANDROID__)
268 ALOGW("Zip: empty archive?");
269#endif
270 return kEmptyArchive;
271 }
272
273 if (cdInfo.cd_size >= SIZE_MAX) {
274 ALOGW("Zip: The size of central directory doesn't fit in range of size_t: %" PRIu64,
275 cdInfo.cd_size);
276 return kInvalidFile;
277 }
278
279 ALOGV("+++ num_entries=%" PRIu64 " dir_size=%" PRIu64 " dir_offset=%" PRIu64, cdInfo.num_records,
280 cdInfo.cd_size, cdInfo.cd_start_offset);
281
282 // It all looks good. Create a mapping for the CD, and set the fields in archive.
283 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(cdInfo.cd_start_offset),
284 static_cast<size_t>(cdInfo.cd_size))) {
285 return kMmapFailed;
286 }
287
288 archive->num_entries = cdInfo.num_records;
289 archive->directory_offset = cdInfo.cd_start_offset;
290
291 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000292}
293
294/*
295 * Parses the Zip archive's Central Directory. Allocates and populates the
296 * hash table.
297 *
298 * Returns 0 on success.
299 */
300static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700301 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
302 const size_t cd_length = archive->central_directory.GetMapLength();
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700303 const uint64_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000304
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700305 if (num_entries <= UINT16_MAX) {
306 archive->cd_entry_map = CdEntryMapZip32::Create(static_cast<uint16_t>(num_entries));
Tianjie Xu0ef97832020-03-15 21:23:24 -0700307 } else {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700308 archive->cd_entry_map = CdEntryMapZip64::Create();
Tianjie Xu0ef97832020-03-15 21:23:24 -0700309 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800310 if (archive->cd_entry_map == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800311 return kAllocationFailed;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700312 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000313
314 /*
315 * Walk through the central directory, adding entries to the hash
316 * table and verifying values.
317 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100318 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000319 const uint8_t* ptr = cd_ptr;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700320 for (uint64_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700321 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700322 ALOGW("Zip: ran off the end (item #%" PRIu64 ", %zu bytes of central directory)", i,
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800323 cd_length);
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700324#if defined(__ANDROID__)
325 android_errorWriteLog(0x534e4554, "36392138");
326#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800327 return kInvalidFile;
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700328 }
329
Jiyong Parkcd997e62017-06-30 17:23:33 +0900330 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100331 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700332 ALOGW("Zip: missed a central dir sig (at %" PRIu64 ")", i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800333 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000334 }
335
Narayan Kamath926973e2014-06-09 14:18:14 +0100336 const uint16_t file_name_length = cdr->file_name_length;
337 const uint16_t extra_length = cdr->extra_field_length;
338 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100339 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
340
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700341 if (file_name_length >= cd_length || file_name > cd_end - file_name_length) {
342 ALOGW("Zip: file name for entry %" PRIu64
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700343 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
344 i, file_name_length, cd_length);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800345 return kInvalidEntryName;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700346 }
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700347
348 const uint8_t* extra_field = file_name + file_name_length;
349 if (extra_length >= cd_length || extra_field > cd_end - extra_length) {
350 ALOGW("Zip: extra field for entry %" PRIu64
351 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
352 i, extra_length, cd_length);
353 return kInvalidFile;
354 }
355
356 off64_t local_header_offset = cdr->local_file_header_offset;
357 if (local_header_offset == UINT32_MAX) {
358 // TODO(xunchang) parse the zip64 eocd
359 ALOGW("Zip: Parsing zip64 cd entry isn't supported yet");
360 return kInvalidFile;
361 }
362
363 if (local_header_offset >= archive->directory_offset) {
364 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu64,
365 static_cast<int64_t>(local_header_offset), i);
366 return kInvalidFile;
367 }
368
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700369 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000370 if (!IsValidEntryName(file_name, file_name_length)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700371 ALOGW("Zip: invalid file name at entry %" PRIu64, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800372 return kInvalidEntryName;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100373 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000374
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700375 // Add the CDE filename to the hash table.
376 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800377 if (auto add_result =
378 archive->cd_entry_map->AddToMap(entry_name, archive->central_directory.GetBasePtr());
379 add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000380 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800381 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000382 }
383
Narayan Kamath926973e2014-06-09 14:18:14 +0100384 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
385 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700386 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu64, ptr - cd_ptr, cd_length, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800387 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000388 }
389 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100390
391 uint32_t lfh_start_bytes;
392 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
393 sizeof(uint32_t), 0)) {
394 ALOGW("Zip: Unable to read header for entry at offset == 0.");
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800395 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100396 }
397
398 if (lfh_start_bytes != LocalFileHeader::kSignature) {
399 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
400#if defined(__ANDROID__)
401 android_errorWriteLog(0x534e4554, "64211847");
402#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800403 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100404 }
405
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700406 ALOGV("+++ zip good scan %" PRIu64 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000407
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800408 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000409}
410
Jiyong Parkcd997e62017-06-30 17:23:33 +0900411static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800412 int32_t result = MapCentralDirectory(debug_file_name, archive);
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700413 return result != kSuccess ? result : ParseZipArchive(archive);
Narayan Kamath7462f022013-11-21 13:05:04 +0000414}
415
Jiyong Parkcd997e62017-06-30 17:23:33 +0900416int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
417 bool assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700418 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000419 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000420 return OpenArchiveInternal(archive, debug_file_name);
421}
422
Ryan Mitchell23150e42020-03-09 09:33:46 -0700423int32_t OpenArchiveFdRange(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
424 off64_t length, off64_t offset, bool assume_ownership) {
425 ZipArchive* archive = new ZipArchive(MappedZipFile(fd, length, offset), assume_ownership);
426 *handle = archive;
427
428 if (length < 0) {
429 ALOGW("Invalid zip length %" PRId64, length);
430 return kIoError;
431 }
432
433 if (offset < 0) {
434 ALOGW("Invalid zip offset %" PRId64, offset);
435 return kIoError;
436 }
437
438 return OpenArchiveInternal(archive, debug_file_name);
439}
440
Narayan Kamath7462f022013-11-21 13:05:04 +0000441int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800442 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Ryan Mitchell23150e42020-03-09 09:33:46 -0700443 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000444 *handle = archive;
445
Narayan Kamath7462f022013-11-21 13:05:04 +0000446 if (fd < 0) {
447 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
448 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000449 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700450
Narayan Kamath7462f022013-11-21 13:05:04 +0000451 return OpenArchiveInternal(archive, fileName);
452}
453
Elliott Hughesf66460b2019-10-22 11:44:50 -0700454int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900455 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700456 ZipArchive* archive = new ZipArchive(address, length);
457 *handle = archive;
458 return OpenArchiveInternal(archive, debug_file_name);
459}
460
Elliott Hughes26724132019-10-25 09:57:58 -0700461ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
462 ZipArchiveInfo result;
463 result.archive_size = archive->mapped_zip.GetFileLength();
464 result.entry_count = archive->num_entries;
465 return result;
466}
467
Narayan Kamath7462f022013-11-21 13:05:04 +0000468/*
469 * Close a ZipArchive, closing the file and freeing the contents.
470 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700471void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000472 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100473 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000474}
475
Narayan Kamath162b7052017-06-05 13:21:12 +0100476static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100477 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700478 off64_t offset = entry->offset;
479 if (entry->method != kCompressStored) {
480 offset += entry->compressed_length;
481 } else {
482 offset += entry->uncompressed_length;
483 }
484
485 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000486 return kIoError;
487 }
488
Narayan Kamath926973e2014-06-09 14:18:14 +0100489 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700490 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
491 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000492
Narayan Kamath162b7052017-06-05 13:21:12 +0100493 // Validate that the values in the data descriptor match those in the central
494 // directory.
495 if (entry->compressed_length != descriptor->compressed_size ||
496 entry->uncompressed_length != descriptor->uncompressed_size ||
497 entry->crc32 != descriptor->crc32) {
498 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
499 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
500 entry->compressed_length, entry->uncompressed_length, entry->crc32,
501 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
502 return kInconsistentInformation;
503 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000504
505 return 0;
506}
507
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800508static int32_t FindEntry(const ZipArchive* archive, std::string_view entryName,
509 const uint64_t nameOffset, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000510 // Recover the start of the central directory entry from the filename
511 // pointer. The filename is the first entry past the fixed-size data,
512 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700513 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800514 const uint8_t* ptr = base_ptr + nameOffset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100515 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000516
517 // This is the base of our mmapped region, we have to sanity check that
518 // the name that's in the hash table is a pointer to a location within
519 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700520 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000521 ALOGW("Zip: Invalid entry pointer");
522 return kInvalidOffset;
523 }
524
Jiyong Parkcd997e62017-06-30 17:23:33 +0900525 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100526
Narayan Kamath7462f022013-11-21 13:05:04 +0000527 // The offset of the start of the central directory in the zipfile.
528 // We keep this lying around so that we can sanity check all our lengths
529 // and our per-file structures.
530 const off64_t cd_offset = archive->directory_offset;
531
532 // Fill out the compression method, modification time, crc32
533 // and other interesting attributes from the central directory. These
534 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100535 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900536 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100537 data->crc32 = cdr->crc32;
538 data->compressed_length = cdr->compressed_size;
539 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000540
541 // Figure out the local header offset from the central directory. The
542 // actual file data will begin after the local header and the name /
543 // extra comments.
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700544 off64_t local_header_offset = cdr->local_file_header_offset;
545 // One of the info field is UINT32_MAX, try to parse the real value in the zip64 extended info in
546 // the extra field.
547 if (cdr->uncompressed_size == UINT32_MAX || cdr->compressed_size == UINT32_MAX ||
548 cdr->local_file_header_offset == UINT32_MAX) {
549 ALOGW("Zip: Parsing zip64 local file header isn't supported yet");
550 return kInvalidFile;
551 }
552
Narayan Kamath926973e2014-06-09 14:18:14 +0100553 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000554 ALOGW("Zip: bad local hdr offset in zip");
555 return kInvalidOffset;
556 }
557
Narayan Kamath926973e2014-06-09 14:18:14 +0100558 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700559 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800560 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900561 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000562 return kIoError;
563 }
564
Jiyong Parkcd997e62017-06-30 17:23:33 +0900565 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100566
567 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700568 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900569 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000570 return kInvalidOffset;
571 }
572
573 // Paranoia: Match the values specified in the local file header
574 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700575
Narayan Kamath162b7052017-06-05 13:21:12 +0100576 // Warn if central directory and local file header don't agree on the use
577 // of a trailing Data Descriptor. The reference implementation is inconsistent
578 // and appears to use the LFH value during extraction (unzip) but the CD value
579 // while displayng information about archives (zipinfo). The spec remains
580 // silent on this inconsistency as well.
581 //
582 // For now, always use the version from the LFH but make sure that the values
583 // specified in the central directory match those in the data descriptor.
584 //
585 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
586 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
587 // encoded using UTF-8). This implementation does not check for the presence of
588 // that flag and always enforces that entry names are valid UTF-8.
589 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
590 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700591 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700592 }
593
594 // If there is no trailing data descriptor, verify that the central directory and local file
595 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100596 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000597 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900598 if (data->compressed_length != lfh->compressed_size ||
599 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
600 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
601 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
602 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
603 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000604 return kInconsistentInformation;
605 }
606 } else {
607 data->has_data_descriptor = 1;
608 }
609
Elliott Hughes55fd2932017-05-28 22:59:04 -0700610 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
Elliott Hughes26724132019-10-25 09:57:58 -0700611 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700612 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700613 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700614 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
615 } else {
616 data->unix_mode = 0777;
617 }
618
Elliott Hughesd5095252019-10-28 21:35:52 -0700619 // 4.4.4: general purpose bit flags.
620 data->gpbf = lfh->gpb_flags;
621
Elliott Hughes26724132019-10-25 09:57:58 -0700622 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
623 // Currently only needed to implement zipinfo.
624 data->is_text = (cdr->internal_file_attributes & 1);
625
Narayan Kamath7462f022013-11-21 13:05:04 +0000626 // Check that the local file header name matches the declared
627 // name in the central directory.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800628 CHECK_LE(entryName.size(), UINT16_MAX);
629 auto nameLen = static_cast<uint16_t>(entryName.size());
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700630 if (lfh->file_name_length != nameLen) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800631 ALOGW("Zip: lfh name length did not match central directory for %s: %" PRIu16 " %" PRIu16,
632 std::string(entryName).c_str(), lfh->file_name_length, nameLen);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700633 return kInconsistentInformation;
634 }
635 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
636 if (name_offset + lfh->file_name_length > cd_offset) {
637 ALOGW("Zip: lfh name has invalid declared length");
638 return kInvalidOffset;
639 }
640 std::vector<uint8_t> name_buf(nameLen);
641 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
642 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
643 return kIoError;
644 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800645 if (memcmp(entryName.data(), name_buf.data(), nameLen) != 0) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700646 ALOGW("Zip: lfh name did not match central directory");
Narayan Kamath7462f022013-11-21 13:05:04 +0000647 return kInconsistentInformation;
648 }
649
Jiyong Parkcd997e62017-06-30 17:23:33 +0900650 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
651 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000652 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800653 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000654 return kInvalidOffset;
655 }
656
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800657 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700658 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900659 static_cast<int64_t>(data_offset), data->compressed_length,
660 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000661 return kInvalidOffset;
662 }
663
664 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900665 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
666 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
667 static_cast<int64_t>(data_offset), data->uncompressed_length,
668 static_cast<int64_t>(cd_offset));
669 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000670 }
671
672 data->offset = data_offset;
673 return 0;
674}
675
676struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000677 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100678
Songchun Fanc33f5262020-03-24 09:15:51 -0700679 std::function<bool(std::string_view)> matcher;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700680
681 uint32_t position = 0;
682
Songchun Fanc33f5262020-03-24 09:15:51 -0700683 IterationHandle(ZipArchive* archive, std::function<bool(std::string_view)> in_matcher)
684 : archive(archive), matcher(std::move(in_matcher)) {}
685
686 bool Match(std::string_view entry_name) const { return matcher(entry_name); }
Narayan Kamath7462f022013-11-21 13:05:04 +0000687};
688
Ryan Prichard3673f992018-10-10 22:41:14 -0700689int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700690 const std::string_view optional_prefix,
691 const std::string_view optional_suffix) {
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700692 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
693 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
694 ALOGW("Zip: prefix/suffix too long");
695 return kInvalidEntryName;
696 }
Songchun Fanc33f5262020-03-24 09:15:51 -0700697 auto matcher = [prefix = std::string(optional_prefix),
698 suffix = std::string(optional_suffix)](std::string_view name) mutable {
699 return android::base::StartsWith(name, prefix) && android::base::EndsWith(name, suffix);
700 };
701 return StartIteration(archive, cookie_ptr, std::move(matcher));
702}
703
704int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
705 std::function<bool(std::string_view)> matcher) {
706 if (archive == nullptr || archive->cd_entry_map == nullptr) {
707 ALOGW("Zip: Invalid ZipArchiveHandle");
708 return kInvalidHandle;
709 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000710
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800711 archive->cd_entry_map->ResetIteration();
Songchun Fanc33f5262020-03-24 09:15:51 -0700712 *cookie_ptr = new IterationHandle(archive, matcher);
Narayan Kamath7462f022013-11-21 13:05:04 +0000713 return 0;
714}
715
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100716void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100717 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100718}
719
Elliott Hughesb17bf522019-05-03 22:38:44 -0700720int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
721 ZipEntry* data) {
722 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
723 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
724 return kInvalidEntryName;
725 }
726
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800727 const auto [result, offset] =
728 archive->cd_entry_map->GetCdEntryOffset(entryName, archive->central_directory.GetBasePtr());
729 if (result != 0) {
Elliott Hughesb17bf522019-05-03 22:38:44 -0700730 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800731 return static_cast<int32_t>(result); // kEntryNotFound is safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700732 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700733 // We know there are at most hash_table_size entries, safe to truncate.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800734 return FindEntry(archive, entryName, offset, data);
Elliott Hughesb17bf522019-05-03 22:38:44 -0700735}
736
Elliott Hughese06a8082019-05-22 18:56:41 -0700737int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700738 std::string_view sv;
739 int32_t result = Next(cookie, data, &sv);
740 if (result == 0 && name) {
741 *name = std::string(sv);
742 }
743 return result;
744}
745
746int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800747 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800748 if (handle == nullptr) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100749 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000750 return kInvalidHandle;
751 }
752
753 ZipArchive* archive = handle->archive;
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800754 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000755 ALOGW("Zip: Invalid ZipArchiveHandle");
756 return kInvalidHandle;
757 }
758
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800759 auto entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
760 while (entry != std::pair<std::string_view, uint64_t>()) {
761 const auto [entry_name, offset] = entry;
Songchun Fanc33f5262020-03-24 09:15:51 -0700762 if (handle->Match(entry_name)) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800763 const int error = FindEntry(archive, entry_name, offset, data);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700764 if (!error && name) {
765 *name = entry_name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000766 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000767 return error;
768 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800769 entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000770 }
771
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800772 archive->cd_entry_map->ResetIteration();
Narayan Kamath7462f022013-11-21 13:05:04 +0000773 return kIterationEnd;
774}
775
Narayan Kamathf899bd52015-04-17 11:53:14 +0100776// A Writer that writes data to a fixed size memory region.
777// The size of the memory region must be equal to the total size of
778// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100779class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100780 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900781 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100782
783 virtual bool Append(uint8_t* buf, size_t buf_size) override {
784 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700785 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900786 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100787 return false;
788 }
789
790 memcpy(buf_ + bytes_written_, buf, buf_size);
791 bytes_written_ += buf_size;
792 return true;
793 }
794
795 private:
796 uint8_t* const buf_;
797 const size_t size_;
798 size_t bytes_written_;
799};
800
801// A Writer that appends data to a file |fd| at its current position.
802// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100803class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100804 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100805 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
806 // guaranteeing that the file descriptor is valid and that there's enough
807 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800808 // is truncated to the correct length (no truncation if |fd| references a
809 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100810 //
811 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800812 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100813 const uint32_t declared_length = entry->uncompressed_length;
814 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
815 if (current_offset == -1) {
816 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800817 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100818 }
819
Narayan Kamathf899bd52015-04-17 11:53:14 +0100820#if defined(__linux__)
821 if (declared_length > 0) {
822 // Make sure we have enough space on the volume to extract the compressed
823 // entry. Note that the call to ftruncate below will change the file size but
824 // will not allocate space on disk and this call to fallocate will not
825 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700826 // Note: fallocate is only supported by the following filesystems -
827 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
828 // EOPNOTSUPP error when issued in other filesystems.
829 // Hence, check for the return error code before concluding that the
830 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700831 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700832 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700833 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100834 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
835 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800836 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100837 }
838 }
839#endif // __linux__
840
Tao Baoa456c212016-11-15 10:08:07 -0800841 struct stat sb;
842 if (fstat(fd, &sb) == -1) {
843 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800844 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100845 }
846
Tao Baoa456c212016-11-15 10:08:07 -0800847 // Block device doesn't support ftruncate(2).
848 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700849 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -0800850 if (result == -1) {
851 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
852 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800853 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800854 }
855 }
856
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800857 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100858 }
859
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700860 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800861 : fd_(other.fd_),
862 declared_length_(other.declared_length_),
863 total_bytes_written_(other.total_bytes_written_) {
864 other.fd_ = -1;
865 }
866
867 bool IsValid() const { return fd_ != -1; }
868
Narayan Kamathf899bd52015-04-17 11:53:14 +0100869 virtual bool Append(uint8_t* buf, size_t buf_size) override {
870 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700871 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900872 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100873 return false;
874 }
875
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100876 const bool result = android::base::WriteFully(fd_, buf, buf_size);
877 if (result) {
878 total_bytes_written_ += buf_size;
879 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700880 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100881 }
882
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100883 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100884 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900885
Narayan Kamathf899bd52015-04-17 11:53:14 +0100886 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800887 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900888 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100889
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800890 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100891 const size_t declared_length_;
892 size_t total_bytes_written_;
893};
894
Narayan Kamath485b3642017-10-26 14:42:39 +0100895class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100896 public:
897 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
898 : Reader(), zip_file_(zip_file), entry_(entry) {}
899
900 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
901 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
902 }
903
904 virtual ~EntryReader() {}
905
906 private:
907 const MappedZipFile& zip_file_;
908 const ZipEntry* entry_;
909};
910
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800911// This method is using libz macros with old-style-casts
912#pragma GCC diagnostic push
913#pragma GCC diagnostic ignored "-Wold-style-cast"
914static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
915 return inflateInit2(stream, window_bits);
916}
917#pragma GCC diagnostic pop
918
Narayan Kamath485b3642017-10-26 14:42:39 +0100919namespace zip_archive {
920
921// Moved out of line to avoid -Wweak-vtables.
922Reader::~Reader() {}
923Writer::~Writer() {}
924
925int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
926 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700927 const size_t kBufSize = 32768;
928 std::vector<uint8_t> read_buf(kBufSize);
929 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000930 z_stream zstream;
931 int zerr;
932
933 /*
934 * Initialize the zlib stream struct.
935 */
936 memset(&zstream, 0, sizeof(zstream));
937 zstream.zalloc = Z_NULL;
938 zstream.zfree = Z_NULL;
939 zstream.opaque = Z_NULL;
940 zstream.next_in = NULL;
941 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700942 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000943 zstream.avail_out = kBufSize;
944 zstream.data_type = Z_UNKNOWN;
945
946 /*
947 * Use the undocumented "negative window bits" feature to tell zlib
948 * that there's no zlib header waiting for it.
949 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800950 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000951 if (zerr != Z_OK) {
952 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900953 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000954 } else {
955 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
956 }
957
958 return kZlibError;
959 }
960
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800961 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900962 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800963 };
964
965 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
966
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000967 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700968 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100969 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000970 do {
971 /* read as much as we can */
972 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700973 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100974 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700975 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100976 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700977 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800978 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000979 }
980
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100981 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000982
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700983 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100984 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000985 }
986
987 /* uncompress the data */
988 zerr = inflate(&zstream, Z_NO_FLUSH);
989 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900990 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
991 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800992 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000993 }
994
995 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900996 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700997 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100998 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000999 return kIoError;
1000 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001001 DCHECK_LE(write_size, kBufSize);
1002 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +00001003 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001004
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001005 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001006 zstream.avail_out = kBufSize;
1007 }
1008 } while (zerr == Z_OK);
1009
Elliott Hughese8f4b142018-10-19 16:09:39 -07001010 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001011
Narayan Kamath162b7052017-06-05 13:21:12 +01001012 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1013 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1014 // doesn't bother calculating the checksum in that scenario. We just do
1015 // it ourselves above because there are no additional gains to be made by
1016 // having zlib calculate it for us, since they do it by calling crc32 in
1017 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001018 if (compute_crc) {
1019 *crc_out = crc;
1020 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001021
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001022 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001023 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1024 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001025 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001026 }
1027
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001028 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001029}
Narayan Kamath485b3642017-10-26 14:42:39 +01001030} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001031
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001032static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001033 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001034 const EntryReader reader(mapped_zip, entry);
1035
Narayan Kamath485b3642017-10-26 14:42:39 +01001036 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1037 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001038}
1039
Narayan Kamath485b3642017-10-26 14:42:39 +01001040static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1041 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001042 static const uint32_t kBufSize = 32768;
1043 std::vector<uint8_t> buf(kBufSize);
1044
1045 const uint32_t length = entry->uncompressed_length;
1046 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -07001047 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001048 while (count < length) {
1049 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001050 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001051
Adam Lesinskide117e42017-06-19 10:27:38 -07001052 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001053 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001054
1055 // Make sure to read at offset to ensure concurrent access to the fd.
1056 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001057 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -07001058 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001059 return kIoError;
1060 }
1061
1062 if (!writer->Append(&buf[0], block_size)) {
1063 return kIoError;
1064 }
1065 crc = crc32(crc, &buf[0], block_size);
1066 count += block_size;
1067 }
1068
1069 *crc_out = crc;
1070
1071 return 0;
1072}
1073
Ryan Prichard3673f992018-10-10 22:41:14 -07001074int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001075 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001076
1077 // this should default to kUnknownCompressionMethod.
1078 int32_t return_value = -1;
1079 uint64_t crc = 0;
1080 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001081 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001082 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001083 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001084 }
1085
1086 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001087 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001088 if (return_value) {
1089 return return_value;
1090 }
1091 }
1092
Narayan Kamath162b7052017-06-05 13:21:12 +01001093 // Validate that the CRC matches the calculated value.
1094 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001095 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001096 return kInconsistentInformation;
1097 }
1098
1099 return return_value;
1100}
1101
Ryan Prichard3673f992018-10-10 22:41:14 -07001102int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001103 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001104 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001105}
1106
Ryan Prichard3673f992018-10-10 22:41:14 -07001107int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001108 auto writer = FileWriter::Create(fd, entry);
1109 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001110 return kIoError;
1111 }
1112
Ryan Prichard3673f992018-10-10 22:41:14 -07001113 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001114}
1115
Ryan Prichard3673f992018-10-10 22:41:14 -07001116int GetFileDescriptor(const ZipArchiveHandle archive) {
1117 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001118}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001119
Ryan Mitchell23150e42020-03-09 09:33:46 -07001120off64_t GetFileDescriptorOffset(const ZipArchiveHandle archive) {
1121 return archive->mapped_zip.GetFileOffset();
1122}
1123
Tianjie Xu18c25922016-09-29 15:27:41 -07001124#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001125class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001126 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001127 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1128 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001129
1130 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1131 return proc_function_(buf, buf_size, cookie_);
1132 }
1133
1134 private:
1135 ProcessZipEntryFunction proc_function_;
1136 void* cookie_;
1137};
1138
Ryan Prichard3673f992018-10-10 22:41:14 -07001139int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001140 ProcessZipEntryFunction func, void* cookie) {
1141 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001142 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001143}
1144
Jiyong Parkcd997e62017-06-30 17:23:33 +09001145#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001146
1147int MappedZipFile::GetFileDescriptor() const {
1148 if (!has_fd_) {
1149 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1150 return -1;
1151 }
1152 return fd_;
1153}
1154
Elliott Hughesf66460b2019-10-22 11:44:50 -07001155const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001156 if (has_fd_) {
1157 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1158 return nullptr;
1159 }
1160 return base_ptr_;
1161}
1162
Ryan Mitchell23150e42020-03-09 09:33:46 -07001163off64_t MappedZipFile::GetFileOffset() const {
1164 return fd_offset_;
1165}
1166
Tianjie Xu18c25922016-09-29 15:27:41 -07001167off64_t MappedZipFile::GetFileLength() const {
1168 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001169 if (data_length_ != -1) {
1170 return data_length_;
1171 }
1172 data_length_ = lseek64(fd_, 0, SEEK_END);
1173 if (data_length_ == -1) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001174 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1175 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001176 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001177 } else {
1178 if (base_ptr_ == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001179 ALOGE("Zip: invalid file map");
Tianjie Xu18c25922016-09-29 15:27:41 -07001180 return -1;
1181 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001182 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001183 }
1184}
1185
Tianjie Xu18c25922016-09-29 15:27:41 -07001186// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001187bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001188 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001189 if (off < 0) {
1190 ALOGE("Zip: invalid offset %" PRId64, off);
1191 return false;
1192 }
1193
1194 off64_t read_offset;
1195 if (__builtin_add_overflow(fd_offset_, off, &read_offset)) {
1196 ALOGE("Zip: invalid read offset %" PRId64 " overflows, fd offset %" PRId64, off, fd_offset_);
1197 return false;
1198 }
1199
1200 if (data_length_ != -1) {
1201 off64_t read_end;
1202 if (len > std::numeric_limits<off64_t>::max() ||
1203 __builtin_add_overflow(off, static_cast<off64_t>(len), &read_end)) {
1204 ALOGE("Zip: invalid read length %" PRId64 " overflows, offset %" PRId64,
1205 static_cast<off64_t>(len), off);
1206 return false;
1207 }
1208
1209 if (read_end > data_length_) {
1210 ALOGE("Zip: invalid read length %" PRId64 " exceeds data length %" PRId64 ", offset %"
1211 PRId64, static_cast<off64_t>(len), data_length_, off);
1212 return false;
1213 }
1214 }
1215
1216 if (!android::base::ReadFullyAtOffset(fd_, buf, len, read_offset)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001217 ALOGE("Zip: failed to read at offset %" PRId64, off);
Tianjie Xu18c25922016-09-29 15:27:41 -07001218 return false;
1219 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001220 } else {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001221 if (off < 0 || off > data_length_) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001222 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64, off, data_length_);
Adam Lesinskide117e42017-06-19 10:27:38 -07001223 return false;
1224 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001225 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001226 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001227 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001228}
1229
Elliott Hughesf66460b2019-10-22 11:44:50 -07001230void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1231 size_t cd_size) {
1232 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001233 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(),
Ryan Mitchell23150e42020-03-09 09:33:46 -07001239 mapped_zip.GetFileOffset() + cd_start_offset,
1240 cd_size, PROT_READ);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001241 if (!directory_map) {
1242 ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1243 cd_start_offset, cd_size, strerror(errno));
1244 return false;
1245 }
Tianjie Xu18c25922016-09-29 15:27:41 -07001246
Elliott Hughese8f4b142018-10-19 16:09:39 -07001247 CHECK_EQ(directory_map->size(), cd_size);
1248 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001249 } else {
1250 if (mapped_zip.GetBasePtr() == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001251 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
Tianjie Xu18c25922016-09-29 15:27:41 -07001252 return false;
1253 }
1254 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1255 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001256 ALOGE(
1257 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1258 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1259 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001260 return false;
1261 }
1262
1263 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1264 }
1265 return true;
1266}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001267
1268tm ZipEntry::GetModificationTime() const {
1269 tm t = {};
1270
1271 t.tm_hour = (mod_time >> 11) & 0x1f;
1272 t.tm_min = (mod_time >> 5) & 0x3f;
1273 t.tm_sec = (mod_time & 0x1f) << 1;
1274
1275 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1276 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1277 t.tm_mday = (mod_time >> 16) & 0x1f;
1278
1279 return t;
1280}