blob: 5e5e7afd18f5915a17403fb8a2883631660af09c [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) {
Adam Lesinskib354dce2018-03-01 21:32:13 +0000227#if defined(__ANDROID__)
Narayan Kamath7462f022013-11-21 13:05:04 +0000228 ALOGW("Zip: empty archive?");
Adam Lesinskib354dce2018-03-01 21:32:13 +0000229#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000230 return kEmptyArchive;
231 }
232
Jiyong Parkcd997e62017-06-30 17:23:33 +0900233 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32, eocd->num_records,
234 eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000235
236 /*
237 * It all looks good. Create a mapping for the CD, and set the fields
238 * in archive.
239 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700240
241 if (!archive->InitializeCentralDirectory(debug_file_name,
242 static_cast<off64_t>(eocd->cd_start_offset),
243 static_cast<size_t>(eocd->cd_size))) {
244 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000245 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000246 }
247
Narayan Kamath926973e2014-06-09 14:18:14 +0100248 archive->num_entries = eocd->num_records;
249 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000250
251 return 0;
252}
253
254/*
255 * Find the zip Central Directory and memory-map it.
256 *
257 * On success, returns 0 after populating fields from the EOCD area:
258 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700259 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000260 * num_entries
261 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700262static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000263 // Test file length. We use lseek64 to make sure the file
264 // is small enough to be a zip file (Its size must be less than
265 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700266 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000267 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000268 return kInvalidFile;
269 }
270
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800271 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100272 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000273 return kInvalidFile;
274 }
275
Narayan Kamath926973e2014-06-09 14:18:14 +0100276 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
277 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000278 return kInvalidFile;
279 }
280
281 /*
282 * Perform the traditional EOCD snipe hunt.
283 *
284 * We're searching for the End of Central Directory magic number,
285 * which appears at the start of the EOCD block. It's followed by
286 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
287 * need to read the last part of the file into a buffer, dig through
288 * it to find the magic number, parse some values out, and use those
289 * to determine the extent of the CD.
290 *
291 * We start by pulling in the last part of the file.
292 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100293 off64_t read_amount = kMaxEOCDSearch;
294 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000295 read_amount = file_length;
296 }
297
Tianjie Xu18c25922016-09-29 15:27:41 -0700298 std::vector<uint8_t> scan_buffer(read_amount);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900299 int32_t result =
300 MapCentralDirectory0(debug_file_name, archive, file_length, read_amount, scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000301 return result;
302}
303
304/*
305 * Parses the Zip archive's Central Directory. Allocates and populates the
306 * hash table.
307 *
308 * Returns 0 on success.
309 */
310static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700311 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
312 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100313 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000314
315 /*
316 * Create hash table. We have a minimum 75% load factor, possibly as
317 * low as 50% after we round off to a power of 2. There must be at
318 * least one unused entry to avoid an infinite loop during creation.
319 */
320 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Jiyong Parkcd997e62017-06-30 17:23:33 +0900321 archive->hash_table =
322 reinterpret_cast<ZipString*>(calloc(archive->hash_table_size, sizeof(ZipString)));
Tianjie Xu9e020e22016-10-10 12:11:30 -0700323 if (archive->hash_table == nullptr) {
324 ALOGW("Zip: unable to allocate the %u-entry hash_table, entry size: %zu",
325 archive->hash_table_size, sizeof(ZipString));
326 return -1;
327 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000328
329 /*
330 * Walk through the central directory, adding entries to the hash
331 * table and verifying values.
332 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100333 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000334 const uint8_t* ptr = cd_ptr;
335 for (uint16_t i = 0; i < num_entries; i++) {
Tianjie Xu0fda1cf2017-04-05 14:46:27 -0700336 if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
337 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
338#if defined(__ANDROID__)
339 android_errorWriteLog(0x534e4554, "36392138");
340#endif
341 return -1;
342 }
343
Jiyong Parkcd997e62017-06-30 17:23:33 +0900344 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100345 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700346 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800347 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000348 }
349
Narayan Kamath926973e2014-06-09 14:18:14 +0100350 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000351 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800352 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900353 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800354 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000355 }
356
Narayan Kamath926973e2014-06-09 14:18:14 +0100357 const uint16_t file_name_length = cdr->file_name_length;
358 const uint16_t extra_length = cdr->extra_field_length;
359 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100360 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
361
Tianjie Xu9e020e22016-10-10 12:11:30 -0700362 if (file_name + file_name_length > cd_end) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900363 ALOGW(
364 "Zip: file name boundary exceeds the central directory range, file_name_length: "
365 "%" PRIx16 ", cd_length: %zu",
366 file_name_length, cd_length);
Tianjie Xu9e020e22016-10-10 12:11:30 -0700367 return -1;
368 }
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000369 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
370 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800371 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100372 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000373
374 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700375 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100376 entry_name.name = file_name;
377 entry_name.name_length = file_name_length;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900378 const int add_result = AddToHash(archive->hash_table, archive->hash_table_size, entry_name);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800379 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000380 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800381 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000382 }
383
Narayan Kamath926973e2014-06-09 14:18:14 +0100384 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
385 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900386 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16, ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800387 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000388 }
389 }
Narayan Kamathc1a56dc2017-08-09 18:32:09 +0100390
391 uint32_t lfh_start_bytes;
392 if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
393 sizeof(uint32_t), 0)) {
394 ALOGW("Zip: Unable to read header for entry at offset == 0.");
395 return -1;
396 }
397
398 if (lfh_start_bytes != LocalFileHeader::kSignature) {
399 ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
400#if defined(__ANDROID__)
401 android_errorWriteLog(0x534e4554, "64211847");
402#endif
403 return -1;
404 }
405
Mark Salyzyn088bf902014-05-08 16:02:20 -0700406 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000407
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800408 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000409}
410
Jiyong Parkcd997e62017-06-30 17:23:33 +0900411static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000412 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700413 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000414 return result;
415 }
416
417 if ((result = ParseZipArchive(archive))) {
418 return result;
419 }
420
421 return 0;
422}
423
Jiyong Parkcd997e62017-06-30 17:23:33 +0900424int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
425 bool assume_ownership) {
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700426 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000427 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000428 return OpenArchiveInternal(archive, debug_file_name);
429}
430
431int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100432 const int fd = open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700433 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000434 *handle = archive;
435
Narayan Kamath7462f022013-11-21 13:05:04 +0000436 if (fd < 0) {
437 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
438 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000439 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700440
Narayan Kamath7462f022013-11-21 13:05:04 +0000441 return OpenArchiveInternal(archive, fileName);
442}
443
Tianjie Xu18c25922016-09-29 15:27:41 -0700444int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900445 ZipArchiveHandle* handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700446 ZipArchive* archive = new ZipArchive(address, length);
447 *handle = archive;
448 return OpenArchiveInternal(archive, debug_file_name);
449}
450
Narayan Kamath7462f022013-11-21 13:05:04 +0000451/*
452 * Close a ZipArchive, closing the file and freeing the contents.
453 */
454void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800455 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000456 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100457 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000458}
459
Narayan Kamath162b7052017-06-05 13:21:12 +0100460static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100461 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Adam Lesinskide117e42017-06-19 10:27:38 -0700462 off64_t offset = entry->offset;
463 if (entry->method != kCompressStored) {
464 offset += entry->compressed_length;
465 } else {
466 offset += entry->uncompressed_length;
467 }
468
469 if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000470 return kIoError;
471 }
472
Narayan Kamath926973e2014-06-09 14:18:14 +0100473 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
Adam Lesinskide117e42017-06-19 10:27:38 -0700474 const uint16_t ddOffset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
475 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + ddOffset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000476
Narayan Kamath162b7052017-06-05 13:21:12 +0100477 // Validate that the values in the data descriptor match those in the central
478 // directory.
479 if (entry->compressed_length != descriptor->compressed_size ||
480 entry->uncompressed_length != descriptor->uncompressed_size ||
481 entry->crc32 != descriptor->crc32) {
482 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
483 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
484 entry->compressed_length, entry->uncompressed_length, entry->crc32,
485 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
486 return kInconsistentInformation;
487 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000488
489 return 0;
490}
491
Jiyong Parkcd997e62017-06-30 17:23:33 +0900492static int32_t FindEntry(const ZipArchive* archive, const int ent, ZipEntry* data) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000493 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000494
495 // Recover the start of the central directory entry from the filename
496 // pointer. The filename is the first entry past the fixed-size data,
497 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100498 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100499 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000500
501 // This is the base of our mmapped region, we have to sanity check that
502 // the name that's in the hash table is a pointer to a location within
503 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700504 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
505 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000506 ALOGW("Zip: Invalid entry pointer");
507 return kInvalidOffset;
508 }
509
Jiyong Parkcd997e62017-06-30 17:23:33 +0900510 const CentralDirectoryRecord* cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
Narayan Kamath926973e2014-06-09 14:18:14 +0100511
Narayan Kamath7462f022013-11-21 13:05:04 +0000512 // The offset of the start of the central directory in the zipfile.
513 // We keep this lying around so that we can sanity check all our lengths
514 // and our per-file structures.
515 const off64_t cd_offset = archive->directory_offset;
516
517 // Fill out the compression method, modification time, crc32
518 // and other interesting attributes from the central directory. These
519 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100520 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900521 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100522 data->crc32 = cdr->crc32;
523 data->compressed_length = cdr->compressed_size;
524 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000525
526 // Figure out the local header offset from the central directory. The
527 // actual file data will begin after the local header and the name /
528 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100529 const off64_t local_header_offset = cdr->local_file_header_offset;
530 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000531 ALOGW("Zip: bad local hdr offset in zip");
532 return kInvalidOffset;
533 }
534
Narayan Kamath926973e2014-06-09 14:18:14 +0100535 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700536 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800537 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900538 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000539 return kIoError;
540 }
541
Jiyong Parkcd997e62017-06-30 17:23:33 +0900542 const LocalFileHeader* lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
Narayan Kamath926973e2014-06-09 14:18:14 +0100543
544 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700545 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Jiyong Parkcd997e62017-06-30 17:23:33 +0900546 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000547 return kInvalidOffset;
548 }
549
550 // Paranoia: Match the values specified in the local file header
551 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700552
Narayan Kamath162b7052017-06-05 13:21:12 +0100553 // Warn if central directory and local file header don't agree on the use
554 // of a trailing Data Descriptor. The reference implementation is inconsistent
555 // and appears to use the LFH value during extraction (unzip) but the CD value
556 // while displayng information about archives (zipinfo). The spec remains
557 // silent on this inconsistency as well.
558 //
559 // For now, always use the version from the LFH but make sure that the values
560 // specified in the central directory match those in the data descriptor.
561 //
562 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
563 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
564 // encoded using UTF-8). This implementation does not check for the presence of
565 // that flag and always enforces that entry names are valid UTF-8.
566 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
567 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700568 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700569 }
570
571 // If there is no trailing data descriptor, verify that the central directory and local file
572 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100573 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000574 data->has_data_descriptor = 0;
Jiyong Parkcd997e62017-06-30 17:23:33 +0900575 if (data->compressed_length != lfh->compressed_size ||
576 data->uncompressed_length != lfh->uncompressed_size || data->crc32 != lfh->crc32) {
577 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
578 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
579 data->compressed_length, data->uncompressed_length, data->crc32, lfh->compressed_size,
580 lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000581 return kInconsistentInformation;
582 }
583 } else {
584 data->has_data_descriptor = 1;
585 }
586
Elliott Hughes55fd2932017-05-28 22:59:04 -0700587 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
588 if ((cdr->version_made_by >> 8) == 3) {
589 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
590 } else {
591 data->unix_mode = 0777;
592 }
593
Narayan Kamath7462f022013-11-21 13:05:04 +0000594 // Check that the local file header name matches the declared
595 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100596 if (lfh->file_name_length == nameLen) {
597 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200598 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000599 ALOGW("Zip: Invalid declared length");
600 return kInvalidOffset;
601 }
602
Tianjie Xu18c25922016-09-29 15:27:41 -0700603 std::vector<uint8_t> name_buf(nameLen);
604 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800605 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000606 return kIoError;
607 }
608
Tianjie Xu18c25922016-09-29 15:27:41 -0700609 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000610 return kInconsistentInformation;
611 }
612
Narayan Kamath7462f022013-11-21 13:05:04 +0000613 } else {
614 ALOGW("Zip: lfh name did not match central directory.");
615 return kInconsistentInformation;
616 }
617
Jiyong Parkcd997e62017-06-30 17:23:33 +0900618 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
619 lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000620 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800621 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000622 return kInvalidOffset;
623 }
624
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800625 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700626 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Jiyong Parkcd997e62017-06-30 17:23:33 +0900627 static_cast<int64_t>(data_offset), data->compressed_length,
628 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000629 return kInvalidOffset;
630 }
631
632 if (data->method == kCompressStored &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900633 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
634 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
635 static_cast<int64_t>(data_offset), data->uncompressed_length,
636 static_cast<int64_t>(cd_offset));
637 return kInvalidOffset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000638 }
639
640 data->offset = data_offset;
641 return 0;
642}
643
644struct IterationHandle {
645 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100646 // We're not using vector here because this code is used in the Windows SDK
647 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700648 ZipString prefix;
649 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000650 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100651
Jiyong Parkcd997e62017-06-30 17:23:33 +0900652 IterationHandle(const ZipString* in_prefix, const ZipString* in_suffix) {
Yusuke Sato07447542015-06-25 14:39:19 -0700653 if (in_prefix) {
654 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
655 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
656 prefix.name = name_copy;
657 prefix.name_length = in_prefix->name_length;
658 } else {
659 prefix.name = NULL;
660 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700661 }
Yusuke Sato07447542015-06-25 14:39:19 -0700662 if (in_suffix) {
663 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
664 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
665 suffix.name = name_copy;
666 suffix.name_length = in_suffix->name_length;
667 } else {
668 suffix.name = NULL;
669 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700670 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100671 }
672
673 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700674 delete[] prefix.name;
675 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100676 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000677};
678
Jiyong Parkcd997e62017-06-30 17:23:33 +0900679int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr, const ZipString* optional_prefix,
Yusuke Sato07447542015-06-25 14:39:19 -0700680 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800681 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000682
683 if (archive == NULL || archive->hash_table == NULL) {
684 ALOGW("Zip: Invalid ZipArchiveHandle");
685 return kInvalidHandle;
686 }
687
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700688 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000689 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000690 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000691
Jiyong Parkcd997e62017-06-30 17:23:33 +0900692 *cookie_ptr = cookie;
Narayan Kamath7462f022013-11-21 13:05:04 +0000693 return 0;
694}
695
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100696void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100697 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100698}
699
Jiyong Parkcd997e62017-06-30 17:23:33 +0900700int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName, ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800701 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100702 if (entryName.name_length == 0) {
703 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000704 return kInvalidEntryName;
705 }
706
Jiyong Parkcd997e62017-06-30 17:23:33 +0900707 const int64_t ent = EntryToIndex(archive->hash_table, archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000708
709 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100710 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000711 return ent;
712 }
713
714 return FindEntry(archive, ent, data);
715}
716
Yusuke Sato07447542015-06-25 14:39:19 -0700717int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800718 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000719 if (handle == NULL) {
720 return kInvalidHandle;
721 }
722
723 ZipArchive* archive = handle->archive;
724 if (archive == NULL || archive->hash_table == NULL) {
725 ALOGW("Zip: Invalid ZipArchiveHandle");
726 return kInvalidHandle;
727 }
728
729 const uint32_t currentOffset = handle->position;
730 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700731 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000732
733 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
734 if (hash_table[i].name != NULL &&
Jiyong Parkcd997e62017-06-30 17:23:33 +0900735 (handle->prefix.name_length == 0 || hash_table[i].StartsWith(handle->prefix)) &&
736 (handle->suffix.name_length == 0 || hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000737 handle->position = (i + 1);
738 const int error = FindEntry(archive, i, data);
739 if (!error) {
740 name->name = hash_table[i].name;
741 name->name_length = hash_table[i].name_length;
742 }
743
744 return error;
745 }
746 }
747
748 handle->position = 0;
749 return kIterationEnd;
750}
751
Narayan Kamathf899bd52015-04-17 11:53:14 +0100752// A Writer that writes data to a fixed size memory region.
753// The size of the memory region must be equal to the total size of
754// the data appended to it.
Narayan Kamath485b3642017-10-26 14:42:39 +0100755class MemoryWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100756 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +0900757 MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100758
759 virtual bool Append(uint8_t* buf, size_t buf_size) override {
760 if (bytes_written_ + buf_size > size_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900761 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", size_,
762 bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100763 return false;
764 }
765
766 memcpy(buf_ + bytes_written_, buf, buf_size);
767 bytes_written_ += buf_size;
768 return true;
769 }
770
771 private:
772 uint8_t* const buf_;
773 const size_t size_;
774 size_t bytes_written_;
775};
776
777// A Writer that appends data to a file |fd| at its current position.
778// The file will be truncated to the end of the written data.
Narayan Kamath485b3642017-10-26 14:42:39 +0100779class FileWriter : public zip_archive::Writer {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100780 public:
Narayan Kamathf899bd52015-04-17 11:53:14 +0100781 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
782 // guaranteeing that the file descriptor is valid and that there's enough
783 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800784 // is truncated to the correct length (no truncation if |fd| references a
785 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100786 //
787 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800788 static FileWriter Create(int fd, const ZipEntry* entry) {
Narayan Kamathf899bd52015-04-17 11:53:14 +0100789 const uint32_t declared_length = entry->uncompressed_length;
790 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
791 if (current_offset == -1) {
792 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800793 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100794 }
795
796 int result = 0;
797#if defined(__linux__)
798 if (declared_length > 0) {
799 // Make sure we have enough space on the volume to extract the compressed
800 // entry. Note that the call to ftruncate below will change the file size but
801 // will not allocate space on disk and this call to fallocate will not
802 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700803 // Note: fallocate is only supported by the following filesystems -
804 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
805 // EOPNOTSUPP error when issued in other filesystems.
806 // Hence, check for the return error code before concluding that the
807 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100808 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700809 if (result == -1 && errno == ENOSPC) {
Elliott Hughes4089d342017-10-27 14:21:12 -0700810 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 ": %s",
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100811 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
812 strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800813 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100814 }
815 }
816#endif // __linux__
817
Tao Baoa456c212016-11-15 10:08:07 -0800818 struct stat sb;
819 if (fstat(fd, &sb) == -1) {
820 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800821 return FileWriter{};
Narayan Kamathf899bd52015-04-17 11:53:14 +0100822 }
823
Tao Baoa456c212016-11-15 10:08:07 -0800824 // Block device doesn't support ftruncate(2).
825 if (!S_ISBLK(sb.st_mode)) {
826 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
827 if (result == -1) {
828 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
829 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800830 return FileWriter{};
Tao Baoa456c212016-11-15 10:08:07 -0800831 }
832 }
833
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800834 return FileWriter(fd, declared_length);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100835 }
836
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800837 FileWriter(FileWriter&& other)
838 : fd_(other.fd_),
839 declared_length_(other.declared_length_),
840 total_bytes_written_(other.total_bytes_written_) {
841 other.fd_ = -1;
842 }
843
844 bool IsValid() const { return fd_ != -1; }
845
Narayan Kamathf899bd52015-04-17 11:53:14 +0100846 virtual bool Append(uint8_t* buf, size_t buf_size) override {
847 if (total_bytes_written_ + buf_size > declared_length_) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900848 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)", declared_length_,
849 total_bytes_written_ + buf_size);
Narayan Kamathf899bd52015-04-17 11:53:14 +0100850 return false;
851 }
852
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100853 const bool result = android::base::WriteFully(fd_, buf, buf_size);
854 if (result) {
855 total_bytes_written_ += buf_size;
856 } else {
857 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100858 }
859
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100860 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100861 }
Jiyong Parkcd997e62017-06-30 17:23:33 +0900862
Narayan Kamathf899bd52015-04-17 11:53:14 +0100863 private:
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800864 explicit FileWriter(const int fd = -1, const size_t declared_length = 0)
Jiyong Parkcd997e62017-06-30 17:23:33 +0900865 : Writer(), fd_(fd), declared_length_(declared_length), total_bytes_written_(0) {}
Narayan Kamathf899bd52015-04-17 11:53:14 +0100866
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -0800867 int fd_;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100868 const size_t declared_length_;
869 size_t total_bytes_written_;
870};
871
Narayan Kamath485b3642017-10-26 14:42:39 +0100872class EntryReader : public zip_archive::Reader {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100873 public:
874 EntryReader(const MappedZipFile& zip_file, const ZipEntry* entry)
875 : Reader(), zip_file_(zip_file), entry_(entry) {}
876
877 virtual bool ReadAtOffset(uint8_t* buf, size_t len, uint32_t offset) const {
878 return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
879 }
880
881 virtual ~EntryReader() {}
882
883 private:
884 const MappedZipFile& zip_file_;
885 const ZipEntry* entry_;
886};
887
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800888// This method is using libz macros with old-style-casts
889#pragma GCC diagnostic push
890#pragma GCC diagnostic ignored "-Wold-style-cast"
891static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
892 return inflateInit2(stream, window_bits);
893}
894#pragma GCC diagnostic pop
895
Narayan Kamath485b3642017-10-26 14:42:39 +0100896namespace zip_archive {
897
898// Moved out of line to avoid -Wweak-vtables.
899Reader::~Reader() {}
900Writer::~Writer() {}
901
902int32_t Inflate(const Reader& reader, const uint32_t compressed_length,
903 const uint32_t uncompressed_length, Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700904 const size_t kBufSize = 32768;
905 std::vector<uint8_t> read_buf(kBufSize);
906 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000907 z_stream zstream;
908 int zerr;
909
910 /*
911 * Initialize the zlib stream struct.
912 */
913 memset(&zstream, 0, sizeof(zstream));
914 zstream.zalloc = Z_NULL;
915 zstream.zfree = Z_NULL;
916 zstream.opaque = Z_NULL;
917 zstream.next_in = NULL;
918 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700919 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000920 zstream.avail_out = kBufSize;
921 zstream.data_type = Z_UNKNOWN;
922
923 /*
924 * Use the undocumented "negative window bits" feature to tell zlib
925 * that there's no zlib header waiting for it.
926 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800927 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000928 if (zerr != Z_OK) {
929 if (zerr == Z_VERSION_ERROR) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900930 ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
Narayan Kamath7462f022013-11-21 13:05:04 +0000931 } else {
932 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
933 }
934
935 return kZlibError;
936 }
937
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800938 auto zstream_deleter = [](z_stream* stream) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900939 inflateEnd(stream); /* free up any allocated structures */
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800940 };
941
942 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
943
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000944 const bool compute_crc = (crc_out != nullptr);
Narayan Kamath162b7052017-06-05 13:21:12 +0100945 uint64_t crc = 0;
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100946 uint32_t remaining_bytes = compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000947 do {
948 /* read as much as we can */
949 if (zstream.avail_in == 0) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100950 const size_t read_size = (remaining_bytes > kBufSize) ? kBufSize : remaining_bytes;
951 const uint32_t offset = (compressed_length - remaining_bytes);
Adam Lesinskide117e42017-06-19 10:27:38 -0700952 // Make sure to read at offset to ensure concurrent access to the fd.
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100953 if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
954 ALOGW("Zip: inflate read failed, getSize = %zu: %s", read_size, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800955 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000956 }
957
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100958 remaining_bytes -= read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000959
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700960 zstream.next_in = &read_buf[0];
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100961 zstream.avail_in = read_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000962 }
963
964 /* uncompress the data */
965 zerr = inflate(&zstream, Z_NO_FLUSH);
966 if (zerr != Z_OK && zerr != Z_STREAM_END) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900967 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
968 zstream.avail_in, zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800969 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000970 }
971
972 /* write when we're full or when we're done */
Jiyong Parkcd997e62017-06-30 17:23:33 +0900973 if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700974 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100975 if (!writer->Append(&write_buf[0], write_size)) {
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000976 return kIoError;
977 } else if (compute_crc) {
Narayan Kamath162b7052017-06-05 13:21:12 +0100978 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +0000979 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000980
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700981 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000982 zstream.avail_out = kBufSize;
983 }
984 } while (zerr == Z_OK);
985
Jiyong Parkcd997e62017-06-30 17:23:33 +0900986 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
Narayan Kamath7462f022013-11-21 13:05:04 +0000987
Narayan Kamath162b7052017-06-05 13:21:12 +0100988 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
989 // "feature" of zlib to tell it there won't be a zlib file header. zlib
990 // doesn't bother calculating the checksum in that scenario. We just do
991 // it ourselves above because there are no additional gains to be made by
992 // having zlib calculate it for us, since they do it by calling crc32 in
993 // the same manner that we have above.
Narayan Kamath2d1e23f2017-10-30 11:17:28 +0000994 if (compute_crc) {
995 *crc_out = crc;
996 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000997
Narayan Kamath8b8faed2017-10-26 14:08:38 +0100998 if (zstream.total_out != uncompressed_length || remaining_bytes != 0) {
Jiyong Parkcd997e62017-06-30 17:23:33 +0900999 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")", zstream.total_out,
1000 uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001001 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +00001002 }
1003
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -08001004 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +00001005}
Narayan Kamath485b3642017-10-26 14:42:39 +01001006} // namespace zip_archive
Narayan Kamath7462f022013-11-21 13:05:04 +00001007
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001008static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamath485b3642017-10-26 14:42:39 +01001009 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001010 const EntryReader reader(mapped_zip, entry);
1011
Narayan Kamath485b3642017-10-26 14:42:39 +01001012 return zip_archive::Inflate(reader, entry->compressed_length, entry->uncompressed_length, writer,
1013 crc_out);
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001014}
1015
Narayan Kamath485b3642017-10-26 14:42:39 +01001016static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
1017 zip_archive::Writer* writer, uint64_t* crc_out) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001018 static const uint32_t kBufSize = 32768;
1019 std::vector<uint8_t> buf(kBufSize);
1020
1021 const uint32_t length = entry->uncompressed_length;
1022 uint32_t count = 0;
1023 uint64_t crc = 0;
1024 while (count < length) {
1025 uint32_t remaining = length - count;
Adam Lesinskide117e42017-06-19 10:27:38 -07001026 off64_t offset = entry->offset + count;
Narayan Kamathf899bd52015-04-17 11:53:14 +01001027
Adam Lesinskide117e42017-06-19 10:27:38 -07001028 // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
Yabin Cuib2a77002016-02-08 16:26:33 -08001029 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Adam Lesinskide117e42017-06-19 10:27:38 -07001030
1031 // Make sure to read at offset to ensure concurrent access to the fd.
1032 if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1033 ALOGW("CopyFileToFile: copy read failed, block_size = %zu, offset = %" PRId64 ": %s",
1034 block_size, static_cast<int64_t>(offset), strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +01001035 return kIoError;
1036 }
1037
1038 if (!writer->Append(&buf[0], block_size)) {
1039 return kIoError;
1040 }
1041 crc = crc32(crc, &buf[0], block_size);
1042 count += block_size;
1043 }
1044
1045 *crc_out = crc;
1046
1047 return 0;
1048}
1049
Narayan Kamath485b3642017-10-26 14:42:39 +01001050int32_t ExtractToWriter(ZipArchiveHandle handle, ZipEntry* entry, zip_archive::Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001051 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +00001052 const uint16_t method = entry->method;
Narayan Kamath7462f022013-11-21 13:05:04 +00001053
1054 // this should default to kUnknownCompressionMethod.
1055 int32_t return_value = -1;
1056 uint64_t crc = 0;
1057 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001058 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001059 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001060 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001061 }
1062
1063 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001064 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001065 if (return_value) {
1066 return return_value;
1067 }
1068 }
1069
Narayan Kamath162b7052017-06-05 13:21:12 +01001070 // Validate that the CRC matches the calculated value.
1071 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001072 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001073 return kInconsistentInformation;
1074 }
1075
1076 return return_value;
1077}
1078
Jiyong Parkcd997e62017-06-30 17:23:33 +09001079int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry, uint8_t* begin, uint32_t size) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001080 MemoryWriter writer(begin, size);
1081 return ExtractToWriter(handle, entry, &writer);
Narayan Kamathf899bd52015-04-17 11:53:14 +01001082}
1083
Jiyong Parkcd997e62017-06-30 17:23:33 +09001084int32_t ExtractEntryToFile(ZipArchiveHandle handle, ZipEntry* entry, int fd) {
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001085 auto writer = FileWriter::Create(fd, entry);
1086 if (!writer.IsValid()) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001087 return kIoError;
1088 }
1089
Yurii Zubrytskyi834326c2017-12-20 01:01:01 -08001090 return ExtractToWriter(handle, entry, &writer);
Narayan Kamath7462f022013-11-21 13:05:04 +00001091}
1092
1093const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001094 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1095 // match.
1096 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1097 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1098
1099 const uint32_t idx = -error_code;
1100 if (idx < arraysize(kErrorMessages)) {
1101 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001102 }
1103
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001104 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001105}
1106
1107int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001108 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001109}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001110
Jiyong Parkcd997e62017-06-30 17:23:33 +09001111ZipString::ZipString(const char* entry_name) : name(reinterpret_cast<const uint8_t*>(entry_name)) {
Colin Cross7c6c7f02016-09-16 10:15:51 -07001112 size_t len = strlen(entry_name);
1113 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1114 name_length = static_cast<uint16_t>(len);
1115}
Tianjie Xu18c25922016-09-29 15:27:41 -07001116
1117#if !defined(_WIN32)
Narayan Kamath485b3642017-10-26 14:42:39 +01001118class ProcessWriter : public zip_archive::Writer {
Tianjie Xu18c25922016-09-29 15:27:41 -07001119 public:
Jiyong Parkcd997e62017-06-30 17:23:33 +09001120 ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1121 : Writer(), proc_function_(func), cookie_(cookie) {}
Tianjie Xu18c25922016-09-29 15:27:41 -07001122
1123 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1124 return proc_function_(buf, buf_size, cookie_);
1125 }
1126
1127 private:
1128 ProcessZipEntryFunction proc_function_;
1129 void* cookie_;
1130};
1131
1132int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1133 ProcessZipEntryFunction func, void* cookie) {
1134 ProcessWriter writer(func, cookie);
1135 return ExtractToWriter(handle, entry, &writer);
1136}
1137
Jiyong Parkcd997e62017-06-30 17:23:33 +09001138#endif //! defined(_WIN32)
Tianjie Xu18c25922016-09-29 15:27:41 -07001139
1140int MappedZipFile::GetFileDescriptor() const {
1141 if (!has_fd_) {
1142 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1143 return -1;
1144 }
1145 return fd_;
1146}
1147
1148void* MappedZipFile::GetBasePtr() const {
1149 if (has_fd_) {
1150 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1151 return nullptr;
1152 }
1153 return base_ptr_;
1154}
1155
1156off64_t MappedZipFile::GetFileLength() const {
1157 if (has_fd_) {
1158 off64_t result = lseek64(fd_, 0, SEEK_END);
1159 if (result == -1) {
1160 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1161 }
1162 return result;
1163 } else {
1164 if (base_ptr_ == nullptr) {
1165 ALOGE("Zip: invalid file map\n");
1166 return -1;
1167 }
1168 return static_cast<off64_t>(data_length_);
1169 }
1170}
1171
Tianjie Xu18c25922016-09-29 15:27:41 -07001172// Attempts to read |len| bytes into |buf| at offset |off|.
Narayan Kamath8b8faed2017-10-26 14:08:38 +01001173bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
Tianjie Xu18c25922016-09-29 15:27:41 -07001174 if (has_fd_) {
Adam Lesinskide117e42017-06-19 10:27:38 -07001175 if (!android::base::ReadFullyAtOffset(fd_, buf, len, off)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001176 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1177 return false;
1178 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001179 } else {
1180 if (off < 0 || off > static_cast<off64_t>(data_length_)) {
1181 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n", off, data_length_);
1182 return false;
1183 }
1184 memcpy(buf, static_cast<uint8_t*>(base_ptr_) + off, len);
Tianjie Xu18c25922016-09-29 15:27:41 -07001185 }
Adam Lesinskide117e42017-06-19 10:27:38 -07001186 return true;
Tianjie Xu18c25922016-09-29 15:27:41 -07001187}
1188
1189void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1190 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1191 length_ = cd_size;
1192}
1193
1194bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1195 size_t cd_size) {
1196 if (mapped_zip.HasFd()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001197 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(), cd_start_offset,
1198 cd_size, true /* read only */)) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001199 return false;
1200 }
1201
1202 CHECK_EQ(directory_map->getDataLength(), cd_size);
Jiyong Parkcd997e62017-06-30 17:23:33 +09001203 central_directory.Initialize(directory_map->getDataPtr(), 0 /*offset*/, cd_size);
Tianjie Xu18c25922016-09-29 15:27:41 -07001204 } else {
1205 if (mapped_zip.GetBasePtr() == nullptr) {
1206 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1207 return false;
1208 }
1209 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1210 mapped_zip.GetFileLength()) {
Jiyong Parkcd997e62017-06-30 17:23:33 +09001211 ALOGE(
1212 "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1213 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1214 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
Tianjie Xu18c25922016-09-29 15:27:41 -07001215 return false;
1216 }
1217
1218 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1219 }
1220 return true;
1221}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001222
1223tm ZipEntry::GetModificationTime() const {
1224 tm t = {};
1225
1226 t.tm_hour = (mod_time >> 11) & 0x1f;
1227 t.tm_min = (mod_time >> 5) & 0x3f;
1228 t.tm_sec = (mod_time & 0x1f) << 1;
1229
1230 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1231 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1232 t.tm_mday = (mod_time >> 16) & 0x1f;
1233
1234 return t;
1235}