blob: 2648c594832a13e9cee474d91c5fa6e64aa11efa [file] [log] [blame]
Narayan Kamath7462f022013-11-21 13:05:04 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Read-only access to Zip archives, with minimal heap allocation.
19 */
Narayan Kamath7462f022013-11-21 13:05:04 +000020
Mark Salyzyncfd5b082016-10-17 14:28:00 -070021#define LOG_TAG "ziparchive"
22
Elliott Hughese8f4b142018-10-19 16:09:39 -070023#include "ziparchive/zip_archive.h"
24
Narayan Kamath7462f022013-11-21 13:05:04 +000025#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070026#include <fcntl.h>
27#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000029#include <stdlib.h>
30#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070031#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000032#include <unistd.h>
33
Dan Albert1ae07642015-04-09 14:11:18 -070034#include <memory>
35#include <vector>
36
Elliott Hughes9c8bd662018-10-26 16:14:21 -070037#if defined(__APPLE__)
38#define lseek64 lseek
39#endif
40
Josh Gao1b496342018-07-17 11:08:48 -070041#if defined(__BIONIC__)
42#include <android/fdsan.h>
43#endif
44
Mark Salyzynff2dcd92016-09-28 15:54:45 -070045#include <android-base/file.h>
46#include <android-base/logging.h>
47#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
Elliott Hughese8f4b142018-10-19 16:09:39 -070048#include <android-base/mapped_file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070049#include <android-base/memory.h>
Elliott Hughes50ef29a2019-06-18 18:23:59 -070050#include <android-base/strings.h>
Ryan Mitchellc77f9d32018-08-25 14:06:29 -070051#include <android-base/utf8.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070052#include <log/log.h>
Dan Albert1ae07642015-04-09 14:11:18 -070053#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000054
Narayan Kamath044bc8e2014-12-03 18:22:53 +000055#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070056#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080057#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070058
Dan Albert1ae07642015-04-09 14:11:18 -070059using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000060
Narayan Kamath162b7052017-06-05 13:21:12 +010061// Used to turn on crc checks - verify that the content CRC matches the values
62// specified in the local file header and the central directory.
63static const bool kCrcChecksEnabled = false;
64
Narayan Kamath926973e2014-06-09 14:18:14 +010065// The maximum number of bytes to scan backwards for the EOCD start.
66static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
67
Narayan Kamath7462f022013-11-21 13:05:04 +000068/*
69 * A Read-only Zip archive.
70 *
71 * We want "open" and "find entry by name" to be fast operations, and
72 * we want to use as little memory as possible. We memory-map the zip
73 * central directory, and load a hash table with pointers to the filenames
74 * (which aren't null-terminated). The other fields are at a fixed offset
75 * from the filename, so we don't need to extract those (but we do need
76 * to byte-read and endian-swap them every time we want them).
77 *
78 * It's possible that somebody has handed us a massive (~1GB) zip archive,
79 * so we can't expect to mmap the entire file.
80 *
81 * To speed comparisons when doing a lookup by name, we could make the mapping
82 * "private" (copy-on-write) and null-terminate the filenames after verifying
83 * the record structure. However, this requires a private mapping of
84 * every page that the Central Directory touches. Easier to tuck a copy
85 * of the string length into the hash table entry.
86 */
Narayan Kamath7462f022013-11-21 13:05:04 +000087
Josh Gaoabdfc242018-09-07 12:44:40 -070088#if defined(__BIONIC__)
89uint64_t GetOwnerTag(const ZipArchive* archive) {
90 return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
91 reinterpret_cast<uint64_t>(archive));
92}
93#endif
94
Josh Gao1b496342018-07-17 11:08:48 -070095ZipArchive::ZipArchive(const int fd, bool assume_ownership)
96 : mapped_zip(fd),
97 close_file(assume_ownership),
98 directory_offset(0),
99 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700100 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800101 num_entries(0) {
Josh Gao1b496342018-07-17 11:08:48 -0700102#if defined(__BIONIC__)
103 if (assume_ownership) {
Josh Gaoabdfc242018-09-07 12:44:40 -0700104 android_fdsan_exchange_owner_tag(fd, 0, GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700105 }
106#endif
107}
108
Elliott Hughesf66460b2019-10-22 11:44:50 -0700109ZipArchive::ZipArchive(const void* address, size_t length)
Josh Gao1b496342018-07-17 11:08:48 -0700110 : mapped_zip(address, length),
111 close_file(false),
112 directory_offset(0),
113 central_directory(),
Elliott Hughese8f4b142018-10-19 16:09:39 -0700114 directory_map(),
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800115 num_entries(0) {}
Josh Gao1b496342018-07-17 11:08:48 -0700116
117ZipArchive::~ZipArchive() {
118 if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
119#if defined(__BIONIC__)
Josh Gaoabdfc242018-09-07 12:44:40 -0700120 android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
Josh Gao1b496342018-07-17 11:08:48 -0700121#else
122 close(mapped_zip.GetFileDescriptor());
123#endif
124 }
Josh Gao1b496342018-07-17 11:08:48 -0700125}
126
Tianjie Xu18c25922016-09-29 15:27:41 -0700127static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Andreas Gampe964b95c2019-04-05 13:48:02 -0700128 off64_t file_length, uint32_t read_amount,
Zimuzo5a503ef2018-09-17 19:49:55 +0100129 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000130 const off64_t search_start = file_length - read_amount;
131
Jiyong Parkcd997e62017-06-30 17:23:33 +0900132 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
133 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
134 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000135 return kIoError;
136 }
137
138 /*
139 * Scan backward for the EOCD magic. In an archive without a trailing
140 * comment, we'll find it on the first try. (We may want to consider
141 * doing an initial minimal read; if we don't find it, retry with a
142 * second read as above.)
143 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700144 CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
145 int32_t i = read_amount - sizeof(EocdRecord);
Narayan Kamath926973e2014-06-09 14:18:14 +0100146 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700147 if (scan_buffer[i] == 0x50) {
148 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
149 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
150 ALOGV("+++ Found EOCD at buf+%d", i);
151 break;
152 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000153 }
154 }
155 if (i < 0) {
156 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
157 return kInvalidFile;
158 }
159
160 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100161 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000162 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100163 * Verify that there's no trailing space at the end of the central directory
164 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000165 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900166 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100167 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100168 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100169 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100170 return kInvalidFile;
171 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000172
Narayan Kamath926973e2014-06-09 14:18:14 +0100173 /*
174 * Grab the CD offset and size, and the number of entries in the
175 * archive and verify that they look reasonable.
176 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700177 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100178 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900179 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000180 return kInvalidOffset;
181 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100182 if (eocd->num_records == 0) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000183#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000184 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000185#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000186 return kEmptyArchive;
187 }
188
Jiyong Parkcd997e62017-06-30 17:23:33 +0900189 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
190 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000191
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800192 // It all looks good. Create a mapping for the CD, and set the fields
193 // in archive.
Elliott Hughese8f4b142018-10-19 16:09:39 -0700194 if (!archive->InitializeCentralDirectory(static_cast<off64_t>(eocd->cd_start_offset),
Tianjie Xu18c25922016-09-29 15:27:41 -0700195 static_cast<size_t>(eocd->cd_size))) {
Narayan Kamatheaf98852013-12-11 14:51:51 +0000196 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000197 }
198
Narayan Kamath926973e2014-06-09 14:18:14 +0100199 archive->num_entries = eocd->num_records;
200 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000201
202 return 0;
203}
204
205/*
206 * Find the zip Central Directory and memory-map it.
207 *
208 * On success, returns 0 after populating fields from the EOCD area:
209 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700210 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000211 * num_entries
212 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700213static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000214 // Test file length. We use lseek64 to make sure the file
215 // is small enough to be a zip file (Its size must be less than
216 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700217 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000218 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000219 return kInvalidFile;
220 }
221
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800222 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100223 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000224 return kInvalidFile;
225 }
226
Narayan Kamath926973e2014-06-09 14:18:14 +0100227 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
228 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000229 return kInvalidFile;
230 }
231
232 /*
233 * Perform the traditional EOCD snipe hunt.
234 *
235 * We're searching for the End of Central Directory magic number,
236 * which appears at the start of the EOCD block. It's followed by
237 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
238 * need to read the last part of the file into a buffer, dig through
239 * it to find the magic number, parse some values out, and use those
240 * to determine the extent of the CD.
241 *
242 * We start by pulling in the last part of the file.
243 */
Andreas Gampe964b95c2019-04-05 13:48:02 -0700244 uint32_t read_amount = kMaxEOCDSearch;
Narayan Kamath926973e2014-06-09 14:18:14 +0100245 if (file_length < read_amount) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700246 read_amount = static_cast<uint32_t>(file_length);
Narayan Kamath7462f022013-11-21 13:05:04 +0000247 }
248
Tianjie Xu18c25922016-09-29 15:27:41 -0700249 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900250 int32_t result =
251 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000252 return result;
253}
254
255/*
256 * Parses the Zip archive's Central Directory. Allocates and populates the
257 * hash table.
258 *
259 * Returns 0 on success.
260 */
261static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700262 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
263 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100264 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000265
Tianjie Xu0ef97832020-03-15 21:23:24 -0700266 // TODO(xunchang) parse the zip64 Eocd
267 if (num_entries > UINT16_MAX) {
268 archive->cd_entry_map = CdEntryMapZip64::Create();
269 } else {
270 archive->cd_entry_map = CdEntryMapZip32::Create(num_entries);
271 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800272 if (archive->cd_entry_map == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800273 return kAllocationFailed;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700274 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000275
276 /*
277 * Walk through the central directory, adding entries to the hash
278 * table and verifying values.
279 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100280 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000281 const uint8_t* ptr = cd_ptr;
282 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700283 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800284 ALOGW("Zip: ran off the end (item #%" PRIu16 ", %zu bytes of central directory)", i,
285 cd_length);
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700286#if defined(__ANDROID__)
287 android_errorWriteLog(0x534e4554, "36392138");
288#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800289 return kInvalidFile;
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700290 }
291
Jiyong Parkcd997e62017-06-30 17:23:33 +0900292 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100293 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700294 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800295 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000296 }
297
Narayan Kamath926973e2014-06-09 14:18:14 +0100298 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000299 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800300 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900301 static_cast<int64_t>(local_header_offset), i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800302 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000303 }
304
Narayan Kamath926973e2014-06-09 14:18:14 +0100305 const uint16_t file_name_length = cdr->file_name_length;
306 const uint16_t extra_length = cdr->extra_field_length;
307 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100308 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
309
Tianjie Xu9e020e22016-10-10 12:11:30 -0700310 if (file_name + file_name_length > cd_end) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700311 ALOGW("Zip: file name for entry %" PRIu16
312 " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
313 i, file_name_length, cd_length);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800314 return kInvalidEntryName;
Tianjie Xu9e020e22016-10-10 12:11:30 -0700315 }
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700316 // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000317 if (!IsValidEntryName(file_name, file_name_length)) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700318 ALOGW("Zip: invalid file name at entry %" PRIu16, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800319 return kInvalidEntryName;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100320 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000321
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700322 // Add the CDE filename to the hash table.
323 std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800324 if (auto add_result =
325 archive->cd_entry_map->AddToMap(entry_name, archive->central_directory.GetBasePtr());
326 add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000327 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800328 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000329 }
330
Narayan Kamath926973e2014-06-09 14:18:14 +0100331 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
332 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900333 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800334 return kInvalidFile;
Narayan Kamath7462f022013-11-21 13:05:04 +0000335 }
336 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100337
338 uint32_t lfh_start_bytes;
339 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
340 sizeof(uint32_t), 0)) {
341 ALOGW("Zip: Unable to read header for entry at offset == 0.");
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800342 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100343 }
344
345 if (lfh_start_bytes != LocalFileHeader::kSignature) {
346 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
347#if defined(__ANDROID__)
348 android_errorWriteLog(0x534e4554, "64211847");
349#endif
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800350 return kInvalidFile;
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100351 }
352
Mark Salyzyn088bf902014-05-08 16:02:20 -0700353 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000354
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800355 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000356}
357
Jiyong Parkcd997e62017-06-30 17:23:33 +0900358static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -0800359 int32_t result = MapCentralDirectory(debug_file_name, archive);
360 return result != 0 ? result : ParseZipArchive(archive);
Narayan Kamath7462f022013-11-21 13:05:04 +0000361}
362
Jiyong Parkcd997e62017-06-30 17:23:33 +0900363int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
364 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700365 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000366 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000367 return OpenArchiveInternal(archive, debug_file_name);
368}
369
370int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Nick Kralevich3bdf7442018-12-18 12:48:06 -0800371 const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700372 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000373 *handle = archive;
374
Narayan Kamath7462f022013-11-21 13:05:04 +0000375 if (fd < 0) {
376 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
377 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000378 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700379
Narayan Kamath7462f022013-11-21 13:05:04 +0000380 return OpenArchiveInternal(archive, fileName);
381}
382
Elliott Hughesf66460b2019-10-22 11:44:50 -0700383int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900384 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700385 ZipArchive* archive = new ZipArchive(address, length);
386 *handle = archive;
387 return OpenArchiveInternal(archive, debug_file_name);
388}
389
Elliott Hughes26724132019-10-25 09:57:58 -0700390ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
391 ZipArchiveInfo result;
392 result.archive_size = archive->mapped_zip.GetFileLength();
393 result.entry_count = archive->num_entries;
394 return result;
395}
396
Narayan Kamath7462f022013-11-21 13:05:04 +0000397/*
398 * Close a ZipArchive, closing the file and freeing the contents.
399 */
Ryan Prichard3673f992018-10-10 22:41:14 -0700400void CloseArchive(ZipArchiveHandle archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000401 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100402 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000403}
404
Narayan Kamath162b7052017-06-05 13:21:12 +0100405static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100406 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700407 off64_t offset = entry->offset;
408 if (entry->method != kCompressStored) {
409 offset += entry->compressed_length;
410 } else {
411 offset += entry->uncompressed_length;
412 }
413
414 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000415 return kIoError;
416 }
417
Narayan Kamath926973e2014-06-09 14:18:14 +0100418 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700419 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
420 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000421
Narayan Kamath162b7052017-06-05 13:21:12 +0100422 // Validate that the values in the data descriptor match those in the central
423 // directory.
424 if (entry->compressed_length != descriptor->compressed_size ||
425 entry->uncompressed_length != descriptor->uncompressed_size ||
426 entry->crc32 != descriptor->crc32) {
427 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
428 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
429 entry->compressed_length, entry->uncompressed_length, entry->crc32,
430 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
431 return kInconsistentInformation;
432 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000433
434 return 0;
435}
436
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800437static int32_t FindEntry(const ZipArchive* archive, std::string_view entryName,
438 const uint64_t nameOffset, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000439 // Recover the start of the central directory entry from the filename
440 // pointer. The filename is the first entry past the fixed-size data,
441 // so we can just subtract back from that.
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700442 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800443 const uint8_t* ptr = base_ptr + nameOffset;
Narayan Kamath926973e2014-06-09 14:18:14 +0100444 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000445
446 // This is the base of our mmapped region, we have to sanity check that
447 // the name that's in the hash table is a pointer to a location within
448 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700449 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000450 ALOGW("Zip: Invalid entry pointer");
451 return kInvalidOffset;
452 }
453
Jiyong Parkcd997e62017-06-30 17:23:33 +0900454 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100455
Narayan Kamath7462f022013-11-21 13:05:04 +0000456 // The offset of the start of the central directory in the zipfile.
457 // We keep this lying around so that we can sanity check all our lengths
458 // and our per-file structures.
459 const off64_t cd_offset = archive->directory_offset;
460
461 // Fill out the compression method, modification time, crc32
462 // and other interesting attributes from the central directory. These
463 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100464 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900465 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100466 data->crc32 = cdr->crc32;
467 data->compressed_length = cdr->compressed_size;
468 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000469
470 // Figure out the local header offset from the central directory. The
471 // actual file data will begin after the local header and the name /
472 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100473 const off64_t local_header_offset = cdr->local_file_header_offset;
474 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000475 ALOGW("Zip: bad local hdr offset in zip");
476 return kInvalidOffset;
477 }
478
Narayan Kamath926973e2014-06-09 14:18:14 +0100479 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700480 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800481 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900482 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000483 return kIoError;
484 }
485
Jiyong Parkcd997e62017-06-30 17:23:33 +0900486 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100487
488 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700489 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900490 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000491 return kInvalidOffset;
492 }
493
494 // Paranoia: Match the values specified in the local file header
495 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700496
Narayan Kamath162b7052017-06-05 13:21:12 +0100497 // Warn if central directory and local file header don't agree on the use
498 // of a trailing Data Descriptor. The reference implementation is inconsistent
499 // and appears to use the LFH value during extraction (unzip) but the CD value
500 // while displayng information about archives (zipinfo). The spec remains
501 // silent on this inconsistency as well.
502 //
503 // For now, always use the version from the LFH but make sure that the values
504 // specified in the central directory match those in the data descriptor.
505 //
506 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
507 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
508 // encoded using UTF-8). This implementation does not check for the presence of
509 // that flag and always enforces that entry names are valid UTF-8.
510 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
511 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700512 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700513 }
514
515 // If there is no trailing data descriptor, verify that the central directory and local file
516 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100517 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000518 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900519 if (data->compressed_length != lfh->compressed_size ||
520 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
521 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
522 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
523 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
524 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000525 return kInconsistentInformation;
526 }
527 } else {
528 data->has_data_descriptor = 1;
529 }
530
Elliott Hughes55fd2932017-05-28 22:59:04 -0700531 // 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 -0700532 data->version_made_by = cdr->version_made_by;
Elliott Hughesd5095252019-10-28 21:35:52 -0700533 data->external_file_attributes = cdr->external_file_attributes;
Elliott Hughes26724132019-10-25 09:57:58 -0700534 if ((data->version_made_by >> 8) == 3) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700535 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
536 } else {
537 data->unix_mode = 0777;
538 }
539
Elliott Hughesd5095252019-10-28 21:35:52 -0700540 // 4.4.4: general purpose bit flags.
541 data->gpbf = lfh->gpb_flags;
542
Elliott Hughes26724132019-10-25 09:57:58 -0700543 // 4.4.14: the lowest bit of the internal file attributes field indicates text.
544 // Currently only needed to implement zipinfo.
545 data->is_text = (cdr->internal_file_attributes & 1);
546
Narayan Kamath7462f022013-11-21 13:05:04 +0000547 // Check that the local file header name matches the declared
548 // name in the central directory.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800549 CHECK_LE(entryName.size(), UINT16_MAX);
550 auto nameLen = static_cast<uint16_t>(entryName.size());
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700551 if (lfh->file_name_length != nameLen) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800552 ALOGW("Zip: lfh name length did not match central directory for %s: %" PRIu16 " %" PRIu16,
553 std::string(entryName).c_str(), lfh->file_name_length, nameLen);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700554 return kInconsistentInformation;
555 }
556 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
557 if (name_offset + lfh->file_name_length > cd_offset) {
558 ALOGW("Zip: lfh name has invalid declared length");
559 return kInvalidOffset;
560 }
561 std::vector<uint8_t> name_buf(nameLen);
562 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
563 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
564 return kIoError;
565 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800566 if (memcmp(entryName.data(), name_buf.data(), nameLen) != 0) {
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700567 ALOGW("Zip: lfh name did not match central directory");
Narayan Kamath7462f022013-11-21 13:05:04 +0000568 return kInconsistentInformation;
569 }
570
Jiyong Parkcd997e62017-06-30 17:23:33 +0900571 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
572 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000573 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800574 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000575 return kInvalidOffset;
576 }
577
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800578 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700579 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900580 static_cast<int64_t>(data_offset), data->compressed_length,
581 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000582 return kInvalidOffset;
583 }
584
585 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900586 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
587 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
588 static_cast<int64_t>(data_offset), data->uncompressed_length,
589 static_cast<int64_t>(cd_offset));
590 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000591 }
592
593 data->offset = data_offset;
594 return 0;
595}
596
597struct IterationHandle {
Narayan Kamath7462f022013-11-21 13:05:04 +0000598 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100599
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700600 std::string prefix;
601 std::string suffix;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700602
603 uint32_t position = 0;
604
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700605 IterationHandle(ZipArchive* archive, std::string_view in_prefix, std::string_view in_suffix)
606 : archive(archive), prefix(in_prefix), suffix(in_suffix) {}
Narayan Kamath7462f022013-11-21 13:05:04 +0000607};
608
Ryan Prichard3673f992018-10-10 22:41:14 -0700609int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700610 const std::string_view optional_prefix,
611 const std::string_view optional_suffix) {
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800612 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000613 ALOGW("Zip: Invalid ZipArchiveHandle");
614 return kInvalidHandle;
615 }
616
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700617 if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
618 optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
619 ALOGW("Zip: prefix/suffix too long");
620 return kInvalidEntryName;
621 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000622
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800623 archive->cd_entry_map->ResetIteration();
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700624 *cookie_ptr = new IterationHandle(archive, optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000625 return 0;
626}
627
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100628void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100629 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100630}
631
Elliott Hughesb17bf522019-05-03 22:38:44 -0700632int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
633 ZipEntry* data) {
634 if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
635 ALOGW("Zip: Invalid filename of length %zu", entryName.size());
636 return kInvalidEntryName;
637 }
638
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800639 const auto [result, offset] =
640 archive->cd_entry_map->GetCdEntryOffset(entryName, archive->central_directory.GetBasePtr());
641 if (result != 0) {
Elliott Hughesb17bf522019-05-03 22:38:44 -0700642 ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800643 return static_cast<int32_t>(result); // kEntryNotFound is safe to truncate.
Elliott Hughesb17bf522019-05-03 22:38:44 -0700644 }
Elliott Hughesa5ff19e2019-05-07 09:27:59 -0700645 // We know there are at most hash_table_size entries, safe to truncate.
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800646 return FindEntry(archive, entryName, offset, data);
Elliott Hughesb17bf522019-05-03 22:38:44 -0700647}
648
Elliott Hughese06a8082019-05-22 18:56:41 -0700649int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
Elliott Hughes1e40c302019-06-12 12:12:47 -0700650 std::string_view sv;
651 int32_t result = Next(cookie, data, &sv);
652 if (result == 0 && name) {
653 *name = std::string(sv);
654 }
655 return result;
656}
657
658int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800659 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800660 if (handle == nullptr) {
Zimuzo5a503ef2018-09-17 19:49:55 +0100661 ALOGW("Zip: Null ZipArchiveHandle");
Narayan Kamath7462f022013-11-21 13:05:04 +0000662 return kInvalidHandle;
663 }
664
665 ZipArchive* archive = handle->archive;
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800666 if (archive == nullptr || archive->cd_entry_map == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000667 ALOGW("Zip: Invalid ZipArchiveHandle");
668 return kInvalidHandle;
669 }
670
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800671 auto entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
672 while (entry != std::pair<std::string_view, uint64_t>()) {
673 const auto [entry_name, offset] = entry;
674 if (android::base::StartsWith(entry_name, handle->prefix) &&
675 android::base::EndsWith(entry_name, handle->suffix)) {
676 const int error = FindEntry(archive, entry_name, offset, data);
Elliott Hughes50ef29a2019-06-18 18:23:59 -0700677 if (!error && name) {
678 *name = entry_name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000679 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000680 return error;
681 }
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800682 entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
Narayan Kamath7462f022013-11-21 13:05:04 +0000683 }
684
Tianjie Xu28f8eae2020-03-05 16:31:23 -0800685 archive->cd_entry_map->ResetIteration();
Narayan Kamath7462f022013-11-21 13:05:04 +0000686 return kIterationEnd;
687}
688
Narayan Kamathf899bd52015-04-17 11:53:14 +0100689// A Writer that writes data to a fixed size memory region.
690// The size of the memory region must be equal to the total size of
691// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100692class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100693 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900694 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100695
696 virtual bool Append(uint8_t* buf, size_t buf_size) override {
697 if (bytes_written_ + buf_size > size_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700698 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900699 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100700 return false;
701 }
702
703 memcpy(buf_ + bytes_written_, buf, buf_size);
704 bytes_written_ += buf_size;
705 return true;
706 }
707
708 private:
709 uint8_t* const buf_;
710 const size_t size_;
711 size_t bytes_written_;
712};
713
714// A Writer that appends data to a file |fd| at its current position.
715// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100716class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100717 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100718 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
719 // guaranteeing that the file descriptor is valid and that there's enough
720 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800721 // is truncated to the correct length (no truncation if |fd| references a
722 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100723 //
724 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800725 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100726 const uint32_t declared_length = entry->uncompressed_length;
727 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
728 if (current_offset == -1) {
729 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800730 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100731 }
732
Narayan Kamathf899bd52015-04-17 11:53:14 +0100733#if defined(__linux__)
734 if (declared_length > 0) {
735 // Make sure we have enough space on the volume to extract the compressed
736 // entry. Note that the call to ftruncate below will change the file size but
737 // will not allocate space on disk and this call to fallocate will not
738 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700739 // Note: fallocate is only supported by the following filesystems -
740 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
741 // EOPNOTSUPP error when issued in other filesystems.
742 // Hence, check for the return error code before concluding that the
743 // disk does not have enough space.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700744 long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700745 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700746 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100747 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
748 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800749 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100750 }
751 }
752#endif // __linux__
753
Tao Baoa456c212016-11-15 10:08:07 -0800754 struct stat sb;
755 if (fstat(fd, &sb) == -1) {
756 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800757 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100758 }
759
Tao Baoa456c212016-11-15 10:08:07 -0800760 // Block device doesn't support ftruncate(2).
761 if (!S_ISBLK(sb.st_mode)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700762 long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
Tao Baoa456c212016-11-15 10:08:07 -0800763 if (result == -1) {
764 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
765 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800766 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800767 }
768 }
769
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800770 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100771 }
772
Chih-Hung Hsieh747eb142018-09-25 11:16:22 -0700773 FileWriter(FileWriter&& other) noexcept
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800774 : fd_(other.fd_),
775 declared_length_(other.declared_length_),
776 total_bytes_written_(other.total_bytes_written_) {
777 other.fd_ = -1;
778 }
779
780 bool IsValid() const { return fd_ != -1; }
781
Narayan Kamathf899bd52015-04-17 11:53:14 +0100782 virtual bool Append(uint8_t* buf, size_t buf_size) override {
783 if (total_bytes_written_ + buf_size > declared_length_) {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700784 ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", declared_length_,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900785 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100786 return false;
787 }
788
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100789 const bool result = android::base::WriteFully(fd_, buf, buf_size);
790 if (result) {
791 total_bytes_written_ += buf_size;
792 } else {
Elliott Hughese8f4b142018-10-19 16:09:39 -0700793 ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100794 }
795
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100796 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100797 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900798
Narayan Kamathf899bd52015-04-17 11:53:14 +0100799 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800800 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900801 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100802
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800803 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100804 const size_t declared_length_;
805 size_t total_bytes_written_;
806};
807
Narayan Kamath485b3642017-10-26 14:42:39 +0100808class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100809 public:
810 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
811 : Reader(), zip_file_(zip_file), entry_(entry) {}
812
813 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
814 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
815 }
816
817 virtual ~EntryReader() {}
818
819 private:
820 const MappedZipFile& zip_file_;
821 const ZipEntry* entry_;
822};
823
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800824// This method is using libz macros with old-style-casts
825#pragma GCC diagnostic push
826#pragma GCC diagnostic ignored "-Wold-style-cast"
827static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
828 return inflateInit2(stream, window_bits);
829}
830#pragma GCC diagnostic pop
831
Narayan Kamath485b3642017-10-26 14:42:39 +0100832namespace zip_archive {
833
834// Moved out of line to avoid -Wweak-vtables.
835Reader::~Reader() {}
836Writer::~Writer() {}
837
838int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
839 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700840 const size_t kBufSize = 32768;
841 std::vector<uint8_t> read_buf(kBufSize);
842 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000843 z_stream zstream;
844 int zerr;
845
846 /*
847 * Initialize the zlib stream struct.
848 */
849 memset(&zstream, 0, sizeof(zstream));
850 zstream.zalloc = Z_NULL;
851 zstream.zfree = Z_NULL;
852 zstream.opaque = Z_NULL;
853 zstream.next_in = NULL;
854 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700855 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000856 zstream.avail_out = kBufSize;
857 zstream.data_type = Z_UNKNOWN;
858
859 /*
860 * Use the undocumented "negative window bits" feature to tell zlib
861 * that there's no zlib header waiting for it.
862 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800863 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000864 if (zerr != Z_OK) {
865 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900866 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000867 } else {
868 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
869 }
870
871 return kZlibError;
872 }
873
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800874 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900875 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800876 };
877
878 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
879
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000880 const bool compute_crc = (crc_out != nullptr);
Andreas Gampe964b95c2019-04-05 13:48:02 -0700881 uLong crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100882 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000883 do {
884 /* read as much as we can */
885 if (zstream.avail_in == 0) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700886 const uint32_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100887 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700888 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100889 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700890 ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800891 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000892 }
893
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100894 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000895
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700896 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100897 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000898 }
899
900 /* uncompress the data */
901 zerr = inflate(&zstream, Z_NO_FLUSH);
902 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900903 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
904 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800905 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000906 }
907
908 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900909 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700910 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100911 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000912 return kIoError;
913 } else if (compute_crc) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700914 DCHECK_LE(write_size, kBufSize);
915 crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
Narayan Kamath7462f022013-11-21 13:05:04 +0000916 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000917
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700918 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000919 zstream.avail_out = kBufSize;
920 }
921 } while (zerr == Z_OK);
922
Elliott Hughese8f4b142018-10-19 16:09:39 -0700923 CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +0000924
Narayan Kamath162b7052017-06-05 13:21:12 +0100925 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
926 // "feature" of zlib to tell it there won't be a zlib file header. zlib
927 // doesn't bother calculating the checksum in that scenario. We just do
928 // it ourselves above because there are no additional gains to be made by
929 // having zlib calculate it for us, since they do it by calling crc32 in
930 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000931 if (compute_crc) {
932 *crc_out = crc;
933 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000934
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100935 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900936 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
937 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800938 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +0000939 }
940
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800941 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000942}
Narayan Kamath485b3642017-10-26 14:42:39 +0100943} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +0000944
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100945static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +0100946 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100947 const EntryReader reader(mapped_zip, entry);
948
Narayan Kamath485b3642017-10-26 14:42:39 +0100949 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
950 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100951}
952
Narayan Kamath485b3642017-10-26 14:42:39 +0100953static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
954 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100955 static const uint32_t kBufSize = 32768;
956 std::vector<uint8_t> buf(kBufSize);
957
958 const uint32_t length = entry->uncompressed_length;
959 uint32_t count = 0;
Andreas Gampe964b95c2019-04-05 13:48:02 -0700960 uLong crc = 0;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100961 while (count < length) {
962 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -0700963 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100964
Adam Lesinskide117e42017-06-19 10:27:38 -0700965 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Andreas Gampe964b95c2019-04-05 13:48:02 -0700966 const uint32_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -0700967
968 // Make sure to read at offset to ensure concurrent access to the fd.
969 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
Andreas Gampe964b95c2019-04-05 13:48:02 -0700970 ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
Adam Lesinskide117e42017-06-19 10:27:38 -0700971 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100972 return kIoError;
973 }
974
975 if (!writer->Append(&buf[0], block_size)) {
976 return kIoError;
977 }
978 crc = crc32(crc, &buf[0], block_size);
979 count += block_size;
980 }
981
982 *crc_out = crc;
983
984 return 0;
985}
986
Ryan Prichard3673f992018-10-10 22:41:14 -0700987int32_t ExtractToWriter(ZipArchiveHandle archive, ZipEntry* entry, zip_archive::Writer* writer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000988 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +0000989
990 // this should default to kUnknownCompressionMethod.
991 int32_t return_value = -1;
992 uint64_t crc = 0;
993 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700994 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +0000995 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700996 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +0000997 }
998
999 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001000 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001001 if (return_value) {
1002 return return_value;
1003 }
1004 }
1005
Narayan Kamath162b7052017-06-05 13:21:12 +01001006 // Validate that the CRC matches the calculated value.
1007 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001008 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001009 return kInconsistentInformation;
1010 }
1011
1012 return return_value;
1013}
1014
Ryan Prichard3673f992018-10-10 22:41:14 -07001015int32_t ExtractToMemory(ZipArchiveHandle archive, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001016 MemoryWriter writer(begin, size);
Ryan Prichard3673f992018-10-10 22:41:14 -07001017 return ExtractToWriter(archive, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001018}
1019
Ryan Prichard3673f992018-10-10 22:41:14 -07001020int32_t ExtractEntryToFile(ZipArchiveHandle archive, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001021 auto writer = FileWriter::Create(fd, entry);
1022 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001023 return kIoError;
1024 }
1025
Ryan Prichard3673f992018-10-10 22:41:14 -07001026 return ExtractToWriter(archive, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001027}
1028
1029const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001030 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1031 // match.
1032 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1033 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1034
1035 const uint32_t idx = -error_code;
1036 if (idx < arraysize(kErrorMessages)) {
1037 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001038 }
1039
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001040 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001041}
1042
Ryan Prichard3673f992018-10-10 22:41:14 -07001043int GetFileDescriptor(const ZipArchiveHandle archive) {
1044 return archive->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001045}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001046
Tianjie Xu18c25922016-09-29 15:27:41 -07001047#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001048class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001049 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001050 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1051 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001052
1053 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1054 return proc_function_(buf, buf_size, cookie_);
1055 }
1056
1057 private:
1058 ProcessZipEntryFunction proc_function_;
1059 void* cookie_;
1060};
1061
Ryan Prichard3673f992018-10-10 22:41:14 -07001062int32_t ProcessZipEntryContents(ZipArchiveHandle archive, ZipEntry* entry,
Tianjie Xu18c25922016-09-29 15:27:41 -07001063 ProcessZipEntryFunction func, void* cookie) {
1064 ProcessWriter writer(func, cookie);
Ryan Prichard3673f992018-10-10 22:41:14 -07001065 return ExtractToWriter(archive, entry, &writer);
Tianjie Xu18c25922016-09-29 15:27:41 -07001066}
1067
Jiyong Parkcd997e62017-06-30 17:23:33 +09001068#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001069
1070int MappedZipFile::GetFileDescriptor() const {
1071 if (!has_fd_) {
1072 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1073 return -1;
1074 }
1075 return fd_;
1076}
1077
Elliott Hughesf66460b2019-10-22 11:44:50 -07001078const void* MappedZipFile::GetBasePtr() const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001079 if (has_fd_) {
1080 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1081 return nullptr;
1082 }
1083 return base_ptr_;
1084}
1085
1086off64_t MappedZipFile::GetFileLength() const {
1087 if (has_fd_) {
1088 off64_t result = lseek64(fd_, 0, SEEK_END);
1089 if (result == -1) {
1090 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1091 }
1092 return result;
1093 } else {
1094 if (base_ptr_ == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001095 ALOGE("Zip: invalid file map");
Tianjie Xu18c25922016-09-29 15:27:41 -07001096 return -1;
1097 }
1098 return static_cast<off64_t>(data_length_);
1099 }
1100}
1101
Tianjie Xu18c25922016-09-29 15:27:41 -07001102// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001103bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001104 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001105 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001106 ALOGE("Zip: failed to read at offset %" PRId64, off);
Tianjie Xu18c25922016-09-29 15:27:41 -07001107 return false;
1108 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001109 } else {
1110 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001111 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64, off, data_length_);
Adam Lesinskide117e42017-06-19 10:27:38 -07001112 return false;
1113 }
Elliott Hughesf66460b2019-10-22 11:44:50 -07001114 memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001115 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001116 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001117}
1118
Elliott Hughesf66460b2019-10-22 11:44:50 -07001119void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1120 size_t cd_size) {
1121 base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
Tianjie Xu18c25922016-09-29 15:27:41 -07001122 length_ = cd_size;
1123}
1124
Elliott Hughese8f4b142018-10-19 16:09:39 -07001125bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001126 if (mapped_zip.HasFd()) {
Elliott Hughese8f4b142018-10-19 16:09:39 -07001127 directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1128 cd_start_offset, cd_size, PROT_READ);
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001129 if (!directory_map) {
1130 ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1131 cd_start_offset, cd_size, strerror(errno));
1132 return false;
1133 }
Tianjie Xu18c25922016-09-29 15:27:41 -07001134
Elliott Hughese8f4b142018-10-19 16:09:39 -07001135 CHECK_EQ(directory_map->size(), cd_size);
1136 central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001137 } else {
1138 if (mapped_zip.GetBasePtr() == nullptr) {
Elliott Hughesfba2a1a2019-12-16 16:16:16 -08001139 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
Tianjie Xu18c25922016-09-29 15:27:41 -07001140 return false;
1141 }
1142 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1143 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001144 ALOGE(
1145 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1146 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1147 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001148 return false;
1149 }
1150
1151 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1152 }
1153 return true;
1154}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001155
1156tm ZipEntry::GetModificationTime() const {
1157 tm t = {};
1158
1159 t.tm_hour = (mod_time >> 11) & 0x1f;
1160 t.tm_min = (mod_time >> 5) & 0x3f;
1161 t.tm_sec = (mod_time & 0x1f) << 1;
1162
1163 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1164 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1165 t.tm_mday = (mod_time >> 16) & 0x1f;
1166
1167 return t;
1168}