blob: 19f95d4a01e817f1d8bd2fcd7568369fb9eb971e [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
Narayan Kamath162b7052017-06-05 13:21:12 +010060// Used to turn on crc checks - verify that the content CRC matches the values
61// specified in the local file header and the central directory.
Yurii Zubrytskyi8d8f6372020-04-06 19:35:33 -070062static constexpr bool kCrcChecksEnabled = false;
Narayan Kamath162b7052017-06-05 13:21:12 +010063
Narayan Kamath926973e2014-06-09 14:18:14 +010064// The maximum number of bytes to scan backwards for the EOCD start.
65static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
66
Tianjie Xu69ee4b72020-03-11 11:59:10 -070067// Set a reasonable cap (256 GiB) for the zip file size. So the data is always valid when
68// we parse the fields in cd or local headers as 64 bits signed integers.
69static constexpr uint64_t kMaxFileLength = 256 * static_cast<uint64_t>(1u << 30u);
70
Narayan Kamath7462f022013-11-21 13:05:04 +000071/*
72 * A Read-only Zip archive.
73 *
74 * We want "open" and "find entry by name" to be fast operations, and
75 * we want to use as little memory as possible. We memory-map the zip
76 * central directory, and load a hash table with pointers to the filenames
77 * (which aren't null-terminated). The other fields are at a fixed offset
78 * from the filename, so we don't need to extract those (but we do need
79 * to byte-read and endian-swap them every time we want them).
80 *
81 * It's possible that somebody has handed us a massive (~1GB) zip archive,
82 * so we can't expect to mmap the entire file.
83 *
84 * To speed comparisons when doing a lookup by name, we could make the mapping
85 * "private" (copy-on-write) and null-terminate the filenames after verifying
86 * the record structure. However, this requires a private mapping of
87 * every page that the Central Directory touches. Easier to tuck a copy
88 * of the string length into the hash table entry.
89 */
Narayan Kamath7462f022013-11-21 13:05:04 +000090
Josh Gaoabdfc242018-09-07 12:44:40 -070091#if defined(__BIONIC__)
92uint64_t GetOwnerTag(const ZipArchive* archive) {
93 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
94 reinterpret_cast<uint64_t>(archive));
95}
96#endif
97
Ryan Mitchell23150e42020-03-09 09:33:46 -070098ZipArchive::ZipArchive(MappedZipFile&& map, bool assume_ownership)
99 : mapped_zip(map),
Josh Gao1b496342018-07-17 11:08:48 -0700100 close_file(assume_ownership),
101 directory_offset(0),
102 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700103 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800104 num_entries(0) {
Josh Gao1b496342018-07-17 11:08:48 -0700105#if defined(__BIONIC__)
106 if (assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700107 CHECK(mapped_zip.HasFd());
108 android_fdsan_exchange_owner_tag(mapped_zip.GetFileDescriptor(), 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700109 }
110#endif
111}
112
Elliott Hughesf66460b2019-10-22 11:44:50 -0700113ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700114 : mapped_zip(address, length),
115 close_file(false),
116 directory_offset(0),
117 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700118 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800119 num_entries(0) {}
Josh Gao1b496342018-07-17 11:08:48 -0700120
121ZipArchive::~ZipArchive() {
122 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
123#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700124 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700125#else
126 close(mapped_zip.GetFileDescriptor());
127#endif
128 }
Josh Gao1b496342018-07-17 11:08:48 -0700129}
130
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700131struct CentralDirectoryInfo {
132 uint64_t num_records;
133 // The size of the central directory (in bytes).
134 uint64_t cd_size;
135 // The offset of the start of the central directory, relative
136 // to the start of the file.
137 uint64_t cd_start_offset;
138};
139
Tianjie6ab29122020-03-18 17:44:30 -0700140static ZipError FindCentralDirectoryInfoForZip64(const char* debugFileName, ZipArchive* archive,
141 off64_t eocdOffset, CentralDirectoryInfo* cdInfo) {
142 if (eocdOffset <= sizeof(Zip64EocdLocator)) {
143 ALOGW("Zip: %s: Not enough space for zip64 eocd locator", debugFileName);
144 return kInvalidFile;
145 }
146 // We expect to find the zip64 eocd locator immediately before the zip eocd.
147 const int64_t locatorOffset = eocdOffset - sizeof(Zip64EocdLocator);
148 Zip64EocdLocator zip64EocdLocator{};
149 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>((&zip64EocdLocator)),
150 sizeof(Zip64EocdLocator), locatorOffset)) {
151 ALOGW("Zip: %s: Read %zu from offset %" PRId64 " failed %s", debugFileName,
152 sizeof(Zip64EocdLocator), locatorOffset, debugFileName);
153 return kIoError;
154 }
155
156 if (zip64EocdLocator.locator_signature != Zip64EocdLocator::kSignature) {
157 ALOGW("Zip: %s: Zip64 eocd locator signature not found at offset %" PRId64, debugFileName,
158 locatorOffset);
159 return kInvalidFile;
160 }
161
162 const int64_t zip64EocdOffset = zip64EocdLocator.zip64_eocd_offset;
Tianjie173aba02020-03-28 18:28:43 -0700163 if (locatorOffset <= sizeof(Zip64EocdRecord) ||
164 zip64EocdOffset > locatorOffset - sizeof(Zip64EocdRecord)) {
165 ALOGW("Zip: %s: Bad zip64 eocd offset %" PRId64 ", eocd locator offset %" PRId64, debugFileName,
166 zip64EocdOffset, locatorOffset);
Tianjie6ab29122020-03-18 17:44:30 -0700167 return kInvalidOffset;
168 }
169
170 Zip64EocdRecord zip64EocdRecord{};
171 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&zip64EocdRecord),
172 sizeof(Zip64EocdRecord), zip64EocdOffset)) {
173 ALOGW("Zip: %s: read %zu from offset %" PRId64 " failed %s", debugFileName,
Tianjie173aba02020-03-28 18:28:43 -0700174 sizeof(Zip64EocdLocator), zip64EocdOffset, debugFileName);
Tianjie6ab29122020-03-18 17:44:30 -0700175 return kIoError;
176 }
177
178 if (zip64EocdRecord.record_signature != Zip64EocdRecord::kSignature) {
179 ALOGW("Zip: %s: Zip64 eocd record signature not found at offset %" PRId64, debugFileName,
180 zip64EocdOffset);
181 return kInvalidFile;
182 }
183
Tianjie173aba02020-03-28 18:28:43 -0700184 if (zip64EocdOffset <= zip64EocdRecord.cd_size ||
185 zip64EocdRecord.cd_start_offset > zip64EocdOffset - zip64EocdRecord.cd_size) {
Tianjie6ab29122020-03-18 17:44:30 -0700186 ALOGW("Zip: %s: Bad offset for zip64 central directory. cd offset %" PRIu64 ", cd size %" PRIu64
187 ", zip64 eocd offset %" PRIu64,
188 debugFileName, zip64EocdRecord.cd_start_offset, zip64EocdRecord.cd_size, zip64EocdOffset);
189 return kInvalidOffset;
190 }
191
192 *cdInfo = {.num_records = zip64EocdRecord.num_records,
193 .cd_size = zip64EocdRecord.cd_size,
194 .cd_start_offset = zip64EocdRecord.cd_start_offset};
195
196 return kSuccess;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700197}
198
199static ZipError FindCentralDirectoryInfo(const char* debug_file_name, ZipArchive* archive,
200 off64_t file_length, uint32_t read_amount,
201 CentralDirectoryInfo* cdInfo) {
202 std::vector<uint8_t> scan_buffer(read_amount);
Narayan Kamath7462f022013-11-21 13:05:04 +0000203 const off64_t search_start = file_length - read_amount;
204
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700205 if (!archive->mapped_zip.ReadAtOffset(scan_buffer.data(), read_amount, search_start)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900206 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
207 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000208 return kIoError;
209 }
210
211 /*
212 * Scan backward for the EOCD magic. In an archive without a trailing
213 * comment, we'll find it on the first try. (We may want to consider
214 * doing an initial minimal read; if we don't find it, retry with a
215 * second read as above.)
216 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700217 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
218 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100219 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700220 if (scan_buffer[i] == 0x50) {
221 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
Tianjie0ec0eaa2020-03-26 12:34:44 -0700222 if (android::base::get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
Dan Albert1ae07642015-04-09 14:11:18 -0700223 ALOGV("+++ Found EOCD at buf+%d", i);
224 break;
225 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000226 }
227 }
228 if (i < 0) {
229 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
230 return kInvalidFile;
231 }
232
233 const off64_t eocd_offset = search_start + i;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700234 auto eocd = reinterpret_cast<const EocdRecord*>(scan_buffer.data() + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000235 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100236 * Verify that there's no trailing space at the end of the central directory
237 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000238 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900239 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100240 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100241 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100242 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100243 return kInvalidFile;
244 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000245
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700246 // One of the field is 0xFFFFFFFF, look for the zip64 EOCD instead.
247 if (eocd->cd_size == UINT32_MAX || eocd->cd_start_offset == UINT32_MAX) {
248 ALOGV("Looking for the zip64 EOCD, cd_size: %" PRIu32 "cd_start_offset: %" PRId32,
249 eocd->cd_size, eocd->cd_start_offset);
Tianjie6ab29122020-03-18 17:44:30 -0700250 return FindCentralDirectoryInfoForZip64(debug_file_name, archive, eocd_offset, cdInfo);
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700251 }
252
Narayan Kamath926973e2014-06-09 14:18:14 +0100253 /*
254 * Grab the CD offset and size, and the number of entries in the
255 * archive and verify that they look reasonable.
256 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700257 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100258 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900259 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000260 return kInvalidOffset;
261 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000262
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700263 *cdInfo = {.num_records = eocd->num_records,
264 .cd_size = eocd->cd_size,
265 .cd_start_offset = eocd->cd_start_offset};
266 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000267}
268
269/*
270 * Find the zip Central Directory and memory-map it.
271 *
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700272 * On success, returns kSuccess after populating fields from the EOCD area:
Narayan Kamath7462f022013-11-21 13:05:04 +0000273 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700274 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000275 * num_entries
276 */
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700277static ZipError MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
278 // 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 -0700279 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000280 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000281 return kInvalidFile;
282 }
283
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700284 if (file_length > kMaxFileLength) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100285 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000286 return kInvalidFile;
287 }
288
Narayan Kamath926973e2014-06-09 14:18:14 +0100289 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
290 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000291 return kInvalidFile;
292 }
293
294 /*
295 * Perform the traditional EOCD snipe hunt.
296 *
297 * We're searching for the End of Central Directory magic number,
298 * which appears at the start of the EOCD block. It's followed by
299 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
300 * need to read the last part of the file into a buffer, dig through
301 * it to find the magic number, parse some values out, and use those
302 * to determine the extent of the CD.
303 *
304 * We start by pulling in the last part of the file.
305 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700306 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100307 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700308 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000309 }
310
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700311 CentralDirectoryInfo cdInfo = {};
312 if (auto result =
313 FindCentralDirectoryInfo(debug_file_name, archive, file_length, read_amount, &cdInfo);
314 result != kSuccess) {
315 return result;
316 }
317
318 if (cdInfo.num_records == 0) {
319#if defined(__ANDROID__)
320 ALOGW("Zip: empty archive?");
321#endif
322 return kEmptyArchive;
323 }
324
325 if (cdInfo.cd_size >= SIZE_MAX) {
326 ALOGW("Zip: The size of central directory doesn't fit in range of size_t: %" PRIu64,
327 cdInfo.cd_size);
328 return kInvalidFile;
329 }
330
331 ALOGV("+++ num_entries=%" PRIu64 " dir_size=%" PRIu64 " dir_offset=%" PRIu64, cdInfo.num_records,
332 cdInfo.cd_size, cdInfo.cd_start_offset);
333
334 // It all looks good. Create a mapping for the CD, and set the fields in archive.
335 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(cdInfo.cd_start_offset),
336 static_cast<size_t>(cdInfo.cd_size))) {
337 return kMmapFailed;
338 }
339
340 archive->num_entries = cdInfo.num_records;
341 archive->directory_offset = cdInfo.cd_start_offset;
342
343 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000344}
345
Tianjie6ab29122020-03-18 17:44:30 -0700346static ZipError ParseZip64ExtendedInfoInExtraField(
347 const uint8_t* extraFieldStart, uint16_t extraFieldLength, uint32_t zip32UncompressedSize,
348 uint32_t zip32CompressedSize, std::optional<uint32_t> zip32LocalFileHeaderOffset,
349 Zip64ExtendedInfo* zip64Info) {
350 if (extraFieldLength <= 4) {
351 ALOGW("Zip: Extra field isn't large enough to hold zip64 info, size %" PRIu16,
352 extraFieldLength);
353 return kInvalidFile;
354 }
355
356 // Each header MUST consist of:
357 // Header ID - 2 bytes
358 // Data Size - 2 bytes
359 uint16_t offset = 0;
360 while (offset < extraFieldLength - 4) {
Tianjie0ec0eaa2020-03-26 12:34:44 -0700361 auto readPtr = const_cast<uint8_t*>(extraFieldStart + offset);
362 auto headerId = ConsumeUnaligned<uint16_t>(&readPtr);
363 auto dataSize = ConsumeUnaligned<uint16_t>(&readPtr);
Tianjie6ab29122020-03-18 17:44:30 -0700364
365 offset += 4;
366 if (dataSize > extraFieldLength - offset) {
367 ALOGW("Zip: Data size exceeds the boundary of extra field, data size %" PRIu16, dataSize);
368 return kInvalidOffset;
369 }
370
371 // Skip the other types of extensible data fields. Details in
372 // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT section 4.5
373 if (headerId != Zip64ExtendedInfo::kHeaderId) {
374 offset += dataSize;
375 continue;
376 }
377
Tianjie0ec0eaa2020-03-26 12:34:44 -0700378 std::optional<uint64_t> uncompressedFileSize;
379 std::optional<uint64_t> compressedFileSize;
380 std::optional<uint64_t> localHeaderOffset;
381 if (zip32UncompressedSize == UINT32_MAX) {
382 uncompressedFileSize = ConsumeUnaligned<uint64_t>(&readPtr);
383 }
384 if (zip32CompressedSize == UINT32_MAX) {
385 compressedFileSize = ConsumeUnaligned<uint64_t>(&readPtr);
Tianjie6ab29122020-03-18 17:44:30 -0700386 }
387 if (zip32LocalFileHeaderOffset == UINT32_MAX) {
Tianjie0ec0eaa2020-03-26 12:34:44 -0700388 localHeaderOffset = ConsumeUnaligned<uint64_t>(&readPtr);
Tianjie6ab29122020-03-18 17:44:30 -0700389 }
390
Tianjie0ec0eaa2020-03-26 12:34:44 -0700391 // calculate how many bytes we read after the data size field.
392 size_t bytesRead = readPtr - (extraFieldStart + offset);
393 if (bytesRead == 0) {
Tianjie6ab29122020-03-18 17:44:30 -0700394 ALOGW("Zip: Data size should not be 0 in zip64 extended field");
395 return kInvalidFile;
396 }
397
Tianjie0ec0eaa2020-03-26 12:34:44 -0700398 if (dataSize != bytesRead) {
Tianjie6ab29122020-03-18 17:44:30 -0700399 auto localOffsetString = zip32LocalFileHeaderOffset.has_value()
400 ? std::to_string(zip32LocalFileHeaderOffset.value())
401 : "missing";
Tianjie0ec0eaa2020-03-26 12:34:44 -0700402 ALOGW("Zip: Invalid data size in zip64 extended field, expect %zu , get %" PRIu16
Tianjie6ab29122020-03-18 17:44:30 -0700403 ", uncompressed size %" PRIu32 ", compressed size %" PRIu32 ", local header offset %s",
Tianjie0ec0eaa2020-03-26 12:34:44 -0700404 bytesRead, dataSize, zip32UncompressedSize, zip32CompressedSize,
Tianjie6ab29122020-03-18 17:44:30 -0700405 localOffsetString.c_str());
406 return kInvalidFile;
407 }
408
Tianjie6ab29122020-03-18 17:44:30 -0700409 zip64Info->uncompressed_file_size = uncompressedFileSize;
410 zip64Info->compressed_file_size = compressedFileSize;
411 zip64Info->local_header_offset = localHeaderOffset;
412 return kSuccess;
413 }
414
415 ALOGW("Zip: zip64 extended info isn't found in the extra field.");
416 return kInvalidFile;
417}
418
Narayan Kamath7462f022013-11-21 13:05:04 +0000419/*
420 * Parses the Zip archive's Central Directory. Allocates and populates the
421 * hash table.
422 *
423 * Returns 0 on success.
424 */
Tianjie6ab29122020-03-18 17:44:30 -0700425static ZipError ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700426 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
427 const size_t cd_length = archive->central_directory.GetMapLength();
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700428 const uint64_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000429
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700430 if (num_entries <= UINT16_MAX) {
431 archive->cd_entry_map = CdEntryMapZip32::Create(static_cast<uint16_t>(num_entries));
Tianjie Xu0ef97832020-03-15 21:23:24 -0700432 } else {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700433 archive->cd_entry_map = CdEntryMapZip64::Create();
Tianjie Xu0ef97832020-03-15 21:23:24 -0700434 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800435 if (archive->cd_entry_map == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800436 return kAllocationFailed;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700437 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000438
439 /*
440 * Walk through the central directory, adding entries to the hash
441 * table and verifying values.
442 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100443 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000444 const uint8_t* ptr = cd_ptr;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700445 for (uint64_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700446 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700447 ALOGW("Zip: ran off the end (item #%" PRIu64 ", %zu bytes of central directory)", i,
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800448 cd_length);
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700449#if defined(__ANDROID__)
450 android_errorWriteLog(0x534e4554, "36392138");
451#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800452 return kInvalidFile;
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700453 }
454
Tianjie6ab29122020-03-18 17:44:30 -0700455 auto cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100456 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700457 ALOGW("Zip: missed a central dir sig (at %" PRIu64 ")", i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800458 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000459 }
460
Narayan Kamath926973e2014-06-09 14:18:14 +0100461 const uint16_t file_name_length = cdr->file_name_length;
462 const uint16_t extra_length = cdr->extra_field_length;
463 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100464 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
465
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700466 if (file_name_length >= cd_length || file_name > cd_end - file_name_length) {
467 ALOGW("Zip: file name for entry %" PRIu64
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700468 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
469 i, file_name_length, cd_length);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800470 return kInvalidEntryName;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700471 }
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700472
473 const uint8_t* extra_field = file_name + file_name_length;
474 if (extra_length >= cd_length || extra_field > cd_end - extra_length) {
475 ALOGW("Zip: extra field for entry %" PRIu64
476 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
477 i, extra_length, cd_length);
478 return kInvalidFile;
479 }
480
481 off64_t local_header_offset = cdr->local_file_header_offset;
482 if (local_header_offset == UINT32_MAX) {
Tianjie6ab29122020-03-18 17:44:30 -0700483 Zip64ExtendedInfo zip64_info{};
484 if (auto status = ParseZip64ExtendedInfoInExtraField(
485 extra_field, extra_length, cdr->uncompressed_size, cdr->compressed_size,
486 cdr->local_file_header_offset, &zip64_info);
487 status != kSuccess) {
488 return status;
489 }
490 CHECK(zip64_info.local_header_offset.has_value());
491 local_header_offset = zip64_info.local_header_offset.value();
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700492 }
493
494 if (local_header_offset >= archive->directory_offset) {
495 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu64,
496 static_cast<int64_t>(local_header_offset), i);
497 return kInvalidFile;
498 }
499
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700500 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000501 if (!IsValidEntryName(file_name, file_name_length)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700502 ALOGW("Zip: invalid file name at entry %" PRIu64, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800503 return kInvalidEntryName;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100504 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000505
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700506 // Add the CDE filename to the hash table.
507 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800508 if (auto add_result =
509 archive->cd_entry_map->AddToMap(entry_name, archive->central_directory.GetBasePtr());
510 add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000511 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800512 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000513 }
514
Narayan Kamath926973e2014-06-09 14:18:14 +0100515 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
516 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700517 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu64, ptr - cd_ptr, cd_length, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800518 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000519 }
520 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100521
522 uint32_t lfh_start_bytes;
523 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
524 sizeof(uint32_t), 0)) {
525 ALOGW("Zip: Unable to read header for entry at offset == 0.");
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800526 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100527 }
528
529 if (lfh_start_bytes != LocalFileHeader::kSignature) {
530 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
531#if defined(__ANDROID__)
532 android_errorWriteLog(0x534e4554, "64211847");
533#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800534 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100535 }
536
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700537 ALOGV("+++ zip good scan %" PRIu64 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000538
Tianjie6ab29122020-03-18 17:44:30 -0700539 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000540}
541
Jiyong Parkcd997e62017-06-30 17:23:33 +0900542static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800543 int32_t result = MapCentralDirectory(debug_file_name, archive);
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700544 return result != kSuccess ? result : ParseZipArchive(archive);
Narayan Kamath7462f022013-11-21 13:05:04 +0000545}
546
Jiyong Parkcd997e62017-06-30 17:23:33 +0900547int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
548 bool assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700549 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000550 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000551 return OpenArchiveInternal(archive, debug_file_name);
552}
553
Ryan Mitchell23150e42020-03-09 09:33:46 -0700554int32_t OpenArchiveFdRange(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
555 off64_t length, off64_t offset, bool assume_ownership) {
556 ZipArchive* archive = new ZipArchive(MappedZipFile(fd, length, offset), assume_ownership);
557 *handle = archive;
558
559 if (length < 0) {
560 ALOGW("Invalid zip length %" PRId64, length);
561 return kIoError;
562 }
563
564 if (offset < 0) {
565 ALOGW("Invalid zip offset %" PRId64, offset);
566 return kIoError;
567 }
568
569 return OpenArchiveInternal(archive, debug_file_name);
570}
571
Narayan Kamath7462f022013-11-21 13:05:04 +0000572int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800573 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Ryan Mitchell23150e42020-03-09 09:33:46 -0700574 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000575 *handle = archive;
576
Narayan Kamath7462f022013-11-21 13:05:04 +0000577 if (fd < 0) {
578 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
579 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000580 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700581
Narayan Kamath7462f022013-11-21 13:05:04 +0000582 return OpenArchiveInternal(archive, fileName);
583}
584
Elliott Hughesf66460b2019-10-22 11:44:50 -0700585int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900586 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700587 ZipArchive* archive = new ZipArchive(address, length);
588 *handle = archive;
589 return OpenArchiveInternal(archive, debug_file_name);
590}
591
Elliott Hughes26724132019-10-25 09:57:58 -0700592ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
593 ZipArchiveInfo result;
594 result.archive_size = archive->mapped_zip.GetFileLength();
595 result.entry_count = archive->num_entries;
596 return result;
597}
598
Narayan Kamath7462f022013-11-21 13:05:04 +0000599/*
600 * Close a ZipArchive, closing the file and freeing the contents.
601 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700602void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000603 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100604 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000605}
606
Tianjie85c5d232020-04-01 23:08:34 -0700607static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, const ZipEntry64* entry) {
Tianjie0ec0eaa2020-03-26 12:34:44 -0700608 // Maximum possible size for data descriptor: 2 * 4 + 2 * 8 = 24 bytes
609 uint8_t ddBuf[24];
Adam Lesinskide117e42017-06-19 10:27:38 -0700610 off64_t offset = entry->offset;
611 if (entry->method != kCompressStored) {
612 offset += entry->compressed_length;
613 } else {
614 offset += entry->uncompressed_length;
615 }
616
617 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000618 return kIoError;
619 }
620
Narayan Kamath926973e2014-06-09 14:18:14 +0100621 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Tianjie0ec0eaa2020-03-26 12:34:44 -0700622 uint8_t* ddReadPtr = (ddSignature == DataDescriptor::kOptSignature) ? ddBuf + 4 : ddBuf;
623 DataDescriptor descriptor{};
624 descriptor.crc32 = ConsumeUnaligned<uint32_t>(&ddReadPtr);
625 if (entry->zip64_format_size) {
626 descriptor.compressed_size = ConsumeUnaligned<uint64_t>(&ddReadPtr);
627 descriptor.uncompressed_size = ConsumeUnaligned<uint64_t>(&ddReadPtr);
628 } else {
629 descriptor.compressed_size = ConsumeUnaligned<uint32_t>(&ddReadPtr);
630 descriptor.uncompressed_size = ConsumeUnaligned<uint32_t>(&ddReadPtr);
631 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000632
Narayan Kamath162b7052017-06-05 13:21:12 +0100633 // Validate that the values in the data descriptor match those in the central
634 // directory.
Tianjie0ec0eaa2020-03-26 12:34:44 -0700635 if (entry->compressed_length != descriptor.compressed_size ||
636 entry->uncompressed_length != descriptor.uncompressed_size ||
637 entry->crc32 != descriptor.crc32) {
Tianjie85c5d232020-04-01 23:08:34 -0700638 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu64 ", %" PRIu64 ", %" PRIx32
Tianjie0ec0eaa2020-03-26 12:34:44 -0700639 "}, was {%" PRIu64 ", %" PRIu64 ", %" PRIx32 "}",
Narayan Kamath162b7052017-06-05 13:21:12 +0100640 entry->compressed_length, entry->uncompressed_length, entry->crc32,
Tianjie0ec0eaa2020-03-26 12:34:44 -0700641 descriptor.compressed_size, descriptor.uncompressed_size, descriptor.crc32);
Narayan Kamath162b7052017-06-05 13:21:12 +0100642 return kInconsistentInformation;
643 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000644
645 return 0;
646}
647
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800648static int32_t FindEntry(const ZipArchive* archive, std::string_view entryName,
Tianjie85c5d232020-04-01 23:08:34 -0700649 const uint64_t nameOffset, ZipEntry64* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000650 // Recover the start of the central directory entry from the filename
651 // pointer. The filename is the first entry past the fixed-size data,
652 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700653 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800654 const uint8_t* ptr = base_ptr + nameOffset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100655 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000656
657 // This is the base of our mmapped region, we have to sanity check that
658 // the name that's in the hash table is a pointer to a location within
659 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700660 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000661 ALOGW("Zip: Invalid entry pointer");
662 return kInvalidOffset;
663 }
664
Tianjie6ab29122020-03-18 17:44:30 -0700665 auto cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100666
Narayan Kamath7462f022013-11-21 13:05:04 +0000667 // The offset of the start of the central directory in the zipfile.
668 // We keep this lying around so that we can sanity check all our lengths
669 // and our per-file structures.
670 const off64_t cd_offset = archive->directory_offset;
671
672 // Fill out the compression method, modification time, crc32
673 // and other interesting attributes from the central directory. These
674 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100675 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900676 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100677 data->crc32 = cdr->crc32;
678 data->compressed_length = cdr->compressed_size;
679 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000680
681 // Figure out the local header offset from the central directory. The
682 // actual file data will begin after the local header and the name /
683 // extra comments.
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700684 off64_t local_header_offset = cdr->local_file_header_offset;
685 // One of the info field is UINT32_MAX, try to parse the real value in the zip64 extended info in
686 // the extra field.
687 if (cdr->uncompressed_size == UINT32_MAX || cdr->compressed_size == UINT32_MAX ||
688 cdr->local_file_header_offset == UINT32_MAX) {
Tianjie6ab29122020-03-18 17:44:30 -0700689 const uint8_t* extra_field = ptr + sizeof(CentralDirectoryRecord) + cdr->file_name_length;
690 Zip64ExtendedInfo zip64_info{};
691 if (auto status = ParseZip64ExtendedInfoInExtraField(
692 extra_field, cdr->extra_field_length, cdr->uncompressed_size, cdr->compressed_size,
693 cdr->local_file_header_offset, &zip64_info);
694 status != kSuccess) {
695 return status;
696 }
697
Tianjie85c5d232020-04-01 23:08:34 -0700698 data->uncompressed_length = zip64_info.uncompressed_file_size.value_or(cdr->uncompressed_size);
699 data->compressed_length = zip64_info.compressed_file_size.value_or(cdr->compressed_size);
Tianjie0ec0eaa2020-03-26 12:34:44 -0700700 local_header_offset = zip64_info.local_header_offset.value_or(local_header_offset);
701 data->zip64_format_size =
702 cdr->uncompressed_size == UINT32_MAX || cdr->compressed_size == UINT32_MAX;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700703 }
704
Narayan Kamath926973e2014-06-09 14:18:14 +0100705 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000706 ALOGW("Zip: bad local hdr offset in zip");
707 return kInvalidOffset;
708 }
709
Narayan Kamath926973e2014-06-09 14:18:14 +0100710 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700711 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800712 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900713 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000714 return kIoError;
715 }
716
Tianjie6ab29122020-03-18 17:44:30 -0700717 auto lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100718 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700719 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900720 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000721 return kInvalidOffset;
722 }
723
Tianjie6ab29122020-03-18 17:44:30 -0700724 // Check that the local file header name matches the declared name in the central directory.
725 CHECK_LE(entryName.size(), UINT16_MAX);
726 auto nameLen = static_cast<uint16_t>(entryName.size());
727 if (lfh->file_name_length != nameLen) {
728 ALOGW("Zip: lfh name length did not match central directory for %s: %" PRIu16 " %" PRIu16,
729 std::string(entryName).c_str(), lfh->file_name_length, nameLen);
730 return kInconsistentInformation;
731 }
732 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
733 if (name_offset > cd_offset - lfh->file_name_length) {
734 ALOGW("Zip: lfh name has invalid declared length");
735 return kInvalidOffset;
736 }
737
738 std::vector<uint8_t> name_buf(nameLen);
739 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
740 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
741 return kIoError;
742 }
743 if (memcmp(entryName.data(), name_buf.data(), nameLen) != 0) {
744 ALOGW("Zip: lfh name did not match central directory");
745 return kInconsistentInformation;
746 }
747
748 uint64_t lfh_uncompressed_size = lfh->uncompressed_size;
749 uint64_t lfh_compressed_size = lfh->compressed_size;
750 if (lfh_uncompressed_size == UINT32_MAX || lfh_compressed_size == UINT32_MAX) {
Tianjie0ec0eaa2020-03-26 12:34:44 -0700751 if (lfh_uncompressed_size != UINT32_MAX || lfh_compressed_size != UINT32_MAX) {
752 ALOGW(
753 "Zip: The zip64 extended field in the local header MUST include BOTH original and "
754 "compressed file size fields.");
755 return kInvalidFile;
756 }
757
Tianjie6ab29122020-03-18 17:44:30 -0700758 const off64_t lfh_extra_field_offset = name_offset + lfh->file_name_length;
759 const uint16_t lfh_extra_field_size = lfh->extra_field_length;
760 if (lfh_extra_field_offset > cd_offset - lfh_extra_field_size) {
761 ALOGW("Zip: extra field has a bad size for entry %s", std::string(entryName).c_str());
762 return kInvalidOffset;
763 }
764
765 std::vector<uint8_t> local_extra_field(lfh_extra_field_size);
766 if (!archive->mapped_zip.ReadAtOffset(local_extra_field.data(), lfh_extra_field_size,
767 lfh_extra_field_offset)) {
768 ALOGW("Zip: failed reading lfh extra field from offset %" PRId64, lfh_extra_field_offset);
769 return kIoError;
770 }
771
772 Zip64ExtendedInfo zip64_info{};
773 if (auto status = ParseZip64ExtendedInfoInExtraField(
774 local_extra_field.data(), lfh_extra_field_size, lfh->uncompressed_size,
775 lfh->compressed_size, std::nullopt, &zip64_info);
776 status != kSuccess) {
777 return status;
778 }
779
780 CHECK(zip64_info.uncompressed_file_size.has_value());
781 CHECK(zip64_info.compressed_file_size.has_value());
782 lfh_uncompressed_size = zip64_info.uncompressed_file_size.value();
783 lfh_compressed_size = zip64_info.compressed_file_size.value();
784 }
785
Narayan Kamath7462f022013-11-21 13:05:04 +0000786 // Paranoia: Match the values specified in the local file header
787 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700788
Narayan Kamath162b7052017-06-05 13:21:12 +0100789 // Warn if central directory and local file header don't agree on the use
790 // of a trailing Data Descriptor. The reference implementation is inconsistent
791 // and appears to use the LFH value during extraction (unzip) but the CD value
792 // while displayng information about archives (zipinfo). The spec remains
793 // silent on this inconsistency as well.
794 //
795 // For now, always use the version from the LFH but make sure that the values
796 // specified in the central directory match those in the data descriptor.
797 //
798 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
799 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
800 // encoded using UTF-8). This implementation does not check for the presence of
801 // that flag and always enforces that entry names are valid UTF-8.
802 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
803 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700804 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700805 }
806
807 // If there is no trailing data descriptor, verify that the central directory and local file
808 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100809 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000810 data->has_data_descriptor = 0;
Tianjie6ab29122020-03-18 17:44:30 -0700811 if (data->compressed_length != lfh_compressed_size ||
812 data->uncompressed_length != lfh_uncompressed_size || data->crc32 != lfh->crc32) {
Tianjie85c5d232020-04-01 23:08:34 -0700813 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu64 ", %" PRIu64 ", %" PRIx32
Tianjie6ab29122020-03-18 17:44:30 -0700814 "}, was {%" PRIu64 ", %" PRIu64 ", %" PRIx32 "}",
815 data->compressed_length, data->uncompressed_length, data->crc32, lfh_compressed_size,
816 lfh_uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000817 return kInconsistentInformation;
818 }
819 } else {
820 data->has_data_descriptor = 1;
821 }
822
Elliott Hughes55fd2932017-05-28 22:59:04 -0700823 // 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 -0700824 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700825 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700826 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700827 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
828 } else {
829 data->unix_mode = 0777;
830 }
831
Elliott Hughesd5095252019-10-28 21:35:52 -0700832 // 4.4.4: general purpose bit flags.
833 data->gpbf = lfh->gpb_flags;
834
Elliott Hughes26724132019-10-25 09:57:58 -0700835 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
836 // Currently only needed to implement zipinfo.
837 data->is_text = (cdr->internal_file_attributes & 1);
838
Jiyong Parkcd997e62017-06-30 17:23:33 +0900839 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
840 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000841 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800842 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000843 return kInvalidOffset;
844 }
845
Tianjie85c5d232020-04-01 23:08:34 -0700846 if (data->compressed_length > cd_offset - data_offset) {
847 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu64 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900848 static_cast<int64_t>(data_offset), data->compressed_length,
849 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000850 return kInvalidOffset;
851 }
852
Tianjie85c5d232020-04-01 23:08:34 -0700853 if (data->method == kCompressStored && data->uncompressed_length > cd_offset - data_offset) {
854 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu64 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900855 static_cast<int64_t>(data_offset), data->uncompressed_length,
856 static_cast<int64_t>(cd_offset));
857 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000858 }
859
860 data->offset = data_offset;
861 return 0;
862}
863
864struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000865 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100866
Songchun Fanc33f5262020-03-24 09:15:51 -0700867 std::function<bool(std::string_view)> matcher;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700868
869 uint32_t position = 0;
870
Songchun Fanc33f5262020-03-24 09:15:51 -0700871 IterationHandle(ZipArchive* archive, std::function<bool(std::string_view)> in_matcher)
872 : archive(archive), matcher(std::move(in_matcher)) {}
873
874 bool Match(std::string_view entry_name) const { return matcher(entry_name); }
Narayan Kamath7462f022013-11-21 13:05:04 +0000875};
876
Ryan Prichard3673f992018-10-10 22:41:14 -0700877int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700878 const std::string_view optional_prefix,
879 const std::string_view optional_suffix) {
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700880 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
881 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
882 ALOGW("Zip: prefix/suffix too long");
883 return kInvalidEntryName;
884 }
Songchun Fanc33f5262020-03-24 09:15:51 -0700885 auto matcher = [prefix = std::string(optional_prefix),
886 suffix = std::string(optional_suffix)](std::string_view name) mutable {
887 return android::base::StartsWith(name, prefix) && android::base::EndsWith(name, suffix);
888 };
889 return StartIteration(archive, cookie_ptr, std::move(matcher));
890}
891
892int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
893 std::function<bool(std::string_view)> matcher) {
894 if (archive == nullptr || archive->cd_entry_map == nullptr) {
895 ALOGW("Zip: Invalid ZipArchiveHandle");
896 return kInvalidHandle;
897 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000898
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800899 archive->cd_entry_map->ResetIteration();
Songchun Fanc33f5262020-03-24 09:15:51 -0700900 *cookie_ptr = new IterationHandle(archive, matcher);
Narayan Kamath7462f022013-11-21 13:05:04 +0000901 return 0;
902}
903
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100904void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100905 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100906}
907
Tianjie85c5d232020-04-01 23:08:34 -0700908int32_t ZipEntry::CopyFromZipEntry64(ZipEntry* dst, const ZipEntry64* src) {
909 if (src->compressed_length > UINT32_MAX || src->uncompressed_length > UINT32_MAX) {
910 ALOGW(
911 "Zip: the entry size is too large to fit into the 32 bits ZipEntry, uncompressed "
912 "length %" PRIu64 ", compressed length %" PRIu64,
913 src->uncompressed_length, src->compressed_length);
914 return kUnsupportedEntrySize;
915 }
916
917 *dst = *src;
918 dst->uncompressed_length = static_cast<uint32_t>(src->uncompressed_length);
919 dst->compressed_length = static_cast<uint32_t>(src->compressed_length);
920 return kSuccess;
921}
922
Elliott Hughesb17bf522019-05-03 22:38:44 -0700923int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
924 ZipEntry* data) {
Tianjie85c5d232020-04-01 23:08:34 -0700925 ZipEntry64 entry64;
926 if (auto status = FindEntry(archive, entryName, &entry64); status != kSuccess) {
927 return status;
928 }
929
930 return ZipEntry::CopyFromZipEntry64(data, &entry64);
931}
932
933int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
934 ZipEntry64* data) {
Elliott Hughesb17bf522019-05-03 22:38:44 -0700935 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
936 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
937 return kInvalidEntryName;
938 }
939
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800940 const auto [result, offset] =
941 archive->cd_entry_map->GetCdEntryOffset(entryName, archive->central_directory.GetBasePtr());
942 if (result != 0) {
Elliott Hughesb17bf522019-05-03 22:38:44 -0700943 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800944 return static_cast<int32_t>(result); // kEntryNotFound is safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700945 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700946 // We know there are at most hash_table_size entries, safe to truncate.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800947 return FindEntry(archive, entryName, offset, data);
Elliott Hughesb17bf522019-05-03 22:38:44 -0700948}
949
Elliott Hughese06a8082019-05-22 18:56:41 -0700950int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Tianjie85c5d232020-04-01 23:08:34 -0700951 ZipEntry64 entry64;
952 if (auto status = Next(cookie, &entry64, name); status != kSuccess) {
953 return status;
954 }
955
956 return ZipEntry::CopyFromZipEntry64(data, &entry64);
957}
958
959int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
960 ZipEntry64 entry64;
961 if (auto status = Next(cookie, &entry64, name); status != kSuccess) {
962 return status;
963 }
964
965 return ZipEntry::CopyFromZipEntry64(data, &entry64);
966}
967
968int32_t Next(void* cookie, ZipEntry64* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700969 std::string_view sv;
970 int32_t result = Next(cookie, data, &sv);
971 if (result == 0 && name) {
972 *name = std::string(sv);
973 }
974 return result;
975}
976
Tianjie85c5d232020-04-01 23:08:34 -0700977int32_t Next(void* cookie, ZipEntry64* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800978 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800979 if (handle == nullptr) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100980 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000981 return kInvalidHandle;
982 }
983
984 ZipArchive* archive = handle->archive;
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800985 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000986 ALOGW("Zip: Invalid ZipArchiveHandle");
987 return kInvalidHandle;
988 }
989
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800990 auto entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
991 while (entry != std::pair<std::string_view, uint64_t>()) {
992 const auto [entry_name, offset] = entry;
Songchun Fanc33f5262020-03-24 09:15:51 -0700993 if (handle->Match(entry_name)) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800994 const int error = FindEntry(archive, entry_name, offset, data);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700995 if (!error && name) {
996 *name = entry_name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000997 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000998 return error;
999 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -08001000 entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +00001001 }
1002
Tianjie Xu28f8eae2020-03-05 16:31:23 -08001003 archive->cd_entry_map->ResetIteration();
Narayan Kamath7462f022013-11-21 13:05:04 +00001004 return kIterationEnd;
1005}
1006
Narayan Kamathf899bd52015-04-17 11:53:14 +01001007// A Writer that writes data to a fixed size memory region.
1008// The size of the memory region must be equal to the total size of
1009// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +01001010class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001011 public:
Tianjie088c4032020-04-07 00:12:54 -07001012 static std::unique_ptr<MemoryWriter> Create(uint8_t* buf, size_t size, const ZipEntry64* entry) {
Tianjie85c5d232020-04-01 23:08:34 -07001013 const uint64_t declared_length = entry->uncompressed_length;
1014 if (declared_length > size) {
1015 ALOGW("Zip: file size %" PRIu64 " is larger than the buffer size %zu.", declared_length,
1016 size);
Tianjie088c4032020-04-07 00:12:54 -07001017 return nullptr;
Tianjie85c5d232020-04-01 23:08:34 -07001018 }
1019
Tianjie088c4032020-04-07 00:12:54 -07001020 return std::unique_ptr<MemoryWriter>(new MemoryWriter(buf, size));
Tianjie85c5d232020-04-01 23:08:34 -07001021 }
1022
Narayan Kamathf899bd52015-04-17 11:53:14 +01001023 virtual bool Append(uint8_t* buf, size_t buf_size) override {
Tianjie85c5d232020-04-01 23:08:34 -07001024 if (size_ < buf_size || bytes_written_ > size_ - buf_size) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001025 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +09001026 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001027 return false;
1028 }
1029
1030 memcpy(buf_ + bytes_written_, buf, buf_size);
1031 bytes_written_ += buf_size;
1032 return true;
1033 }
1034
1035 private:
Tianjie85c5d232020-04-01 23:08:34 -07001036 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
1037
1038 uint8_t* const buf_{nullptr};
Narayan Kamathf899bd52015-04-17 11:53:14 +01001039 const size_t size_;
1040 size_t bytes_written_;
1041};
1042
1043// A Writer that appends data to a file |fd| at its current position.
1044// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +01001045class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001046 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +01001047 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
1048 // guaranteeing that the file descriptor is valid and that there's enough
1049 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -08001050 // is truncated to the correct length (no truncation if |fd| references a
1051 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +01001052 //
1053 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Tianjie088c4032020-04-07 00:12:54 -07001054 static std::unique_ptr<FileWriter> Create(int fd, const ZipEntry64* entry) {
Tianjie85c5d232020-04-01 23:08:34 -07001055 const uint64_t declared_length = entry->uncompressed_length;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001056 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
1057 if (current_offset == -1) {
1058 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Tianjie088c4032020-04-07 00:12:54 -07001059 return nullptr;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001060 }
1061
Tianjie85c5d232020-04-01 23:08:34 -07001062 if (declared_length > SIZE_MAX || declared_length > INT64_MAX) {
1063 ALOGW("Zip: file size %" PRIu64 " is too large to extract.", declared_length);
Tianjie088c4032020-04-07 00:12:54 -07001064 return nullptr;
Tianjie85c5d232020-04-01 23:08:34 -07001065 }
1066
Narayan Kamathf899bd52015-04-17 11:53:14 +01001067#if defined(__linux__)
1068 if (declared_length > 0) {
1069 // Make sure we have enough space on the volume to extract the compressed
1070 // entry. Note that the call to ftruncate below will change the file size but
1071 // will not allocate space on disk and this call to fallocate will not
1072 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -07001073 // Note: fallocate is only supported by the following filesystems -
1074 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
1075 // EOPNOTSUPP error when issued in other filesystems.
1076 // Hence, check for the return error code before concluding that the
1077 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001078 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -07001079 if (result == -1 && errno == ENOSPC) {
Tianjie85c5d232020-04-01 23:08:34 -07001080 ALOGW("Zip: unable to allocate %" PRIu64 " bytes at offset %" PRId64 ": %s",
1081 declared_length, static_cast<int64_t>(current_offset), strerror(errno));
Tianjie088c4032020-04-07 00:12:54 -07001082 return nullptr;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001083 }
1084 }
1085#endif // __linux__
1086
Tao Baoa456c212016-11-15 10:08:07 -08001087 struct stat sb;
1088 if (fstat(fd, &sb) == -1) {
1089 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Tianjie088c4032020-04-07 00:12:54 -07001090 return nullptr;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001091 }
1092
Tao Baoa456c212016-11-15 10:08:07 -08001093 // Block device doesn't support ftruncate(2).
1094 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001095 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -08001096 if (result == -1) {
1097 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
1098 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Tianjie088c4032020-04-07 00:12:54 -07001099 return nullptr;
Tao Baoa456c212016-11-15 10:08:07 -08001100 }
1101 }
1102
Tianjie088c4032020-04-07 00:12:54 -07001103 return std::unique_ptr<FileWriter>(new FileWriter(fd, declared_length));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001104 }
1105
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -07001106 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001107 : fd_(other.fd_),
1108 declared_length_(other.declared_length_),
1109 total_bytes_written_(other.total_bytes_written_) {
1110 other.fd_ = -1;
1111 }
1112
Narayan Kamathf899bd52015-04-17 11:53:14 +01001113 virtual bool Append(uint8_t* buf, size_t buf_size) override {
Tianjie85c5d232020-04-01 23:08:34 -07001114 if (declared_length_ < buf_size || total_bytes_written_ > declared_length_ - buf_size) {
1115 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +09001116 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001117 return false;
1118 }
1119
Narayan Kamathe97e66e2015-04-27 16:25:53 +01001120 const bool result = android::base::WriteFully(fd_, buf, buf_size);
1121 if (result) {
1122 total_bytes_written_ += buf_size;
1123 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001124 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001125 }
1126
Narayan Kamathe97e66e2015-04-27 16:25:53 +01001127 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001128 }
Jiyong Parkcd997e62017-06-30 17:23:33 +09001129
Narayan Kamathf899bd52015-04-17 11:53:14 +01001130 private:
Tianjie85c5d232020-04-01 23:08:34 -07001131 explicit FileWriter(const int fd = -1, const uint64_t declared_length = 0)
1132 : Writer(),
1133 fd_(fd),
1134 declared_length_(static_cast<size_t>(declared_length)),
1135 total_bytes_written_(0) {
1136 CHECK_LE(declared_length, SIZE_MAX);
1137 }
Narayan Kamathf899bd52015-04-17 11:53:14 +01001138
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001139 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001140 const size_t declared_length_;
1141 size_t total_bytes_written_;
1142};
1143
Narayan Kamath485b3642017-10-26 14:42:39 +01001144class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001145 public:
Tianjie85c5d232020-04-01 23:08:34 -07001146 EntryReader(const MappedZipFile& zip_file, const ZipEntry64* entry)
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001147 : Reader(), zip_file_(zip_file), entry_(entry) {}
1148
Tianjie85c5d232020-04-01 23:08:34 -07001149 virtual bool ReadAtOffset(uint8_t* buf, size_t len, off64_t offset) const {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001150 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
1151 }
1152
1153 virtual ~EntryReader() {}
1154
1155 private:
1156 const MappedZipFile& zip_file_;
Tianjie85c5d232020-04-01 23:08:34 -07001157 const ZipEntry64* entry_;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001158};
1159
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -08001160// This method is using libz macros with old-style-casts
1161#pragma GCC diagnostic push
1162#pragma GCC diagnostic ignored "-Wold-style-cast"
1163static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
1164 return inflateInit2(stream, window_bits);
1165}
1166#pragma GCC diagnostic pop
1167
Narayan Kamath485b3642017-10-26 14:42:39 +01001168namespace zip_archive {
1169
1170// Moved out of line to avoid -Wweak-vtables.
1171Reader::~Reader() {}
1172Writer::~Writer() {}
1173
Tianjie85c5d232020-04-01 23:08:34 -07001174int32_t Inflate(const Reader& reader, const uint64_t compressed_length,
1175 const uint64_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001176 const size_t kBufSize = 32768;
1177 std::vector<uint8_t> read_buf(kBufSize);
1178 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +00001179 z_stream zstream;
1180 int zerr;
1181
1182 /*
1183 * Initialize the zlib stream struct.
1184 */
1185 memset(&zstream, 0, sizeof(zstream));
1186 zstream.zalloc = Z_NULL;
1187 zstream.zfree = Z_NULL;
1188 zstream.opaque = Z_NULL;
1189 zstream.next_in = NULL;
1190 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001191 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001192 zstream.avail_out = kBufSize;
1193 zstream.data_type = Z_UNKNOWN;
1194
1195 /*
1196 * Use the undocumented "negative window bits" feature to tell zlib
1197 * that there's no zlib header waiting for it.
1198 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -08001199 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +00001200 if (zerr != Z_OK) {
1201 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001202 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +00001203 } else {
1204 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
1205 }
1206
1207 return kZlibError;
1208 }
1209
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001210 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001211 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001212 };
1213
1214 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1215
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001216 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -07001217 uLong crc = 0;
Tianjie85c5d232020-04-01 23:08:34 -07001218 uint64_t remaining_bytes = compressed_length;
1219 uint64_t total_output = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001220 do {
1221 /* read as much as we can */
1222 if (zstream.avail_in == 0) {
Tianjie85c5d232020-04-01 23:08:34 -07001223 const uint32_t read_size =
1224 (remaining_bytes > kBufSize) ? kBufSize : static_cast<uint32_t>(remaining_bytes);
1225 const off64_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001226 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001227 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001228 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001229 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001230 }
1231
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001232 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001233
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001234 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001235 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001236 }
1237
1238 /* uncompress the data */
1239 zerr = inflate(&zstream, Z_NO_FLUSH);
1240 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001241 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1242 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001243 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001244 }
1245
1246 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001247 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001248 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001249 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001250 return kIoError;
1251 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001252 DCHECK_LE(write_size, kBufSize);
1253 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +00001254 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001255
Tianjie85c5d232020-04-01 23:08:34 -07001256 total_output += kBufSize - zstream.avail_out;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001257 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001258 zstream.avail_out = kBufSize;
1259 }
1260 } while (zerr == Z_OK);
1261
Elliott Hughese8f4b142018-10-19 16:09:39 -07001262 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001263
Narayan Kamath162b7052017-06-05 13:21:12 +01001264 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1265 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1266 // doesn't bother calculating the checksum in that scenario. We just do
1267 // it ourselves above because there are no additional gains to be made by
1268 // having zlib calculate it for us, since they do it by calling crc32 in
1269 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001270 if (compute_crc) {
1271 *crc_out = crc;
1272 }
Tianjie85c5d232020-04-01 23:08:34 -07001273 if (total_output != uncompressed_length || remaining_bytes != 0) {
1274 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu64 ")", zstream.total_out,
Jiyong Parkcd997e62017-06-30 17:23:33 +09001275 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001276 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001277 }
1278
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001279 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001280}
Narayan Kamath485b3642017-10-26 14:42:39 +01001281} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001282
Tianjie85c5d232020-04-01 23:08:34 -07001283static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry64* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001284 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001285 const EntryReader reader(mapped_zip, entry);
1286
Narayan Kamath485b3642017-10-26 14:42:39 +01001287 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1288 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001289}
1290
Tianjie85c5d232020-04-01 23:08:34 -07001291static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry64* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001292 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001293 static const uint32_t kBufSize = 32768;
1294 std::vector<uint8_t> buf(kBufSize);
1295
Tianjie85c5d232020-04-01 23:08:34 -07001296 const uint64_t length = entry->uncompressed_length;
1297 uint64_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -07001298 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001299 while (count < length) {
Tianjie85c5d232020-04-01 23:08:34 -07001300 uint64_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001301 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001302
Adam Lesinskide117e42017-06-19 10:27:38 -07001303 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Tianjie85c5d232020-04-01 23:08:34 -07001304 const uint32_t block_size =
1305 (remaining > kBufSize) ? kBufSize : static_cast<uint32_t>(remaining);
Adam Lesinskide117e42017-06-19 10:27:38 -07001306
1307 // Make sure to read at offset to ensure concurrent access to the fd.
1308 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001309 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -07001310 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001311 return kIoError;
1312 }
1313
1314 if (!writer->Append(&buf[0], block_size)) {
1315 return kIoError;
1316 }
Yurii Zubrytskyi8d8f6372020-04-06 19:35:33 -07001317 if (crc_out) {
1318 crc = crc32(crc, &buf[0], block_size);
1319 }
Narayan Kamathf899bd52015-04-17 11:53:14 +01001320 count += block_size;
1321 }
1322
Yurii Zubrytskyi8d8f6372020-04-06 19:35:33 -07001323 if (crc_out) {
1324 *crc_out = crc;
1325 }
Narayan Kamathf899bd52015-04-17 11:53:14 +01001326
1327 return 0;
1328}
1329
Tianjie85c5d232020-04-01 23:08:34 -07001330int32_t ExtractToWriter(ZipArchiveHandle handle, const ZipEntry64* entry,
1331 zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001332 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001333
1334 // this should default to kUnknownCompressionMethod.
1335 int32_t return_value = -1;
1336 uint64_t crc = 0;
1337 if (method == kCompressStored) {
Yurii Zubrytskyi8d8f6372020-04-06 19:35:33 -07001338 return_value =
1339 CopyEntryToWriter(handle->mapped_zip, entry, writer, kCrcChecksEnabled ? &crc : nullptr);
Narayan Kamath7462f022013-11-21 13:05:04 +00001340 } else if (method == kCompressDeflated) {
Yurii Zubrytskyi8d8f6372020-04-06 19:35:33 -07001341 return_value =
1342 InflateEntryToWriter(handle->mapped_zip, entry, writer, kCrcChecksEnabled ? &crc : nullptr);
Narayan Kamath7462f022013-11-21 13:05:04 +00001343 }
1344
1345 if (!return_value && entry->has_data_descriptor) {
Tianjie85c5d232020-04-01 23:08:34 -07001346 return_value = ValidateDataDescriptor(handle->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001347 if (return_value) {
1348 return return_value;
1349 }
1350 }
1351
Narayan Kamath162b7052017-06-05 13:21:12 +01001352 // Validate that the CRC matches the calculated value.
1353 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001354 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001355 return kInconsistentInformation;
1356 }
1357
1358 return return_value;
1359}
1360
Tianjie85c5d232020-04-01 23:08:34 -07001361int32_t ExtractToMemory(ZipArchiveHandle archive, const ZipEntry* entry, uint8_t* begin,
1362 size_t size) {
1363 ZipEntry64 entry64(*entry);
1364 return ExtractToMemory(archive, &entry64, begin, size);
1365}
1366
1367int32_t ExtractToMemory(ZipArchiveHandle archive, const ZipEntry64* entry, uint8_t* begin,
1368 size_t size) {
1369 auto writer = MemoryWriter::Create(begin, size, entry);
Tianjie088c4032020-04-07 00:12:54 -07001370 if (!writer) {
Tianjie85c5d232020-04-01 23:08:34 -07001371 return kIoError;
1372 }
1373
Tianjie088c4032020-04-07 00:12:54 -07001374 return ExtractToWriter(archive, entry, writer.get());
Narayan Kamathf899bd52015-04-17 11:53:14 +01001375}
1376
Tianjie85c5d232020-04-01 23:08:34 -07001377int32_t ExtractEntryToFile(ZipArchiveHandle archive, const ZipEntry* entry, int fd) {
1378 ZipEntry64 entry64(*entry);
1379 return ExtractEntryToFile(archive, &entry64, fd);
1380}
1381
1382int32_t ExtractEntryToFile(ZipArchiveHandle archive, const ZipEntry64* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001383 auto writer = FileWriter::Create(fd, entry);
Tianjie088c4032020-04-07 00:12:54 -07001384 if (!writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001385 return kIoError;
1386 }
1387
Tianjie088c4032020-04-07 00:12:54 -07001388 return ExtractToWriter(archive, entry, writer.get());
Narayan Kamath7462f022013-11-21 13:05:04 +00001389}
1390
Ryan Prichard3673f992018-10-10 22:41:14 -07001391int GetFileDescriptor(const ZipArchiveHandle archive) {
1392 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001393}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001394
Ryan Mitchell23150e42020-03-09 09:33:46 -07001395off64_t GetFileDescriptorOffset(const ZipArchiveHandle archive) {
1396 return archive->mapped_zip.GetFileOffset();
1397}
1398
Tianjie Xu18c25922016-09-29 15:27:41 -07001399#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001400class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001401 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001402 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1403 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001404
1405 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1406 return proc_function_(buf, buf_size, cookie_);
1407 }
1408
1409 private:
1410 ProcessZipEntryFunction proc_function_;
1411 void* cookie_;
1412};
1413
Tianjie85c5d232020-04-01 23:08:34 -07001414int32_t ProcessZipEntryContents(ZipArchiveHandle archive, const ZipEntry* entry,
1415 ProcessZipEntryFunction func, void* cookie) {
1416 ZipEntry64 entry64(*entry);
1417 return ProcessZipEntryContents(archive, &entry64, func, cookie);
1418}
1419
1420int32_t ProcessZipEntryContents(ZipArchiveHandle archive, const ZipEntry64* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001421 ProcessZipEntryFunction func, void* cookie) {
1422 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001423 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001424}
1425
Jiyong Parkcd997e62017-06-30 17:23:33 +09001426#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001427
1428int MappedZipFile::GetFileDescriptor() const {
1429 if (!has_fd_) {
1430 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1431 return -1;
1432 }
1433 return fd_;
1434}
1435
Elliott Hughesf66460b2019-10-22 11:44:50 -07001436const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001437 if (has_fd_) {
1438 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1439 return nullptr;
1440 }
1441 return base_ptr_;
1442}
1443
Ryan Mitchell23150e42020-03-09 09:33:46 -07001444off64_t MappedZipFile::GetFileOffset() const {
1445 return fd_offset_;
1446}
1447
Tianjie Xu18c25922016-09-29 15:27:41 -07001448off64_t MappedZipFile::GetFileLength() const {
1449 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001450 if (data_length_ != -1) {
1451 return data_length_;
1452 }
1453 data_length_ = lseek64(fd_, 0, SEEK_END);
1454 if (data_length_ == -1) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001455 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1456 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001457 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001458 } else {
1459 if (base_ptr_ == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001460 ALOGE("Zip: invalid file map");
Tianjie Xu18c25922016-09-29 15:27:41 -07001461 return -1;
1462 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001463 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001464 }
1465}
1466
Tianjie Xu18c25922016-09-29 15:27:41 -07001467// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001468bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001469 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001470 if (off < 0) {
1471 ALOGE("Zip: invalid offset %" PRId64, off);
1472 return false;
1473 }
1474
1475 off64_t read_offset;
1476 if (__builtin_add_overflow(fd_offset_, off, &read_offset)) {
1477 ALOGE("Zip: invalid read offset %" PRId64 " overflows, fd offset %" PRId64, off, fd_offset_);
1478 return false;
1479 }
1480
1481 if (data_length_ != -1) {
1482 off64_t read_end;
1483 if (len > std::numeric_limits<off64_t>::max() ||
1484 __builtin_add_overflow(off, static_cast<off64_t>(len), &read_end)) {
1485 ALOGE("Zip: invalid read length %" PRId64 " overflows, offset %" PRId64,
1486 static_cast<off64_t>(len), off);
1487 return false;
1488 }
1489
1490 if (read_end > data_length_) {
1491 ALOGE("Zip: invalid read length %" PRId64 " exceeds data length %" PRId64 ", offset %"
1492 PRId64, static_cast<off64_t>(len), data_length_, off);
1493 return false;
1494 }
1495 }
1496
1497 if (!android::base::ReadFullyAtOffset(fd_, buf, len, read_offset)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001498 ALOGE("Zip: failed to read at offset %" PRId64, off);
Tianjie Xu18c25922016-09-29 15:27:41 -07001499 return false;
1500 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001501 } else {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001502 if (off < 0 || off > data_length_) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001503 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64, off, data_length_);
Adam Lesinskide117e42017-06-19 10:27:38 -07001504 return false;
1505 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001506 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001507 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001508 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001509}
1510
Elliott Hughesf66460b2019-10-22 11:44:50 -07001511void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1512 size_t cd_size) {
1513 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001514 length_ = cd_size;
1515}
1516
Elliott Hughese8f4b142018-10-19 16:09:39 -07001517bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001518 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001519 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
Ryan Mitchell23150e42020-03-09 09:33:46 -07001520 mapped_zip.GetFileOffset() + cd_start_offset,
1521 cd_size, PROT_READ);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001522 if (!directory_map) {
1523 ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1524 cd_start_offset, cd_size, strerror(errno));
1525 return false;
1526 }
Tianjie Xu18c25922016-09-29 15:27:41 -07001527
Elliott Hughese8f4b142018-10-19 16:09:39 -07001528 CHECK_EQ(directory_map->size(), cd_size);
1529 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001530 } else {
1531 if (mapped_zip.GetBasePtr() == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001532 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
Tianjie Xu18c25922016-09-29 15:27:41 -07001533 return false;
1534 }
1535 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1536 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001537 ALOGE(
1538 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1539 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1540 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001541 return false;
1542 }
1543
1544 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1545 }
1546 return true;
1547}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001548
Tianjie85c5d232020-04-01 23:08:34 -07001549tm ZipEntryCommon::GetModificationTime() const {
Elliott Hughes55fd2932017-05-28 22:59:04 -07001550 tm t = {};
1551
1552 t.tm_hour = (mod_time >> 11) & 0x1f;
1553 t.tm_min = (mod_time >> 5) & 0x3f;
1554 t.tm_sec = (mod_time & 0x1f) << 1;
1555
1556 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1557 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1558 t.tm_mday = (mod_time >> 16) & 0x1f;
1559
1560 return t;
1561}