blob: 35d0f0b6a8c254dcd33c8596a5acbcb0dce29d68 [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) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000103 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100104 uint16_t len = name.name_length;
105 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000106
107 while (len--) {
108 hash = hash * 31 + *str++;
109 }
110
111 return hash;
112}
113
114/*
115 * Convert a ZipEntry to a hash table index, verifying that it's in a
116 * valid range.
117 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900118static int64_t EntryToIndex(const ZipString* hash_table, const uint32_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700119 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100120 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000121
122 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
123 uint32_t ent = hash & (hash_table_size - 1);
124 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700125 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000126 return ent;
127 }
128
129 ent = (ent + 1) & (hash_table_size - 1);
130 }
131
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100132 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000133 return kEntryNotFound;
134}
135
136/*
137 * Add a new entry to the hash table.
138 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900139static int32_t AddToHash(ZipString* hash_table, const uint64_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700140 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100141 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000142 uint32_t ent = hash & (hash_table_size - 1);
143
144 /*
145 * We over-allocated the table, so we're guaranteed to find an empty slot.
146 * Further, we guarantee that the hashtable size is not 0.
147 */
148 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700149 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000150 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100151 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000152 return kDuplicateEntry;
153 }
154 ent = (ent + 1) & (hash_table_size - 1);
155 }
156
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100157 hash_table[ent].name = name.name;
158 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000159 return 0;
160}
161
Tianjie Xu18c25922016-09-29 15:27:41 -0700162static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900163 off64_t file_length, off64_t read_amount, uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000164 const off64_t search_start = file_length - read_amount;
165
Jiyong Parkcd997e62017-06-30 17:23:33 +0900166 if (!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
167 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
168 static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000169 return kIoError;
170 }
171
172 /*
173 * Scan backward for the EOCD magic. In an archive without a trailing
174 * comment, we'll find it on the first try. (We may want to consider
175 * doing an initial minimal read; if we don't find it, retry with a
176 * second read as above.)
177 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100178 int i = read_amount - sizeof(EocdRecord);
179 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700180 if (scan_buffer[i] == 0x50) {
181 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
182 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
183 ALOGV("+++ Found EOCD at buf+%d", i);
184 break;
185 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000186 }
187 }
188 if (i < 0) {
189 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
190 return kInvalidFile;
191 }
192
193 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100194 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000195 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100196 * Verify that there's no trailing space at the end of the central directory
197 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000198 */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900199 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
Narayan Kamath926973e2014-06-09 14:18:14 +0100200 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100201 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100202 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100203 return kInvalidFile;
204 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000205
Narayan Kamath926973e2014-06-09 14:18:14 +0100206 /*
207 * Grab the CD offset and size, and the number of entries in the
208 * archive and verify that they look reasonable.
209 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700210 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100211 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900212 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700213#if defined(__ANDROID__)
214 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
215 android_errorWriteLog(0x534e4554, "31251826");
216 }
217#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000218 return kInvalidOffset;
219 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100220 if (eocd->num_records == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000221 ALOGW("Zip: empty archive?");
222 return kEmptyArchive;
223 }
224
Jiyong Parkcd997e62017-06-30 17:23:33 +0900225 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
226 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000227
228 /*
229 * It all looks good. Create a mapping for the CD, and set the fields
230 * in archive.
231 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700232
233 if (!archive->InitializeCentralDirectory(debug_file_name,
234 static_cast<off64_t>(eocd->cd_start_offset),
235 static_cast<size_t>(eocd->cd_size))) {
236 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000237 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000238 }
239
Narayan Kamath926973e2014-06-09 14:18:14 +0100240 archive->num_entries = eocd->num_records;
241 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000242
243 return 0;
244}
245
246/*
247 * Find the zip Central Directory and memory-map it.
248 *
249 * On success, returns 0 after populating fields from the EOCD area:
250 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700251 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000252 * num_entries
253 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700254static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000255 // Test file length. We use lseek64 to make sure the file
256 // is small enough to be a zip file (Its size must be less than
257 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700258 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000259 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000260 return kInvalidFile;
261 }
262
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800263 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100264 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000265 return kInvalidFile;
266 }
267
Narayan Kamath926973e2014-06-09 14:18:14 +0100268 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
269 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000270 return kInvalidFile;
271 }
272
273 /*
274 * Perform the traditional EOCD snipe hunt.
275 *
276 * We're searching for the End of Central Directory magic number,
277 * which appears at the start of the EOCD block. It's followed by
278 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
279 * need to read the last part of the file into a buffer, dig through
280 * it to find the magic number, parse some values out, and use those
281 * to determine the extent of the CD.
282 *
283 * We start by pulling in the last part of the file.
284 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100285 off64_t read_amount = kMaxEOCDSearch;
286 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000287 read_amount = file_length;
288 }
289
Tianjie Xu18c25922016-09-29 15:27:41 -0700290 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900291 int32_t result =
292 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000293 return result;
294}
295
296/*
297 * Parses the Zip archive's Central Directory. Allocates and populates the
298 * hash table.
299 *
300 * Returns 0 on success.
301 */
302static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700303 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
304 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100305 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000306
307 /*
308 * Create hash table. We have a minimum 75% load factor, possibly as
309 * low as 50% after we round off to a power of 2. There must be at
310 * least one unused entry to avoid an infinite loop during creation.
311 */
312 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900313 archive->hash_table =
314 reinterpret_cast<ZipString*>(calloc(archive->hash_table_size, sizeof(ZipString)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700315 if (archive->hash_table == nullptr) {
316 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
317 archive->hash_table_size, sizeof(ZipString));
318 return -1;
319 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000320
321 /*
322 * Walk through the central directory, adding entries to the hash
323 * table and verifying values.
324 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100325 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000326 const uint8_t* ptr = cd_ptr;
327 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700328 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
329 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
330#if defined(__ANDROID__)
331 android_errorWriteLog(0x534e4554, "36392138");
332#endif
333 return -1;
334 }
335
Jiyong Parkcd997e62017-06-30 17:23:33 +0900336 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100337 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700338 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800339 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000340 }
341
Narayan Kamath926973e2014-06-09 14:18:14 +0100342 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000343 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800344 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900345 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800346 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000347 }
348
Narayan Kamath926973e2014-06-09 14:18:14 +0100349 const uint16_t file_name_length = cdr->file_name_length;
350 const uint16_t extra_length = cdr->extra_field_length;
351 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100352 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
353
Tianjie Xu9e020e22016-10-10 12:11:30 -0700354 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900355 ALOGW(
356 "Zip: file name boundary exceeds the central directory range, file_name_length: "
357 "%" PRIx16 ", cd_length: %zu",
358 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700359 return -1;
360 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000361 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
362 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800363 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100364 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000365
366 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700367 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100368 entry_name.name = file_name;
369 entry_name.name_length = file_name_length;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900370 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800371 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000372 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800373 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000374 }
375
Narayan Kamath926973e2014-06-09 14:18:14 +0100376 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
377 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900378 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800379 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000380 }
381 }
Mark Salyzyn088bf902014-05-08 16:02:20 -0700382 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000383
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800384 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000385}
386
Jiyong Parkcd997e62017-06-30 17:23:33 +0900387static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000388 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700389 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000390 return result;
391 }
392
393 if ((result = ParseZipArchive(archive))) {
394 return result;
395 }
396
397 return 0;
398}
399
Jiyong Parkcd997e62017-06-30 17:23:33 +0900400int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
401 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700402 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000403 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000404 return OpenArchiveInternal(archive, debug_file_name);
405}
406
407int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100408 const int fd = open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700409 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000410 *handle = archive;
411
Narayan Kamath7462f022013-11-21 13:05:04 +0000412 if (fd < 0) {
413 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
414 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000415 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700416
Narayan Kamath7462f022013-11-21 13:05:04 +0000417 return OpenArchiveInternal(archive, fileName);
418}
419
Tianjie Xu18c25922016-09-29 15:27:41 -0700420int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900421 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700422 ZipArchive* archive = new ZipArchive(address, length);
423 *handle = archive;
424 return OpenArchiveInternal(archive, debug_file_name);
425}
426
Narayan Kamath7462f022013-11-21 13:05:04 +0000427/*
428 * Close a ZipArchive, closing the file and freeing the contents.
429 */
430void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800431 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000432 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100433 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000434}
435
Narayan Kamath162b7052017-06-05 13:21:12 +0100436static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100437 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700438 off64_t offset = entry->offset;
439 if (entry->method != kCompressStored) {
440 offset += entry->compressed_length;
441 } else {
442 offset += entry->uncompressed_length;
443 }
444
445 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000446 return kIoError;
447 }
448
Narayan Kamath926973e2014-06-09 14:18:14 +0100449 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700450 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
451 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000452
Narayan Kamath162b7052017-06-05 13:21:12 +0100453 // Validate that the values in the data descriptor match those in the central
454 // directory.
455 if (entry->compressed_length != descriptor->compressed_size ||
456 entry->uncompressed_length != descriptor->uncompressed_size ||
457 entry->crc32 != descriptor->crc32) {
458 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
459 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
460 entry->compressed_length, entry->uncompressed_length, entry->crc32,
461 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
462 return kInconsistentInformation;
463 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000464
465 return 0;
466}
467
Jiyong Parkcd997e62017-06-30 17:23:33 +0900468static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000469 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000470
471 // Recover the start of the central directory entry from the filename
472 // pointer. The filename is the first entry past the fixed-size data,
473 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100474 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100475 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000476
477 // This is the base of our mmapped region, we have to sanity check that
478 // the name that's in the hash table is a pointer to a location within
479 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700480 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
481 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000482 ALOGW("Zip: Invalid entry pointer");
483 return kInvalidOffset;
484 }
485
Jiyong Parkcd997e62017-06-30 17:23:33 +0900486 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100487
Narayan Kamath7462f022013-11-21 13:05:04 +0000488 // The offset of the start of the central directory in the zipfile.
489 // We keep this lying around so that we can sanity check all our lengths
490 // and our per-file structures.
491 const off64_t cd_offset = archive->directory_offset;
492
493 // Fill out the compression method, modification time, crc32
494 // and other interesting attributes from the central directory. These
495 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100496 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900497 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100498 data->crc32 = cdr->crc32;
499 data->compressed_length = cdr->compressed_size;
500 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000501
502 // Figure out the local header offset from the central directory. The
503 // actual file data will begin after the local header and the name /
504 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100505 const off64_t local_header_offset = cdr->local_file_header_offset;
506 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000507 ALOGW("Zip: bad local hdr offset in zip");
508 return kInvalidOffset;
509 }
510
Narayan Kamath926973e2014-06-09 14:18:14 +0100511 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700512 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800513 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900514 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000515 return kIoError;
516 }
517
Jiyong Parkcd997e62017-06-30 17:23:33 +0900518 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100519
520 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700521 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900522 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000523 return kInvalidOffset;
524 }
525
526 // Paranoia: Match the values specified in the local file header
527 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700528
Narayan Kamath162b7052017-06-05 13:21:12 +0100529 // Warn if central directory and local file header don't agree on the use
530 // of a trailing Data Descriptor. The reference implementation is inconsistent
531 // and appears to use the LFH value during extraction (unzip) but the CD value
532 // while displayng information about archives (zipinfo). The spec remains
533 // silent on this inconsistency as well.
534 //
535 // For now, always use the version from the LFH but make sure that the values
536 // specified in the central directory match those in the data descriptor.
537 //
538 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
539 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
540 // encoded using UTF-8). This implementation does not check for the presence of
541 // that flag and always enforces that entry names are valid UTF-8.
542 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
543 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700544 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700545 }
546
547 // If there is no trailing data descriptor, verify that the central directory and local file
548 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100549 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000550 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900551 if (data->compressed_length != lfh->compressed_size ||
552 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
553 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
554 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
555 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
556 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000557 return kInconsistentInformation;
558 }
559 } else {
560 data->has_data_descriptor = 1;
561 }
562
Elliott Hughes55fd2932017-05-28 22:59:04 -0700563 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
564 if ((cdr->version_made_by >> 8) == 3) {
565 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
566 } else {
567 data->unix_mode = 0777;
568 }
569
Narayan Kamath7462f022013-11-21 13:05:04 +0000570 // Check that the local file header name matches the declared
571 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100572 if (lfh->file_name_length == nameLen) {
573 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200574 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000575 ALOGW("Zip: Invalid declared length");
576 return kInvalidOffset;
577 }
578
Tianjie Xu18c25922016-09-29 15:27:41 -0700579 std::vector<uint8_t> name_buf(nameLen);
580 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800581 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000582 return kIoError;
583 }
584
Tianjie Xu18c25922016-09-29 15:27:41 -0700585 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000586 return kInconsistentInformation;
587 }
588
Narayan Kamath7462f022013-11-21 13:05:04 +0000589 } else {
590 ALOGW("Zip: lfh name did not match central directory.");
591 return kInconsistentInformation;
592 }
593
Jiyong Parkcd997e62017-06-30 17:23:33 +0900594 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
595 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000596 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800597 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000598 return kInvalidOffset;
599 }
600
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800601 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700602 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900603 static_cast<int64_t>(data_offset), data->compressed_length,
604 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000605 return kInvalidOffset;
606 }
607
608 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900609 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
610 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
611 static_cast<int64_t>(data_offset), data->uncompressed_length,
612 static_cast<int64_t>(cd_offset));
613 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000614 }
615
616 data->offset = data_offset;
617 return 0;
618}
619
620struct IterationHandle {
621 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100622 // We're not using vector here because this code is used in the Windows SDK
623 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700624 ZipString prefix;
625 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000626 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100627
Jiyong Parkcd997e62017-06-30 17:23:33 +0900628 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700629 if (in_prefix) {
630 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
631 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
632 prefix.name = name_copy;
633 prefix.name_length = in_prefix->name_length;
634 } else {
635 prefix.name = NULL;
636 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700637 }
Yusuke Sato07447542015-06-25 14:39:19 -0700638 if (in_suffix) {
639 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
640 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
641 suffix.name = name_copy;
642 suffix.name_length = in_suffix->name_length;
643 } else {
644 suffix.name = NULL;
645 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700646 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100647 }
648
649 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700650 delete[] prefix.name;
651 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100652 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000653};
654
Jiyong Parkcd997e62017-06-30 17:23:33 +0900655int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700656 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800657 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000658
659 if (archive == NULL || archive->hash_table == NULL) {
660 ALOGW("Zip: Invalid ZipArchiveHandle");
661 return kInvalidHandle;
662 }
663
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700664 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000665 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000666 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000667
Jiyong Parkcd997e62017-06-30 17:23:33 +0900668 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000669 return 0;
670}
671
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100672void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100673 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100674}
675
Jiyong Parkcd997e62017-06-30 17:23:33 +0900676int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800677 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100678 if (entryName.name_length == 0) {
679 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000680 return kInvalidEntryName;
681 }
682
Jiyong Parkcd997e62017-06-30 17:23:33 +0900683 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000684
685 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100686 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000687 return ent;
688 }
689
690 return FindEntry(archive, ent, data);
691}
692
Yusuke Sato07447542015-06-25 14:39:19 -0700693int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800694 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000695 if (handle == NULL) {
696 return kInvalidHandle;
697 }
698
699 ZipArchive* archive = handle->archive;
700 if (archive == NULL || archive->hash_table == NULL) {
701 ALOGW("Zip: Invalid ZipArchiveHandle");
702 return kInvalidHandle;
703 }
704
705 const uint32_t currentOffset = handle->position;
706 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700707 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000708
709 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
710 if (hash_table[i].name != NULL &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900711 (handle->prefix.name_length == 0 || hash_table[i].StartsWith(handle->prefix)) &&
712 (handle->suffix.name_length == 0 || hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000713 handle->position = (i + 1);
714 const int error = FindEntry(archive, i, data);
715 if (!error) {
716 name->name = hash_table[i].name;
717 name->name_length = hash_table[i].name_length;
718 }
719
720 return error;
721 }
722 }
723
724 handle->position = 0;
725 return kIterationEnd;
726}
727
Narayan Kamathf899bd52015-04-17 11:53:14 +0100728// A Writer that writes data to a fixed size memory region.
729// The size of the memory region must be equal to the total size of
730// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100731class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100732 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900733 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100734
735 virtual bool Append(uint8_t* buf, size_t buf_size) override {
736 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900737 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
738 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100739 return false;
740 }
741
742 memcpy(buf_ + bytes_written_, buf, buf_size);
743 bytes_written_ += buf_size;
744 return true;
745 }
746
747 private:
748 uint8_t* const buf_;
749 const size_t size_;
750 size_t bytes_written_;
751};
752
753// A Writer that appends data to a file |fd| at its current position.
754// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100755class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100756 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100757 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
758 // guaranteeing that the file descriptor is valid and that there's enough
759 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800760 // is truncated to the correct length (no truncation if |fd| references a
761 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100762 //
763 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
764 static std::unique_ptr<FileWriter> Create(int fd, const ZipEntry* entry) {
765 const uint32_t declared_length = entry->uncompressed_length;
766 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
767 if (current_offset == -1) {
768 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
769 return nullptr;
770 }
771
772 int result = 0;
773#if defined(__linux__)
774 if (declared_length > 0) {
775 // Make sure we have enough space on the volume to extract the compressed
776 // entry. Note that the call to ftruncate below will change the file size but
777 // will not allocate space on disk and this call to fallocate will not
778 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700779 // Note: fallocate is only supported by the following filesystems -
780 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
781 // EOPNOTSUPP error when issued in other filesystems.
782 // Hence, check for the return error code before concluding that the
783 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100784 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700785 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700786 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100787 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
788 strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100789 return std::unique_ptr<FileWriter>(nullptr);
790 }
791 }
792#endif // __linux__
793
Tao Baoa456c212016-11-15 10:08:07 -0800794 struct stat sb;
795 if (fstat(fd, &sb) == -1) {
796 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100797 return std::unique_ptr<FileWriter>(nullptr);
798 }
799
Tao Baoa456c212016-11-15 10:08:07 -0800800 // Block device doesn't support ftruncate(2).
801 if (!S_ISBLK(sb.st_mode)) {
802 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
803 if (result == -1) {
804 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
805 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
806 return std::unique_ptr<FileWriter>(nullptr);
807 }
808 }
809
Narayan Kamathf899bd52015-04-17 11:53:14 +0100810 return std::unique_ptr<FileWriter>(new FileWriter(fd, declared_length));
811 }
812
813 virtual bool Append(uint8_t* buf, size_t buf_size) override {
814 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900815 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
816 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100817 return false;
818 }
819
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100820 const bool result = android::base::WriteFully(fd_, buf, buf_size);
821 if (result) {
822 total_bytes_written_ += buf_size;
823 } else {
824 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100825 }
826
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100827 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100828 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900829
Narayan Kamathf899bd52015-04-17 11:53:14 +0100830 private:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900831 FileWriter(const int fd, const size_t declared_length)
832 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100833
834 const int fd_;
835 const size_t declared_length_;
836 size_t total_bytes_written_;
837};
838
Narayan Kamath485b3642017-10-26 14:42:39 +0100839class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100840 public:
841 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
842 : Reader(), zip_file_(zip_file), entry_(entry) {}
843
844 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
845 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
846 }
847
848 virtual ~EntryReader() {}
849
850 private:
851 const MappedZipFile& zip_file_;
852 const ZipEntry* entry_;
853};
854
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800855// This method is using libz macros with old-style-casts
856#pragma GCC diagnostic push
857#pragma GCC diagnostic ignored "-Wold-style-cast"
858static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
859 return inflateInit2(stream, window_bits);
860}
861#pragma GCC diagnostic pop
862
Narayan Kamath485b3642017-10-26 14:42:39 +0100863namespace zip_archive {
864
865// Moved out of line to avoid -Wweak-vtables.
866Reader::~Reader() {}
867Writer::~Writer() {}
868
869int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
870 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700871 const size_t kBufSize = 32768;
872 std::vector<uint8_t> read_buf(kBufSize);
873 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000874 z_stream zstream;
875 int zerr;
876
877 /*
878 * Initialize the zlib stream struct.
879 */
880 memset(&zstream, 0, sizeof(zstream));
881 zstream.zalloc = Z_NULL;
882 zstream.zfree = Z_NULL;
883 zstream.opaque = Z_NULL;
884 zstream.next_in = NULL;
885 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700886 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000887 zstream.avail_out = kBufSize;
888 zstream.data_type = Z_UNKNOWN;
889
890 /*
891 * Use the undocumented "negative window bits" feature to tell zlib
892 * that there's no zlib header waiting for it.
893 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800894 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000895 if (zerr != Z_OK) {
896 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900897 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000898 } else {
899 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
900 }
901
902 return kZlibError;
903 }
904
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800905 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900906 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800907 };
908
909 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
910
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000911 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100912 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100913 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000914 do {
915 /* read as much as we can */
916 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100917 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
918 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700919 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100920 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
921 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800922 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000923 }
924
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100925 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000926
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700927 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100928 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000929 }
930
931 /* uncompress the data */
932 zerr = inflate(&zstream, Z_NO_FLUSH);
933 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900934 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
935 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800936 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000937 }
938
939 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900940 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700941 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100942 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000943 return kIoError;
944 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +0100945 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +0000946 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000947
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700948 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000949 zstream.avail_out = kBufSize;
950 }
951 } while (zerr == Z_OK);
952
Jiyong Parkcd997e62017-06-30 17:23:33 +0900953 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +0000954
Narayan Kamath162b7052017-06-05 13:21:12 +0100955 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
956 // "feature" of zlib to tell it there won't be a zlib file header. zlib
957 // doesn't bother calculating the checksum in that scenario. We just do
958 // it ourselves above because there are no additional gains to be made by
959 // having zlib calculate it for us, since they do it by calling crc32 in
960 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000961 if (compute_crc) {
962 *crc_out = crc;
963 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000964
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100965 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900966 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
967 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800968 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +0000969 }
970
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800971 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000972}
Narayan Kamath485b3642017-10-26 14:42:39 +0100973} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +0000974
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100975static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +0100976 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100977 const EntryReader reader(mapped_zip, entry);
978
Narayan Kamath485b3642017-10-26 14:42:39 +0100979 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
980 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100981}
982
Narayan Kamath485b3642017-10-26 14:42:39 +0100983static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
984 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100985 static const uint32_t kBufSize = 32768;
986 std::vector<uint8_t> buf(kBufSize);
987
988 const uint32_t length = entry->uncompressed_length;
989 uint32_t count = 0;
990 uint64_t crc = 0;
991 while (count < length) {
992 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -0700993 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100994
Adam Lesinskide117e42017-06-19 10:27:38 -0700995 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -0800996 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -0700997
998 // Make sure to read at offset to ensure concurrent access to the fd.
999 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1000 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1001 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001002 return kIoError;
1003 }
1004
1005 if (!writer->Append(&buf[0], block_size)) {
1006 return kIoError;
1007 }
1008 crc = crc32(crc, &buf[0], block_size);
1009 count += block_size;
1010 }
1011
1012 *crc_out = crc;
1013
1014 return 0;
1015}
1016
Narayan Kamath485b3642017-10-26 14:42:39 +01001017int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001018 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001019 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001020
1021 // this should default to kUnknownCompressionMethod.
1022 int32_t return_value = -1;
1023 uint64_t crc = 0;
1024 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001025 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001026 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001027 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001028 }
1029
1030 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001031 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001032 if (return_value) {
1033 return return_value;
1034 }
1035 }
1036
Narayan Kamath162b7052017-06-05 13:21:12 +01001037 // Validate that the CRC matches the calculated value.
1038 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001039 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001040 return kInconsistentInformation;
1041 }
1042
1043 return return_value;
1044}
1045
Jiyong Parkcd997e62017-06-30 17:23:33 +09001046int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Narayan Kamath485b3642017-10-26 14:42:39 +01001047 std::unique_ptr<zip_archive::Writer> writer(new MemoryWriter(begin, size));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001048 return ExtractToWriter(handle, entry, writer.get());
1049}
1050
Jiyong Parkcd997e62017-06-30 17:23:33 +09001051int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Narayan Kamath485b3642017-10-26 14:42:39 +01001052 std::unique_ptr<zip_archive::Writer> writer(FileWriter::Create(fd, entry));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001053 if (writer.get() == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001054 return kIoError;
1055 }
1056
Narayan Kamathf899bd52015-04-17 11:53:14 +01001057 return ExtractToWriter(handle, entry, writer.get());
Narayan Kamath7462f022013-11-21 13:05:04 +00001058}
1059
1060const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001061 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1062 // match.
1063 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1064 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1065
1066 const uint32_t idx = -error_code;
1067 if (idx < arraysize(kErrorMessages)) {
1068 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001069 }
1070
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001071 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001072}
1073
1074int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001075 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001076}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001077
Jiyong Parkcd997e62017-06-30 17:23:33 +09001078ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001079 size_t len = strlen(entry_name);
1080 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1081 name_length = static_cast<uint16_t>(len);
1082}
Tianjie Xu18c25922016-09-29 15:27:41 -07001083
1084#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001085class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001086 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001087 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1088 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001089
1090 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1091 return proc_function_(buf, buf_size, cookie_);
1092 }
1093
1094 private:
1095 ProcessZipEntryFunction proc_function_;
1096 void* cookie_;
1097};
1098
1099int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1100 ProcessZipEntryFunction func, void* cookie) {
1101 ProcessWriter writer(func, cookie);
1102 return ExtractToWriter(handle, entry, &writer);
1103}
1104
Jiyong Parkcd997e62017-06-30 17:23:33 +09001105#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001106
1107int MappedZipFile::GetFileDescriptor() const {
1108 if (!has_fd_) {
1109 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1110 return -1;
1111 }
1112 return fd_;
1113}
1114
1115void* MappedZipFile::GetBasePtr() const {
1116 if (has_fd_) {
1117 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1118 return nullptr;
1119 }
1120 return base_ptr_;
1121}
1122
1123off64_t MappedZipFile::GetFileLength() const {
1124 if (has_fd_) {
1125 off64_t result = lseek64(fd_, 0, SEEK_END);
1126 if (result == -1) {
1127 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1128 }
1129 return result;
1130 } else {
1131 if (base_ptr_ == nullptr) {
1132 ALOGE("Zip: invalid file map\n");
1133 return -1;
1134 }
1135 return static_cast<off64_t>(data_length_);
1136 }
1137}
1138
Tianjie Xu18c25922016-09-29 15:27:41 -07001139// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001140bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001141 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001142 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001143 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1144 return false;
1145 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001146 } else {
1147 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1148 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1149 return false;
1150 }
1151 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001152 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001153 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001154}
1155
1156void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1157 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1158 length_ = cd_size;
1159}
1160
1161bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1162 size_t cd_size) {
1163 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001164 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1165 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001166 return false;
1167 }
1168
1169 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001170 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001171 } else {
1172 if (mapped_zip.GetBasePtr() == nullptr) {
1173 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1174 return false;
1175 }
1176 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1177 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001178 ALOGE(
1179 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1180 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1181 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001182 return false;
1183 }
1184
1185 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1186 }
1187 return true;
1188}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001189
1190tm ZipEntry::GetModificationTime() const {
1191 tm t = {};
1192
1193 t.tm_hour = (mod_time >> 11) & 0x1f;
1194 t.tm_min = (mod_time >> 5) & 0x3f;
1195 t.tm_sec = (mod_time & 0x1f) << 1;
1196
1197 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1198 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1199 t.tm_mday = (mod_time >> 16) & 0x1f;
1200
1201 return t;
1202}