blob: 9812026b4a2769addfd4e848059c521b3ba14c36 [file] [log] [blame]
Narayan Kamath7462f022013-11-21 13:05:04 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Read-only access to Zip archives, with minimal heap allocation.
19 */
Narayan Kamath7462f022013-11-21 13:05:04 +000020
Mark Salyzyncfd5b082016-10-17 14:28:00 -070021#define LOG_TAG "ziparchive"
22
Elliott Hughese8f4b142018-10-19 16:09:39 -070023#include "ziparchive/zip_archive.h"
24
Narayan Kamath7462f022013-11-21 13:05:04 +000025#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070026#include <fcntl.h>
27#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000029#include <stdlib.h>
30#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070031#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000032#include <unistd.h>
33
Dan Albert1ae07642015-04-09 14:11:18 -070034#include <memory>
Songchun Fanc33f5262020-03-24 09:15:51 -070035#include <optional>
Dan Albert1ae07642015-04-09 14:11:18 -070036#include <vector>
37
Elliott Hughes9c8bd662018-10-26 16:14:21 -070038#if defined(__APPLE__)
39#define lseek64 lseek
40#endif
41
Josh Gao1b496342018-07-17 11:08:48 -070042#if defined(__BIONIC__)
43#include <android/fdsan.h>
44#endif
45
Mark Salyzynff2dcd92016-09-28 15:54:45 -070046#include <android-base/file.h>
47#include <android-base/logging.h>
48#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
Elliott Hughese8f4b142018-10-19 16:09:39 -070049#include <android-base/mapped_file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070050#include <android-base/memory.h>
Elliott Hughes50ef29a2019-06-18 18:23:59 -070051#include <android-base/strings.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070052#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070053#include <log/log.h>
Dan Albert1ae07642015-04-09 14:11:18 -070054#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000055
Narayan Kamath044bc8e2014-12-03 18:22:53 +000056#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070057#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080058#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070059
Dan Albert1ae07642015-04-09 14:11:18 -070060using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000061
Narayan Kamath162b7052017-06-05 13:21:12 +010062// Used to turn on crc checks - verify that the content CRC matches the values
63// specified in the local file header and the central directory.
64static const bool kCrcChecksEnabled = false;
65
Narayan Kamath926973e2014-06-09 14:18:14 +010066// The maximum number of bytes to scan backwards for the EOCD start.
67static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
68
Tianjie Xu69ee4b72020-03-11 11:59:10 -070069// Set a reasonable cap (256 GiB) for the zip file size. So the data is always valid when
70// we parse the fields in cd or local headers as 64 bits signed integers.
71static constexpr uint64_t kMaxFileLength = 256 * static_cast<uint64_t>(1u << 30u);
72
Narayan Kamath7462f022013-11-21 13:05:04 +000073/*
74 * A Read-only Zip archive.
75 *
76 * We want "open" and "find entry by name" to be fast operations, and
77 * we want to use as little memory as possible. We memory-map the zip
78 * central directory, and load a hash table with pointers to the filenames
79 * (which aren't null-terminated). The other fields are at a fixed offset
80 * from the filename, so we don't need to extract those (but we do need
81 * to byte-read and endian-swap them every time we want them).
82 *
83 * It's possible that somebody has handed us a massive (~1GB) zip archive,
84 * so we can't expect to mmap the entire file.
85 *
86 * To speed comparisons when doing a lookup by name, we could make the mapping
87 * "private" (copy-on-write) and null-terminate the filenames after verifying
88 * the record structure. However, this requires a private mapping of
89 * every page that the Central Directory touches. Easier to tuck a copy
90 * of the string length into the hash table entry.
91 */
Narayan Kamath7462f022013-11-21 13:05:04 +000092
Josh Gaoabdfc242018-09-07 12:44:40 -070093#if defined(__BIONIC__)
94uint64_t GetOwnerTag(const ZipArchive* archive) {
95 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
96 reinterpret_cast<uint64_t>(archive));
97}
98#endif
99
Ryan Mitchell23150e42020-03-09 09:33:46 -0700100ZipArchive::ZipArchive(MappedZipFile&& map, bool assume_ownership)
101 : mapped_zip(map),
Josh Gao1b496342018-07-17 11:08:48 -0700102 close_file(assume_ownership),
103 directory_offset(0),
104 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700105 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800106 num_entries(0) {
Josh Gao1b496342018-07-17 11:08:48 -0700107#if defined(__BIONIC__)
108 if (assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700109 CHECK(mapped_zip.HasFd());
110 android_fdsan_exchange_owner_tag(mapped_zip.GetFileDescriptor(), 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700111 }
112#endif
113}
114
Elliott Hughesf66460b2019-10-22 11:44:50 -0700115ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700116 : mapped_zip(address, length),
117 close_file(false),
118 directory_offset(0),
119 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700120 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800121 num_entries(0) {}
Josh Gao1b496342018-07-17 11:08:48 -0700122
123ZipArchive::~ZipArchive() {
124 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
125#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700126 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700127#else
128 close(mapped_zip.GetFileDescriptor());
129#endif
130 }
Josh Gao1b496342018-07-17 11:08:48 -0700131}
132
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700133struct CentralDirectoryInfo {
134 uint64_t num_records;
135 // The size of the central directory (in bytes).
136 uint64_t cd_size;
137 // The offset of the start of the central directory, relative
138 // to the start of the file.
139 uint64_t cd_start_offset;
140};
141
Tianjie6ab29122020-03-18 17:44:30 -0700142static ZipError FindCentralDirectoryInfoForZip64(const char* debugFileName, ZipArchive* archive,
143 off64_t eocdOffset, CentralDirectoryInfo* cdInfo) {
144 if (eocdOffset <= sizeof(Zip64EocdLocator)) {
145 ALOGW("Zip: %s: Not enough space for zip64 eocd locator", debugFileName);
146 return kInvalidFile;
147 }
148 // We expect to find the zip64 eocd locator immediately before the zip eocd.
149 const int64_t locatorOffset = eocdOffset - sizeof(Zip64EocdLocator);
150 Zip64EocdLocator zip64EocdLocator{};
151 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>((&zip64EocdLocator)),
152 sizeof(Zip64EocdLocator), locatorOffset)) {
153 ALOGW("Zip: %s: Read %zu from offset %" PRId64 " failed %s", debugFileName,
154 sizeof(Zip64EocdLocator), locatorOffset, debugFileName);
155 return kIoError;
156 }
157
158 if (zip64EocdLocator.locator_signature != Zip64EocdLocator::kSignature) {
159 ALOGW("Zip: %s: Zip64 eocd locator signature not found at offset %" PRId64, debugFileName,
160 locatorOffset);
161 return kInvalidFile;
162 }
163
164 const int64_t zip64EocdOffset = zip64EocdLocator.zip64_eocd_offset;
165 if (zip64EocdOffset > locatorOffset - sizeof(Zip64EocdRecord)) {
166 ALOGW("Zip: %s: Bad zip64 eocd offset %" PRIu64, debugFileName, zip64EocdOffset);
167 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,
174 sizeof(Zip64EocdLocator), static_cast<int64_t>(zip64EocdOffset), debugFileName);
175 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
184 if (zip64EocdRecord.cd_start_offset > zip64EocdOffset - zip64EocdRecord.cd_size) {
185 ALOGW("Zip: %s: Bad offset for zip64 central directory. cd offset %" PRIu64 ", cd size %" PRIu64
186 ", zip64 eocd offset %" PRIu64,
187 debugFileName, zip64EocdRecord.cd_start_offset, zip64EocdRecord.cd_size, zip64EocdOffset);
188 return kInvalidOffset;
189 }
190
191 *cdInfo = {.num_records = zip64EocdRecord.num_records,
192 .cd_size = zip64EocdRecord.cd_size,
193 .cd_start_offset = zip64EocdRecord.cd_start_offset};
194
195 return kSuccess;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700196}
197
198static ZipError FindCentralDirectoryInfo(const char* debug_file_name, ZipArchive* archive,
199 off64_t file_length, uint32_t read_amount,
200 CentralDirectoryInfo* cdInfo) {
201 std::vector<uint8_t> scan_buffer(read_amount);
Narayan Kamath7462f022013-11-21 13:05:04 +0000202 const off64_t search_start = file_length - read_amount;
203
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700204 if (!archive->mapped_zip.ReadAtOffset(scan_buffer.data(), read_amount, search_start)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900205 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
206 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000207 return kIoError;
208 }
209
210 /*
211 * Scan backward for the EOCD magic. In an archive without a trailing
212 * comment, we'll find it on the first try. (We may want to consider
213 * doing an initial minimal read; if we don't find it, retry with a
214 * second read as above.)
215 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700216 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
217 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100218 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700219 if (scan_buffer[i] == 0x50) {
220 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
221 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
222 ALOGV("+++ Found EOCD at buf+%d", i);
223 break;
224 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000225 }
226 }
227 if (i < 0) {
228 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
229 return kInvalidFile;
230 }
231
232 const off64_t eocd_offset = search_start + i;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700233 auto eocd = reinterpret_cast<const EocdRecord*>(scan_buffer.data() + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000234 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100235 * Verify that there's no trailing space at the end of the central directory
236 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000237 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900238 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100239 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100240 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100241 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100242 return kInvalidFile;
243 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000244
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700245 // One of the field is 0xFFFFFFFF, look for the zip64 EOCD instead.
246 if (eocd->cd_size == UINT32_MAX || eocd->cd_start_offset == UINT32_MAX) {
247 ALOGV("Looking for the zip64 EOCD, cd_size: %" PRIu32 "cd_start_offset: %" PRId32,
248 eocd->cd_size, eocd->cd_start_offset);
Tianjie6ab29122020-03-18 17:44:30 -0700249 return FindCentralDirectoryInfoForZip64(debug_file_name, archive, eocd_offset, cdInfo);
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700250 }
251
Narayan Kamath926973e2014-06-09 14:18:14 +0100252 /*
253 * Grab the CD offset and size, and the number of entries in the
254 * archive and verify that they look reasonable.
255 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700256 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100257 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900258 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000259 return kInvalidOffset;
260 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000261
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700262 *cdInfo = {.num_records = eocd->num_records,
263 .cd_size = eocd->cd_size,
264 .cd_start_offset = eocd->cd_start_offset};
265 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000266}
267
268/*
269 * Find the zip Central Directory and memory-map it.
270 *
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700271 * On success, returns kSuccess after populating fields from the EOCD area:
Narayan Kamath7462f022013-11-21 13:05:04 +0000272 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700273 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000274 * num_entries
275 */
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700276static ZipError MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
277 // 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 -0700278 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000279 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000280 return kInvalidFile;
281 }
282
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700283 if (file_length > kMaxFileLength) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100284 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000285 return kInvalidFile;
286 }
287
Narayan Kamath926973e2014-06-09 14:18:14 +0100288 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
289 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000290 return kInvalidFile;
291 }
292
293 /*
294 * Perform the traditional EOCD snipe hunt.
295 *
296 * We're searching for the End of Central Directory magic number,
297 * which appears at the start of the EOCD block. It's followed by
298 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
299 * need to read the last part of the file into a buffer, dig through
300 * it to find the magic number, parse some values out, and use those
301 * to determine the extent of the CD.
302 *
303 * We start by pulling in the last part of the file.
304 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700305 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100306 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700307 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000308 }
309
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700310 CentralDirectoryInfo cdInfo = {};
311 if (auto result =
312 FindCentralDirectoryInfo(debug_file_name, archive, file_length, read_amount, &cdInfo);
313 result != kSuccess) {
314 return result;
315 }
316
317 if (cdInfo.num_records == 0) {
318#if defined(__ANDROID__)
319 ALOGW("Zip: empty archive?");
320#endif
321 return kEmptyArchive;
322 }
323
324 if (cdInfo.cd_size >= SIZE_MAX) {
325 ALOGW("Zip: The size of central directory doesn't fit in range of size_t: %" PRIu64,
326 cdInfo.cd_size);
327 return kInvalidFile;
328 }
329
330 ALOGV("+++ num_entries=%" PRIu64 " dir_size=%" PRIu64 " dir_offset=%" PRIu64, cdInfo.num_records,
331 cdInfo.cd_size, cdInfo.cd_start_offset);
332
333 // It all looks good. Create a mapping for the CD, and set the fields in archive.
334 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(cdInfo.cd_start_offset),
335 static_cast<size_t>(cdInfo.cd_size))) {
336 return kMmapFailed;
337 }
338
339 archive->num_entries = cdInfo.num_records;
340 archive->directory_offset = cdInfo.cd_start_offset;
341
342 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000343}
344
Tianjie6ab29122020-03-18 17:44:30 -0700345static ZipError ParseZip64ExtendedInfoInExtraField(
346 const uint8_t* extraFieldStart, uint16_t extraFieldLength, uint32_t zip32UncompressedSize,
347 uint32_t zip32CompressedSize, std::optional<uint32_t> zip32LocalFileHeaderOffset,
348 Zip64ExtendedInfo* zip64Info) {
349 if (extraFieldLength <= 4) {
350 ALOGW("Zip: Extra field isn't large enough to hold zip64 info, size %" PRIu16,
351 extraFieldLength);
352 return kInvalidFile;
353 }
354
355 // Each header MUST consist of:
356 // Header ID - 2 bytes
357 // Data Size - 2 bytes
358 uint16_t offset = 0;
359 while (offset < extraFieldLength - 4) {
360 auto headerId = get_unaligned<uint16_t>(extraFieldStart + offset);
361 auto dataSize = get_unaligned<uint16_t>(extraFieldStart + offset + 2);
362
363 offset += 4;
364 if (dataSize > extraFieldLength - offset) {
365 ALOGW("Zip: Data size exceeds the boundary of extra field, data size %" PRIu16, dataSize);
366 return kInvalidOffset;
367 }
368
369 // Skip the other types of extensible data fields. Details in
370 // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT section 4.5
371 if (headerId != Zip64ExtendedInfo::kHeaderId) {
372 offset += dataSize;
373 continue;
374 }
375
376 uint16_t expectedDataSize = 0;
377 // We expect the extended field to include both uncompressed and compressed size.
378 if (zip32UncompressedSize == UINT32_MAX || zip32CompressedSize == UINT32_MAX) {
379 expectedDataSize += 16;
380 }
381 if (zip32LocalFileHeaderOffset == UINT32_MAX) {
382 expectedDataSize += 8;
383 }
384
385 if (expectedDataSize == 0) {
386 ALOGW("Zip: Data size should not be 0 in zip64 extended field");
387 return kInvalidFile;
388 }
389
390 if (dataSize != expectedDataSize) {
391 auto localOffsetString = zip32LocalFileHeaderOffset.has_value()
392 ? std::to_string(zip32LocalFileHeaderOffset.value())
393 : "missing";
394 ALOGW("Zip: Invalid data size in zip64 extended field, expect %" PRIu16 ", get %" PRIu16
395 ", uncompressed size %" PRIu32 ", compressed size %" PRIu32 ", local header offset %s",
396 expectedDataSize, dataSize, zip32UncompressedSize, zip32CompressedSize,
397 localOffsetString.c_str());
398 return kInvalidFile;
399 }
400
401 std::optional<uint64_t> uncompressedFileSize;
402 std::optional<uint64_t> compressedFileSize;
403 std::optional<uint64_t> localHeaderOffset;
404 if (zip32UncompressedSize == UINT32_MAX || zip32CompressedSize == UINT32_MAX) {
405 uncompressedFileSize = get_unaligned<uint64_t>(extraFieldStart + offset);
406 compressedFileSize = get_unaligned<uint64_t>(extraFieldStart + offset + 8);
407 offset += 16;
408
409 // TODO(xunchang) Support handling file large than UINT32_MAX. It's theoretically possible
410 // for libz to (de)compressing file larger than UINT32_MAX. But we should use our own
411 // bytes counter to replace stream.total_out.
412 if (uncompressedFileSize.value() >= UINT32_MAX || compressedFileSize.value() >= UINT32_MAX) {
413 ALOGW(
414 "Zip: File size larger than UINT32_MAX isn't supported yet. uncompressed size %" PRIu64
415 ", compressed size %" PRIu64,
416 uncompressedFileSize.value(), compressedFileSize.value());
417 return kInvalidFile;
418 }
419 }
420
421 if (zip32LocalFileHeaderOffset == UINT32_MAX) {
422 localHeaderOffset = get_unaligned<uint64_t>(extraFieldStart + offset);
423 offset += 8;
424 }
425
426 zip64Info->uncompressed_file_size = uncompressedFileSize;
427 zip64Info->compressed_file_size = compressedFileSize;
428 zip64Info->local_header_offset = localHeaderOffset;
429 return kSuccess;
430 }
431
432 ALOGW("Zip: zip64 extended info isn't found in the extra field.");
433 return kInvalidFile;
434}
435
Narayan Kamath7462f022013-11-21 13:05:04 +0000436/*
437 * Parses the Zip archive's Central Directory. Allocates and populates the
438 * hash table.
439 *
440 * Returns 0 on success.
441 */
Tianjie6ab29122020-03-18 17:44:30 -0700442static ZipError ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700443 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
444 const size_t cd_length = archive->central_directory.GetMapLength();
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700445 const uint64_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000446
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700447 if (num_entries <= UINT16_MAX) {
448 archive->cd_entry_map = CdEntryMapZip32::Create(static_cast<uint16_t>(num_entries));
Tianjie Xu0ef97832020-03-15 21:23:24 -0700449 } else {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700450 archive->cd_entry_map = CdEntryMapZip64::Create();
Tianjie Xu0ef97832020-03-15 21:23:24 -0700451 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800452 if (archive->cd_entry_map == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800453 return kAllocationFailed;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700454 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000455
456 /*
457 * Walk through the central directory, adding entries to the hash
458 * table and verifying values.
459 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100460 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000461 const uint8_t* ptr = cd_ptr;
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700462 for (uint64_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700463 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700464 ALOGW("Zip: ran off the end (item #%" PRIu64 ", %zu bytes of central directory)", i,
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800465 cd_length);
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700466#if defined(__ANDROID__)
467 android_errorWriteLog(0x534e4554, "36392138");
468#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800469 return kInvalidFile;
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700470 }
471
Tianjie6ab29122020-03-18 17:44:30 -0700472 auto cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100473 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700474 ALOGW("Zip: missed a central dir sig (at %" PRIu64 ")", i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800475 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000476 }
477
Narayan Kamath926973e2014-06-09 14:18:14 +0100478 const uint16_t file_name_length = cdr->file_name_length;
479 const uint16_t extra_length = cdr->extra_field_length;
480 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100481 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
482
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700483 if (file_name_length >= cd_length || file_name > cd_end - file_name_length) {
484 ALOGW("Zip: file name for entry %" PRIu64
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700485 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
486 i, file_name_length, cd_length);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800487 return kInvalidEntryName;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700488 }
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700489
490 const uint8_t* extra_field = file_name + file_name_length;
491 if (extra_length >= cd_length || extra_field > cd_end - extra_length) {
492 ALOGW("Zip: extra field for entry %" PRIu64
493 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
494 i, extra_length, cd_length);
495 return kInvalidFile;
496 }
497
498 off64_t local_header_offset = cdr->local_file_header_offset;
499 if (local_header_offset == UINT32_MAX) {
Tianjie6ab29122020-03-18 17:44:30 -0700500 Zip64ExtendedInfo zip64_info{};
501 if (auto status = ParseZip64ExtendedInfoInExtraField(
502 extra_field, extra_length, cdr->uncompressed_size, cdr->compressed_size,
503 cdr->local_file_header_offset, &zip64_info);
504 status != kSuccess) {
505 return status;
506 }
507 CHECK(zip64_info.local_header_offset.has_value());
508 local_header_offset = zip64_info.local_header_offset.value();
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700509 }
510
511 if (local_header_offset >= archive->directory_offset) {
512 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu64,
513 static_cast<int64_t>(local_header_offset), i);
514 return kInvalidFile;
515 }
516
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700517 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000518 if (!IsValidEntryName(file_name, file_name_length)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700519 ALOGW("Zip: invalid file name at entry %" PRIu64, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800520 return kInvalidEntryName;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100521 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000522
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700523 // Add the CDE filename to the hash table.
524 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800525 if (auto add_result =
526 archive->cd_entry_map->AddToMap(entry_name, archive->central_directory.GetBasePtr());
527 add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000528 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800529 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000530 }
531
Narayan Kamath926973e2014-06-09 14:18:14 +0100532 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
533 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700534 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu64, ptr - cd_ptr, cd_length, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800535 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000536 }
537 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100538
539 uint32_t lfh_start_bytes;
540 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
541 sizeof(uint32_t), 0)) {
542 ALOGW("Zip: Unable to read header for entry at offset == 0.");
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800543 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100544 }
545
546 if (lfh_start_bytes != LocalFileHeader::kSignature) {
547 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
548#if defined(__ANDROID__)
549 android_errorWriteLog(0x534e4554, "64211847");
550#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800551 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100552 }
553
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700554 ALOGV("+++ zip good scan %" PRIu64 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000555
Tianjie6ab29122020-03-18 17:44:30 -0700556 return kSuccess;
Narayan Kamath7462f022013-11-21 13:05:04 +0000557}
558
Jiyong Parkcd997e62017-06-30 17:23:33 +0900559static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800560 int32_t result = MapCentralDirectory(debug_file_name, archive);
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700561 return result != kSuccess ? result : ParseZipArchive(archive);
Narayan Kamath7462f022013-11-21 13:05:04 +0000562}
563
Jiyong Parkcd997e62017-06-30 17:23:33 +0900564int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
565 bool assume_ownership) {
Ryan Mitchell23150e42020-03-09 09:33:46 -0700566 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000567 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000568 return OpenArchiveInternal(archive, debug_file_name);
569}
570
Ryan Mitchell23150e42020-03-09 09:33:46 -0700571int32_t OpenArchiveFdRange(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
572 off64_t length, off64_t offset, bool assume_ownership) {
573 ZipArchive* archive = new ZipArchive(MappedZipFile(fd, length, offset), assume_ownership);
574 *handle = archive;
575
576 if (length < 0) {
577 ALOGW("Invalid zip length %" PRId64, length);
578 return kIoError;
579 }
580
581 if (offset < 0) {
582 ALOGW("Invalid zip offset %" PRId64, offset);
583 return kIoError;
584 }
585
586 return OpenArchiveInternal(archive, debug_file_name);
587}
588
Narayan Kamath7462f022013-11-21 13:05:04 +0000589int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800590 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Ryan Mitchell23150e42020-03-09 09:33:46 -0700591 ZipArchive* archive = new ZipArchive(MappedZipFile(fd), true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000592 *handle = archive;
593
Narayan Kamath7462f022013-11-21 13:05:04 +0000594 if (fd < 0) {
595 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
596 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000597 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700598
Narayan Kamath7462f022013-11-21 13:05:04 +0000599 return OpenArchiveInternal(archive, fileName);
600}
601
Elliott Hughesf66460b2019-10-22 11:44:50 -0700602int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900603 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700604 ZipArchive* archive = new ZipArchive(address, length);
605 *handle = archive;
606 return OpenArchiveInternal(archive, debug_file_name);
607}
608
Elliott Hughes26724132019-10-25 09:57:58 -0700609ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
610 ZipArchiveInfo result;
611 result.archive_size = archive->mapped_zip.GetFileLength();
612 result.entry_count = archive->num_entries;
613 return result;
614}
615
Narayan Kamath7462f022013-11-21 13:05:04 +0000616/*
617 * Close a ZipArchive, closing the file and freeing the contents.
618 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700619void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000620 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100621 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000622}
623
Narayan Kamath162b7052017-06-05 13:21:12 +0100624static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100625 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700626 off64_t offset = entry->offset;
627 if (entry->method != kCompressStored) {
628 offset += entry->compressed_length;
629 } else {
630 offset += entry->uncompressed_length;
631 }
632
633 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000634 return kIoError;
635 }
636
Narayan Kamath926973e2014-06-09 14:18:14 +0100637 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700638 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
639 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000640
Narayan Kamath162b7052017-06-05 13:21:12 +0100641 // Validate that the values in the data descriptor match those in the central
642 // directory.
643 if (entry->compressed_length != descriptor->compressed_size ||
644 entry->uncompressed_length != descriptor->uncompressed_size ||
645 entry->crc32 != descriptor->crc32) {
646 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
647 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
648 entry->compressed_length, entry->uncompressed_length, entry->crc32,
649 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
650 return kInconsistentInformation;
651 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000652
653 return 0;
654}
655
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800656static int32_t FindEntry(const ZipArchive* archive, std::string_view entryName,
657 const uint64_t nameOffset, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000658 // Recover the start of the central directory entry from the filename
659 // pointer. The filename is the first entry past the fixed-size data,
660 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700661 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800662 const uint8_t* ptr = base_ptr + nameOffset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100663 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000664
665 // This is the base of our mmapped region, we have to sanity check that
666 // the name that's in the hash table is a pointer to a location within
667 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700668 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000669 ALOGW("Zip: Invalid entry pointer");
670 return kInvalidOffset;
671 }
672
Tianjie6ab29122020-03-18 17:44:30 -0700673 auto cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100674
Narayan Kamath7462f022013-11-21 13:05:04 +0000675 // The offset of the start of the central directory in the zipfile.
676 // We keep this lying around so that we can sanity check all our lengths
677 // and our per-file structures.
678 const off64_t cd_offset = archive->directory_offset;
679
680 // Fill out the compression method, modification time, crc32
681 // and other interesting attributes from the central directory. These
682 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100683 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900684 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100685 data->crc32 = cdr->crc32;
686 data->compressed_length = cdr->compressed_size;
687 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000688
689 // Figure out the local header offset from the central directory. The
690 // actual file data will begin after the local header and the name /
691 // extra comments.
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700692 off64_t local_header_offset = cdr->local_file_header_offset;
693 // One of the info field is UINT32_MAX, try to parse the real value in the zip64 extended info in
694 // the extra field.
695 if (cdr->uncompressed_size == UINT32_MAX || cdr->compressed_size == UINT32_MAX ||
696 cdr->local_file_header_offset == UINT32_MAX) {
Tianjie6ab29122020-03-18 17:44:30 -0700697 const uint8_t* extra_field = ptr + sizeof(CentralDirectoryRecord) + cdr->file_name_length;
698 Zip64ExtendedInfo zip64_info{};
699 if (auto status = ParseZip64ExtendedInfoInExtraField(
700 extra_field, cdr->extra_field_length, cdr->uncompressed_size, cdr->compressed_size,
701 cdr->local_file_header_offset, &zip64_info);
702 status != kSuccess) {
703 return status;
704 }
705
706 if (cdr->uncompressed_size == UINT32_MAX || cdr->compressed_size == UINT32_MAX) {
707 CHECK(zip64_info.uncompressed_file_size.has_value());
708 CHECK(zip64_info.compressed_file_size.has_value());
709 // TODO(xunchang) remove the size limit and support entry length > UINT32_MAX.
710 data->uncompressed_length = static_cast<uint32_t>(zip64_info.uncompressed_file_size.value());
711 data->compressed_length = static_cast<uint32_t>(zip64_info.compressed_file_size.value());
712 }
713
714 if (local_header_offset == UINT32_MAX) {
715 CHECK(zip64_info.local_header_offset.has_value());
716 local_header_offset = zip64_info.local_header_offset.value();
717 }
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700718 }
719
Narayan Kamath926973e2014-06-09 14:18:14 +0100720 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000721 ALOGW("Zip: bad local hdr offset in zip");
722 return kInvalidOffset;
723 }
724
Narayan Kamath926973e2014-06-09 14:18:14 +0100725 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700726 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800727 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900728 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000729 return kIoError;
730 }
731
Tianjie6ab29122020-03-18 17:44:30 -0700732 auto lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100733 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700734 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900735 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000736 return kInvalidOffset;
737 }
738
Tianjie6ab29122020-03-18 17:44:30 -0700739 // Check that the local file header name matches the declared name in the central directory.
740 CHECK_LE(entryName.size(), UINT16_MAX);
741 auto nameLen = static_cast<uint16_t>(entryName.size());
742 if (lfh->file_name_length != nameLen) {
743 ALOGW("Zip: lfh name length did not match central directory for %s: %" PRIu16 " %" PRIu16,
744 std::string(entryName).c_str(), lfh->file_name_length, nameLen);
745 return kInconsistentInformation;
746 }
747 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
748 if (name_offset > cd_offset - lfh->file_name_length) {
749 ALOGW("Zip: lfh name has invalid declared length");
750 return kInvalidOffset;
751 }
752
753 std::vector<uint8_t> name_buf(nameLen);
754 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
755 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
756 return kIoError;
757 }
758 if (memcmp(entryName.data(), name_buf.data(), nameLen) != 0) {
759 ALOGW("Zip: lfh name did not match central directory");
760 return kInconsistentInformation;
761 }
762
763 uint64_t lfh_uncompressed_size = lfh->uncompressed_size;
764 uint64_t lfh_compressed_size = lfh->compressed_size;
765 if (lfh_uncompressed_size == UINT32_MAX || lfh_compressed_size == UINT32_MAX) {
766 const off64_t lfh_extra_field_offset = name_offset + lfh->file_name_length;
767 const uint16_t lfh_extra_field_size = lfh->extra_field_length;
768 if (lfh_extra_field_offset > cd_offset - lfh_extra_field_size) {
769 ALOGW("Zip: extra field has a bad size for entry %s", std::string(entryName).c_str());
770 return kInvalidOffset;
771 }
772
773 std::vector<uint8_t> local_extra_field(lfh_extra_field_size);
774 if (!archive->mapped_zip.ReadAtOffset(local_extra_field.data(), lfh_extra_field_size,
775 lfh_extra_field_offset)) {
776 ALOGW("Zip: failed reading lfh extra field from offset %" PRId64, lfh_extra_field_offset);
777 return kIoError;
778 }
779
780 Zip64ExtendedInfo zip64_info{};
781 if (auto status = ParseZip64ExtendedInfoInExtraField(
782 local_extra_field.data(), lfh_extra_field_size, lfh->uncompressed_size,
783 lfh->compressed_size, std::nullopt, &zip64_info);
784 status != kSuccess) {
785 return status;
786 }
787
788 CHECK(zip64_info.uncompressed_file_size.has_value());
789 CHECK(zip64_info.compressed_file_size.has_value());
790 lfh_uncompressed_size = zip64_info.uncompressed_file_size.value();
791 lfh_compressed_size = zip64_info.compressed_file_size.value();
792 }
793
Narayan Kamath7462f022013-11-21 13:05:04 +0000794 // Paranoia: Match the values specified in the local file header
795 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700796
Narayan Kamath162b7052017-06-05 13:21:12 +0100797 // Warn if central directory and local file header don't agree on the use
798 // of a trailing Data Descriptor. The reference implementation is inconsistent
799 // and appears to use the LFH value during extraction (unzip) but the CD value
800 // while displayng information about archives (zipinfo). The spec remains
801 // silent on this inconsistency as well.
802 //
803 // For now, always use the version from the LFH but make sure that the values
804 // specified in the central directory match those in the data descriptor.
805 //
806 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
807 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
808 // encoded using UTF-8). This implementation does not check for the presence of
809 // that flag and always enforces that entry names are valid UTF-8.
810 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
811 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700812 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700813 }
814
815 // If there is no trailing data descriptor, verify that the central directory and local file
816 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100817 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000818 data->has_data_descriptor = 0;
Tianjie6ab29122020-03-18 17:44:30 -0700819 if (data->compressed_length != lfh_compressed_size ||
820 data->uncompressed_length != lfh_uncompressed_size || data->crc32 != lfh->crc32) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900821 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
Tianjie6ab29122020-03-18 17:44:30 -0700822 "}, was {%" PRIu64 ", %" PRIu64 ", %" PRIx32 "}",
823 data->compressed_length, data->uncompressed_length, data->crc32, lfh_compressed_size,
824 lfh_uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000825 return kInconsistentInformation;
826 }
827 } else {
828 data->has_data_descriptor = 1;
829 }
830
Elliott Hughes55fd2932017-05-28 22:59:04 -0700831 // 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 -0700832 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700833 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700834 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700835 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
836 } else {
837 data->unix_mode = 0777;
838 }
839
Elliott Hughesd5095252019-10-28 21:35:52 -0700840 // 4.4.4: general purpose bit flags.
841 data->gpbf = lfh->gpb_flags;
842
Elliott Hughes26724132019-10-25 09:57:58 -0700843 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
844 // Currently only needed to implement zipinfo.
845 data->is_text = (cdr->internal_file_attributes & 1);
846
Jiyong Parkcd997e62017-06-30 17:23:33 +0900847 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
848 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000849 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800850 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000851 return kInvalidOffset;
852 }
853
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800854 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700855 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900856 static_cast<int64_t>(data_offset), data->compressed_length,
857 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000858 return kInvalidOffset;
859 }
860
861 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900862 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
863 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
864 static_cast<int64_t>(data_offset), data->uncompressed_length,
865 static_cast<int64_t>(cd_offset));
866 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000867 }
868
869 data->offset = data_offset;
870 return 0;
871}
872
873struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000874 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100875
Songchun Fanc33f5262020-03-24 09:15:51 -0700876 std::function<bool(std::string_view)> matcher;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700877
878 uint32_t position = 0;
879
Songchun Fanc33f5262020-03-24 09:15:51 -0700880 IterationHandle(ZipArchive* archive, std::function<bool(std::string_view)> in_matcher)
881 : archive(archive), matcher(std::move(in_matcher)) {}
882
883 bool Match(std::string_view entry_name) const { return matcher(entry_name); }
Narayan Kamath7462f022013-11-21 13:05:04 +0000884};
885
Ryan Prichard3673f992018-10-10 22:41:14 -0700886int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700887 const std::string_view optional_prefix,
888 const std::string_view optional_suffix) {
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700889 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
890 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
891 ALOGW("Zip: prefix/suffix too long");
892 return kInvalidEntryName;
893 }
Songchun Fanc33f5262020-03-24 09:15:51 -0700894 auto matcher = [prefix = std::string(optional_prefix),
895 suffix = std::string(optional_suffix)](std::string_view name) mutable {
896 return android::base::StartsWith(name, prefix) && android::base::EndsWith(name, suffix);
897 };
898 return StartIteration(archive, cookie_ptr, std::move(matcher));
899}
900
901int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
902 std::function<bool(std::string_view)> matcher) {
903 if (archive == nullptr || archive->cd_entry_map == nullptr) {
904 ALOGW("Zip: Invalid ZipArchiveHandle");
905 return kInvalidHandle;
906 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000907
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800908 archive->cd_entry_map->ResetIteration();
Songchun Fanc33f5262020-03-24 09:15:51 -0700909 *cookie_ptr = new IterationHandle(archive, matcher);
Narayan Kamath7462f022013-11-21 13:05:04 +0000910 return 0;
911}
912
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100913void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100914 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100915}
916
Elliott Hughesb17bf522019-05-03 22:38:44 -0700917int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
918 ZipEntry* data) {
919 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
920 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
921 return kInvalidEntryName;
922 }
923
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800924 const auto [result, offset] =
925 archive->cd_entry_map->GetCdEntryOffset(entryName, archive->central_directory.GetBasePtr());
926 if (result != 0) {
Elliott Hughesb17bf522019-05-03 22:38:44 -0700927 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800928 return static_cast<int32_t>(result); // kEntryNotFound is safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700929 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700930 // We know there are at most hash_table_size entries, safe to truncate.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800931 return FindEntry(archive, entryName, offset, data);
Elliott Hughesb17bf522019-05-03 22:38:44 -0700932}
933
Elliott Hughese06a8082019-05-22 18:56:41 -0700934int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700935 std::string_view sv;
936 int32_t result = Next(cookie, data, &sv);
937 if (result == 0 && name) {
938 *name = std::string(sv);
939 }
940 return result;
941}
942
943int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800944 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800945 if (handle == nullptr) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100946 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000947 return kInvalidHandle;
948 }
949
950 ZipArchive* archive = handle->archive;
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800951 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000952 ALOGW("Zip: Invalid ZipArchiveHandle");
953 return kInvalidHandle;
954 }
955
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800956 auto entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
957 while (entry != std::pair<std::string_view, uint64_t>()) {
958 const auto [entry_name, offset] = entry;
Songchun Fanc33f5262020-03-24 09:15:51 -0700959 if (handle->Match(entry_name)) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800960 const int error = FindEntry(archive, entry_name, offset, data);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700961 if (!error && name) {
962 *name = entry_name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000963 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000964 return error;
965 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800966 entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000967 }
968
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800969 archive->cd_entry_map->ResetIteration();
Narayan Kamath7462f022013-11-21 13:05:04 +0000970 return kIterationEnd;
971}
972
Narayan Kamathf899bd52015-04-17 11:53:14 +0100973// A Writer that writes data to a fixed size memory region.
974// The size of the memory region must be equal to the total size of
975// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100976class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100977 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900978 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100979
980 virtual bool Append(uint8_t* buf, size_t buf_size) override {
981 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700982 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900983 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100984 return false;
985 }
986
987 memcpy(buf_ + bytes_written_, buf, buf_size);
988 bytes_written_ += buf_size;
989 return true;
990 }
991
992 private:
993 uint8_t* const buf_;
994 const size_t size_;
995 size_t bytes_written_;
996};
997
998// A Writer that appends data to a file |fd| at its current position.
999// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +01001000class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001001 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +01001002 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
1003 // guaranteeing that the file descriptor is valid and that there's enough
1004 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -08001005 // is truncated to the correct length (no truncation if |fd| references a
1006 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +01001007 //
1008 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001009 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001010 const uint32_t declared_length = entry->uncompressed_length;
1011 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
1012 if (current_offset == -1) {
1013 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001014 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +01001015 }
1016
Narayan Kamathf899bd52015-04-17 11:53:14 +01001017#if defined(__linux__)
1018 if (declared_length > 0) {
1019 // Make sure we have enough space on the volume to extract the compressed
1020 // entry. Note that the call to ftruncate below will change the file size but
1021 // will not allocate space on disk and this call to fallocate will not
1022 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -07001023 // Note: fallocate is only supported by the following filesystems -
1024 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
1025 // EOPNOTSUPP error when issued in other filesystems.
1026 // Hence, check for the return error code before concluding that the
1027 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001028 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -07001029 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -07001030 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +01001031 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
1032 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001033 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +01001034 }
1035 }
1036#endif // __linux__
1037
Tao Baoa456c212016-11-15 10:08:07 -08001038 struct stat sb;
1039 if (fstat(fd, &sb) == -1) {
1040 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001041 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +01001042 }
1043
Tao Baoa456c212016-11-15 10:08:07 -08001044 // Block device doesn't support ftruncate(2).
1045 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001046 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -08001047 if (result == -1) {
1048 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
1049 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001050 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -08001051 }
1052 }
1053
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001054 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001055 }
1056
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -07001057 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001058 : fd_(other.fd_),
1059 declared_length_(other.declared_length_),
1060 total_bytes_written_(other.total_bytes_written_) {
1061 other.fd_ = -1;
1062 }
1063
1064 bool IsValid() const { return fd_ != -1; }
1065
Narayan Kamathf899bd52015-04-17 11:53:14 +01001066 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1067 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001068 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +09001069 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001070 return false;
1071 }
1072
Narayan Kamathe97e66e2015-04-27 16:25:53 +01001073 const bool result = android::base::WriteFully(fd_, buf, buf_size);
1074 if (result) {
1075 total_bytes_written_ += buf_size;
1076 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001077 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001078 }
1079
Narayan Kamathe97e66e2015-04-27 16:25:53 +01001080 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001081 }
Jiyong Parkcd997e62017-06-30 17:23:33 +09001082
Narayan Kamathf899bd52015-04-17 11:53:14 +01001083 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001084 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +09001085 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +01001086
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001087 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001088 const size_t declared_length_;
1089 size_t total_bytes_written_;
1090};
1091
Narayan Kamath485b3642017-10-26 14:42:39 +01001092class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001093 public:
1094 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
1095 : Reader(), zip_file_(zip_file), entry_(entry) {}
1096
1097 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
1098 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
1099 }
1100
1101 virtual ~EntryReader() {}
1102
1103 private:
1104 const MappedZipFile& zip_file_;
1105 const ZipEntry* entry_;
1106};
1107
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -08001108// This method is using libz macros with old-style-casts
1109#pragma GCC diagnostic push
1110#pragma GCC diagnostic ignored "-Wold-style-cast"
1111static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
1112 return inflateInit2(stream, window_bits);
1113}
1114#pragma GCC diagnostic pop
1115
Narayan Kamath485b3642017-10-26 14:42:39 +01001116namespace zip_archive {
1117
1118// Moved out of line to avoid -Wweak-vtables.
1119Reader::~Reader() {}
1120Writer::~Writer() {}
1121
1122int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
1123 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001124 const size_t kBufSize = 32768;
1125 std::vector<uint8_t> read_buf(kBufSize);
1126 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +00001127 z_stream zstream;
1128 int zerr;
1129
1130 /*
1131 * Initialize the zlib stream struct.
1132 */
1133 memset(&zstream, 0, sizeof(zstream));
1134 zstream.zalloc = Z_NULL;
1135 zstream.zfree = Z_NULL;
1136 zstream.opaque = Z_NULL;
1137 zstream.next_in = NULL;
1138 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001139 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001140 zstream.avail_out = kBufSize;
1141 zstream.data_type = Z_UNKNOWN;
1142
1143 /*
1144 * Use the undocumented "negative window bits" feature to tell zlib
1145 * that there's no zlib header waiting for it.
1146 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -08001147 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +00001148 if (zerr != Z_OK) {
1149 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001150 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +00001151 } else {
1152 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
1153 }
1154
1155 return kZlibError;
1156 }
1157
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001158 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001159 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001160 };
1161
1162 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1163
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001164 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -07001165 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001166 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +00001167 do {
1168 /* read as much as we can */
1169 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001170 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001171 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -07001172 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001173 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001174 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001175 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001176 }
1177
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001178 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001179
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001180 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001181 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +00001182 }
1183
1184 /* uncompress the data */
1185 zerr = inflate(&zstream, Z_NO_FLUSH);
1186 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001187 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1188 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001189 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +00001190 }
1191
1192 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +09001193 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001194 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +01001195 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001196 return kIoError;
1197 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001198 DCHECK_LE(write_size, kBufSize);
1199 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +00001200 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001201
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -07001202 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +00001203 zstream.avail_out = kBufSize;
1204 }
1205 } while (zerr == Z_OK);
1206
Elliott Hughese8f4b142018-10-19 16:09:39 -07001207 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +00001208
Narayan Kamath162b7052017-06-05 13:21:12 +01001209 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1210 // "feature" of zlib to tell it there won't be a zlib file header. zlib
1211 // doesn't bother calculating the checksum in that scenario. We just do
1212 // it ourselves above because there are no additional gains to be made by
1213 // having zlib calculate it for us, since they do it by calling crc32 in
1214 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +00001215 if (compute_crc) {
1216 *crc_out = crc;
1217 }
Narayan Kamath7462f022013-11-21 13:05:04 +00001218
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001219 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001220 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1221 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001222 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001223 }
1224
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001225 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001226}
Narayan Kamath485b3642017-10-26 14:42:39 +01001227} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001228
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001229static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001230 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001231 const EntryReader reader(mapped_zip, entry);
1232
Narayan Kamath485b3642017-10-26 14:42:39 +01001233 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1234 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001235}
1236
Narayan Kamath485b3642017-10-26 14:42:39 +01001237static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1238 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001239 static const uint32_t kBufSize = 32768;
1240 std::vector<uint8_t> buf(kBufSize);
1241
1242 const uint32_t length = entry->uncompressed_length;
1243 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -07001244 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001245 while (count < length) {
1246 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001247 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001248
Adam Lesinskide117e42017-06-19 10:27:38 -07001249 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -07001250 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001251
1252 // Make sure to read at offset to ensure concurrent access to the fd.
1253 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -07001254 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -07001255 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001256 return kIoError;
1257 }
1258
1259 if (!writer->Append(&buf[0], block_size)) {
1260 return kIoError;
1261 }
1262 crc = crc32(crc, &buf[0], block_size);
1263 count += block_size;
1264 }
1265
1266 *crc_out = crc;
1267
1268 return 0;
1269}
1270
Ryan Prichard3673f992018-10-10 22:41:14 -07001271int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001272 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001273
1274 // this should default to kUnknownCompressionMethod.
1275 int32_t return_value = -1;
1276 uint64_t crc = 0;
1277 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001278 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001279 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001280 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001281 }
1282
1283 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001284 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001285 if (return_value) {
1286 return return_value;
1287 }
1288 }
1289
Narayan Kamath162b7052017-06-05 13:21:12 +01001290 // Validate that the CRC matches the calculated value.
1291 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001292 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001293 return kInconsistentInformation;
1294 }
1295
1296 return return_value;
1297}
1298
Ryan Prichard3673f992018-10-10 22:41:14 -07001299int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001300 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001301 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001302}
1303
Ryan Prichard3673f992018-10-10 22:41:14 -07001304int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001305 auto writer = FileWriter::Create(fd, entry);
1306 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001307 return kIoError;
1308 }
1309
Ryan Prichard3673f992018-10-10 22:41:14 -07001310 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001311}
1312
Ryan Prichard3673f992018-10-10 22:41:14 -07001313int GetFileDescriptor(const ZipArchiveHandle archive) {
1314 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001315}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001316
Ryan Mitchell23150e42020-03-09 09:33:46 -07001317off64_t GetFileDescriptorOffset(const ZipArchiveHandle archive) {
1318 return archive->mapped_zip.GetFileOffset();
1319}
1320
Tianjie Xu18c25922016-09-29 15:27:41 -07001321#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001322class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001323 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001324 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1325 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001326
1327 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1328 return proc_function_(buf, buf_size, cookie_);
1329 }
1330
1331 private:
1332 ProcessZipEntryFunction proc_function_;
1333 void* cookie_;
1334};
1335
Ryan Prichard3673f992018-10-10 22:41:14 -07001336int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001337 ProcessZipEntryFunction func, void* cookie) {
1338 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001339 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001340}
1341
Jiyong Parkcd997e62017-06-30 17:23:33 +09001342#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001343
1344int MappedZipFile::GetFileDescriptor() const {
1345 if (!has_fd_) {
1346 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1347 return -1;
1348 }
1349 return fd_;
1350}
1351
Elliott Hughesf66460b2019-10-22 11:44:50 -07001352const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001353 if (has_fd_) {
1354 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1355 return nullptr;
1356 }
1357 return base_ptr_;
1358}
1359
Ryan Mitchell23150e42020-03-09 09:33:46 -07001360off64_t MappedZipFile::GetFileOffset() const {
1361 return fd_offset_;
1362}
1363
Tianjie Xu18c25922016-09-29 15:27:41 -07001364off64_t MappedZipFile::GetFileLength() const {
1365 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001366 if (data_length_ != -1) {
1367 return data_length_;
1368 }
1369 data_length_ = lseek64(fd_, 0, SEEK_END);
1370 if (data_length_ == -1) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001371 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1372 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001373 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001374 } else {
1375 if (base_ptr_ == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001376 ALOGE("Zip: invalid file map");
Tianjie Xu18c25922016-09-29 15:27:41 -07001377 return -1;
1378 }
Ryan Mitchell23150e42020-03-09 09:33:46 -07001379 return data_length_;
Tianjie Xu18c25922016-09-29 15:27:41 -07001380 }
1381}
1382
Tianjie Xu18c25922016-09-29 15:27:41 -07001383// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001384bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001385 if (has_fd_) {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001386 if (off < 0) {
1387 ALOGE("Zip: invalid offset %" PRId64, off);
1388 return false;
1389 }
1390
1391 off64_t read_offset;
1392 if (__builtin_add_overflow(fd_offset_, off, &read_offset)) {
1393 ALOGE("Zip: invalid read offset %" PRId64 " overflows, fd offset %" PRId64, off, fd_offset_);
1394 return false;
1395 }
1396
1397 if (data_length_ != -1) {
1398 off64_t read_end;
1399 if (len > std::numeric_limits<off64_t>::max() ||
1400 __builtin_add_overflow(off, static_cast<off64_t>(len), &read_end)) {
1401 ALOGE("Zip: invalid read length %" PRId64 " overflows, offset %" PRId64,
1402 static_cast<off64_t>(len), off);
1403 return false;
1404 }
1405
1406 if (read_end > data_length_) {
1407 ALOGE("Zip: invalid read length %" PRId64 " exceeds data length %" PRId64 ", offset %"
1408 PRId64, static_cast<off64_t>(len), data_length_, off);
1409 return false;
1410 }
1411 }
1412
1413 if (!android::base::ReadFullyAtOffset(fd_, buf, len, read_offset)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001414 ALOGE("Zip: failed to read at offset %" PRId64, off);
Tianjie Xu18c25922016-09-29 15:27:41 -07001415 return false;
1416 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001417 } else {
Ryan Mitchell23150e42020-03-09 09:33:46 -07001418 if (off < 0 || off > data_length_) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001419 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64, off, data_length_);
Adam Lesinskide117e42017-06-19 10:27:38 -07001420 return false;
1421 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001422 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001423 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001424 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001425}
1426
Elliott Hughesf66460b2019-10-22 11:44:50 -07001427void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1428 size_t cd_size) {
1429 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001430 length_ = cd_size;
1431}
1432
Elliott Hughese8f4b142018-10-19 16:09:39 -07001433bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001434 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001435 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
Ryan Mitchell23150e42020-03-09 09:33:46 -07001436 mapped_zip.GetFileOffset() + cd_start_offset,
1437 cd_size, PROT_READ);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001438 if (!directory_map) {
1439 ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1440 cd_start_offset, cd_size, strerror(errno));
1441 return false;
1442 }
Tianjie Xu18c25922016-09-29 15:27:41 -07001443
Elliott Hughese8f4b142018-10-19 16:09:39 -07001444 CHECK_EQ(directory_map->size(), cd_size);
1445 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001446 } else {
1447 if (mapped_zip.GetBasePtr() == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001448 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
Tianjie Xu18c25922016-09-29 15:27:41 -07001449 return false;
1450 }
1451 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1452 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001453 ALOGE(
1454 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1455 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1456 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001457 return false;
1458 }
1459
1460 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1461 }
1462 return true;
1463}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001464
1465tm ZipEntry::GetModificationTime() const {
1466 tm t = {};
1467
1468 t.tm_hour = (mod_time >> 11) & 0x1f;
1469 t.tm_min = (mod_time >> 5) & 0x3f;
1470 t.tm_sec = (mod_time & 0x1f) << 1;
1471
1472 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1473 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1474 t.tm_mday = (mod_time >> 16) & 0x1f;
1475
1476 return t;
1477}