blob: 6da5c99bdade192424ead62b8a5b2a5e1a6b6724 [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
Narayan Kamath7462f022013-11-21 13:05:04 +000023#include <assert.h>
24#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070025#include <fcntl.h>
26#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000027#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <stdlib.h>
29#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070030#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000031#include <unistd.h>
32
Dan Albert1ae07642015-04-09 14:11:18 -070033#include <memory>
34#include <vector>
35
Mark Salyzynff2dcd92016-09-28 15:54:45 -070036#include <android-base/file.h>
37#include <android-base/logging.h>
38#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
39#include <android-base/memory.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070040#include <log/log.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070041#include <utils/Compat.h>
42#include <utils/FileMap.h>
Christopher Ferrise6884ce2015-11-10 14:55:12 -080043#include "ziparchive/zip_archive.h"
Dan Albert1ae07642015-04-09 14:11:18 -070044#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000045
Narayan Kamath044bc8e2014-12-03 18:22:53 +000046#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070047#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080048#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070049
Dan Albert1ae07642015-04-09 14:11:18 -070050using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000051
Narayan Kamath162b7052017-06-05 13:21:12 +010052// Used to turn on crc checks - verify that the content CRC matches the values
53// specified in the local file header and the central directory.
54static const bool kCrcChecksEnabled = false;
55
Narayan Kamath926973e2014-06-09 14:18:14 +010056// This is for windows. If we don't open a file in binary mode, weird
Narayan Kamath7462f022013-11-21 13:05:04 +000057// things will happen.
58#ifndef O_BINARY
59#define O_BINARY 0
60#endif
61
Narayan Kamath926973e2014-06-09 14:18:14 +010062// The maximum number of bytes to scan backwards for the EOCD start.
63static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
64
Narayan Kamath7462f022013-11-21 13:05:04 +000065/*
66 * A Read-only Zip archive.
67 *
68 * We want "open" and "find entry by name" to be fast operations, and
69 * we want to use as little memory as possible. We memory-map the zip
70 * central directory, and load a hash table with pointers to the filenames
71 * (which aren't null-terminated). The other fields are at a fixed offset
72 * from the filename, so we don't need to extract those (but we do need
73 * to byte-read and endian-swap them every time we want them).
74 *
75 * It's possible that somebody has handed us a massive (~1GB) zip archive,
76 * so we can't expect to mmap the entire file.
77 *
78 * To speed comparisons when doing a lookup by name, we could make the mapping
79 * "private" (copy-on-write) and null-terminate the filenames after verifying
80 * the record structure. However, this requires a private mapping of
81 * every page that the Central Directory touches. Easier to tuck a copy
82 * of the string length into the hash table entry.
83 */
Narayan Kamath7462f022013-11-21 13:05:04 +000084
Narayan Kamath7462f022013-11-21 13:05:04 +000085/*
86 * Round up to the next highest power of 2.
87 *
88 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
89 */
90static uint32_t RoundUpPower2(uint32_t val) {
91 val--;
92 val |= val >> 1;
93 val |= val >> 2;
94 val |= val >> 4;
95 val |= val >> 8;
96 val |= val >> 16;
97 val++;
98
99 return val;
100}
101
Yusuke Sato07447542015-06-25 14:39:19 -0700102static uint32_t ComputeHash(const ZipString& name) {
Sebastian Pop1f93d712017-11-28 16:36:48 -0600103#if !defined(_WIN32)
104 return std::hash<std::string_view>{}(
105 std::string_view(reinterpret_cast<const char*>(name.name), name.name_length));
106#else
107 // Remove this code path once the windows compiler knows how to compile the above statement.
Narayan Kamath7462f022013-11-21 13:05:04 +0000108 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100109 uint16_t len = name.name_length;
110 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000111
112 while (len--) {
113 hash = hash * 31 + *str++;
114 }
115
116 return hash;
Sebastian Pop1f93d712017-11-28 16:36:48 -0600117#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000118}
119
120/*
121 * Convert a ZipEntry to a hash table index, verifying that it's in a
122 * valid range.
123 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900124static int64_t EntryToIndex(const ZipString* hash_table, const uint32_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700125 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100126 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000127
128 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
129 uint32_t ent = hash & (hash_table_size - 1);
130 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700131 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000132 return ent;
133 }
134
135 ent = (ent + 1) & (hash_table_size - 1);
136 }
137
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100138 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000139 return kEntryNotFound;
140}
141
142/*
143 * Add a new entry to the hash table.
144 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900145static int32_t AddToHash(ZipString* hash_table, const uint64_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700146 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100147 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000148 uint32_t ent = hash & (hash_table_size - 1);
149
150 /*
151 * We over-allocated the table, so we're guaranteed to find an empty slot.
152 * Further, we guarantee that the hashtable size is not 0.
153 */
154 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700155 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000156 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100157 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000158 return kDuplicateEntry;
159 }
160 ent = (ent + 1) & (hash_table_size - 1);
161 }
162
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100163 hash_table[ent].name = name.name;
164 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000165 return 0;
166}
167
Tianjie Xu18c25922016-09-29 15:27:41 -0700168static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900169 off64_t file_length, off64_t read_amount, uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000170 const off64_t search_start = file_length - read_amount;
171
Jiyong Parkcd997e62017-06-30 17:23:33 +0900172 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
173 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
174 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000175 return kIoError;
176 }
177
178 /*
179 * Scan backward for the EOCD magic. In an archive without a trailing
180 * comment, we'll find it on the first try. (We may want to consider
181 * doing an initial minimal read; if we don't find it, retry with a
182 * second read as above.)
183 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100184 int i = read_amount - sizeof(EocdRecord);
185 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700186 if (scan_buffer[i] == 0x50) {
187 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
188 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
189 ALOGV("+++ Found EOCD at buf+%d", i);
190 break;
191 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000192 }
193 }
194 if (i < 0) {
195 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
196 return kInvalidFile;
197 }
198
199 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100200 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000201 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100202 * Verify that there's no trailing space at the end of the central directory
203 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000204 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900205 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100206 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100207 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100208 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100209 return kInvalidFile;
210 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000211
Narayan Kamath926973e2014-06-09 14:18:14 +0100212 /*
213 * Grab the CD offset and size, and the number of entries in the
214 * archive and verify that they look reasonable.
215 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700216 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100217 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900218 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700219#if defined(__ANDROID__)
220 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
221 android_errorWriteLog(0x534e4554, "31251826");
222 }
223#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000224 return kInvalidOffset;
225 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100226 if (eocd->num_records == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000227 ALOGW("Zip: empty archive?");
228 return kEmptyArchive;
229 }
230
Jiyong Parkcd997e62017-06-30 17:23:33 +0900231 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
232 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000233
234 /*
235 * It all looks good. Create a mapping for the CD, and set the fields
236 * in archive.
237 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700238
239 if (!archive->InitializeCentralDirectory(debug_file_name,
240 static_cast<off64_t>(eocd->cd_start_offset),
241 static_cast<size_t>(eocd->cd_size))) {
242 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000243 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000244 }
245
Narayan Kamath926973e2014-06-09 14:18:14 +0100246 archive->num_entries = eocd->num_records;
247 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000248
249 return 0;
250}
251
252/*
253 * Find the zip Central Directory and memory-map it.
254 *
255 * On success, returns 0 after populating fields from the EOCD area:
256 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700257 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000258 * num_entries
259 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700260static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000261 // Test file length. We use lseek64 to make sure the file
262 // is small enough to be a zip file (Its size must be less than
263 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700264 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000265 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000266 return kInvalidFile;
267 }
268
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800269 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100270 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000271 return kInvalidFile;
272 }
273
Narayan Kamath926973e2014-06-09 14:18:14 +0100274 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
275 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000276 return kInvalidFile;
277 }
278
279 /*
280 * Perform the traditional EOCD snipe hunt.
281 *
282 * We're searching for the End of Central Directory magic number,
283 * which appears at the start of the EOCD block. It's followed by
284 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
285 * need to read the last part of the file into a buffer, dig through
286 * it to find the magic number, parse some values out, and use those
287 * to determine the extent of the CD.
288 *
289 * We start by pulling in the last part of the file.
290 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100291 off64_t read_amount = kMaxEOCDSearch;
292 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000293 read_amount = file_length;
294 }
295
Tianjie Xu18c25922016-09-29 15:27:41 -0700296 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900297 int32_t result =
298 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000299 return result;
300}
301
302/*
303 * Parses the Zip archive's Central Directory. Allocates and populates the
304 * hash table.
305 *
306 * Returns 0 on success.
307 */
308static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700309 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
310 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100311 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000312
313 /*
314 * Create hash table. We have a minimum 75% load factor, possibly as
315 * low as 50% after we round off to a power of 2. There must be at
316 * least one unused entry to avoid an infinite loop during creation.
317 */
318 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900319 archive->hash_table =
320 reinterpret_cast<ZipString*>(calloc(archive->hash_table_size, sizeof(ZipString)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700321 if (archive->hash_table == nullptr) {
322 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
323 archive->hash_table_size, sizeof(ZipString));
324 return -1;
325 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000326
327 /*
328 * Walk through the central directory, adding entries to the hash
329 * table and verifying values.
330 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100331 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000332 const uint8_t* ptr = cd_ptr;
333 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700334 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
335 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
336#if defined(__ANDROID__)
337 android_errorWriteLog(0x534e4554, "36392138");
338#endif
339 return -1;
340 }
341
Jiyong Parkcd997e62017-06-30 17:23:33 +0900342 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100343 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700344 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800345 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000346 }
347
Narayan Kamath926973e2014-06-09 14:18:14 +0100348 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000349 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800350 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900351 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800352 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000353 }
354
Narayan Kamath926973e2014-06-09 14:18:14 +0100355 const uint16_t file_name_length = cdr->file_name_length;
356 const uint16_t extra_length = cdr->extra_field_length;
357 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100358 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
359
Tianjie Xu9e020e22016-10-10 12:11:30 -0700360 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900361 ALOGW(
362 "Zip: file name boundary exceeds the central directory range, file_name_length: "
363 "%" PRIx16 ", cd_length: %zu",
364 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700365 return -1;
366 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000367 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
368 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800369 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100370 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000371
372 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700373 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100374 entry_name.name = file_name;
375 entry_name.name_length = file_name_length;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900376 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800377 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000378 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800379 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000380 }
381
Narayan Kamath926973e2014-06-09 14:18:14 +0100382 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
383 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900384 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800385 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000386 }
387 }
Mark Salyzyn088bf902014-05-08 16:02:20 -0700388 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000389
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800390 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000391}
392
Jiyong Parkcd997e62017-06-30 17:23:33 +0900393static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000394 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700395 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000396 return result;
397 }
398
399 if ((result = ParseZipArchive(archive))) {
400 return result;
401 }
402
403 return 0;
404}
405
Jiyong Parkcd997e62017-06-30 17:23:33 +0900406int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
407 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700408 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000409 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000410 return OpenArchiveInternal(archive, debug_file_name);
411}
412
413int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100414 const int fd = open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700415 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000416 *handle = archive;
417
Narayan Kamath7462f022013-11-21 13:05:04 +0000418 if (fd < 0) {
419 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
420 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000421 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700422
Narayan Kamath7462f022013-11-21 13:05:04 +0000423 return OpenArchiveInternal(archive, fileName);
424}
425
Tianjie Xu18c25922016-09-29 15:27:41 -0700426int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900427 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700428 ZipArchive* archive = new ZipArchive(address, length);
429 *handle = archive;
430 return OpenArchiveInternal(archive, debug_file_name);
431}
432
Narayan Kamath7462f022013-11-21 13:05:04 +0000433/*
434 * Close a ZipArchive, closing the file and freeing the contents.
435 */
436void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800437 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000438 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100439 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000440}
441
Narayan Kamath162b7052017-06-05 13:21:12 +0100442static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100443 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700444 off64_t offset = entry->offset;
445 if (entry->method != kCompressStored) {
446 offset += entry->compressed_length;
447 } else {
448 offset += entry->uncompressed_length;
449 }
450
451 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000452 return kIoError;
453 }
454
Narayan Kamath926973e2014-06-09 14:18:14 +0100455 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700456 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
457 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000458
Narayan Kamath162b7052017-06-05 13:21:12 +0100459 // Validate that the values in the data descriptor match those in the central
460 // directory.
461 if (entry->compressed_length != descriptor->compressed_size ||
462 entry->uncompressed_length != descriptor->uncompressed_size ||
463 entry->crc32 != descriptor->crc32) {
464 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
465 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
466 entry->compressed_length, entry->uncompressed_length, entry->crc32,
467 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
468 return kInconsistentInformation;
469 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000470
471 return 0;
472}
473
Jiyong Parkcd997e62017-06-30 17:23:33 +0900474static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000475 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000476
477 // Recover the start of the central directory entry from the filename
478 // pointer. The filename is the first entry past the fixed-size data,
479 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100480 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100481 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000482
483 // This is the base of our mmapped region, we have to sanity check that
484 // the name that's in the hash table is a pointer to a location within
485 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700486 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
487 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000488 ALOGW("Zip: Invalid entry pointer");
489 return kInvalidOffset;
490 }
491
Jiyong Parkcd997e62017-06-30 17:23:33 +0900492 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100493
Narayan Kamath7462f022013-11-21 13:05:04 +0000494 // The offset of the start of the central directory in the zipfile.
495 // We keep this lying around so that we can sanity check all our lengths
496 // and our per-file structures.
497 const off64_t cd_offset = archive->directory_offset;
498
499 // Fill out the compression method, modification time, crc32
500 // and other interesting attributes from the central directory. These
501 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100502 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900503 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100504 data->crc32 = cdr->crc32;
505 data->compressed_length = cdr->compressed_size;
506 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000507
508 // Figure out the local header offset from the central directory. The
509 // actual file data will begin after the local header and the name /
510 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100511 const off64_t local_header_offset = cdr->local_file_header_offset;
512 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000513 ALOGW("Zip: bad local hdr offset in zip");
514 return kInvalidOffset;
515 }
516
Narayan Kamath926973e2014-06-09 14:18:14 +0100517 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700518 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800519 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900520 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000521 return kIoError;
522 }
523
Jiyong Parkcd997e62017-06-30 17:23:33 +0900524 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100525
526 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700527 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900528 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000529 return kInvalidOffset;
530 }
531
532 // Paranoia: Match the values specified in the local file header
533 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700534
Narayan Kamath162b7052017-06-05 13:21:12 +0100535 // Warn if central directory and local file header don't agree on the use
536 // of a trailing Data Descriptor. The reference implementation is inconsistent
537 // and appears to use the LFH value during extraction (unzip) but the CD value
538 // while displayng information about archives (zipinfo). The spec remains
539 // silent on this inconsistency as well.
540 //
541 // For now, always use the version from the LFH but make sure that the values
542 // specified in the central directory match those in the data descriptor.
543 //
544 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
545 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
546 // encoded using UTF-8). This implementation does not check for the presence of
547 // that flag and always enforces that entry names are valid UTF-8.
548 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
549 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700550 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700551 }
552
553 // If there is no trailing data descriptor, verify that the central directory and local file
554 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100555 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000556 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900557 if (data->compressed_length != lfh->compressed_size ||
558 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
559 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
560 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
561 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
562 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000563 return kInconsistentInformation;
564 }
565 } else {
566 data->has_data_descriptor = 1;
567 }
568
Elliott Hughes55fd2932017-05-28 22:59:04 -0700569 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
570 if ((cdr->version_made_by >> 8) == 3) {
571 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
572 } else {
573 data->unix_mode = 0777;
574 }
575
Narayan Kamath7462f022013-11-21 13:05:04 +0000576 // Check that the local file header name matches the declared
577 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100578 if (lfh->file_name_length == nameLen) {
579 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200580 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000581 ALOGW("Zip: Invalid declared length");
582 return kInvalidOffset;
583 }
584
Tianjie Xu18c25922016-09-29 15:27:41 -0700585 std::vector<uint8_t> name_buf(nameLen);
586 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800587 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000588 return kIoError;
589 }
590
Tianjie Xu18c25922016-09-29 15:27:41 -0700591 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000592 return kInconsistentInformation;
593 }
594
Narayan Kamath7462f022013-11-21 13:05:04 +0000595 } else {
596 ALOGW("Zip: lfh name did not match central directory.");
597 return kInconsistentInformation;
598 }
599
Jiyong Parkcd997e62017-06-30 17:23:33 +0900600 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
601 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000602 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800603 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000604 return kInvalidOffset;
605 }
606
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800607 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700608 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900609 static_cast<int64_t>(data_offset), data->compressed_length,
610 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000611 return kInvalidOffset;
612 }
613
614 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900615 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
616 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
617 static_cast<int64_t>(data_offset), data->uncompressed_length,
618 static_cast<int64_t>(cd_offset));
619 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000620 }
621
622 data->offset = data_offset;
623 return 0;
624}
625
626struct IterationHandle {
627 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100628 // We're not using vector here because this code is used in the Windows SDK
629 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700630 ZipString prefix;
631 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000632 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100633
Jiyong Parkcd997e62017-06-30 17:23:33 +0900634 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700635 if (in_prefix) {
636 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
637 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
638 prefix.name = name_copy;
639 prefix.name_length = in_prefix->name_length;
640 } else {
641 prefix.name = NULL;
642 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700643 }
Yusuke Sato07447542015-06-25 14:39:19 -0700644 if (in_suffix) {
645 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
646 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
647 suffix.name = name_copy;
648 suffix.name_length = in_suffix->name_length;
649 } else {
650 suffix.name = NULL;
651 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700652 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100653 }
654
655 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700656 delete[] prefix.name;
657 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100658 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000659};
660
Jiyong Parkcd997e62017-06-30 17:23:33 +0900661int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700662 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800663 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000664
665 if (archive == NULL || archive->hash_table == NULL) {
666 ALOGW("Zip: Invalid ZipArchiveHandle");
667 return kInvalidHandle;
668 }
669
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700670 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000671 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000672 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000673
Jiyong Parkcd997e62017-06-30 17:23:33 +0900674 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000675 return 0;
676}
677
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100678void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100679 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100680}
681
Jiyong Parkcd997e62017-06-30 17:23:33 +0900682int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800683 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100684 if (entryName.name_length == 0) {
685 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000686 return kInvalidEntryName;
687 }
688
Jiyong Parkcd997e62017-06-30 17:23:33 +0900689 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000690
691 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100692 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000693 return ent;
694 }
695
696 return FindEntry(archive, ent, data);
697}
698
Yusuke Sato07447542015-06-25 14:39:19 -0700699int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800700 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000701 if (handle == NULL) {
702 return kInvalidHandle;
703 }
704
705 ZipArchive* archive = handle->archive;
706 if (archive == NULL || archive->hash_table == NULL) {
707 ALOGW("Zip: Invalid ZipArchiveHandle");
708 return kInvalidHandle;
709 }
710
711 const uint32_t currentOffset = handle->position;
712 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700713 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000714
715 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
716 if (hash_table[i].name != NULL &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900717 (handle->prefix.name_length == 0 || hash_table[i].StartsWith(handle->prefix)) &&
718 (handle->suffix.name_length == 0 || hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000719 handle->position = (i + 1);
720 const int error = FindEntry(archive, i, data);
721 if (!error) {
722 name->name = hash_table[i].name;
723 name->name_length = hash_table[i].name_length;
724 }
725
726 return error;
727 }
728 }
729
730 handle->position = 0;
731 return kIterationEnd;
732}
733
Narayan Kamathf899bd52015-04-17 11:53:14 +0100734// A Writer that writes data to a fixed size memory region.
735// The size of the memory region must be equal to the total size of
736// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100737class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100738 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900739 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100740
741 virtual bool Append(uint8_t* buf, size_t buf_size) override {
742 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900743 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
744 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100745 return false;
746 }
747
748 memcpy(buf_ + bytes_written_, buf, buf_size);
749 bytes_written_ += buf_size;
750 return true;
751 }
752
753 private:
754 uint8_t* const buf_;
755 const size_t size_;
756 size_t bytes_written_;
757};
758
759// A Writer that appends data to a file |fd| at its current position.
760// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100761class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100762 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100763 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
764 // guaranteeing that the file descriptor is valid and that there's enough
765 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800766 // is truncated to the correct length (no truncation if |fd| references a
767 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100768 //
769 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
770 static std::unique_ptr<FileWriter> Create(int fd, const ZipEntry* entry) {
771 const uint32_t declared_length = entry->uncompressed_length;
772 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
773 if (current_offset == -1) {
774 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
775 return nullptr;
776 }
777
778 int result = 0;
779#if defined(__linux__)
780 if (declared_length > 0) {
781 // Make sure we have enough space on the volume to extract the compressed
782 // entry. Note that the call to ftruncate below will change the file size but
783 // will not allocate space on disk and this call to fallocate will not
784 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700785 // Note: fallocate is only supported by the following filesystems -
786 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
787 // EOPNOTSUPP error when issued in other filesystems.
788 // Hence, check for the return error code before concluding that the
789 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100790 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700791 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700792 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100793 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
794 strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100795 return std::unique_ptr<FileWriter>(nullptr);
796 }
797 }
798#endif // __linux__
799
Tao Baoa456c212016-11-15 10:08:07 -0800800 struct stat sb;
801 if (fstat(fd, &sb) == -1) {
802 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100803 return std::unique_ptr<FileWriter>(nullptr);
804 }
805
Tao Baoa456c212016-11-15 10:08:07 -0800806 // Block device doesn't support ftruncate(2).
807 if (!S_ISBLK(sb.st_mode)) {
808 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
809 if (result == -1) {
810 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
811 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
812 return std::unique_ptr<FileWriter>(nullptr);
813 }
814 }
815
Narayan Kamathf899bd52015-04-17 11:53:14 +0100816 return std::unique_ptr<FileWriter>(new FileWriter(fd, declared_length));
817 }
818
819 virtual bool Append(uint8_t* buf, size_t buf_size) override {
820 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900821 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
822 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100823 return false;
824 }
825
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100826 const bool result = android::base::WriteFully(fd_, buf, buf_size);
827 if (result) {
828 total_bytes_written_ += buf_size;
829 } else {
830 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100831 }
832
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100833 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100834 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900835
Narayan Kamathf899bd52015-04-17 11:53:14 +0100836 private:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900837 FileWriter(const int fd, const size_t declared_length)
838 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100839
840 const int fd_;
841 const size_t declared_length_;
842 size_t total_bytes_written_;
843};
844
Narayan Kamath485b3642017-10-26 14:42:39 +0100845class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100846 public:
847 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
848 : Reader(), zip_file_(zip_file), entry_(entry) {}
849
850 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
851 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
852 }
853
854 virtual ~EntryReader() {}
855
856 private:
857 const MappedZipFile& zip_file_;
858 const ZipEntry* entry_;
859};
860
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800861// This method is using libz macros with old-style-casts
862#pragma GCC diagnostic push
863#pragma GCC diagnostic ignored "-Wold-style-cast"
864static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
865 return inflateInit2(stream, window_bits);
866}
867#pragma GCC diagnostic pop
868
Narayan Kamath485b3642017-10-26 14:42:39 +0100869namespace zip_archive {
870
871// Moved out of line to avoid -Wweak-vtables.
872Reader::~Reader() {}
873Writer::~Writer() {}
874
875int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
876 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700877 const size_t kBufSize = 32768;
878 std::vector<uint8_t> read_buf(kBufSize);
879 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000880 z_stream zstream;
881 int zerr;
882
883 /*
884 * Initialize the zlib stream struct.
885 */
886 memset(&zstream, 0, sizeof(zstream));
887 zstream.zalloc = Z_NULL;
888 zstream.zfree = Z_NULL;
889 zstream.opaque = Z_NULL;
890 zstream.next_in = NULL;
891 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700892 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000893 zstream.avail_out = kBufSize;
894 zstream.data_type = Z_UNKNOWN;
895
896 /*
897 * Use the undocumented "negative window bits" feature to tell zlib
898 * that there's no zlib header waiting for it.
899 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800900 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000901 if (zerr != Z_OK) {
902 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900903 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000904 } else {
905 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
906 }
907
908 return kZlibError;
909 }
910
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800911 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900912 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800913 };
914
915 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
916
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000917 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100918 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100919 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000920 do {
921 /* read as much as we can */
922 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100923 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
924 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700925 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100926 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
927 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800928 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000929 }
930
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100931 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000932
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700933 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100934 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000935 }
936
937 /* uncompress the data */
938 zerr = inflate(&zstream, Z_NO_FLUSH);
939 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900940 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
941 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800942 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000943 }
944
945 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900946 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700947 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100948 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000949 return kIoError;
950 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +0100951 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +0000952 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000953
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700954 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000955 zstream.avail_out = kBufSize;
956 }
957 } while (zerr == Z_OK);
958
Jiyong Parkcd997e62017-06-30 17:23:33 +0900959 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +0000960
Narayan Kamath162b7052017-06-05 13:21:12 +0100961 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
962 // "feature" of zlib to tell it there won't be a zlib file header. zlib
963 // doesn't bother calculating the checksum in that scenario. We just do
964 // it ourselves above because there are no additional gains to be made by
965 // having zlib calculate it for us, since they do it by calling crc32 in
966 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000967 if (compute_crc) {
968 *crc_out = crc;
969 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000970
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100971 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900972 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
973 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800974 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +0000975 }
976
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800977 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000978}
Narayan Kamath485b3642017-10-26 14:42:39 +0100979} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +0000980
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100981static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +0100982 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100983 const EntryReader reader(mapped_zip, entry);
984
Narayan Kamath485b3642017-10-26 14:42:39 +0100985 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
986 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100987}
988
Narayan Kamath485b3642017-10-26 14:42:39 +0100989static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
990 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100991 static const uint32_t kBufSize = 32768;
992 std::vector<uint8_t> buf(kBufSize);
993
994 const uint32_t length = entry->uncompressed_length;
995 uint32_t count = 0;
996 uint64_t crc = 0;
997 while (count < length) {
998 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -0700999 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001000
Adam Lesinskide117e42017-06-19 10:27:38 -07001001 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001002 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001003
1004 // Make sure to read at offset to ensure concurrent access to the fd.
1005 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1006 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1007 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001008 return kIoError;
1009 }
1010
1011 if (!writer->Append(&buf[0], block_size)) {
1012 return kIoError;
1013 }
1014 crc = crc32(crc, &buf[0], block_size);
1015 count += block_size;
1016 }
1017
1018 *crc_out = crc;
1019
1020 return 0;
1021}
1022
Narayan Kamath485b3642017-10-26 14:42:39 +01001023int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001024 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001025 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001026
1027 // this should default to kUnknownCompressionMethod.
1028 int32_t return_value = -1;
1029 uint64_t crc = 0;
1030 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001031 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001032 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001033 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001034 }
1035
1036 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001037 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001038 if (return_value) {
1039 return return_value;
1040 }
1041 }
1042
Narayan Kamath162b7052017-06-05 13:21:12 +01001043 // Validate that the CRC matches the calculated value.
1044 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001045 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001046 return kInconsistentInformation;
1047 }
1048
1049 return return_value;
1050}
1051
Jiyong Parkcd997e62017-06-30 17:23:33 +09001052int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Narayan Kamath485b3642017-10-26 14:42:39 +01001053 std::unique_ptr<zip_archive::Writer> writer(new MemoryWriter(begin, size));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001054 return ExtractToWriter(handle, entry, writer.get());
1055}
1056
Jiyong Parkcd997e62017-06-30 17:23:33 +09001057int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Narayan Kamath485b3642017-10-26 14:42:39 +01001058 std::unique_ptr<zip_archive::Writer> writer(FileWriter::Create(fd, entry));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001059 if (writer.get() == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001060 return kIoError;
1061 }
1062
Narayan Kamathf899bd52015-04-17 11:53:14 +01001063 return ExtractToWriter(handle, entry, writer.get());
Narayan Kamath7462f022013-11-21 13:05:04 +00001064}
1065
1066const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001067 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1068 // match.
1069 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1070 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1071
1072 const uint32_t idx = -error_code;
1073 if (idx < arraysize(kErrorMessages)) {
1074 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001075 }
1076
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001077 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001078}
1079
1080int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001081 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001082}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001083
Jiyong Parkcd997e62017-06-30 17:23:33 +09001084ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001085 size_t len = strlen(entry_name);
1086 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1087 name_length = static_cast<uint16_t>(len);
1088}
Tianjie Xu18c25922016-09-29 15:27:41 -07001089
1090#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001091class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001092 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001093 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1094 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001095
1096 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1097 return proc_function_(buf, buf_size, cookie_);
1098 }
1099
1100 private:
1101 ProcessZipEntryFunction proc_function_;
1102 void* cookie_;
1103};
1104
1105int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1106 ProcessZipEntryFunction func, void* cookie) {
1107 ProcessWriter writer(func, cookie);
1108 return ExtractToWriter(handle, entry, &writer);
1109}
1110
Jiyong Parkcd997e62017-06-30 17:23:33 +09001111#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001112
1113int MappedZipFile::GetFileDescriptor() const {
1114 if (!has_fd_) {
1115 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1116 return -1;
1117 }
1118 return fd_;
1119}
1120
1121void* MappedZipFile::GetBasePtr() const {
1122 if (has_fd_) {
1123 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1124 return nullptr;
1125 }
1126 return base_ptr_;
1127}
1128
1129off64_t MappedZipFile::GetFileLength() const {
1130 if (has_fd_) {
1131 off64_t result = lseek64(fd_, 0, SEEK_END);
1132 if (result == -1) {
1133 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1134 }
1135 return result;
1136 } else {
1137 if (base_ptr_ == nullptr) {
1138 ALOGE("Zip: invalid file map\n");
1139 return -1;
1140 }
1141 return static_cast<off64_t>(data_length_);
1142 }
1143}
1144
Tianjie Xu18c25922016-09-29 15:27:41 -07001145// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001146bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001147 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001148 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001149 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1150 return false;
1151 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001152 } else {
1153 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1154 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1155 return false;
1156 }
1157 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001158 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001159 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001160}
1161
1162void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1163 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1164 length_ = cd_size;
1165}
1166
1167bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1168 size_t cd_size) {
1169 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001170 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1171 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001172 return false;
1173 }
1174
1175 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001176 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001177 } else {
1178 if (mapped_zip.GetBasePtr() == nullptr) {
1179 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1180 return false;
1181 }
1182 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1183 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001184 ALOGE(
1185 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1186 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1187 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001188 return false;
1189 }
1190
1191 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1192 }
1193 return true;
1194}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001195
1196tm ZipEntry::GetModificationTime() const {
1197 tm t = {};
1198
1199 t.tm_hour = (mod_time >> 11) & 0x1f;
1200 t.tm_min = (mod_time >> 5) & 0x3f;
1201 t.tm_sec = (mod_time & 0x1f) << 1;
1202
1203 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1204 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1205 t.tm_mday = (mod_time >> 16) & 0x1f;
1206
1207 return t;
1208}