blob: aa8bafc8767a611812d2006a83fa1fd3bbc9ce21 [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>
Elliott Hughes50ef29a2019-06-18 18:23:59 -070050#include <android-base/strings.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070051#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070052#include <log/log.h>
Dan Albert1ae07642015-04-09 14:11:18 -070053#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000054
Narayan Kamath044bc8e2014-12-03 18:22:53 +000055#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070056#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080057#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070058
Dan Albert1ae07642015-04-09 14:11:18 -070059using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000060
Narayan Kamath162b7052017-06-05 13:21:12 +010061// Used to turn on crc checks - verify that the content CRC matches the values
62// specified in the local file header and the central directory.
63static const bool kCrcChecksEnabled = false;
64
Narayan Kamath926973e2014-06-09 14:18:14 +010065// The maximum number of bytes to scan backwards for the EOCD start.
66static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
67
Narayan Kamath7462f022013-11-21 13:05:04 +000068/*
69 * A Read-only Zip archive.
70 *
71 * We want "open" and "find entry by name" to be fast operations, and
72 * we want to use as little memory as possible. We memory-map the zip
73 * central directory, and load a hash table with pointers to the filenames
74 * (which aren't null-terminated). The other fields are at a fixed offset
75 * from the filename, so we don't need to extract those (but we do need
76 * to byte-read and endian-swap them every time we want them).
77 *
78 * It's possible that somebody has handed us a massive (~1GB) zip archive,
79 * so we can't expect to mmap the entire file.
80 *
81 * To speed comparisons when doing a lookup by name, we could make the mapping
82 * "private" (copy-on-write) and null-terminate the filenames after verifying
83 * the record structure. However, this requires a private mapping of
84 * every page that the Central Directory touches. Easier to tuck a copy
85 * of the string length into the hash table entry.
86 */
Narayan Kamath7462f022013-11-21 13:05:04 +000087
Josh Gaoabdfc242018-09-07 12:44:40 -070088#if defined(__BIONIC__)
89uint64_t GetOwnerTag(const ZipArchive* archive) {
90 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
91 reinterpret_cast<uint64_t>(archive));
92}
93#endif
94
Ryan Mitchell23150e42020-03-09 09:33:46 -070095ZipArchive::ZipArchive(MappedZipFile&& map, bool assume_ownership)
96 : mapped_zip(map),
Josh Gao1b496342018-07-17 11:08:48 -070097 close_file(assume_ownership),
98 directory_offset(0),
99 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700100 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800101 num_entries(0) {
Josh Gao1b496342018-07-17 11:08:48 -0700102#if defined(__BIONIC__)
103 if (assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700104 CHECK(mapped_zip.HasFd());
105 android_fdsan_exchange_owner_tag(mapped_zip.GetFileDescriptor(), 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700106 }
107#endif
108}
109
Elliott Hughesf66460b2019-10-22 11:44:50 -0700110ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700111 : mapped_zip(address, length),
112 close_file(false),
113 directory_offset(0),
114 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700115 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800116 num_entries(0) {}
Josh Gao1b496342018-07-17 11:08:48 -0700117
118ZipArchive::~ZipArchive() {
119 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
120#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700121 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700122#else
123 close(mapped_zip.GetFileDescriptor());
124#endif
125 }
Josh Gao1b496342018-07-17 11:08:48 -0700126}
127
Tianjie Xu18c25922016-09-29 15:27:41 -0700128static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Andreas Gampe964b95c2019-04-05 13:48:02 -0700129 off64_t file_length, uint32_t read_amount,
Zimuzo5a503ef2018-09-17 19:49:55 +0100130 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000131 const off64_t search_start = file_length - read_amount;
132
Jiyong Parkcd997e62017-06-30 17:23:33 +0900133 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
134 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
135 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000136 return kIoError;
137 }
138
139 /*
140 * Scan backward for the EOCD magic. In an archive without a trailing
141 * comment, we'll find it on the first try. (We may want to consider
142 * doing an initial minimal read; if we don't find it, retry with a
143 * second read as above.)
144 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700145 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
146 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100147 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700148 if (scan_buffer[i] == 0x50) {
149 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
150 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
151 ALOGV("+++ Found EOCD at buf+%d", i);
152 break;
153 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000154 }
155 }
156 if (i < 0) {
157 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
158 return kInvalidFile;
159 }
160
161 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100162 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000163 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100164 * Verify that there's no trailing space at the end of the central directory
165 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000166 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900167 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100168 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100169 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100170 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100171 return kInvalidFile;
172 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000173
Narayan Kamath926973e2014-06-09 14:18:14 +0100174 /*
175 * Grab the CD offset and size, and the number of entries in the
176 * archive and verify that they look reasonable.
177 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700178 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100179 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900180 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000181 return kInvalidOffset;
182 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100183 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000184#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000185 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000186#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000187 return kEmptyArchive;
188 }
189
Jiyong Parkcd997e62017-06-30 17:23:33 +0900190 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
191 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000192
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800193 // It all looks good. Create a mapping for the CD, and set the fields
194 // in archive.
Elliott Hughese8f4b142018-10-19 16:09:39 -0700195 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700196 static_cast<size_t>(eocd->cd_size))) {
Narayan Kamatheaf98852013-12-11 14:51:51 +0000197 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000198 }
199
Narayan Kamath926973e2014-06-09 14:18:14 +0100200 archive->num_entries = eocd->num_records;
201 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000202
203 return 0;
204}
205
206/*
207 * Find the zip Central Directory and memory-map it.
208 *
209 * On success, returns 0 after populating fields from the EOCD area:
210 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700211 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000212 * num_entries
213 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700214static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000215 // Test file length. We use lseek64 to make sure the file
216 // is small enough to be a zip file (Its size must be less than
217 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700218 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000219 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000220 return kInvalidFile;
221 }
222
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800223 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100224 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000225 return kInvalidFile;
226 }
227
Narayan Kamath926973e2014-06-09 14:18:14 +0100228 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
229 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000230 return kInvalidFile;
231 }
232
233 /*
234 * Perform the traditional EOCD snipe hunt.
235 *
236 * We're searching for the End of Central Directory magic number,
237 * which appears at the start of the EOCD block. It's followed by
238 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
239 * need to read the last part of the file into a buffer, dig through
240 * it to find the magic number, parse some values out, and use those
241 * to determine the extent of the CD.
242 *
243 * We start by pulling in the last part of the file.
244 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700245 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100246 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700247 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000248 }
249
Tianjie Xu18c25922016-09-29 15:27:41 -0700250 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900251 int32_t result =
252 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000253 return result;
254}
255
256/*
257 * Parses the Zip archive's Central Directory. Allocates and populates the
258 * hash table.
259 *
260 * Returns 0 on success.
261 */
262static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700263 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
264 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100265 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000266
Tianjie Xu0ef97832020-03-15 21:23:24 -0700267 // TODO(xunchang) parse the zip64 Eocd
268 if (num_entries > UINT16_MAX) {
269 archive->cd_entry_map = CdEntryMapZip64::Create();
270 } else {
271 archive->cd_entry_map = CdEntryMapZip32::Create(num_entries);
272 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800273 if (archive->cd_entry_map == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800274 return kAllocationFailed;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700275 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000276
277 /*
278 * Walk through the central directory, adding entries to the hash
279 * table and verifying values.
280 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100281 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000282 const uint8_t* ptr = cd_ptr;
283 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700284 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800285 ALOGW("Zip: ran off the end (item #%" PRIu16 ", %zu bytes of central directory)", i,
286 cd_length);
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700287#if defined(__ANDROID__)
288 android_errorWriteLog(0x534e4554, "36392138");
289#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800290 return kInvalidFile;
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700291 }
292
Jiyong Parkcd997e62017-06-30 17:23:33 +0900293 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100294 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700295 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800296 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000297 }
298
Narayan Kamath926973e2014-06-09 14:18:14 +0100299 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000300 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800301 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900302 static_cast<int64_t>(local_header_offset), i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800303 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000304 }
305
Narayan Kamath926973e2014-06-09 14:18:14 +0100306 const uint16_t file_name_length = cdr->file_name_length;
307 const uint16_t extra_length = cdr->extra_field_length;
308 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100309 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
310
Tianjie Xu9e020e22016-10-10 12:11:30 -0700311 if (file_name + file_name_length > cd_end) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700312 ALOGW("Zip: file name for entry %" PRIu16
313 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
314 i, file_name_length, cd_length);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800315 return kInvalidEntryName;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700316 }
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700317 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000318 if (!IsValidEntryName(file_name, file_name_length)) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700319 ALOGW("Zip: invalid file name at entry %" PRIu16, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800320 return kInvalidEntryName;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100321 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000322
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700323 // Add the CDE filename to the hash table.
324 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800325 if (auto add_result =
326 archive->cd_entry_map->AddToMap(entry_name, archive->central_directory.GetBasePtr());
327 add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000328 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800329 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000330 }
331
Narayan Kamath926973e2014-06-09 14:18:14 +0100332 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
333 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900334 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800335 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000336 }
337 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100338
339 uint32_t lfh_start_bytes;
340 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
341 sizeof(uint32_t), 0)) {
342 ALOGW("Zip: Unable to read header for entry at offset == 0.");
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800343 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100344 }
345
346 if (lfh_start_bytes != LocalFileHeader::kSignature) {
347 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
348#if defined(__ANDROID__)
349 android_errorWriteLog(0x534e4554, "64211847");
350#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800351 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100352 }
353
Mark Salyzyn088bf902014-05-08 16:02:20 -0700354 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000355
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800356 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000357}
358
Jiyong Parkcd997e62017-06-30 17:23:33 +0900359static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800360 int32_t result = MapCentralDirectory(debug_file_name, archive);
361 return result != 0 ? result : ParseZipArchive(archive);
Narayan Kamath7462f022013-11-21 13:05:04 +0000362}
363
Jiyong Parkcd997e62017-06-30 17:23:33 +0900364int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
365 bool assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700366 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000367 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000368 return OpenArchiveInternal(archive, debug_file_name);
369}
370
Ryan Mitchell23150e42020-03-09 09:33:46 -0700371int32_t OpenArchiveFdRange(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
372 off64_t length, off64_t offset, bool assume_ownership) {
373 ZipArchive* archive = new ZipArchive(MappedZipFile(fd, length, offset), assume_ownership);
374 *handle = archive;
375
376 if (length < 0) {
377 ALOGW("Invalid zip length %" PRId64, length);
378 return kIoError;
379 }
380
381 if (offset < 0) {
382 ALOGW("Invalid zip offset %" PRId64, offset);
383 return kIoError;
384 }
385
386 return OpenArchiveInternal(archive, debug_file_name);
387}
388
Narayan Kamath7462f022013-11-21 13:05:04 +0000389int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800390 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Ryan Mitchell23150e42020-03-09 09:33:46 -0700391 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000392 *handle = archive;
393
Narayan Kamath7462f022013-11-21 13:05:04 +0000394 if (fd < 0) {
395 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
396 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000397 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700398
Narayan Kamath7462f022013-11-21 13:05:04 +0000399 return OpenArchiveInternal(archive, fileName);
400}
401
Elliott Hughesf66460b2019-10-22 11:44:50 -0700402int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900403 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700404 ZipArchive* archive = new ZipArchive(address, length);
405 *handle = archive;
406 return OpenArchiveInternal(archive, debug_file_name);
407}
408
Elliott Hughes26724132019-10-25 09:57:58 -0700409ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
410 ZipArchiveInfo result;
411 result.archive_size = archive->mapped_zip.GetFileLength();
412 result.entry_count = archive->num_entries;
413 return result;
414}
415
Narayan Kamath7462f022013-11-21 13:05:04 +0000416/*
417 * Close a ZipArchive, closing the file and freeing the contents.
418 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700419void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000420 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100421 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000422}
423
Narayan Kamath162b7052017-06-05 13:21:12 +0100424static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100425 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700426 off64_t offset = entry->offset;
427 if (entry->method != kCompressStored) {
428 offset += entry->compressed_length;
429 } else {
430 offset += entry->uncompressed_length;
431 }
432
433 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000434 return kIoError;
435 }
436
Narayan Kamath926973e2014-06-09 14:18:14 +0100437 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700438 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
439 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000440
Narayan Kamath162b7052017-06-05 13:21:12 +0100441 // Validate that the values in the data descriptor match those in the central
442 // directory.
443 if (entry->compressed_length != descriptor->compressed_size ||
444 entry->uncompressed_length != descriptor->uncompressed_size ||
445 entry->crc32 != descriptor->crc32) {
446 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
447 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
448 entry->compressed_length, entry->uncompressed_length, entry->crc32,
449 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
450 return kInconsistentInformation;
451 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000452
453 return 0;
454}
455
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800456static int32_t FindEntry(const ZipArchive* archive, std::string_view entryName,
457 const uint64_t nameOffset, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000458 // Recover the start of the central directory entry from the filename
459 // pointer. The filename is the first entry past the fixed-size data,
460 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700461 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800462 const uint8_t* ptr = base_ptr + nameOffset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100463 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000464
465 // This is the base of our mmapped region, we have to sanity check that
466 // the name that's in the hash table is a pointer to a location within
467 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700468 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000469 ALOGW("Zip: Invalid entry pointer");
470 return kInvalidOffset;
471 }
472
Jiyong Parkcd997e62017-06-30 17:23:33 +0900473 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100474
Narayan Kamath7462f022013-11-21 13:05:04 +0000475 // The offset of the start of the central directory in the zipfile.
476 // We keep this lying around so that we can sanity check all our lengths
477 // and our per-file structures.
478 const off64_t cd_offset = archive->directory_offset;
479
480 // Fill out the compression method, modification time, crc32
481 // and other interesting attributes from the central directory. These
482 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100483 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900484 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100485 data->crc32 = cdr->crc32;
486 data->compressed_length = cdr->compressed_size;
487 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000488
489 // Figure out the local header offset from the central directory. The
490 // actual file data will begin after the local header and the name /
491 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100492 const off64_t local_header_offset = cdr->local_file_header_offset;
493 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000494 ALOGW("Zip: bad local hdr offset in zip");
495 return kInvalidOffset;
496 }
497
Narayan Kamath926973e2014-06-09 14:18:14 +0100498 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700499 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800500 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900501 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000502 return kIoError;
503 }
504
Jiyong Parkcd997e62017-06-30 17:23:33 +0900505 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100506
507 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700508 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900509 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000510 return kInvalidOffset;
511 }
512
513 // Paranoia: Match the values specified in the local file header
514 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700515
Narayan Kamath162b7052017-06-05 13:21:12 +0100516 // Warn if central directory and local file header don't agree on the use
517 // of a trailing Data Descriptor. The reference implementation is inconsistent
518 // and appears to use the LFH value during extraction (unzip) but the CD value
519 // while displayng information about archives (zipinfo). The spec remains
520 // silent on this inconsistency as well.
521 //
522 // For now, always use the version from the LFH but make sure that the values
523 // specified in the central directory match those in the data descriptor.
524 //
525 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
526 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
527 // encoded using UTF-8). This implementation does not check for the presence of
528 // that flag and always enforces that entry names are valid UTF-8.
529 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
530 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700531 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700532 }
533
534 // If there is no trailing data descriptor, verify that the central directory and local file
535 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100536 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000537 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900538 if (data->compressed_length != lfh->compressed_size ||
539 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
540 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
541 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
542 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
543 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000544 return kInconsistentInformation;
545 }
546 } else {
547 data->has_data_descriptor = 1;
548 }
549
Elliott Hughes55fd2932017-05-28 22:59:04 -0700550 // 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 -0700551 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700552 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700553 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700554 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
555 } else {
556 data->unix_mode = 0777;
557 }
558
Elliott Hughesd5095252019-10-28 21:35:52 -0700559 // 4.4.4: general purpose bit flags.
560 data->gpbf = lfh->gpb_flags;
561
Elliott Hughes26724132019-10-25 09:57:58 -0700562 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
563 // Currently only needed to implement zipinfo.
564 data->is_text = (cdr->internal_file_attributes & 1);
565
Narayan Kamath7462f022013-11-21 13:05:04 +0000566 // Check that the local file header name matches the declared
567 // name in the central directory.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800568 CHECK_LE(entryName.size(), UINT16_MAX);
569 auto nameLen = static_cast<uint16_t>(entryName.size());
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700570 if (lfh->file_name_length != nameLen) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800571 ALOGW("Zip: lfh name length did not match central directory for %s: %" PRIu16 " %" PRIu16,
572 std::string(entryName).c_str(), lfh->file_name_length, nameLen);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700573 return kInconsistentInformation;
574 }
575 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
576 if (name_offset + lfh->file_name_length > cd_offset) {
577 ALOGW("Zip: lfh name has invalid declared length");
578 return kInvalidOffset;
579 }
580 std::vector<uint8_t> name_buf(nameLen);
581 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
582 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
583 return kIoError;
584 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800585 if (memcmp(entryName.data(), name_buf.data(), nameLen) != 0) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700586 ALOGW("Zip: lfh name did not match central directory");
Narayan Kamath7462f022013-11-21 13:05:04 +0000587 return kInconsistentInformation;
588 }
589
Jiyong Parkcd997e62017-06-30 17:23:33 +0900590 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
591 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000592 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800593 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000594 return kInvalidOffset;
595 }
596
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800597 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700598 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900599 static_cast<int64_t>(data_offset), data->compressed_length,
600 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000601 return kInvalidOffset;
602 }
603
604 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900605 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
606 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
607 static_cast<int64_t>(data_offset), data->uncompressed_length,
608 static_cast<int64_t>(cd_offset));
609 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000610 }
611
612 data->offset = data_offset;
613 return 0;
614}
615
616struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000617 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100618
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700619 std::string prefix;
620 std::string suffix;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700621
622 uint32_t position = 0;
623
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700624 IterationHandle(ZipArchive* archive, std::string_view in_prefix, std::string_view in_suffix)
625 : archive(archive), prefix(in_prefix), suffix(in_suffix) {}
Narayan Kamath7462f022013-11-21 13:05:04 +0000626};
627
Ryan Prichard3673f992018-10-10 22:41:14 -0700628int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700629 const std::string_view optional_prefix,
630 const std::string_view optional_suffix) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800631 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000632 ALOGW("Zip: Invalid ZipArchiveHandle");
633 return kInvalidHandle;
634 }
635
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700636 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
637 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
638 ALOGW("Zip: prefix/suffix too long");
639 return kInvalidEntryName;
640 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000641
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800642 archive->cd_entry_map->ResetIteration();
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700643 *cookie_ptr = new IterationHandle(archive, optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000644 return 0;
645}
646
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100647void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100648 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100649}
650
Elliott Hughesb17bf522019-05-03 22:38:44 -0700651int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
652 ZipEntry* data) {
653 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
654 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
655 return kInvalidEntryName;
656 }
657
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800658 const auto [result, offset] =
659 archive->cd_entry_map->GetCdEntryOffset(entryName, archive->central_directory.GetBasePtr());
660 if (result != 0) {
Elliott Hughesb17bf522019-05-03 22:38:44 -0700661 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800662 return static_cast<int32_t>(result); // kEntryNotFound is safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700663 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700664 // We know there are at most hash_table_size entries, safe to truncate.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800665 return FindEntry(archive, entryName, offset, data);
Elliott Hughesb17bf522019-05-03 22:38:44 -0700666}
667
Elliott Hughese06a8082019-05-22 18:56:41 -0700668int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700669 std::string_view sv;
670 int32_t result = Next(cookie, data, &sv);
671 if (result == 0 && name) {
672 *name = std::string(sv);
673 }
674 return result;
675}
676
677int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800678 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800679 if (handle == nullptr) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100680 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000681 return kInvalidHandle;
682 }
683
684 ZipArchive* archive = handle->archive;
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800685 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000686 ALOGW("Zip: Invalid ZipArchiveHandle");
687 return kInvalidHandle;
688 }
689
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800690 auto entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
691 while (entry != std::pair<std::string_view, uint64_t>()) {
692 const auto [entry_name, offset] = entry;
693 if (android::base::StartsWith(entry_name, handle->prefix) &&
694 android::base::EndsWith(entry_name, handle->suffix)) {
695 const int error = FindEntry(archive, entry_name, offset, data);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700696 if (!error && name) {
697 *name = entry_name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000698 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000699 return error;
700 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800701 entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000702 }
703
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800704 archive->cd_entry_map->ResetIteration();
Narayan Kamath7462f022013-11-21 13:05:04 +0000705 return kIterationEnd;
706}
707
Narayan Kamathf899bd52015-04-17 11:53:14 +0100708// A Writer that writes data to a fixed size memory region.
709// The size of the memory region must be equal to the total size of
710// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100711class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100712 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900713 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100714
715 virtual bool Append(uint8_t* buf, size_t buf_size) override {
716 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700717 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900718 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100719 return false;
720 }
721
722 memcpy(buf_ + bytes_written_, buf, buf_size);
723 bytes_written_ += buf_size;
724 return true;
725 }
726
727 private:
728 uint8_t* const buf_;
729 const size_t size_;
730 size_t bytes_written_;
731};
732
733// A Writer that appends data to a file |fd| at its current position.
734// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100735class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100736 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100737 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
738 // guaranteeing that the file descriptor is valid and that there's enough
739 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800740 // is truncated to the correct length (no truncation if |fd| references a
741 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100742 //
743 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800744 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100745 const uint32_t declared_length = entry->uncompressed_length;
746 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
747 if (current_offset == -1) {
748 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800749 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100750 }
751
Narayan Kamathf899bd52015-04-17 11:53:14 +0100752#if defined(__linux__)
753 if (declared_length > 0) {
754 // Make sure we have enough space on the volume to extract the compressed
755 // entry. Note that the call to ftruncate below will change the file size but
756 // will not allocate space on disk and this call to fallocate will not
757 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700758 // Note: fallocate is only supported by the following filesystems -
759 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
760 // EOPNOTSUPP error when issued in other filesystems.
761 // Hence, check for the return error code before concluding that the
762 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700763 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700764 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700765 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100766 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
767 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800768 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100769 }
770 }
771#endif // __linux__
772
Tao Baoa456c212016-11-15 10:08:07 -0800773 struct stat sb;
774 if (fstat(fd, &sb) == -1) {
775 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800776 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100777 }
778
Tao Baoa456c212016-11-15 10:08:07 -0800779 // Block device doesn't support ftruncate(2).
780 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700781 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -0800782 if (result == -1) {
783 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
784 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800785 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800786 }
787 }
788
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800789 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100790 }
791
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700792 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800793 : fd_(other.fd_),
794 declared_length_(other.declared_length_),
795 total_bytes_written_(other.total_bytes_written_) {
796 other.fd_ = -1;
797 }
798
799 bool IsValid() const { return fd_ != -1; }
800
Narayan Kamathf899bd52015-04-17 11:53:14 +0100801 virtual bool Append(uint8_t* buf, size_t buf_size) override {
802 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700803 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900804 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100805 return false;
806 }
807
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100808 const bool result = android::base::WriteFully(fd_, buf, buf_size);
809 if (result) {
810 total_bytes_written_ += buf_size;
811 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700812 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100813 }
814
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100815 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100816 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900817
Narayan Kamathf899bd52015-04-17 11:53:14 +0100818 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800819 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900820 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100821
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800822 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100823 const size_t declared_length_;
824 size_t total_bytes_written_;
825};
826
Narayan Kamath485b3642017-10-26 14:42:39 +0100827class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100828 public:
829 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
830 : Reader(), zip_file_(zip_file), entry_(entry) {}
831
832 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
833 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
834 }
835
836 virtual ~EntryReader() {}
837
838 private:
839 const MappedZipFile& zip_file_;
840 const ZipEntry* entry_;
841};
842
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800843// This method is using libz macros with old-style-casts
844#pragma GCC diagnostic push
845#pragma GCC diagnostic ignored "-Wold-style-cast"
846static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
847 return inflateInit2(stream, window_bits);
848}
849#pragma GCC diagnostic pop
850
Narayan Kamath485b3642017-10-26 14:42:39 +0100851namespace zip_archive {
852
853// Moved out of line to avoid -Wweak-vtables.
854Reader::~Reader() {}
855Writer::~Writer() {}
856
857int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
858 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700859 const size_t kBufSize = 32768;
860 std::vector<uint8_t> read_buf(kBufSize);
861 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000862 z_stream zstream;
863 int zerr;
864
865 /*
866 * Initialize the zlib stream struct.
867 */
868 memset(&zstream, 0, sizeof(zstream));
869 zstream.zalloc = Z_NULL;
870 zstream.zfree = Z_NULL;
871 zstream.opaque = Z_NULL;
872 zstream.next_in = NULL;
873 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700874 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000875 zstream.avail_out = kBufSize;
876 zstream.data_type = Z_UNKNOWN;
877
878 /*
879 * Use the undocumented "negative window bits" feature to tell zlib
880 * that there's no zlib header waiting for it.
881 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800882 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000883 if (zerr != Z_OK) {
884 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900885 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000886 } else {
887 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
888 }
889
890 return kZlibError;
891 }
892
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800893 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900894 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800895 };
896
897 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
898
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000899 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700900 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100901 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000902 do {
903 /* read as much as we can */
904 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700905 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100906 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700907 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100908 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700909 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800910 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000911 }
912
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100913 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000914
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700915 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100916 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000917 }
918
919 /* uncompress the data */
920 zerr = inflate(&zstream, Z_NO_FLUSH);
921 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900922 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
923 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800924 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000925 }
926
927 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900928 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700929 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100930 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000931 return kIoError;
932 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700933 DCHECK_LE(write_size, kBufSize);
934 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +0000935 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000936
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700937 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000938 zstream.avail_out = kBufSize;
939 }
940 } while (zerr == Z_OK);
941
Elliott Hughese8f4b142018-10-19 16:09:39 -0700942 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +0000943
Narayan Kamath162b7052017-06-05 13:21:12 +0100944 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
945 // "feature" of zlib to tell it there won't be a zlib file header. zlib
946 // doesn't bother calculating the checksum in that scenario. We just do
947 // it ourselves above because there are no additional gains to be made by
948 // having zlib calculate it for us, since they do it by calling crc32 in
949 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000950 if (compute_crc) {
951 *crc_out = crc;
952 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000953
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100954 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900955 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
956 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800957 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +0000958 }
959
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800960 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000961}
Narayan Kamath485b3642017-10-26 14:42:39 +0100962} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +0000963
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100964static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +0100965 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100966 const EntryReader reader(mapped_zip, entry);
967
Narayan Kamath485b3642017-10-26 14:42:39 +0100968 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
969 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100970}
971
Narayan Kamath485b3642017-10-26 14:42:39 +0100972static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
973 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100974 static const uint32_t kBufSize = 32768;
975 std::vector<uint8_t> buf(kBufSize);
976
977 const uint32_t length = entry->uncompressed_length;
978 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -0700979 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100980 while (count < length) {
981 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -0700982 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100983
Adam Lesinskide117e42017-06-19 10:27:38 -0700984 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700985 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -0700986
987 // Make sure to read at offset to ensure concurrent access to the fd.
988 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700989 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -0700990 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100991 return kIoError;
992 }
993
994 if (!writer->Append(&buf[0], block_size)) {
995 return kIoError;
996 }
997 crc = crc32(crc, &buf[0], block_size);
998 count += block_size;
999 }
1000
1001 *crc_out = crc;
1002
1003 return 0;
1004}
1005
Ryan Prichard3673f992018-10-10 22:41:14 -07001006int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001007 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001008
1009 // this should default to kUnknownCompressionMethod.
1010 int32_t return_value = -1;
1011 uint64_t crc = 0;
1012 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001013 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001014 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001015 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001016 }
1017
1018 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001019 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001020 if (return_value) {
1021 return return_value;
1022 }
1023 }
1024
Narayan Kamath162b7052017-06-05 13:21:12 +01001025 // Validate that the CRC matches the calculated value.
1026 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001027 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001028 return kInconsistentInformation;
1029 }
1030
1031 return return_value;
1032}
1033
Ryan Prichard3673f992018-10-10 22:41:14 -07001034int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001035 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001036 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001037}
1038
Ryan Prichard3673f992018-10-10 22:41:14 -07001039int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001040 auto writer = FileWriter::Create(fd, entry);
1041 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001042 return kIoError;
1043 }
1044
Ryan Prichard3673f992018-10-10 22:41:14 -07001045 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001046}
1047
Ryan Prichard3673f992018-10-10 22:41:14 -07001048int GetFileDescriptor(const ZipArchiveHandle archive) {
1049 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001050}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001051
Ryan Mitchell23150e42020-03-09 09:33:46 -07001052off64_t GetFileDescriptorOffset(const ZipArchiveHandle archive) {
1053 return archive->mapped_zip.GetFileOffset();
1054}
1055
Tianjie Xu18c25922016-09-29 15:27:41 -07001056#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001057class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001058 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001059 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1060 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001061
1062 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1063 return proc_function_(buf, buf_size, cookie_);
1064 }
1065
1066 private:
1067 ProcessZipEntryFunction proc_function_;
1068 void* cookie_;
1069};
1070
Ryan Prichard3673f992018-10-10 22:41:14 -07001071int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001072 ProcessZipEntryFunction func, void* cookie) {
1073 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001074 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001075}
1076
Jiyong Parkcd997e62017-06-30 17:23:33 +09001077#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001078
1079int MappedZipFile::GetFileDescriptor() const {
1080 if (!has_fd_) {
1081 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1082 return -1;
1083 }
1084 return fd_;
1085}
1086
Elliott Hughesf66460b2019-10-22 11:44:50 -07001087const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001088 if (has_fd_) {
1089 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1090 return nullptr;
1091 }
1092 return base_ptr_;
1093}
1094
Ryan Mitchell23150e42020-03-09 09:33:46 -07001095off64_t MappedZipFile::GetFileOffset() const {
1096 return fd_offset_;
1097}
1098
Tianjie Xu18c25922016-09-29 15:27:41 -07001099off64_t MappedZipFile::GetFileLength() const {
1100 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001101 if (data_length_ != -1) {
1102 return data_length_;
1103 }
1104 data_length_ = lseek64(fd_, 0, SEEK_END);
1105 if (data_length_ == -1) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001106 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1107 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001108 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001109 } else {
1110 if (base_ptr_ == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001111 ALOGE("Zip: invalid file map");
Tianjie Xu18c25922016-09-29 15:27:41 -07001112 return -1;
1113 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001114 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001115 }
1116}
1117
Tianjie Xu18c25922016-09-29 15:27:41 -07001118// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001119bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001120 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001121 if (off < 0) {
1122 ALOGE("Zip: invalid offset %" PRId64, off);
1123 return false;
1124 }
1125
1126 off64_t read_offset;
1127 if (__builtin_add_overflow(fd_offset_, off, &read_offset)) {
1128 ALOGE("Zip: invalid read offset %" PRId64 " overflows, fd offset %" PRId64, off, fd_offset_);
1129 return false;
1130 }
1131
1132 if (data_length_ != -1) {
1133 off64_t read_end;
1134 if (len > std::numeric_limits<off64_t>::max() ||
1135 __builtin_add_overflow(off, static_cast<off64_t>(len), &read_end)) {
1136 ALOGE("Zip: invalid read length %" PRId64 " overflows, offset %" PRId64,
1137 static_cast<off64_t>(len), off);
1138 return false;
1139 }
1140
1141 if (read_end > data_length_) {
1142 ALOGE("Zip: invalid read length %" PRId64 " exceeds data length %" PRId64 ", offset %"
1143 PRId64, static_cast<off64_t>(len), data_length_, off);
1144 return false;
1145 }
1146 }
1147
1148 if (!android::base::ReadFullyAtOffset(fd_, buf, len, read_offset)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001149 ALOGE("Zip: failed to read at offset %" PRId64, off);
Tianjie Xu18c25922016-09-29 15:27:41 -07001150 return false;
1151 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001152 } else {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001153 if (off < 0 || off > data_length_) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001154 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64, off, data_length_);
Adam Lesinskide117e42017-06-19 10:27:38 -07001155 return false;
1156 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001157 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001158 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001159 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001160}
1161
Elliott Hughesf66460b2019-10-22 11:44:50 -07001162void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1163 size_t cd_size) {
1164 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001165 length_ = cd_size;
1166}
1167
Elliott Hughese8f4b142018-10-19 16:09:39 -07001168bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001169 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001170 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
Ryan Mitchell23150e42020-03-09 09:33:46 -07001171 mapped_zip.GetFileOffset() + cd_start_offset,
1172 cd_size, PROT_READ);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001173 if (!directory_map) {
1174 ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1175 cd_start_offset, cd_size, strerror(errno));
1176 return false;
1177 }
Tianjie Xu18c25922016-09-29 15:27:41 -07001178
Elliott Hughese8f4b142018-10-19 16:09:39 -07001179 CHECK_EQ(directory_map->size(), cd_size);
1180 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001181 } else {
1182 if (mapped_zip.GetBasePtr() == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001183 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
Tianjie Xu18c25922016-09-29 15:27:41 -07001184 return false;
1185 }
1186 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1187 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001188 ALOGE(
1189 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1190 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1191 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001192 return false;
1193 }
1194
1195 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1196 }
1197 return true;
1198}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001199
1200tm ZipEntry::GetModificationTime() const {
1201 tm t = {};
1202
1203 t.tm_hour = (mod_time >> 11) & 0x1f;
1204 t.tm_min = (mod_time >> 5) & 0x3f;
1205 t.tm_sec = (mod_time & 0x1f) << 1;
1206
1207 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1208 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1209 t.tm_mday = (mod_time >> 16) & 0x1f;
1210
1211 return t;
1212}