blob: f9f8c73d9b269fdb15021a0ef3f1c1abaf288b9a [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 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100388
389 uint32_t lfh_start_bytes;
390 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
391 sizeof(uint32_t), 0)) {
392 ALOGW("Zip: Unable to read header for entry at offset == 0.");
393 return -1;
394 }
395
396 if (lfh_start_bytes != LocalFileHeader::kSignature) {
397 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
398#if defined(__ANDROID__)
399 android_errorWriteLog(0x534e4554, "64211847");
400#endif
401 return -1;
402 }
403
Mark Salyzyn088bf902014-05-08 16:02:20 -0700404 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000405
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800406 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000407}
408
Jiyong Parkcd997e62017-06-30 17:23:33 +0900409static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000410 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700411 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000412 return result;
413 }
414
415 if ((result = ParseZipArchive(archive))) {
416 return result;
417 }
418
419 return 0;
420}
421
Jiyong Parkcd997e62017-06-30 17:23:33 +0900422int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
423 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700424 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000425 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000426 return OpenArchiveInternal(archive, debug_file_name);
427}
428
429int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100430 const int fd = open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700431 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000432 *handle = archive;
433
Narayan Kamath7462f022013-11-21 13:05:04 +0000434 if (fd < 0) {
435 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
436 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000437 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700438
Narayan Kamath7462f022013-11-21 13:05:04 +0000439 return OpenArchiveInternal(archive, fileName);
440}
441
Tianjie Xu18c25922016-09-29 15:27:41 -0700442int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900443 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700444 ZipArchive* archive = new ZipArchive(address, length);
445 *handle = archive;
446 return OpenArchiveInternal(archive, debug_file_name);
447}
448
Narayan Kamath7462f022013-11-21 13:05:04 +0000449/*
450 * Close a ZipArchive, closing the file and freeing the contents.
451 */
452void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800453 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000454 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100455 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000456}
457
Narayan Kamath162b7052017-06-05 13:21:12 +0100458static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100459 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700460 off64_t offset = entry->offset;
461 if (entry->method != kCompressStored) {
462 offset += entry->compressed_length;
463 } else {
464 offset += entry->uncompressed_length;
465 }
466
467 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000468 return kIoError;
469 }
470
Narayan Kamath926973e2014-06-09 14:18:14 +0100471 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700472 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
473 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000474
Narayan Kamath162b7052017-06-05 13:21:12 +0100475 // Validate that the values in the data descriptor match those in the central
476 // directory.
477 if (entry->compressed_length != descriptor->compressed_size ||
478 entry->uncompressed_length != descriptor->uncompressed_size ||
479 entry->crc32 != descriptor->crc32) {
480 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
481 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
482 entry->compressed_length, entry->uncompressed_length, entry->crc32,
483 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
484 return kInconsistentInformation;
485 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000486
487 return 0;
488}
489
Jiyong Parkcd997e62017-06-30 17:23:33 +0900490static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000491 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000492
493 // Recover the start of the central directory entry from the filename
494 // pointer. The filename is the first entry past the fixed-size data,
495 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100496 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100497 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000498
499 // This is the base of our mmapped region, we have to sanity check that
500 // the name that's in the hash table is a pointer to a location within
501 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700502 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
503 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000504 ALOGW("Zip: Invalid entry pointer");
505 return kInvalidOffset;
506 }
507
Jiyong Parkcd997e62017-06-30 17:23:33 +0900508 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100509
Narayan Kamath7462f022013-11-21 13:05:04 +0000510 // The offset of the start of the central directory in the zipfile.
511 // We keep this lying around so that we can sanity check all our lengths
512 // and our per-file structures.
513 const off64_t cd_offset = archive->directory_offset;
514
515 // Fill out the compression method, modification time, crc32
516 // and other interesting attributes from the central directory. These
517 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100518 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900519 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100520 data->crc32 = cdr->crc32;
521 data->compressed_length = cdr->compressed_size;
522 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000523
524 // Figure out the local header offset from the central directory. The
525 // actual file data will begin after the local header and the name /
526 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100527 const off64_t local_header_offset = cdr->local_file_header_offset;
528 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000529 ALOGW("Zip: bad local hdr offset in zip");
530 return kInvalidOffset;
531 }
532
Narayan Kamath926973e2014-06-09 14:18:14 +0100533 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700534 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800535 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900536 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000537 return kIoError;
538 }
539
Jiyong Parkcd997e62017-06-30 17:23:33 +0900540 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100541
542 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700543 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900544 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000545 return kInvalidOffset;
546 }
547
548 // Paranoia: Match the values specified in the local file header
549 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700550
Narayan Kamath162b7052017-06-05 13:21:12 +0100551 // Warn if central directory and local file header don't agree on the use
552 // of a trailing Data Descriptor. The reference implementation is inconsistent
553 // and appears to use the LFH value during extraction (unzip) but the CD value
554 // while displayng information about archives (zipinfo). The spec remains
555 // silent on this inconsistency as well.
556 //
557 // For now, always use the version from the LFH but make sure that the values
558 // specified in the central directory match those in the data descriptor.
559 //
560 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
561 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
562 // encoded using UTF-8). This implementation does not check for the presence of
563 // that flag and always enforces that entry names are valid UTF-8.
564 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
565 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700566 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700567 }
568
569 // If there is no trailing data descriptor, verify that the central directory and local file
570 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100571 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000572 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900573 if (data->compressed_length != lfh->compressed_size ||
574 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
575 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
576 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
577 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
578 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000579 return kInconsistentInformation;
580 }
581 } else {
582 data->has_data_descriptor = 1;
583 }
584
Elliott Hughes55fd2932017-05-28 22:59:04 -0700585 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
586 if ((cdr->version_made_by >> 8) == 3) {
587 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
588 } else {
589 data->unix_mode = 0777;
590 }
591
Narayan Kamath7462f022013-11-21 13:05:04 +0000592 // Check that the local file header name matches the declared
593 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100594 if (lfh->file_name_length == nameLen) {
595 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200596 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000597 ALOGW("Zip: Invalid declared length");
598 return kInvalidOffset;
599 }
600
Tianjie Xu18c25922016-09-29 15:27:41 -0700601 std::vector<uint8_t> name_buf(nameLen);
602 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800603 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000604 return kIoError;
605 }
606
Tianjie Xu18c25922016-09-29 15:27:41 -0700607 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000608 return kInconsistentInformation;
609 }
610
Narayan Kamath7462f022013-11-21 13:05:04 +0000611 } else {
612 ALOGW("Zip: lfh name did not match central directory.");
613 return kInconsistentInformation;
614 }
615
Jiyong Parkcd997e62017-06-30 17:23:33 +0900616 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
617 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000618 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800619 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000620 return kInvalidOffset;
621 }
622
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800623 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700624 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900625 static_cast<int64_t>(data_offset), data->compressed_length,
626 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000627 return kInvalidOffset;
628 }
629
630 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900631 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
632 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
633 static_cast<int64_t>(data_offset), data->uncompressed_length,
634 static_cast<int64_t>(cd_offset));
635 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000636 }
637
638 data->offset = data_offset;
639 return 0;
640}
641
642struct IterationHandle {
643 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100644 // We're not using vector here because this code is used in the Windows SDK
645 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700646 ZipString prefix;
647 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000648 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100649
Jiyong Parkcd997e62017-06-30 17:23:33 +0900650 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700651 if (in_prefix) {
652 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
653 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
654 prefix.name = name_copy;
655 prefix.name_length = in_prefix->name_length;
656 } else {
657 prefix.name = NULL;
658 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700659 }
Yusuke Sato07447542015-06-25 14:39:19 -0700660 if (in_suffix) {
661 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
662 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
663 suffix.name = name_copy;
664 suffix.name_length = in_suffix->name_length;
665 } else {
666 suffix.name = NULL;
667 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700668 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100669 }
670
671 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700672 delete[] prefix.name;
673 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100674 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000675};
676
Jiyong Parkcd997e62017-06-30 17:23:33 +0900677int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700678 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800679 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000680
681 if (archive == NULL || archive->hash_table == NULL) {
682 ALOGW("Zip: Invalid ZipArchiveHandle");
683 return kInvalidHandle;
684 }
685
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700686 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000687 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000688 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000689
Jiyong Parkcd997e62017-06-30 17:23:33 +0900690 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000691 return 0;
692}
693
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100694void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100695 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100696}
697
Jiyong Parkcd997e62017-06-30 17:23:33 +0900698int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800699 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100700 if (entryName.name_length == 0) {
701 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000702 return kInvalidEntryName;
703 }
704
Jiyong Parkcd997e62017-06-30 17:23:33 +0900705 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000706
707 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100708 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000709 return ent;
710 }
711
712 return FindEntry(archive, ent, data);
713}
714
Yusuke Sato07447542015-06-25 14:39:19 -0700715int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800716 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000717 if (handle == NULL) {
718 return kInvalidHandle;
719 }
720
721 ZipArchive* archive = handle->archive;
722 if (archive == NULL || archive->hash_table == NULL) {
723 ALOGW("Zip: Invalid ZipArchiveHandle");
724 return kInvalidHandle;
725 }
726
727 const uint32_t currentOffset = handle->position;
728 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700729 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000730
731 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
732 if (hash_table[i].name != NULL &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900733 (handle->prefix.name_length == 0 || hash_table[i].StartsWith(handle->prefix)) &&
734 (handle->suffix.name_length == 0 || hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000735 handle->position = (i + 1);
736 const int error = FindEntry(archive, i, data);
737 if (!error) {
738 name->name = hash_table[i].name;
739 name->name_length = hash_table[i].name_length;
740 }
741
742 return error;
743 }
744 }
745
746 handle->position = 0;
747 return kIterationEnd;
748}
749
Narayan Kamathf899bd52015-04-17 11:53:14 +0100750// A Writer that writes data to a fixed size memory region.
751// The size of the memory region must be equal to the total size of
752// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100753class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100754 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900755 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100756
757 virtual bool Append(uint8_t* buf, size_t buf_size) override {
758 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900759 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
760 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100761 return false;
762 }
763
764 memcpy(buf_ + bytes_written_, buf, buf_size);
765 bytes_written_ += buf_size;
766 return true;
767 }
768
769 private:
770 uint8_t* const buf_;
771 const size_t size_;
772 size_t bytes_written_;
773};
774
775// A Writer that appends data to a file |fd| at its current position.
776// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100777class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100778 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100779 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
780 // guaranteeing that the file descriptor is valid and that there's enough
781 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800782 // is truncated to the correct length (no truncation if |fd| references a
783 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100784 //
785 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800786 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100787 const uint32_t declared_length = entry->uncompressed_length;
788 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
789 if (current_offset == -1) {
790 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800791 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100792 }
793
794 int result = 0;
795#if defined(__linux__)
796 if (declared_length > 0) {
797 // Make sure we have enough space on the volume to extract the compressed
798 // entry. Note that the call to ftruncate below will change the file size but
799 // will not allocate space on disk and this call to fallocate will not
800 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700801 // Note: fallocate is only supported by the following filesystems -
802 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
803 // EOPNOTSUPP error when issued in other filesystems.
804 // Hence, check for the return error code before concluding that the
805 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100806 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700807 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700808 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100809 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
810 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800811 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100812 }
813 }
814#endif // __linux__
815
Tao Baoa456c212016-11-15 10:08:07 -0800816 struct stat sb;
817 if (fstat(fd, &sb) == -1) {
818 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800819 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100820 }
821
Tao Baoa456c212016-11-15 10:08:07 -0800822 // Block device doesn't support ftruncate(2).
823 if (!S_ISBLK(sb.st_mode)) {
824 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
825 if (result == -1) {
826 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
827 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800828 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800829 }
830 }
831
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800832 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100833 }
834
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800835 FileWriter(FileWriter&& other)
836 : fd_(other.fd_),
837 declared_length_(other.declared_length_),
838 total_bytes_written_(other.total_bytes_written_) {
839 other.fd_ = -1;
840 }
841
842 bool IsValid() const { return fd_ != -1; }
843
Narayan Kamathf899bd52015-04-17 11:53:14 +0100844 virtual bool Append(uint8_t* buf, size_t buf_size) override {
845 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900846 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
847 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100848 return false;
849 }
850
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100851 const bool result = android::base::WriteFully(fd_, buf, buf_size);
852 if (result) {
853 total_bytes_written_ += buf_size;
854 } else {
855 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100856 }
857
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100858 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100859 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900860
Narayan Kamathf899bd52015-04-17 11:53:14 +0100861 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800862 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900863 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100864
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800865 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100866 const size_t declared_length_;
867 size_t total_bytes_written_;
868};
869
Narayan Kamath485b3642017-10-26 14:42:39 +0100870class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100871 public:
872 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
873 : Reader(), zip_file_(zip_file), entry_(entry) {}
874
875 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
876 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
877 }
878
879 virtual ~EntryReader() {}
880
881 private:
882 const MappedZipFile& zip_file_;
883 const ZipEntry* entry_;
884};
885
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800886// This method is using libz macros with old-style-casts
887#pragma GCC diagnostic push
888#pragma GCC diagnostic ignored "-Wold-style-cast"
889static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
890 return inflateInit2(stream, window_bits);
891}
892#pragma GCC diagnostic pop
893
Narayan Kamath485b3642017-10-26 14:42:39 +0100894namespace zip_archive {
895
896// Moved out of line to avoid -Wweak-vtables.
897Reader::~Reader() {}
898Writer::~Writer() {}
899
900int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
901 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700902 const size_t kBufSize = 32768;
903 std::vector<uint8_t> read_buf(kBufSize);
904 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000905 z_stream zstream;
906 int zerr;
907
908 /*
909 * Initialize the zlib stream struct.
910 */
911 memset(&zstream, 0, sizeof(zstream));
912 zstream.zalloc = Z_NULL;
913 zstream.zfree = Z_NULL;
914 zstream.opaque = Z_NULL;
915 zstream.next_in = NULL;
916 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700917 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000918 zstream.avail_out = kBufSize;
919 zstream.data_type = Z_UNKNOWN;
920
921 /*
922 * Use the undocumented "negative window bits" feature to tell zlib
923 * that there's no zlib header waiting for it.
924 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800925 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000926 if (zerr != Z_OK) {
927 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900928 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000929 } else {
930 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
931 }
932
933 return kZlibError;
934 }
935
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800936 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900937 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800938 };
939
940 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
941
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000942 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100943 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100944 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000945 do {
946 /* read as much as we can */
947 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100948 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
949 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700950 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100951 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
952 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800953 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000954 }
955
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100956 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000957
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700958 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100959 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000960 }
961
962 /* uncompress the data */
963 zerr = inflate(&zstream, Z_NO_FLUSH);
964 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900965 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
966 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800967 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000968 }
969
970 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900971 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700972 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100973 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000974 return kIoError;
975 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +0100976 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +0000977 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000978
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700979 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000980 zstream.avail_out = kBufSize;
981 }
982 } while (zerr == Z_OK);
983
Jiyong Parkcd997e62017-06-30 17:23:33 +0900984 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +0000985
Narayan Kamath162b7052017-06-05 13:21:12 +0100986 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
987 // "feature" of zlib to tell it there won't be a zlib file header. zlib
988 // doesn't bother calculating the checksum in that scenario. We just do
989 // it ourselves above because there are no additional gains to be made by
990 // having zlib calculate it for us, since they do it by calling crc32 in
991 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000992 if (compute_crc) {
993 *crc_out = crc;
994 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000995
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100996 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900997 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
998 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800999 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001000 }
1001
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001002 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001003}
Narayan Kamath485b3642017-10-26 14:42:39 +01001004} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001005
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001006static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001007 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001008 const EntryReader reader(mapped_zip, entry);
1009
Narayan Kamath485b3642017-10-26 14:42:39 +01001010 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1011 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001012}
1013
Narayan Kamath485b3642017-10-26 14:42:39 +01001014static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1015 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001016 static const uint32_t kBufSize = 32768;
1017 std::vector<uint8_t> buf(kBufSize);
1018
1019 const uint32_t length = entry->uncompressed_length;
1020 uint32_t count = 0;
1021 uint64_t crc = 0;
1022 while (count < length) {
1023 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001024 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001025
Adam Lesinskide117e42017-06-19 10:27:38 -07001026 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001027 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001028
1029 // Make sure to read at offset to ensure concurrent access to the fd.
1030 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1031 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1032 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001033 return kIoError;
1034 }
1035
1036 if (!writer->Append(&buf[0], block_size)) {
1037 return kIoError;
1038 }
1039 crc = crc32(crc, &buf[0], block_size);
1040 count += block_size;
1041 }
1042
1043 *crc_out = crc;
1044
1045 return 0;
1046}
1047
Narayan Kamath485b3642017-10-26 14:42:39 +01001048int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001049 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001050 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001051
1052 // this should default to kUnknownCompressionMethod.
1053 int32_t return_value = -1;
1054 uint64_t crc = 0;
1055 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001056 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001057 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001058 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001059 }
1060
1061 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001062 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001063 if (return_value) {
1064 return return_value;
1065 }
1066 }
1067
Narayan Kamath162b7052017-06-05 13:21:12 +01001068 // Validate that the CRC matches the calculated value.
1069 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001070 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001071 return kInconsistentInformation;
1072 }
1073
1074 return return_value;
1075}
1076
Jiyong Parkcd997e62017-06-30 17:23:33 +09001077int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001078 MemoryWriter writer(begin, size);
1079 return ExtractToWriter(handle, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001080}
1081
Jiyong Parkcd997e62017-06-30 17:23:33 +09001082int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001083 auto writer = FileWriter::Create(fd, entry);
1084 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001085 return kIoError;
1086 }
1087
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001088 return ExtractToWriter(handle, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001089}
1090
1091const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001092 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1093 // match.
1094 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1095 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1096
1097 const uint32_t idx = -error_code;
1098 if (idx < arraysize(kErrorMessages)) {
1099 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001100 }
1101
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001102 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001103}
1104
1105int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001106 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001107}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001108
Jiyong Parkcd997e62017-06-30 17:23:33 +09001109ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001110 size_t len = strlen(entry_name);
1111 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1112 name_length = static_cast<uint16_t>(len);
1113}
Tianjie Xu18c25922016-09-29 15:27:41 -07001114
1115#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001116class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001117 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001118 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1119 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001120
1121 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1122 return proc_function_(buf, buf_size, cookie_);
1123 }
1124
1125 private:
1126 ProcessZipEntryFunction proc_function_;
1127 void* cookie_;
1128};
1129
1130int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1131 ProcessZipEntryFunction func, void* cookie) {
1132 ProcessWriter writer(func, cookie);
1133 return ExtractToWriter(handle, entry, &writer);
1134}
1135
Jiyong Parkcd997e62017-06-30 17:23:33 +09001136#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001137
1138int MappedZipFile::GetFileDescriptor() const {
1139 if (!has_fd_) {
1140 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1141 return -1;
1142 }
1143 return fd_;
1144}
1145
1146void* MappedZipFile::GetBasePtr() const {
1147 if (has_fd_) {
1148 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1149 return nullptr;
1150 }
1151 return base_ptr_;
1152}
1153
1154off64_t MappedZipFile::GetFileLength() const {
1155 if (has_fd_) {
1156 off64_t result = lseek64(fd_, 0, SEEK_END);
1157 if (result == -1) {
1158 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1159 }
1160 return result;
1161 } else {
1162 if (base_ptr_ == nullptr) {
1163 ALOGE("Zip: invalid file map\n");
1164 return -1;
1165 }
1166 return static_cast<off64_t>(data_length_);
1167 }
1168}
1169
Tianjie Xu18c25922016-09-29 15:27:41 -07001170// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001171bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001172 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001173 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001174 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1175 return false;
1176 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001177 } else {
1178 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1179 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1180 return false;
1181 }
1182 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001183 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001184 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001185}
1186
1187void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1188 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1189 length_ = cd_size;
1190}
1191
1192bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1193 size_t cd_size) {
1194 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001195 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1196 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001197 return false;
1198 }
1199
1200 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001201 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001202 } else {
1203 if (mapped_zip.GetBasePtr() == nullptr) {
1204 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1205 return false;
1206 }
1207 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1208 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001209 ALOGE(
1210 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1211 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1212 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001213 return false;
1214 }
1215
1216 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1217 }
1218 return true;
1219}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001220
1221tm ZipEntry::GetModificationTime() const {
1222 tm t = {};
1223
1224 t.tm_hour = (mod_time >> 11) & 0x1f;
1225 t.tm_min = (mod_time >> 5) & 0x3f;
1226 t.tm_sec = (mod_time & 0x1f) << 1;
1227
1228 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1229 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1230 t.tm_mday = (mod_time >> 16) & 0x1f;
1231
1232 return t;
1233}