blob: efe10966e6e3a59e8dcc162d724a79fbe1034015 [file] [log] [blame]
Narayan Kamath7462f022013-11-21 13:05:04 +00001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17/*
18 * Read-only access to Zip archives, with minimal heap allocation.
19 */
Narayan Kamath7462f022013-11-21 13:05:04 +000020
Mark Salyzyncfd5b082016-10-17 14:28:00 -070021#define LOG_TAG "ziparchive"
22
Narayan Kamath7462f022013-11-21 13:05:04 +000023#include <assert.h>
24#include <errno.h>
Mark Salyzyn99ef9912014-03-14 14:26:22 -070025#include <fcntl.h>
26#include <inttypes.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000027#include <limits.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000028#include <stdlib.h>
29#include <string.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070030#include <time.h>
Narayan Kamath7462f022013-11-21 13:05:04 +000031#include <unistd.h>
32
Dan Albert1ae07642015-04-09 14:11:18 -070033#include <memory>
34#include <vector>
35
Mark Salyzynff2dcd92016-09-28 15:54:45 -070036#include <android-base/file.h>
37#include <android-base/logging.h>
38#include <android-base/macros.h> // TEMP_FAILURE_RETRY may or may not be in unistd
39#include <android-base/memory.h>
Mark Salyzyncfd5b082016-10-17 14:28:00 -070040#include <log/log.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070041#include <utils/Compat.h>
42#include <utils/FileMap.h>
Christopher Ferrise6884ce2015-11-10 14:55:12 -080043#include "ziparchive/zip_archive.h"
Dan Albert1ae07642015-04-09 14:11:18 -070044#include "zlib.h"
Narayan Kamath7462f022013-11-21 13:05:04 +000045
Narayan Kamath044bc8e2014-12-03 18:22:53 +000046#include "entry_name_utils-inl.h"
Adam Lesinskiad4ad8c2015-10-05 18:16:18 -070047#include "zip_archive_common.h"
Christopher Ferrise6884ce2015-11-10 14:55:12 -080048#include "zip_archive_private.h"
Mark Salyzyn99ef9912014-03-14 14:26:22 -070049
Dan Albert1ae07642015-04-09 14:11:18 -070050using android::base::get_unaligned;
Narayan Kamath044bc8e2014-12-03 18:22:53 +000051
Narayan Kamath162b7052017-06-05 13:21:12 +010052// Used to turn on crc checks - verify that the content CRC matches the values
53// specified in the local file header and the central directory.
54static const bool kCrcChecksEnabled = false;
55
Narayan Kamath926973e2014-06-09 14:18:14 +010056// This is for windows. If we don't open a file in binary mode, weird
Narayan Kamath7462f022013-11-21 13:05:04 +000057// things will happen.
58#ifndef O_BINARY
59#define O_BINARY 0
60#endif
61
Narayan Kamath926973e2014-06-09 14:18:14 +010062// The maximum number of bytes to scan backwards for the EOCD start.
63static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
64
Narayan Kamath7462f022013-11-21 13:05:04 +000065/*
66 * A Read-only Zip archive.
67 *
68 * We want "open" and "find entry by name" to be fast operations, and
69 * we want to use as little memory as possible. We memory-map the zip
70 * central directory, and load a hash table with pointers to the filenames
71 * (which aren't null-terminated). The other fields are at a fixed offset
72 * from the filename, so we don't need to extract those (but we do need
73 * to byte-read and endian-swap them every time we want them).
74 *
75 * It's possible that somebody has handed us a massive (~1GB) zip archive,
76 * so we can't expect to mmap the entire file.
77 *
78 * To speed comparisons when doing a lookup by name, we could make the mapping
79 * "private" (copy-on-write) and null-terminate the filenames after verifying
80 * the record structure. However, this requires a private mapping of
81 * every page that the Central Directory touches. Easier to tuck a copy
82 * of the string length into the hash table entry.
83 */
Narayan Kamath7462f022013-11-21 13:05:04 +000084
Narayan Kamath7462f022013-11-21 13:05:04 +000085/*
86 * Round up to the next highest power of 2.
87 *
88 * Found on http://graphics.stanford.edu/~seander/bithacks.html.
89 */
90static uint32_t RoundUpPower2(uint32_t val) {
91 val--;
92 val |= val >> 1;
93 val |= val >> 2;
94 val |= val >> 4;
95 val |= val >> 8;
96 val |= val >> 16;
97 val++;
98
99 return val;
100}
101
Yusuke Sato07447542015-06-25 14:39:19 -0700102static uint32_t ComputeHash(const ZipString& name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000103 uint32_t hash = 0;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100104 uint16_t len = name.name_length;
105 const uint8_t* str = name.name;
Narayan Kamath7462f022013-11-21 13:05:04 +0000106
107 while (len--) {
108 hash = hash * 31 + *str++;
109 }
110
111 return hash;
112}
113
114/*
115 * Convert a ZipEntry to a hash table index, verifying that it's in a
116 * valid range.
117 */
Yusuke Sato07447542015-06-25 14:39:19 -0700118static int64_t EntryToIndex(const ZipString* hash_table,
Narayan Kamath7462f022013-11-21 13:05:04 +0000119 const uint32_t hash_table_size,
Yusuke Sato07447542015-06-25 14:39:19 -0700120 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100121 const uint32_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000122
123 // NOTE: (hash_table_size - 1) is guaranteed to be non-negative.
124 uint32_t ent = hash & (hash_table_size - 1);
125 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700126 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000127 return ent;
128 }
129
130 ent = (ent + 1) & (hash_table_size - 1);
131 }
132
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100133 ALOGV("Zip: Unable to find entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000134 return kEntryNotFound;
135}
136
137/*
138 * Add a new entry to the hash table.
139 */
Yusuke Sato07447542015-06-25 14:39:19 -0700140static int32_t AddToHash(ZipString *hash_table, const uint64_t hash_table_size,
141 const ZipString& name) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100142 const uint64_t hash = ComputeHash(name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000143 uint32_t ent = hash & (hash_table_size - 1);
144
145 /*
146 * We over-allocated the table, so we're guaranteed to find an empty slot.
147 * Further, we guarantee that the hashtable size is not 0.
148 */
149 while (hash_table[ent].name != NULL) {
Yusuke Sato07447542015-06-25 14:39:19 -0700150 if (hash_table[ent] == name) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000151 // We've found a duplicate entry. We don't accept it
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100152 ALOGW("Zip: Found duplicate entry %.*s", name.name_length, name.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000153 return kDuplicateEntry;
154 }
155 ent = (ent + 1) & (hash_table_size - 1);
156 }
157
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100158 hash_table[ent].name = name.name;
159 hash_table[ent].name_length = name.name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000160 return 0;
161}
162
Tianjie Xu18c25922016-09-29 15:27:41 -0700163static int32_t MapCentralDirectory0(const char* debug_file_name, ZipArchive* archive,
164 off64_t file_length, off64_t read_amount,
165 uint8_t* scan_buffer) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000166 const off64_t search_start = file_length - read_amount;
167
Tianjie Xu18c25922016-09-29 15:27:41 -0700168 if(!archive->mapped_zip.ReadAtOffset(scan_buffer, read_amount, search_start)) {
169 ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed",
170 static_cast<int64_t>(read_amount), static_cast<int64_t>(search_start));
Narayan Kamath7462f022013-11-21 13:05:04 +0000171 return kIoError;
172 }
173
174 /*
175 * Scan backward for the EOCD magic. In an archive without a trailing
176 * comment, we'll find it on the first try. (We may want to consider
177 * doing an initial minimal read; if we don't find it, retry with a
178 * second read as above.)
179 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100180 int i = read_amount - sizeof(EocdRecord);
181 for (; i >= 0; i--) {
Dan Albert1ae07642015-04-09 14:11:18 -0700182 if (scan_buffer[i] == 0x50) {
183 uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
184 if (get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
185 ALOGV("+++ Found EOCD at buf+%d", i);
186 break;
187 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000188 }
189 }
190 if (i < 0) {
191 ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
192 return kInvalidFile;
193 }
194
195 const off64_t eocd_offset = search_start + i;
Narayan Kamath926973e2014-06-09 14:18:14 +0100196 const EocdRecord* eocd = reinterpret_cast<const EocdRecord*>(scan_buffer + i);
Narayan Kamath7462f022013-11-21 13:05:04 +0000197 /*
Narayan Kamath926973e2014-06-09 14:18:14 +0100198 * Verify that there's no trailing space at the end of the central directory
199 * and its comment.
Narayan Kamath7462f022013-11-21 13:05:04 +0000200 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100201 const off64_t calculated_length = eocd_offset + sizeof(EocdRecord)
202 + eocd->comment_length;
203 if (calculated_length != file_length) {
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100204 ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
Narayan Kamath926973e2014-06-09 14:18:14 +0100205 static_cast<int64_t>(file_length - calculated_length));
Narayan Kamath4f6b4992014-06-03 13:59:23 +0100206 return kInvalidFile;
207 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000208
Narayan Kamath926973e2014-06-09 14:18:14 +0100209 /*
210 * Grab the CD offset and size, and the number of entries in the
211 * archive and verify that they look reasonable.
212 */
Tianjie Xu1ee48922016-09-21 14:58:11 -0700213 if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100214 ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
215 eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
Tianjie Xu1ee48922016-09-21 14:58:11 -0700216#if defined(__ANDROID__)
217 if (eocd->cd_start_offset + eocd->cd_size <= eocd_offset) {
218 android_errorWriteLog(0x534e4554, "31251826");
219 }
220#endif
Narayan Kamath7462f022013-11-21 13:05:04 +0000221 return kInvalidOffset;
222 }
Narayan Kamath926973e2014-06-09 14:18:14 +0100223 if (eocd->num_records == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000224 ALOGW("Zip: empty archive?");
225 return kEmptyArchive;
226 }
227
Elliott Hughese49236b2015-06-04 15:21:59 -0700228 ALOGV("+++ num_entries=%" PRIu32 " dir_size=%" PRIu32 " dir_offset=%" PRIu32,
Narayan Kamath926973e2014-06-09 14:18:14 +0100229 eocd->num_records, eocd->cd_size, eocd->cd_start_offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000230
231 /*
232 * It all looks good. Create a mapping for the CD, and set the fields
233 * in archive.
234 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700235
236 if (!archive->InitializeCentralDirectory(debug_file_name,
237 static_cast<off64_t>(eocd->cd_start_offset),
238 static_cast<size_t>(eocd->cd_size))) {
239 ALOGE("Zip: failed to intialize central directory.\n");
Narayan Kamatheaf98852013-12-11 14:51:51 +0000240 return kMmapFailed;
Narayan Kamath7462f022013-11-21 13:05:04 +0000241 }
242
Narayan Kamath926973e2014-06-09 14:18:14 +0100243 archive->num_entries = eocd->num_records;
244 archive->directory_offset = eocd->cd_start_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000245
246 return 0;
247}
248
249/*
250 * Find the zip Central Directory and memory-map it.
251 *
252 * On success, returns 0 after populating fields from the EOCD area:
253 * directory_offset
Tianjie Xu18c25922016-09-29 15:27:41 -0700254 * directory_ptr
Narayan Kamath7462f022013-11-21 13:05:04 +0000255 * num_entries
256 */
Tianjie Xu18c25922016-09-29 15:27:41 -0700257static int32_t MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000258
259 // Test file length. We use lseek64 to make sure the file
260 // is small enough to be a zip file (Its size must be less than
261 // 0xffffffff bytes).
Tianjie Xu18c25922016-09-29 15:27:41 -0700262 off64_t file_length = archive->mapped_zip.GetFileLength();
Narayan Kamath7462f022013-11-21 13:05:04 +0000263 if (file_length == -1) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000264 return kInvalidFile;
265 }
266
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800267 if (file_length > static_cast<off64_t>(0xffffffff)) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100268 ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000269 return kInvalidFile;
270 }
271
Narayan Kamath926973e2014-06-09 14:18:14 +0100272 if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
273 ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
Narayan Kamath7462f022013-11-21 13:05:04 +0000274 return kInvalidFile;
275 }
276
277 /*
278 * Perform the traditional EOCD snipe hunt.
279 *
280 * We're searching for the End of Central Directory magic number,
281 * which appears at the start of the EOCD block. It's followed by
282 * 18 bytes of EOCD stuff and up to 64KB of archive comment. We
283 * need to read the last part of the file into a buffer, dig through
284 * it to find the magic number, parse some values out, and use those
285 * to determine the extent of the CD.
286 *
287 * We start by pulling in the last part of the file.
288 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100289 off64_t read_amount = kMaxEOCDSearch;
290 if (file_length < read_amount) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000291 read_amount = file_length;
292 }
293
Tianjie Xu18c25922016-09-29 15:27:41 -0700294 std::vector<uint8_t> scan_buffer(read_amount);
295 int32_t result = MapCentralDirectory0(debug_file_name, archive, file_length, read_amount,
296 scan_buffer.data());
Narayan Kamath7462f022013-11-21 13:05:04 +0000297 return result;
298}
299
300/*
301 * Parses the Zip archive's Central Directory. Allocates and populates the
302 * hash table.
303 *
304 * Returns 0 on success.
305 */
306static int32_t ParseZipArchive(ZipArchive* archive) {
Tianjie Xu18c25922016-09-29 15:27:41 -0700307 const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
308 const size_t cd_length = archive->central_directory.GetMapLength();
Narayan Kamath926973e2014-06-09 14:18:14 +0100309 const uint16_t num_entries = archive->num_entries;
Narayan Kamath7462f022013-11-21 13:05:04 +0000310
311 /*
312 * Create hash table. We have a minimum 75% load factor, possibly as
313 * low as 50% after we round off to a power of 2. There must be at
314 * least one unused entry to avoid an infinite loop during creation.
315 */
316 archive->hash_table_size = RoundUpPower2(1 + (num_entries * 4) / 3);
Yusuke Sato07447542015-06-25 14:39:19 -0700317 archive->hash_table = reinterpret_cast<ZipString*>(calloc(archive->hash_table_size,
318 sizeof(ZipString)));
Narayan Kamath7462f022013-11-21 13:05:04 +0000319
320 /*
321 * Walk through the central directory, adding entries to the hash
322 * table and verifying values.
323 */
Narayan Kamath926973e2014-06-09 14:18:14 +0100324 const uint8_t* const cd_end = cd_ptr + cd_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000325 const uint8_t* ptr = cd_ptr;
326 for (uint16_t i = 0; i < num_entries; i++) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100327 const CentralDirectoryRecord* cdr =
328 reinterpret_cast<const CentralDirectoryRecord*>(ptr);
329 if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700330 ALOGW("Zip: missed a central dir sig (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800331 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000332 }
333
Narayan Kamath926973e2014-06-09 14:18:14 +0100334 if (ptr + sizeof(CentralDirectoryRecord) > cd_end) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700335 ALOGW("Zip: ran off the end (at %" PRIu16 ")", i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800336 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000337 }
338
Narayan Kamath926973e2014-06-09 14:18:14 +0100339 const off64_t local_header_offset = cdr->local_file_header_offset;
Narayan Kamath7462f022013-11-21 13:05:04 +0000340 if (local_header_offset >= archive->directory_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800341 ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu16,
342 static_cast<int64_t>(local_header_offset), i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800343 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000344 }
345
Narayan Kamath926973e2014-06-09 14:18:14 +0100346 const uint16_t file_name_length = cdr->file_name_length;
347 const uint16_t extra_length = cdr->extra_field_length;
348 const uint16_t comment_length = cdr->comment_length;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100349 const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
350
Narayan Kamath044bc8e2014-12-03 18:22:53 +0000351 /* check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters */
352 if (!IsValidEntryName(file_name, file_name_length)) {
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800353 return -1;
Piotr Jastrzebski78271ba2014-08-15 12:53:00 +0100354 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000355
356 /* add the CDE filename to the hash table */
Yusuke Sato07447542015-06-25 14:39:19 -0700357 ZipString entry_name;
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100358 entry_name.name = file_name;
359 entry_name.name_length = file_name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000360 const int add_result = AddToHash(archive->hash_table,
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100361 archive->hash_table_size, entry_name);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800362 if (add_result != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000363 ALOGW("Zip: Error adding entry to hash table %d", add_result);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800364 return add_result;
Narayan Kamath7462f022013-11-21 13:05:04 +0000365 }
366
Narayan Kamath926973e2014-06-09 14:18:14 +0100367 ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
368 if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700369 ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu16,
370 ptr - cd_ptr, cd_length, i);
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800371 return -1;
Narayan Kamath7462f022013-11-21 13:05:04 +0000372 }
373 }
Mark Salyzyn088bf902014-05-08 16:02:20 -0700374 ALOGV("+++ zip good scan %" PRIu16 " entries", num_entries);
Narayan Kamath7462f022013-11-21 13:05:04 +0000375
Dmitriy Ivanov3ea93da2015-03-06 11:48:47 -0800376 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000377}
378
379static int32_t OpenArchiveInternal(ZipArchive* archive,
380 const char* debug_file_name) {
381 int32_t result = -1;
Tianjie Xu18c25922016-09-29 15:27:41 -0700382 if ((result = MapCentralDirectory(debug_file_name, archive)) != 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000383 return result;
384 }
385
386 if ((result = ParseZipArchive(archive))) {
387 return result;
388 }
389
390 return 0;
391}
392
393int32_t OpenArchiveFd(int fd, const char* debug_file_name,
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700394 ZipArchiveHandle* handle, bool assume_ownership) {
395 ZipArchive* archive = new ZipArchive(fd, assume_ownership);
Narayan Kamath7462f022013-11-21 13:05:04 +0000396 *handle = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000397 return OpenArchiveInternal(archive, debug_file_name);
398}
399
400int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
Neil Fullerb1a113f2014-07-25 14:43:04 +0100401 const int fd = open(fileName, O_RDONLY | O_BINARY, 0);
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700402 ZipArchive* archive = new ZipArchive(fd, true);
Narayan Kamath7462f022013-11-21 13:05:04 +0000403 *handle = archive;
404
Narayan Kamath7462f022013-11-21 13:05:04 +0000405 if (fd < 0) {
406 ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
407 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000408 }
Dmitriy Ivanov40b52b22014-07-15 19:33:00 -0700409
Narayan Kamath7462f022013-11-21 13:05:04 +0000410 return OpenArchiveInternal(archive, fileName);
411}
412
Tianjie Xu18c25922016-09-29 15:27:41 -0700413int32_t OpenArchiveFromMemory(void* address, size_t length, const char* debug_file_name,
414 ZipArchiveHandle *handle) {
415 ZipArchive* archive = new ZipArchive(address, length);
416 *handle = archive;
417 return OpenArchiveInternal(archive, debug_file_name);
418}
419
Narayan Kamath7462f022013-11-21 13:05:04 +0000420/*
421 * Close a ZipArchive, closing the file and freeing the contents.
422 */
423void CloseArchive(ZipArchiveHandle handle) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800424 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000425 ALOGV("Closing archive %p", archive);
Neil Fullerb1a113f2014-07-25 14:43:04 +0100426 delete archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000427}
428
Narayan Kamath162b7052017-06-05 13:21:12 +0100429static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, ZipEntry* entry) {
Narayan Kamath926973e2014-06-09 14:18:14 +0100430 uint8_t ddBuf[sizeof(DataDescriptor) + sizeof(DataDescriptor::kOptSignature)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700431 if (!mapped_zip.ReadData(ddBuf, sizeof(ddBuf))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000432 return kIoError;
433 }
434
Narayan Kamath926973e2014-06-09 14:18:14 +0100435 const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
436 const uint16_t offset = (ddSignature == DataDescriptor::kOptSignature) ? 4 : 0;
437 const DataDescriptor* descriptor = reinterpret_cast<const DataDescriptor*>(ddBuf + offset);
Narayan Kamath7462f022013-11-21 13:05:04 +0000438
Narayan Kamath162b7052017-06-05 13:21:12 +0100439 // Validate that the values in the data descriptor match those in the central
440 // directory.
441 if (entry->compressed_length != descriptor->compressed_size ||
442 entry->uncompressed_length != descriptor->uncompressed_size ||
443 entry->crc32 != descriptor->crc32) {
444 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32 ", %" PRIx32
445 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
446 entry->compressed_length, entry->uncompressed_length, entry->crc32,
447 descriptor->compressed_size, descriptor->uncompressed_size, descriptor->crc32);
448 return kInconsistentInformation;
449 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000450
451 return 0;
452}
453
Narayan Kamath7462f022013-11-21 13:05:04 +0000454static int32_t FindEntry(const ZipArchive* archive, const int ent,
455 ZipEntry* data) {
456 const uint16_t nameLen = archive->hash_table[ent].name_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000457
458 // Recover the start of the central directory entry from the filename
459 // pointer. The filename is the first entry past the fixed-size data,
460 // so we can just subtract back from that.
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100461 const uint8_t* ptr = archive->hash_table[ent].name;
Narayan Kamath926973e2014-06-09 14:18:14 +0100462 ptr -= sizeof(CentralDirectoryRecord);
Narayan Kamath7462f022013-11-21 13:05:04 +0000463
464 // This is the base of our mmapped region, we have to sanity check that
465 // the name that's in the hash table is a pointer to a location within
466 // this mapped region.
Tianjie Xu18c25922016-09-29 15:27:41 -0700467 const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
468 if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000469 ALOGW("Zip: Invalid entry pointer");
470 return kInvalidOffset;
471 }
472
Narayan Kamath926973e2014-06-09 14:18:14 +0100473 const CentralDirectoryRecord *cdr =
474 reinterpret_cast<const CentralDirectoryRecord*>(ptr);
475
Narayan Kamath7462f022013-11-21 13:05:04 +0000476 // The offset of the start of the central directory in the zipfile.
477 // We keep this lying around so that we can sanity check all our lengths
478 // and our per-file structures.
479 const off64_t cd_offset = archive->directory_offset;
480
481 // Fill out the compression method, modification time, crc32
482 // and other interesting attributes from the central directory. These
483 // will later be compared against values from the local file header.
Narayan Kamath926973e2014-06-09 14:18:14 +0100484 data->method = cdr->compression_method;
beonit0e99a2f2015-07-18 02:08:16 +0900485 data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
Narayan Kamath926973e2014-06-09 14:18:14 +0100486 data->crc32 = cdr->crc32;
487 data->compressed_length = cdr->compressed_size;
488 data->uncompressed_length = cdr->uncompressed_size;
Narayan Kamath7462f022013-11-21 13:05:04 +0000489
490 // Figure out the local header offset from the central directory. The
491 // actual file data will begin after the local header and the name /
492 // extra comments.
Narayan Kamath926973e2014-06-09 14:18:14 +0100493 const off64_t local_header_offset = cdr->local_file_header_offset;
494 if (local_header_offset + static_cast<off64_t>(sizeof(LocalFileHeader)) >= cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000495 ALOGW("Zip: bad local hdr offset in zip");
496 return kInvalidOffset;
497 }
498
Narayan Kamath926973e2014-06-09 14:18:14 +0100499 uint8_t lfh_buf[sizeof(LocalFileHeader)];
Tianjie Xu18c25922016-09-29 15:27:41 -0700500 if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800501 ALOGW("Zip: failed reading lfh name from offset %" PRId64,
502 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000503 return kIoError;
504 }
505
Narayan Kamath926973e2014-06-09 14:18:14 +0100506 const LocalFileHeader *lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
507
508 if (lfh->lfh_signature != LocalFileHeader::kSignature) {
Mark Salyzyn99ef9912014-03-14 14:26:22 -0700509 ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
Narayan Kamath926973e2014-06-09 14:18:14 +0100510 static_cast<int64_t>(local_header_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000511 return kInvalidOffset;
512 }
513
514 // Paranoia: Match the values specified in the local file header
515 // to those specified in the central directory.
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700516
Narayan Kamath162b7052017-06-05 13:21:12 +0100517 // Warn if central directory and local file header don't agree on the use
518 // of a trailing Data Descriptor. The reference implementation is inconsistent
519 // and appears to use the LFH value during extraction (unzip) but the CD value
520 // while displayng information about archives (zipinfo). The spec remains
521 // silent on this inconsistency as well.
522 //
523 // For now, always use the version from the LFH but make sure that the values
524 // specified in the central directory match those in the data descriptor.
525 //
526 // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
527 // bit 11 (EFS: The language encoding flag, marking that filename and comment are
528 // encoded using UTF-8). This implementation does not check for the presence of
529 // that flag and always enforces that entry names are valid UTF-8.
530 if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
531 ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700532 cdr->gpb_flags, lfh->gpb_flags);
Adam Lesinskid987c9d2017-04-06 18:55:47 -0700533 }
534
535 // If there is no trailing data descriptor, verify that the central directory and local file
536 // header agree on the crc, compressed, and uncompressed sizes of the entry.
Narayan Kamath926973e2014-06-09 14:18:14 +0100537 if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000538 data->has_data_descriptor = 0;
Narayan Kamath926973e2014-06-09 14:18:14 +0100539 if (data->compressed_length != lfh->compressed_size
540 || data->uncompressed_length != lfh->uncompressed_size
541 || data->crc32 != lfh->crc32) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700542 ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu32 ", %" PRIu32
543 ", %" PRIx32 "}, was {%" PRIu32 ", %" PRIu32 ", %" PRIx32 "}",
Narayan Kamath7462f022013-11-21 13:05:04 +0000544 data->compressed_length, data->uncompressed_length, data->crc32,
Narayan Kamath926973e2014-06-09 14:18:14 +0100545 lfh->compressed_size, lfh->uncompressed_size, lfh->crc32);
Narayan Kamath7462f022013-11-21 13:05:04 +0000546 return kInconsistentInformation;
547 }
548 } else {
549 data->has_data_descriptor = 1;
550 }
551
Elliott Hughes55fd2932017-05-28 22:59:04 -0700552 // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
553 if ((cdr->version_made_by >> 8) == 3) {
554 data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
555 } else {
556 data->unix_mode = 0777;
557 }
558
Narayan Kamath7462f022013-11-21 13:05:04 +0000559 // Check that the local file header name matches the declared
560 // name in the central directory.
Narayan Kamath926973e2014-06-09 14:18:14 +0100561 if (lfh->file_name_length == nameLen) {
562 const off64_t name_offset = local_header_offset + sizeof(LocalFileHeader);
Mykola Kondratenko50afc152014-09-08 12:46:37 +0200563 if (name_offset + lfh->file_name_length > cd_offset) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000564 ALOGW("Zip: Invalid declared length");
565 return kInvalidOffset;
566 }
567
Tianjie Xu18c25922016-09-29 15:27:41 -0700568 std::vector<uint8_t> name_buf(nameLen);
569 if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), nameLen, name_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800570 ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000571 return kIoError;
572 }
573
Tianjie Xu18c25922016-09-29 15:27:41 -0700574 if (memcmp(archive->hash_table[ent].name, name_buf.data(), nameLen)) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000575 return kInconsistentInformation;
576 }
577
Narayan Kamath7462f022013-11-21 13:05:04 +0000578 } else {
579 ALOGW("Zip: lfh name did not match central directory.");
580 return kInconsistentInformation;
581 }
582
Narayan Kamath926973e2014-06-09 14:18:14 +0100583 const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader)
584 + lfh->file_name_length + lfh->extra_field_length;
Narayan Kamath48953a12014-01-24 12:32:39 +0000585 if (data_offset > cd_offset) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800586 ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000587 return kInvalidOffset;
588 }
589
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800590 if (static_cast<off64_t>(data_offset + data->compressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700591 ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800592 static_cast<int64_t>(data_offset), data->compressed_length, static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000593 return kInvalidOffset;
594 }
595
596 if (data->method == kCompressStored &&
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800597 static_cast<off64_t>(data_offset + data->uncompressed_length) > cd_offset) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700598 ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu32 " > %" PRId64 ")",
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800599 static_cast<int64_t>(data_offset), data->uncompressed_length,
600 static_cast<int64_t>(cd_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +0000601 return kInvalidOffset;
602 }
603
604 data->offset = data_offset;
605 return 0;
606}
607
608struct IterationHandle {
609 uint32_t position;
Piotr Jastrzebski10aa9a02014-08-19 09:01:20 +0100610 // We're not using vector here because this code is used in the Windows SDK
611 // where the STL is not available.
Yusuke Sato07447542015-06-25 14:39:19 -0700612 ZipString prefix;
613 ZipString suffix;
Narayan Kamath7462f022013-11-21 13:05:04 +0000614 ZipArchive* archive;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100615
Yusuke Sato07447542015-06-25 14:39:19 -0700616 IterationHandle(const ZipString* in_prefix,
617 const ZipString* in_suffix) {
618 if (in_prefix) {
619 uint8_t* name_copy = new uint8_t[in_prefix->name_length];
620 memcpy(name_copy, in_prefix->name, in_prefix->name_length);
621 prefix.name = name_copy;
622 prefix.name_length = in_prefix->name_length;
623 } else {
624 prefix.name = NULL;
625 prefix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700626 }
Yusuke Sato07447542015-06-25 14:39:19 -0700627 if (in_suffix) {
628 uint8_t* name_copy = new uint8_t[in_suffix->name_length];
629 memcpy(name_copy, in_suffix->name, in_suffix->name_length);
630 suffix.name = name_copy;
631 suffix.name_length = in_suffix->name_length;
632 } else {
633 suffix.name = NULL;
634 suffix.name_length = 0;
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700635 }
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100636 }
637
638 ~IterationHandle() {
Yusuke Sato07447542015-06-25 14:39:19 -0700639 delete[] prefix.name;
640 delete[] suffix.name;
Piotr Jastrzebski8e085362014-08-18 11:37:45 +0100641 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000642};
643
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100644int32_t StartIteration(ZipArchiveHandle handle, void** cookie_ptr,
Yusuke Sato07447542015-06-25 14:39:19 -0700645 const ZipString* optional_prefix,
646 const ZipString* optional_suffix) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800647 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000648
649 if (archive == NULL || archive->hash_table == NULL) {
650 ALOGW("Zip: Invalid ZipArchiveHandle");
651 return kInvalidHandle;
652 }
653
Yusuke Satof1d3d3b2015-06-25 14:09:00 -0700654 IterationHandle* cookie = new IterationHandle(optional_prefix, optional_suffix);
Narayan Kamath7462f022013-11-21 13:05:04 +0000655 cookie->position = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000656 cookie->archive = archive;
Narayan Kamath7462f022013-11-21 13:05:04 +0000657
658 *cookie_ptr = cookie ;
659 return 0;
660}
661
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100662void EndIteration(void* cookie) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100663 delete reinterpret_cast<IterationHandle*>(cookie);
Piotr Jastrzebski79c8b342014-08-08 14:02:17 +0100664}
665
Yusuke Sato07447542015-06-25 14:39:19 -0700666int32_t FindEntry(const ZipArchiveHandle handle, const ZipString& entryName,
Narayan Kamath7462f022013-11-21 13:05:04 +0000667 ZipEntry* data) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800668 const ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100669 if (entryName.name_length == 0) {
670 ALOGW("Zip: Invalid filename %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000671 return kInvalidEntryName;
672 }
673
674 const int64_t ent = EntryToIndex(archive->hash_table,
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100675 archive->hash_table_size, entryName);
Narayan Kamath7462f022013-11-21 13:05:04 +0000676
677 if (ent < 0) {
Piotr Jastrzebskiecccc5a2014-08-11 16:35:11 +0100678 ALOGV("Zip: Could not find entry %.*s", entryName.name_length, entryName.name);
Narayan Kamath7462f022013-11-21 13:05:04 +0000679 return ent;
680 }
681
682 return FindEntry(archive, ent, data);
683}
684
Yusuke Sato07447542015-06-25 14:39:19 -0700685int32_t Next(void* cookie, ZipEntry* data, ZipString* name) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800686 IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
Narayan Kamath7462f022013-11-21 13:05:04 +0000687 if (handle == NULL) {
688 return kInvalidHandle;
689 }
690
691 ZipArchive* archive = handle->archive;
692 if (archive == NULL || archive->hash_table == NULL) {
693 ALOGW("Zip: Invalid ZipArchiveHandle");
694 return kInvalidHandle;
695 }
696
697 const uint32_t currentOffset = handle->position;
698 const uint32_t hash_table_length = archive->hash_table_size;
Yusuke Sato07447542015-06-25 14:39:19 -0700699 const ZipString* hash_table = archive->hash_table;
Narayan Kamath7462f022013-11-21 13:05:04 +0000700
701 for (uint32_t i = currentOffset; i < hash_table_length; ++i) {
702 if (hash_table[i].name != NULL &&
Yusuke Sato07447542015-06-25 14:39:19 -0700703 (handle->prefix.name_length == 0 ||
704 hash_table[i].StartsWith(handle->prefix)) &&
705 (handle->suffix.name_length == 0 ||
706 hash_table[i].EndsWith(handle->suffix))) {
Narayan Kamath7462f022013-11-21 13:05:04 +0000707 handle->position = (i + 1);
708 const int error = FindEntry(archive, i, data);
709 if (!error) {
710 name->name = hash_table[i].name;
711 name->name_length = hash_table[i].name_length;
712 }
713
714 return error;
715 }
716 }
717
718 handle->position = 0;
719 return kIterationEnd;
720}
721
Narayan Kamathf899bd52015-04-17 11:53:14 +0100722class Writer {
723 public:
724 virtual bool Append(uint8_t* buf, size_t buf_size) = 0;
725 virtual ~Writer() {}
726 protected:
727 Writer() = default;
728 private:
729 DISALLOW_COPY_AND_ASSIGN(Writer);
730};
731
732// A Writer that writes data to a fixed size memory region.
733// The size of the memory region must be equal to the total size of
734// the data appended to it.
735class MemoryWriter : public Writer {
736 public:
737 MemoryWriter(uint8_t* buf, size_t size) : Writer(),
738 buf_(buf), size_(size), bytes_written_(0) {
739 }
740
741 virtual bool Append(uint8_t* buf, size_t buf_size) override {
742 if (bytes_written_ + buf_size > size_) {
743 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)",
744 size_, bytes_written_ + buf_size);
745 return false;
746 }
747
748 memcpy(buf_ + bytes_written_, buf, buf_size);
749 bytes_written_ += buf_size;
750 return true;
751 }
752
753 private:
754 uint8_t* const buf_;
755 const size_t size_;
756 size_t bytes_written_;
757};
758
759// A Writer that appends data to a file |fd| at its current position.
760// The file will be truncated to the end of the written data.
761class FileWriter : public Writer {
762 public:
763
764 // Creates a FileWriter for |fd| and prepare to write |entry| to it,
765 // guaranteeing that the file descriptor is valid and that there's enough
766 // space on the volume to write out the entry completely and that the file
Tao Baoa456c212016-11-15 10:08:07 -0800767 // is truncated to the correct length (no truncation if |fd| references a
768 // block device).
Narayan Kamathf899bd52015-04-17 11:53:14 +0100769 //
770 // Returns a valid FileWriter on success, |nullptr| if an error occurred.
771 static std::unique_ptr<FileWriter> Create(int fd, const ZipEntry* entry) {
772 const uint32_t declared_length = entry->uncompressed_length;
773 const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
774 if (current_offset == -1) {
775 ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
776 return nullptr;
777 }
778
779 int result = 0;
780#if defined(__linux__)
781 if (declared_length > 0) {
782 // Make sure we have enough space on the volume to extract the compressed
783 // entry. Note that the call to ftruncate below will change the file size but
784 // will not allocate space on disk and this call to fallocate will not
785 // change the file size.
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700786 // Note: fallocate is only supported by the following filesystems -
787 // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
788 // EOPNOTSUPP error when issued in other filesystems.
789 // Hence, check for the return error code before concluding that the
790 // disk does not have enough space.
Narayan Kamathf899bd52015-04-17 11:53:14 +0100791 result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
Badhri Jagan Sridharana68d0d12015-06-02 14:47:57 -0700792 if (result == -1 && errno == ENOSPC) {
Narayan Kamathd5d7abe2016-08-10 12:24:05 +0100793 ALOGW("Zip: unable to allocate %" PRId64 " bytes at offset %" PRId64 " : %s",
794 static_cast<int64_t>(declared_length), static_cast<int64_t>(current_offset),
795 strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100796 return std::unique_ptr<FileWriter>(nullptr);
797 }
798 }
799#endif // __linux__
800
Tao Baoa456c212016-11-15 10:08:07 -0800801 struct stat sb;
802 if (fstat(fd, &sb) == -1) {
803 ALOGW("Zip: unable to fstat file: %s", strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100804 return std::unique_ptr<FileWriter>(nullptr);
805 }
806
Tao Baoa456c212016-11-15 10:08:07 -0800807 // Block device doesn't support ftruncate(2).
808 if (!S_ISBLK(sb.st_mode)) {
809 result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
810 if (result == -1) {
811 ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
812 static_cast<int64_t>(declared_length + current_offset), strerror(errno));
813 return std::unique_ptr<FileWriter>(nullptr);
814 }
815 }
816
Narayan Kamathf899bd52015-04-17 11:53:14 +0100817 return std::unique_ptr<FileWriter>(new FileWriter(fd, declared_length));
818 }
819
820 virtual bool Append(uint8_t* buf, size_t buf_size) override {
821 if (total_bytes_written_ + buf_size > declared_length_) {
822 ALOGW("Zip: Unexpected size " ZD " (declared) vs " ZD " (actual)",
823 declared_length_, total_bytes_written_ + buf_size);
824 return false;
825 }
826
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100827 const bool result = android::base::WriteFully(fd_, buf, buf_size);
828 if (result) {
829 total_bytes_written_ += buf_size;
830 } else {
831 ALOGW("Zip: unable to write " ZD " bytes to file; %s", buf_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100832 }
833
Narayan Kamathe97e66e2015-04-27 16:25:53 +0100834 return result;
Narayan Kamathf899bd52015-04-17 11:53:14 +0100835 }
836 private:
837 FileWriter(const int fd, const size_t declared_length) :
838 Writer(),
839 fd_(fd),
840 declared_length_(declared_length),
841 total_bytes_written_(0) {
842 }
843
844 const int fd_;
845 const size_t declared_length_;
846 size_t total_bytes_written_;
847};
848
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800849// This method is using libz macros with old-style-casts
850#pragma GCC diagnostic push
851#pragma GCC diagnostic ignored "-Wold-style-cast"
852static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
853 return inflateInit2(stream, window_bits);
854}
855#pragma GCC diagnostic pop
856
Tianjie Xu18c25922016-09-29 15:27:41 -0700857static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry,
Narayan Kamathf899bd52015-04-17 11:53:14 +0100858 Writer* writer, uint64_t* crc_out) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700859 const size_t kBufSize = 32768;
860 std::vector<uint8_t> read_buf(kBufSize);
861 std::vector<uint8_t> write_buf(kBufSize);
Narayan Kamath7462f022013-11-21 13:05:04 +0000862 z_stream zstream;
863 int zerr;
864
865 /*
866 * Initialize the zlib stream struct.
867 */
868 memset(&zstream, 0, sizeof(zstream));
869 zstream.zalloc = Z_NULL;
870 zstream.zfree = Z_NULL;
871 zstream.opaque = Z_NULL;
872 zstream.next_in = NULL;
873 zstream.avail_in = 0;
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700874 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000875 zstream.avail_out = kBufSize;
876 zstream.data_type = Z_UNKNOWN;
877
878 /*
879 * Use the undocumented "negative window bits" feature to tell zlib
880 * that there's no zlib header waiting for it.
881 */
Dmitriy Ivanovf94e1592015-03-06 13:27:59 -0800882 zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
Narayan Kamath7462f022013-11-21 13:05:04 +0000883 if (zerr != Z_OK) {
884 if (zerr == Z_VERSION_ERROR) {
885 ALOGE("Installed zlib is not compatible with linked version (%s)",
886 ZLIB_VERSION);
887 } else {
888 ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
889 }
890
891 return kZlibError;
892 }
893
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800894 auto zstream_deleter = [](z_stream* stream) {
895 inflateEnd(stream); /* free up any allocated structures */
896 };
897
898 std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
899
Narayan Kamath7462f022013-11-21 13:05:04 +0000900 const uint32_t uncompressed_length = entry->uncompressed_length;
901
Narayan Kamath162b7052017-06-05 13:21:12 +0100902 uint64_t crc = 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000903 uint32_t compressed_length = entry->compressed_length;
Narayan Kamath7462f022013-11-21 13:05:04 +0000904 do {
905 /* read as much as we can */
906 if (zstream.avail_in == 0) {
Yabin Cuib2a77002016-02-08 16:26:33 -0800907 const size_t getSize = (compressed_length > kBufSize) ? kBufSize : compressed_length;
Tianjie Xu18c25922016-09-29 15:27:41 -0700908 if (!mapped_zip.ReadData(read_buf.data(), getSize)) {
Yabin Cuib2a77002016-02-08 16:26:33 -0800909 ALOGW("Zip: inflate read failed, getSize = %zu: %s", getSize, strerror(errno));
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800910 return kIoError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000911 }
912
913 compressed_length -= getSize;
914
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700915 zstream.next_in = &read_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000916 zstream.avail_in = getSize;
917 }
918
919 /* uncompress the data */
920 zerr = inflate(&zstream, Z_NO_FLUSH);
921 if (zerr != Z_OK && zerr != Z_STREAM_END) {
922 ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)",
923 zerr, zstream.next_in, zstream.avail_in,
924 zstream.next_out, zstream.avail_out);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800925 return kZlibError;
Narayan Kamath7462f022013-11-21 13:05:04 +0000926 }
927
928 /* write when we're full or when we're done */
929 if (zstream.avail_out == 0 ||
930 (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700931 const size_t write_size = zstream.next_out - &write_buf[0];
Narayan Kamathf899bd52015-04-17 11:53:14 +0100932 if (!writer->Append(&write_buf[0], write_size)) {
933 // The file might have declared a bogus length.
934 return kInconsistentInformation;
Narayan Kamath162b7052017-06-05 13:21:12 +0100935 } else {
936 crc = crc32(crc, &write_buf[0], write_size);
Narayan Kamath7462f022013-11-21 13:05:04 +0000937 }
Narayan Kamath7462f022013-11-21 13:05:04 +0000938
Dmitriy Ivanovedbabfe2015-03-12 09:58:15 -0700939 zstream.next_out = &write_buf[0];
Narayan Kamath7462f022013-11-21 13:05:04 +0000940 zstream.avail_out = kBufSize;
941 }
942 } while (zerr == Z_OK);
943
944 assert(zerr == Z_STREAM_END); /* other errors should've been caught */
945
Narayan Kamath162b7052017-06-05 13:21:12 +0100946 // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
947 // "feature" of zlib to tell it there won't be a zlib file header. zlib
948 // doesn't bother calculating the checksum in that scenario. We just do
949 // it ourselves above because there are no additional gains to be made by
950 // having zlib calculate it for us, since they do it by calling crc32 in
951 // the same manner that we have above.
952 *crc_out = crc;
Narayan Kamath7462f022013-11-21 13:05:04 +0000953
954 if (zstream.total_out != uncompressed_length || compressed_length != 0) {
Mark Salyzyn088bf902014-05-08 16:02:20 -0700955 ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu32 ")",
Narayan Kamath7462f022013-11-21 13:05:04 +0000956 zstream.total_out, uncompressed_length);
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800957 return kInconsistentInformation;
Narayan Kamath7462f022013-11-21 13:05:04 +0000958 }
959
Dmitriy Ivanov1f741e52015-03-06 14:26:37 -0800960 return 0;
Narayan Kamath7462f022013-11-21 13:05:04 +0000961}
962
Tianjie Xu18c25922016-09-29 15:27:41 -0700963static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry* entry, Writer* writer,
Narayan Kamathf899bd52015-04-17 11:53:14 +0100964 uint64_t *crc_out) {
965 static const uint32_t kBufSize = 32768;
966 std::vector<uint8_t> buf(kBufSize);
967
968 const uint32_t length = entry->uncompressed_length;
969 uint32_t count = 0;
970 uint64_t crc = 0;
971 while (count < length) {
972 uint32_t remaining = length - count;
973
974 // Safe conversion because kBufSize is narrow enough for a 32 bit signed
975 // value.
Yabin Cuib2a77002016-02-08 16:26:33 -0800976 const size_t block_size = (remaining > kBufSize) ? kBufSize : remaining;
Tianjie Xu18c25922016-09-29 15:27:41 -0700977 if (!mapped_zip.ReadData(buf.data(), block_size)) {
Yabin Cuib2a77002016-02-08 16:26:33 -0800978 ALOGW("CopyFileToFile: copy read failed, block_size = %zu: %s", block_size, strerror(errno));
Narayan Kamathf899bd52015-04-17 11:53:14 +0100979 return kIoError;
980 }
981
982 if (!writer->Append(&buf[0], block_size)) {
983 return kIoError;
984 }
985 crc = crc32(crc, &buf[0], block_size);
986 count += block_size;
987 }
988
989 *crc_out = crc;
990
991 return 0;
992}
993
994int32_t ExtractToWriter(ZipArchiveHandle handle,
995 ZipEntry* entry, Writer* writer) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -0800996 ZipArchive* archive = reinterpret_cast<ZipArchive*>(handle);
Narayan Kamath7462f022013-11-21 13:05:04 +0000997 const uint16_t method = entry->method;
998 off64_t data_offset = entry->offset;
999
Tianjie Xu18c25922016-09-29 15:27:41 -07001000 if (!archive->mapped_zip.SeekToOffset(data_offset)) {
Dmitriy Ivanovf4cb8e22015-03-06 10:50:56 -08001001 ALOGW("Zip: lseek to data at %" PRId64 " failed", static_cast<int64_t>(data_offset));
Narayan Kamath7462f022013-11-21 13:05:04 +00001002 return kIoError;
1003 }
1004
1005 // this should default to kUnknownCompressionMethod.
1006 int32_t return_value = -1;
1007 uint64_t crc = 0;
1008 if (method == kCompressStored) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001009 return_value = CopyEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001010 } else if (method == kCompressDeflated) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001011 return_value = InflateEntryToWriter(archive->mapped_zip, entry, writer, &crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001012 }
1013
1014 if (!return_value && entry->has_data_descriptor) {
Narayan Kamath162b7052017-06-05 13:21:12 +01001015 return_value = ValidateDataDescriptor(archive->mapped_zip, entry);
Narayan Kamath7462f022013-11-21 13:05:04 +00001016 if (return_value) {
1017 return return_value;
1018 }
1019 }
1020
Narayan Kamath162b7052017-06-05 13:21:12 +01001021 // Validate that the CRC matches the calculated value.
1022 if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
Mark Salyzyn088bf902014-05-08 16:02:20 -07001023 ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
Narayan Kamath7462f022013-11-21 13:05:04 +00001024 return kInconsistentInformation;
1025 }
1026
1027 return return_value;
1028}
1029
Narayan Kamathf899bd52015-04-17 11:53:14 +01001030int32_t ExtractToMemory(ZipArchiveHandle handle, ZipEntry* entry,
1031 uint8_t* begin, uint32_t size) {
1032 std::unique_ptr<Writer> writer(new MemoryWriter(begin, size));
1033 return ExtractToWriter(handle, entry, writer.get());
1034}
1035
Narayan Kamath7462f022013-11-21 13:05:04 +00001036int32_t ExtractEntryToFile(ZipArchiveHandle handle,
1037 ZipEntry* entry, int fd) {
Narayan Kamathf899bd52015-04-17 11:53:14 +01001038 std::unique_ptr<Writer> writer(FileWriter::Create(fd, entry));
1039 if (writer.get() == nullptr) {
Narayan Kamath7462f022013-11-21 13:05:04 +00001040 return kIoError;
1041 }
1042
Narayan Kamathf899bd52015-04-17 11:53:14 +01001043 return ExtractToWriter(handle, entry, writer.get());
Narayan Kamath7462f022013-11-21 13:05:04 +00001044}
1045
1046const char* ErrorCodeString(int32_t error_code) {
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001047 // Make sure that the number of entries in kErrorMessages and ErrorCodes
1048 // match.
1049 static_assert((-kLastErrorCode + 1) == arraysize(kErrorMessages),
1050 "(-kLastErrorCode + 1) != arraysize(kErrorMessages)");
1051
1052 const uint32_t idx = -error_code;
1053 if (idx < arraysize(kErrorMessages)) {
1054 return kErrorMessages[idx];
Narayan Kamath7462f022013-11-21 13:05:04 +00001055 }
1056
Narayan Kamath1ef9d2d2017-06-15 13:58:25 +01001057 return "Unknown return code";
Narayan Kamath7462f022013-11-21 13:05:04 +00001058}
1059
1060int GetFileDescriptor(const ZipArchiveHandle handle) {
Tianjie Xu18c25922016-09-29 15:27:41 -07001061 return reinterpret_cast<ZipArchive*>(handle)->mapped_zip.GetFileDescriptor();
Narayan Kamath7462f022013-11-21 13:05:04 +00001062}
Colin Cross7c6c7f02016-09-16 10:15:51 -07001063
1064ZipString::ZipString(const char* entry_name)
1065 : name(reinterpret_cast<const uint8_t*>(entry_name)) {
1066 size_t len = strlen(entry_name);
1067 CHECK_LE(len, static_cast<size_t>(UINT16_MAX));
1068 name_length = static_cast<uint16_t>(len);
1069}
Tianjie Xu18c25922016-09-29 15:27:41 -07001070
1071#if !defined(_WIN32)
1072class ProcessWriter : public Writer {
1073 public:
1074 ProcessWriter(ProcessZipEntryFunction func, void* cookie) : Writer(),
1075 proc_function_(func),
1076 cookie_(cookie) {
1077 }
1078
1079 virtual bool Append(uint8_t* buf, size_t buf_size) override {
1080 return proc_function_(buf, buf_size, cookie_);
1081 }
1082
1083 private:
1084 ProcessZipEntryFunction proc_function_;
1085 void* cookie_;
1086};
1087
1088int32_t ProcessZipEntryContents(ZipArchiveHandle handle, ZipEntry* entry,
1089 ProcessZipEntryFunction func, void* cookie) {
1090 ProcessWriter writer(func, cookie);
1091 return ExtractToWriter(handle, entry, &writer);
1092}
1093
1094#endif //!defined(_WIN32)
1095
1096int MappedZipFile::GetFileDescriptor() const {
1097 if (!has_fd_) {
1098 ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1099 return -1;
1100 }
1101 return fd_;
1102}
1103
1104void* MappedZipFile::GetBasePtr() const {
1105 if (has_fd_) {
1106 ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1107 return nullptr;
1108 }
1109 return base_ptr_;
1110}
1111
1112off64_t MappedZipFile::GetFileLength() const {
1113 if (has_fd_) {
1114 off64_t result = lseek64(fd_, 0, SEEK_END);
1115 if (result == -1) {
1116 ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1117 }
1118 return result;
1119 } else {
1120 if (base_ptr_ == nullptr) {
1121 ALOGE("Zip: invalid file map\n");
1122 return -1;
1123 }
1124 return static_cast<off64_t>(data_length_);
1125 }
1126}
1127
1128bool MappedZipFile::SeekToOffset(off64_t offset) {
1129 if (has_fd_) {
1130 if (lseek64(fd_, offset, SEEK_SET) != offset) {
1131 ALOGE("Zip: lseek to %" PRId64 " failed: %s\n", offset, strerror(errno));
1132 return false;
1133 }
1134 return true;
1135 } else {
1136 if (offset < 0 || offset > static_cast<off64_t>(data_length_)) {
1137 ALOGE("Zip: invalid offset: %" PRId64 ", data length: %" PRId64 "\n" , offset,
1138 data_length_);
1139 return false;
1140 }
1141
1142 read_pos_ = offset;
1143 return true;
1144 }
1145}
1146
1147bool MappedZipFile::ReadData(uint8_t* buffer, size_t read_amount) {
1148 if (has_fd_) {
1149 if(!android::base::ReadFully(fd_, buffer, read_amount)) {
1150 ALOGE("Zip: read from %d failed\n", fd_);
1151 return false;
1152 }
1153 } else {
1154 memcpy(buffer, static_cast<uint8_t*>(base_ptr_) + read_pos_, read_amount);
1155 read_pos_ += read_amount;
1156 }
1157 return true;
1158}
1159
1160// Attempts to read |len| bytes into |buf| at offset |off|.
1161bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) {
1162#if !defined(_WIN32)
1163 if (has_fd_) {
1164 if (static_cast<size_t>(TEMP_FAILURE_RETRY(pread64(fd_, buf, len, off))) != len) {
1165 ALOGE("Zip: failed to read at offset %" PRId64 "\n", off);
1166 return false;
1167 }
1168 return true;
1169 }
1170#endif
1171 if (!SeekToOffset(off)) {
1172 return false;
1173 }
1174 return ReadData(buf, len);
1175
1176}
1177
1178void CentralDirectory::Initialize(void* map_base_ptr, off64_t cd_start_offset, size_t cd_size) {
1179 base_ptr_ = static_cast<uint8_t*>(map_base_ptr) + cd_start_offset;
1180 length_ = cd_size;
1181}
1182
1183bool ZipArchive::InitializeCentralDirectory(const char* debug_file_name, off64_t cd_start_offset,
1184 size_t cd_size) {
1185 if (mapped_zip.HasFd()) {
1186 if (!directory_map->create(debug_file_name, mapped_zip.GetFileDescriptor(),
1187 cd_start_offset, cd_size, true /* read only */)) {
1188 return false;
1189 }
1190
1191 CHECK_EQ(directory_map->getDataLength(), cd_size);
1192 central_directory.Initialize(directory_map->getDataPtr(), 0/*offset*/, cd_size);
1193 } else {
1194 if (mapped_zip.GetBasePtr() == nullptr) {
1195 ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer\n");
1196 return false;
1197 }
1198 if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1199 mapped_zip.GetFileLength()) {
1200 ALOGE("Zip: Failed to map central directory, offset exceeds mapped memory region ("
1201 "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1202 static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
1203 return false;
1204 }
1205
1206 central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1207 }
1208 return true;
1209}
Elliott Hughes55fd2932017-05-28 22:59:04 -07001210
1211tm ZipEntry::GetModificationTime() const {
1212 tm t = {};
1213
1214 t.tm_hour = (mod_time >> 11) & 0x1f;
1215 t.tm_min = (mod_time >> 5) & 0x3f;
1216 t.tm_sec = (mod_time & 0x1f) << 1;
1217
1218 t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1219 t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1220 t.tm_mday = (mod_time >> 16) & 0x1f;
1221
1222 return t;
1223}