1 /*
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  */
20 
21 #define LOG_TAG "ziparchive"
22 
23 #include "ziparchive/zip_archive.h"
24 
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <inttypes.h>
28 #include <limits.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <time.h>
32 #include <unistd.h>
33 
34 #include <memory>
35 #include <optional>
36 #include <span>
37 #include <vector>
38 
39 #if defined(__APPLE__)
40 #define lseek64 lseek
41 #endif
42 
43 #if defined(__BIONIC__)
44 #include <android/fdsan.h>
45 #endif
46 
47 #include <android-base/file.h>
48 #include <android-base/logging.h>
49 #include <android-base/macros.h>  // TEMP_FAILURE_RETRY may or may not be in unistd
50 #include <android-base/mapped_file.h>
51 #include <android-base/memory.h>
52 #include <android-base/strings.h>
53 #include <android-base/utf8.h>
54 #include <log/log.h>
55 
56 #include "entry_name_utils-inl.h"
57 #include "incfs_support/signal_handling.h"
58 #include "incfs_support/util.h"
59 #include "zip_archive_common.h"
60 #include "zip_archive_private.h"
61 #include "zlib.h"
62 
63 // Used to turn on crc checks - verify that the content CRC matches the values
64 // specified in the local file header and the central directory.
65 static constexpr bool kCrcChecksEnabled = false;
66 
67 // The maximum number of bytes to scan backwards for the EOCD start.
68 static const uint32_t kMaxEOCDSearch = kMaxCommentLen + sizeof(EocdRecord);
69 
70 // Set a reasonable cap (256 GiB) for the zip file size. So the data is always valid when
71 // we parse the fields in cd or local headers as 64 bits signed integers.
72 static constexpr uint64_t kMaxFileLength = 256 * static_cast<uint64_t>(1u << 30u);
73 
74 /*
75  * A Read-only Zip archive.
76  *
77  * We want "open" and "find entry by name" to be fast operations, and
78  * we want to use as little memory as possible.  We memory-map the zip
79  * central directory, and load a hash table with pointers to the filenames
80  * (which aren't null-terminated).  The other fields are at a fixed offset
81  * from the filename, so we don't need to extract those (but we do need
82  * to byte-read and endian-swap them every time we want them).
83  *
84  * It's possible that somebody has handed us a massive (~1GB) zip archive,
85  * so we can't expect to mmap the entire file.
86  *
87  * To speed comparisons when doing a lookup by name, we could make the mapping
88  * "private" (copy-on-write) and null-terminate the filenames after verifying
89  * the record structure.  However, this requires a private mapping of
90  * every page that the Central Directory touches.  Easier to tuck a copy
91  * of the string length into the hash table entry.
92  */
93 
94 #if defined(__BIONIC__)
GetOwnerTag(const ZipArchive * archive)95 uint64_t GetOwnerTag(const ZipArchive* archive) {
96   return android_fdsan_create_owner_tag(ANDROID_FDSAN_OWNER_TYPE_ZIPARCHIVE,
97                                         reinterpret_cast<uint64_t>(archive));
98 }
99 #endif
100 
ZipArchive(MappedZipFile && map,bool assume_ownership)101 ZipArchive::ZipArchive(MappedZipFile&& map, bool assume_ownership)
102     : mapped_zip(map),
103       close_file(assume_ownership),
104       directory_offset(0),
105       central_directory(),
106       directory_map(),
107       num_entries(0) {
108 #if defined(__BIONIC__)
109   if (assume_ownership) {
110     CHECK(mapped_zip.HasFd());
111     android_fdsan_exchange_owner_tag(mapped_zip.GetFileDescriptor(), 0, GetOwnerTag(this));
112   }
113 #endif
114 }
115 
ZipArchive(const void * address,size_t length)116 ZipArchive::ZipArchive(const void* address, size_t length)
117     : mapped_zip(address, length),
118       close_file(false),
119       directory_offset(0),
120       central_directory(),
121       directory_map(),
122       num_entries(0) {}
123 
~ZipArchive()124 ZipArchive::~ZipArchive() {
125   if (close_file && mapped_zip.GetFileDescriptor() >= 0) {
126 #if defined(__BIONIC__)
127     android_fdsan_close_with_tag(mapped_zip.GetFileDescriptor(), GetOwnerTag(this));
128 #else
129     close(mapped_zip.GetFileDescriptor());
130 #endif
131   }
132 }
133 
134 struct CentralDirectoryInfo {
135   uint64_t num_records;
136   // The size of the central directory (in bytes).
137   uint64_t cd_size;
138   // The offset of the start of the central directory, relative
139   // to the start of the file.
140   uint64_t cd_start_offset;
141 };
142 
143 // Reads |T| at |readPtr| and increments |readPtr|. Returns std::nullopt if the boundary check
144 // fails.
145 template <typename T>
TryConsumeUnaligned(uint8_t ** readPtr,const uint8_t * bufStart,size_t bufSize)146 static std::optional<T> TryConsumeUnaligned(uint8_t** readPtr, const uint8_t* bufStart,
147                                             size_t bufSize) {
148   if (bufSize < sizeof(T) || *readPtr - bufStart > bufSize - sizeof(T)) {
149     ALOGW("Zip: %zu byte read exceeds the boundary of allocated buf, offset %zu, bufSize %zu",
150           sizeof(T), *readPtr - bufStart, bufSize);
151     return std::nullopt;
152   }
153   return ConsumeUnaligned<T>(readPtr);
154 }
155 
FindCentralDirectoryInfoForZip64(const char * debugFileName,ZipArchive * archive,off64_t eocdOffset,CentralDirectoryInfo * cdInfo)156 static ZipError FindCentralDirectoryInfoForZip64(const char* debugFileName, ZipArchive* archive,
157                                                  off64_t eocdOffset, CentralDirectoryInfo* cdInfo) {
158   if (eocdOffset <= sizeof(Zip64EocdLocator)) {
159     ALOGW("Zip: %s: Not enough space for zip64 eocd locator", debugFileName);
160     return kInvalidFile;
161   }
162   // We expect to find the zip64 eocd locator immediately before the zip eocd.
163   const int64_t locatorOffset = eocdOffset - sizeof(Zip64EocdLocator);
164   Zip64EocdLocator zip64EocdLocator{};
165   if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>((&zip64EocdLocator)),
166                                         sizeof(Zip64EocdLocator), locatorOffset)) {
167     ALOGW("Zip: %s: Read %zu from offset %" PRId64 " failed %s", debugFileName,
168           sizeof(Zip64EocdLocator), locatorOffset, debugFileName);
169     return kIoError;
170   }
171 
172   if (zip64EocdLocator.locator_signature != Zip64EocdLocator::kSignature) {
173     ALOGW("Zip: %s: Zip64 eocd locator signature not found at offset %" PRId64, debugFileName,
174           locatorOffset);
175     return kInvalidFile;
176   }
177 
178   const int64_t zip64EocdOffset = zip64EocdLocator.zip64_eocd_offset;
179   if (locatorOffset <= sizeof(Zip64EocdRecord) ||
180       zip64EocdOffset > locatorOffset - sizeof(Zip64EocdRecord)) {
181     ALOGW("Zip: %s: Bad zip64 eocd offset %" PRId64 ", eocd locator offset %" PRId64, debugFileName,
182           zip64EocdOffset, locatorOffset);
183     return kInvalidOffset;
184   }
185 
186   Zip64EocdRecord zip64EocdRecord{};
187   if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&zip64EocdRecord),
188                                         sizeof(Zip64EocdRecord), zip64EocdOffset)) {
189     ALOGW("Zip: %s: read %zu from offset %" PRId64 " failed %s", debugFileName,
190           sizeof(Zip64EocdLocator), zip64EocdOffset, debugFileName);
191     return kIoError;
192   }
193 
194   if (zip64EocdRecord.record_signature != Zip64EocdRecord::kSignature) {
195     ALOGW("Zip: %s: Zip64 eocd record signature not found at offset %" PRId64, debugFileName,
196           zip64EocdOffset);
197     return kInvalidFile;
198   }
199 
200   if (zip64EocdOffset <= zip64EocdRecord.cd_size ||
201       zip64EocdRecord.cd_start_offset > zip64EocdOffset - zip64EocdRecord.cd_size) {
202     ALOGW("Zip: %s: Bad offset for zip64 central directory. cd offset %" PRIu64 ", cd size %" PRIu64
203           ", zip64 eocd offset %" PRIu64,
204           debugFileName, zip64EocdRecord.cd_start_offset, zip64EocdRecord.cd_size, zip64EocdOffset);
205     return kInvalidOffset;
206   }
207 
208   *cdInfo = {.num_records = zip64EocdRecord.num_records,
209              .cd_size = zip64EocdRecord.cd_size,
210              .cd_start_offset = zip64EocdRecord.cd_start_offset};
211 
212   return kSuccess;
213 }
214 
FindCentralDirectoryInfo(const char * debug_file_name,ZipArchive * archive,off64_t file_length,std::span<uint8_t> scan_buffer,CentralDirectoryInfo * cdInfo)215 static ZipError FindCentralDirectoryInfo(const char* debug_file_name,
216                                          ZipArchive* archive,
217                                          off64_t file_length,
218                                          std::span<uint8_t> scan_buffer,
219                                          CentralDirectoryInfo* cdInfo) {
220   const auto read_amount = static_cast<uint32_t>(scan_buffer.size());
221   const off64_t search_start = file_length - read_amount;
222 
223   if (!archive->mapped_zip.ReadAtOffset(scan_buffer.data(), read_amount, search_start)) {
224     ALOGE("Zip: read %" PRId64 " from offset %" PRId64 " failed", static_cast<int64_t>(read_amount),
225           static_cast<int64_t>(search_start));
226     return kIoError;
227   }
228 
229   /*
230    * Scan backward for the EOCD magic.  In an archive without a trailing
231    * comment, we'll find it on the first try.  (We may want to consider
232    * doing an initial minimal read; if we don't find it, retry with a
233    * second read as above.)
234    */
235   CHECK_LE(read_amount, std::numeric_limits<int32_t>::max());
236   int32_t i = read_amount - sizeof(EocdRecord);
237   for (; i >= 0; i--) {
238     if (scan_buffer[i] == 0x50) {
239       uint32_t* sig_addr = reinterpret_cast<uint32_t*>(&scan_buffer[i]);
240       if (android::base::get_unaligned<uint32_t>(sig_addr) == EocdRecord::kSignature) {
241         ALOGV("+++ Found EOCD at buf+%d", i);
242         break;
243       }
244     }
245   }
246   if (i < 0) {
247     ALOGD("Zip: EOCD not found, %s is not zip", debug_file_name);
248     return kInvalidFile;
249   }
250 
251   const off64_t eocd_offset = search_start + i;
252   auto eocd = reinterpret_cast<const EocdRecord*>(scan_buffer.data() + i);
253   /*
254    * Verify that there's no trailing space at the end of the central directory
255    * and its comment.
256    */
257   const off64_t calculated_length = eocd_offset + sizeof(EocdRecord) + eocd->comment_length;
258   if (calculated_length != file_length) {
259     ALOGW("Zip: %" PRId64 " extraneous bytes at the end of the central directory",
260           static_cast<int64_t>(file_length - calculated_length));
261     return kInvalidFile;
262   }
263 
264   // One of the field is 0xFFFFFFFF, look for the zip64 EOCD instead.
265   if (eocd->cd_size == UINT32_MAX || eocd->cd_start_offset == UINT32_MAX) {
266     ALOGV("Looking for the zip64 EOCD, cd_size: %" PRIu32 "cd_start_offset: %" PRId32,
267           eocd->cd_size, eocd->cd_start_offset);
268     return FindCentralDirectoryInfoForZip64(debug_file_name, archive, eocd_offset, cdInfo);
269   }
270 
271   /*
272    * Grab the CD offset and size, and the number of entries in the
273    * archive and verify that they look reasonable.
274    */
275   if (static_cast<off64_t>(eocd->cd_start_offset) + eocd->cd_size > eocd_offset) {
276     ALOGW("Zip: bad offsets (dir %" PRIu32 ", size %" PRIu32 ", eocd %" PRId64 ")",
277           eocd->cd_start_offset, eocd->cd_size, static_cast<int64_t>(eocd_offset));
278     return kInvalidOffset;
279   }
280 
281   *cdInfo = {.num_records = eocd->num_records,
282              .cd_size = eocd->cd_size,
283              .cd_start_offset = eocd->cd_start_offset};
284   return kSuccess;
285 }
286 
287 /*
288  * Find the zip Central Directory and memory-map it.
289  *
290  * On success, returns kSuccess after populating fields from the EOCD area:
291  *   directory_offset
292  *   directory_ptr
293  *   num_entries
294  */
MapCentralDirectory(const char * debug_file_name,ZipArchive * archive)295 static ZipError MapCentralDirectory(const char* debug_file_name, ZipArchive* archive) {
296   // Test file length. We use lseek64 to make sure the file is small enough to be a zip file.
297   off64_t file_length = archive->mapped_zip.GetFileLength();
298   if (file_length == -1) {
299     return kInvalidFile;
300   }
301 
302   if (file_length > kMaxFileLength) {
303     ALOGV("Zip: zip file too long %" PRId64, static_cast<int64_t>(file_length));
304     return kInvalidFile;
305   }
306 
307   if (file_length < static_cast<off64_t>(sizeof(EocdRecord))) {
308     ALOGV("Zip: length %" PRId64 " is too small to be zip", static_cast<int64_t>(file_length));
309     return kInvalidFile;
310   }
311 
312   /*
313    * Perform the traditional EOCD snipe hunt.
314    *
315    * We're searching for the End of Central Directory magic number,
316    * which appears at the start of the EOCD block.  It's followed by
317    * 18 bytes of EOCD stuff and up to 64KB of archive comment.  We
318    * need to read the last part of the file into a buffer, dig through
319    * it to find the magic number, parse some values out, and use those
320    * to determine the extent of the CD.
321    *
322    * We start by pulling in the last part of the file.
323    */
324   uint32_t read_amount = kMaxEOCDSearch;
325   if (file_length < read_amount) {
326     read_amount = static_cast<uint32_t>(file_length);
327   }
328 
329   CentralDirectoryInfo cdInfo = {};
330   std::vector<uint8_t> scan_buffer(read_amount);
331 
332   SCOPED_SIGBUS_HANDLER({
333     incfs::util::clearAndFree(scan_buffer);
334     return kIoError;
335   });
336 
337   if (auto result = FindCentralDirectoryInfo(debug_file_name, archive,
338                                              file_length, scan_buffer, &cdInfo);
339       result != kSuccess) {
340     return result;
341   }
342 
343   scan_buffer.clear();
344 
345   if (cdInfo.num_records == 0) {
346 #if defined(__ANDROID__)
347     ALOGW("Zip: empty archive?");
348 #endif
349     return kEmptyArchive;
350   }
351 
352   if (cdInfo.cd_size >= SIZE_MAX) {
353     ALOGW("Zip: The size of central directory doesn't fit in range of size_t: %" PRIu64,
354           cdInfo.cd_size);
355     return kInvalidFile;
356   }
357 
358   ALOGV("+++ num_entries=%" PRIu64 " dir_size=%" PRIu64 " dir_offset=%" PRIu64, cdInfo.num_records,
359         cdInfo.cd_size, cdInfo.cd_start_offset);
360 
361   // It all looks good.  Create a mapping for the CD, and set the fields in archive.
362   if (!archive->InitializeCentralDirectory(static_cast<off64_t>(cdInfo.cd_start_offset),
363                                            static_cast<size_t>(cdInfo.cd_size))) {
364     return kMmapFailed;
365   }
366 
367   archive->num_entries = cdInfo.num_records;
368   archive->directory_offset = cdInfo.cd_start_offset;
369 
370   return kSuccess;
371 }
372 
ParseZip64ExtendedInfoInExtraField(const uint8_t * extraFieldStart,uint16_t extraFieldLength,uint32_t zip32UncompressedSize,uint32_t zip32CompressedSize,std::optional<uint32_t> zip32LocalFileHeaderOffset,Zip64ExtendedInfo * zip64Info)373 static ZipError ParseZip64ExtendedInfoInExtraField(
374     const uint8_t* extraFieldStart, uint16_t extraFieldLength, uint32_t zip32UncompressedSize,
375     uint32_t zip32CompressedSize, std::optional<uint32_t> zip32LocalFileHeaderOffset,
376     Zip64ExtendedInfo* zip64Info) {
377   if (extraFieldLength <= 4) {
378     ALOGW("Zip: Extra field isn't large enough to hold zip64 info, size %" PRIu16,
379           extraFieldLength);
380     return kInvalidFile;
381   }
382 
383   // Each header MUST consist of:
384   // Header ID - 2 bytes
385   // Data Size - 2 bytes
386   uint16_t offset = 0;
387   while (offset < extraFieldLength - 4) {
388     auto readPtr = const_cast<uint8_t*>(extraFieldStart + offset);
389     auto headerId = ConsumeUnaligned<uint16_t>(&readPtr);
390     auto dataSize = ConsumeUnaligned<uint16_t>(&readPtr);
391 
392     offset += 4;
393     if (dataSize > extraFieldLength - offset) {
394       ALOGW("Zip: Data size exceeds the boundary of extra field, data size %" PRIu16, dataSize);
395       return kInvalidOffset;
396     }
397 
398     // Skip the other types of extensible data fields. Details in
399     // https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT section 4.5
400     if (headerId != Zip64ExtendedInfo::kHeaderId) {
401       offset += dataSize;
402       continue;
403     }
404     // Layout for Zip64 extended info (not include first 4 bytes of header)
405     // Original
406     // Size       8 bytes    Original uncompressed file size
407 
408     // Compressed
409     // Size       8 bytes    Size of compressed data
410 
411     // Relative Header
412     // Offset     8 bytes    Offset of local header record
413 
414     // Disk Start
415     // Number     4 bytes    Number of the disk on which
416     //                       this file starts
417     if (dataSize == 8 * 3 + 4) {
418       ALOGW(
419           "Zip: Found `Disk Start Number` field in extra block. Ignoring it.");
420       dataSize -= 4;
421     }
422     // Sometimes, only a subset of {uncompressed size, compressed size, relative
423     // header offset} is presents. but golang's zip writer will write out all
424     // 3 even if only 1 is necessary. We should parse all 3 fields if they are
425     // there.
426     const bool completeField = dataSize == 8 * 3;
427 
428     std::optional<uint64_t> uncompressedFileSize;
429     std::optional<uint64_t> compressedFileSize;
430     std::optional<uint64_t> localHeaderOffset;
431     if (zip32UncompressedSize == UINT32_MAX || completeField) {
432       uncompressedFileSize = TryConsumeUnaligned<uint64_t>(
433           &readPtr, extraFieldStart, extraFieldLength);
434       if (!uncompressedFileSize.has_value()) return kInvalidOffset;
435     }
436     if (zip32CompressedSize == UINT32_MAX || completeField) {
437       compressedFileSize = TryConsumeUnaligned<uint64_t>(
438           &readPtr, extraFieldStart, extraFieldLength);
439       if (!compressedFileSize.has_value()) return kInvalidOffset;
440     }
441     if (zip32LocalFileHeaderOffset == UINT32_MAX || completeField) {
442       localHeaderOffset = TryConsumeUnaligned<uint64_t>(
443           &readPtr, extraFieldStart, extraFieldLength);
444       if (!localHeaderOffset.has_value()) return kInvalidOffset;
445     }
446 
447     // calculate how many bytes we read after the data size field.
448     size_t bytesRead = readPtr - (extraFieldStart + offset);
449     if (bytesRead == 0) {
450       ALOGW("Zip: Data size should not be 0 in zip64 extended field");
451       return kInvalidFile;
452     }
453 
454     if (dataSize != bytesRead) {
455       auto localOffsetString = zip32LocalFileHeaderOffset.has_value()
456                                    ? std::to_string(zip32LocalFileHeaderOffset.value())
457                                    : "missing";
458       ALOGW("Zip: Invalid data size in zip64 extended field, expect %zu , get %" PRIu16
459             ", uncompressed size %" PRIu32 ", compressed size %" PRIu32 ", local header offset %s",
460             bytesRead, dataSize, zip32UncompressedSize, zip32CompressedSize,
461             localOffsetString.c_str());
462       return kInvalidFile;
463     }
464 
465     zip64Info->uncompressed_file_size = uncompressedFileSize;
466     zip64Info->compressed_file_size = compressedFileSize;
467     zip64Info->local_header_offset = localHeaderOffset;
468     return kSuccess;
469   }
470 
471   ALOGW("Zip: zip64 extended info isn't found in the extra field.");
472   return kInvalidFile;
473 }
474 
475 /*
476  * Parses the Zip archive's Central Directory.  Allocates and populates the
477  * hash table.
478  *
479  * Returns 0 on success.
480  */
ParseZipArchive(ZipArchive * archive)481 static ZipError ParseZipArchive(ZipArchive* archive) {
482   SCOPED_SIGBUS_HANDLER(return kIoError);
483 
484   const uint8_t* const cd_ptr = archive->central_directory.GetBasePtr();
485   const size_t cd_length = archive->central_directory.GetMapLength();
486   const uint64_t num_entries = archive->num_entries;
487 
488   if (num_entries <= UINT16_MAX) {
489     archive->cd_entry_map = CdEntryMapZip32::Create(static_cast<uint16_t>(num_entries));
490   } else {
491     archive->cd_entry_map = CdEntryMapZip64::Create();
492   }
493   if (archive->cd_entry_map == nullptr) {
494     return kAllocationFailed;
495   }
496 
497   /*
498    * Walk through the central directory, adding entries to the hash
499    * table and verifying values.
500    */
501   const uint8_t* const cd_end = cd_ptr + cd_length;
502   const uint8_t* ptr = cd_ptr;
503   for (uint64_t i = 0; i < num_entries; i++) {
504     if (ptr > cd_end - sizeof(CentralDirectoryRecord)) {
505       ALOGW("Zip: ran off the end (item #%" PRIu64 ", %zu bytes of central directory)", i,
506             cd_length);
507 #if defined(__ANDROID__)
508       android_errorWriteLog(0x534e4554, "36392138");
509 #endif
510       return kInvalidFile;
511     }
512 
513     auto cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
514     if (cdr->record_signature != CentralDirectoryRecord::kSignature) {
515       ALOGW("Zip: missed a central dir sig (at %" PRIu64 ")", i);
516       return kInvalidFile;
517     }
518 
519     const uint16_t file_name_length = cdr->file_name_length;
520     const uint16_t extra_length = cdr->extra_field_length;
521     const uint16_t comment_length = cdr->comment_length;
522     const uint8_t* file_name = ptr + sizeof(CentralDirectoryRecord);
523 
524     if (file_name_length >= cd_length || file_name > cd_end - file_name_length) {
525       ALOGW("Zip: file name for entry %" PRIu64
526             " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
527             i, file_name_length, cd_length);
528       return kInvalidEntryName;
529     }
530 
531     const uint8_t* extra_field = file_name + file_name_length;
532     if (extra_length >= cd_length || extra_field > cd_end - extra_length) {
533       ALOGW("Zip: extra field for entry %" PRIu64
534             " exceeds the central directory range, file_name_length: %" PRIu16 ", cd_length: %zu",
535             i, extra_length, cd_length);
536       return kInvalidFile;
537     }
538 
539     off64_t local_header_offset = cdr->local_file_header_offset;
540     if (local_header_offset == UINT32_MAX) {
541       Zip64ExtendedInfo zip64_info{};
542       if (auto status = ParseZip64ExtendedInfoInExtraField(
543               extra_field, extra_length, cdr->uncompressed_size, cdr->compressed_size,
544               cdr->local_file_header_offset, &zip64_info);
545           status != kSuccess) {
546         return status;
547       }
548       CHECK(zip64_info.local_header_offset.has_value());
549       local_header_offset = zip64_info.local_header_offset.value();
550     }
551 
552     if (local_header_offset >= archive->directory_offset) {
553       ALOGW("Zip: bad LFH offset %" PRId64 " at entry %" PRIu64,
554             static_cast<int64_t>(local_header_offset), i);
555       return kInvalidFile;
556     }
557 
558     // Check that file name is valid UTF-8 and doesn't contain NUL (U+0000) characters.
559     if (!IsValidEntryName(file_name, file_name_length)) {
560       ALOGW("Zip: invalid file name at entry %" PRIu64, i);
561       return kInvalidEntryName;
562     }
563 
564     // Add the CDE filename to the hash table.
565     std::string_view entry_name{reinterpret_cast<const char*>(file_name), file_name_length};
566     if (auto add_result =
567             archive->cd_entry_map->AddToMap(entry_name, archive->central_directory.GetBasePtr());
568         add_result != 0) {
569       ALOGW("Zip: Error adding entry to hash table %d", add_result);
570       return add_result;
571     }
572 
573     ptr += sizeof(CentralDirectoryRecord) + file_name_length + extra_length + comment_length;
574     if ((ptr - cd_ptr) > static_cast<int64_t>(cd_length)) {
575       ALOGW("Zip: bad CD advance (%tu vs %zu) at entry %" PRIu64, ptr - cd_ptr, cd_length, i);
576       return kInvalidFile;
577     }
578   }
579 
580   uint32_t lfh_start_bytes;
581   if (!archive->mapped_zip.ReadAtOffset(reinterpret_cast<uint8_t*>(&lfh_start_bytes),
582                                         sizeof(uint32_t), 0)) {
583     ALOGW("Zip: Unable to read header for entry at offset == 0.");
584     return kInvalidFile;
585   }
586 
587   if (lfh_start_bytes != LocalFileHeader::kSignature) {
588     ALOGW("Zip: Entry at offset zero has invalid LFH signature %" PRIx32, lfh_start_bytes);
589 #if defined(__ANDROID__)
590     android_errorWriteLog(0x534e4554, "64211847");
591 #endif
592     return kInvalidFile;
593   }
594 
595   ALOGV("+++ zip good scan %" PRIu64 " entries", num_entries);
596 
597   return kSuccess;
598 }
599 
OpenArchiveInternal(ZipArchive * archive,const char * debug_file_name)600 static int32_t OpenArchiveInternal(ZipArchive* archive, const char* debug_file_name) {
601   int32_t result = MapCentralDirectory(debug_file_name, archive);
602   return result != kSuccess ? result : ParseZipArchive(archive);
603 }
604 
OpenArchiveFd(int fd,const char * debug_file_name,ZipArchiveHandle * handle,bool assume_ownership)605 int32_t OpenArchiveFd(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
606                       bool assume_ownership) {
607   ZipArchive* archive = new ZipArchive(MappedZipFile(fd), assume_ownership);
608   *handle = archive;
609   return OpenArchiveInternal(archive, debug_file_name);
610 }
611 
OpenArchiveFdRange(int fd,const char * debug_file_name,ZipArchiveHandle * handle,off64_t length,off64_t offset,bool assume_ownership)612 int32_t OpenArchiveFdRange(int fd, const char* debug_file_name, ZipArchiveHandle* handle,
613                            off64_t length, off64_t offset, bool assume_ownership) {
614   ZipArchive* archive = new ZipArchive(MappedZipFile(fd, length, offset), assume_ownership);
615   *handle = archive;
616 
617   if (length < 0) {
618     ALOGW("Invalid zip length %" PRId64, length);
619     return kIoError;
620   }
621 
622   if (offset < 0) {
623     ALOGW("Invalid zip offset %" PRId64, offset);
624     return kIoError;
625   }
626 
627   return OpenArchiveInternal(archive, debug_file_name);
628 }
629 
OpenArchive(const char * fileName,ZipArchiveHandle * handle)630 int32_t OpenArchive(const char* fileName, ZipArchiveHandle* handle) {
631   const int fd = ::android::base::utf8::open(fileName, O_RDONLY | O_BINARY | O_CLOEXEC, 0);
632   ZipArchive* archive = new ZipArchive(MappedZipFile(fd), true);
633   *handle = archive;
634 
635   if (fd < 0) {
636     ALOGW("Unable to open '%s': %s", fileName, strerror(errno));
637     return kIoError;
638   }
639 
640   return OpenArchiveInternal(archive, fileName);
641 }
642 
OpenArchiveFromMemory(const void * address,size_t length,const char * debug_file_name,ZipArchiveHandle * handle)643 int32_t OpenArchiveFromMemory(const void* address, size_t length, const char* debug_file_name,
644                               ZipArchiveHandle* handle) {
645   ZipArchive* archive = new ZipArchive(address, length);
646   *handle = archive;
647   return OpenArchiveInternal(archive, debug_file_name);
648 }
649 
GetArchiveInfo(ZipArchiveHandle archive)650 ZipArchiveInfo GetArchiveInfo(ZipArchiveHandle archive) {
651   ZipArchiveInfo result;
652   result.archive_size = archive->mapped_zip.GetFileLength();
653   result.entry_count = archive->num_entries;
654   return result;
655 }
656 
657 /*
658  * Close a ZipArchive, closing the file and freeing the contents.
659  */
CloseArchive(ZipArchiveHandle archive)660 void CloseArchive(ZipArchiveHandle archive) {
661   ALOGV("Closing archive %p", archive);
662   delete archive;
663 }
664 
ValidateDataDescriptor(MappedZipFile & mapped_zip,const ZipEntry64 * entry)665 static int32_t ValidateDataDescriptor(MappedZipFile& mapped_zip, const ZipEntry64* entry) {
666   SCOPED_SIGBUS_HANDLER(return kIoError);
667 
668   // Maximum possible size for data descriptor: 2 * 4 + 2 * 8 = 24 bytes
669   // The zip format doesn't specify the size of data descriptor. But we won't read OOB here even
670   // if the descriptor isn't present. Because the size cd + eocd in the end of the zipfile is
671   // larger than 24 bytes. And if the descriptor contains invalid data, we'll abort due to
672   // kInconsistentInformation.
673   uint8_t ddBuf[24];
674   off64_t offset = entry->offset;
675   if (entry->method != kCompressStored) {
676     offset += entry->compressed_length;
677   } else {
678     offset += entry->uncompressed_length;
679   }
680 
681   if (!mapped_zip.ReadAtOffset(ddBuf, sizeof(ddBuf), offset)) {
682     return kIoError;
683   }
684 
685   const uint32_t ddSignature = *(reinterpret_cast<const uint32_t*>(ddBuf));
686   uint8_t* ddReadPtr = (ddSignature == DataDescriptor::kOptSignature) ? ddBuf + 4 : ddBuf;
687   DataDescriptor descriptor{};
688   descriptor.crc32 = ConsumeUnaligned<uint32_t>(&ddReadPtr);
689   // Don't use entry->zip64_format_size, because that is set to true even if
690   // both compressed/uncompressed size are < 0xFFFFFFFF.
691   constexpr auto u32max = std::numeric_limits<uint32_t>::max();
692   if (entry->compressed_length >= u32max ||
693       entry->uncompressed_length >= u32max) {
694     descriptor.compressed_size = ConsumeUnaligned<uint64_t>(&ddReadPtr);
695     descriptor.uncompressed_size = ConsumeUnaligned<uint64_t>(&ddReadPtr);
696   } else {
697     descriptor.compressed_size = ConsumeUnaligned<uint32_t>(&ddReadPtr);
698     descriptor.uncompressed_size = ConsumeUnaligned<uint32_t>(&ddReadPtr);
699   }
700 
701   // Validate that the values in the data descriptor match those in the central
702   // directory.
703   if (entry->compressed_length != descriptor.compressed_size ||
704       entry->uncompressed_length != descriptor.uncompressed_size ||
705       entry->crc32 != descriptor.crc32) {
706     ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu64 ", %" PRIu64 ", %" PRIx32
707           "}, was {%" PRIu64 ", %" PRIu64 ", %" PRIx32 "}",
708           entry->compressed_length, entry->uncompressed_length, entry->crc32,
709           descriptor.compressed_size, descriptor.uncompressed_size, descriptor.crc32);
710     return kInconsistentInformation;
711   }
712 
713   return 0;
714 }
715 
FindEntry(const ZipArchive * archive,std::string_view entryName,const uint64_t nameOffset,ZipEntry64 * data)716 static int32_t FindEntry(const ZipArchive* archive, std::string_view entryName,
717                          const uint64_t nameOffset, ZipEntry64* data) {
718   std::vector<uint8_t> name_buf;
719   std::vector<uint8_t> local_extra_field;
720   SCOPED_SIGBUS_HANDLER({
721     incfs::util::clearAndFree(name_buf);
722     incfs::util::clearAndFree(local_extra_field);
723     return kIoError;
724   });
725 
726   // Recover the start of the central directory entry from the filename
727   // pointer.  The filename is the first entry past the fixed-size data,
728   // so we can just subtract back from that.
729   const uint8_t* base_ptr = archive->central_directory.GetBasePtr();
730   const uint8_t* ptr = base_ptr + nameOffset;
731   ptr -= sizeof(CentralDirectoryRecord);
732 
733   // This is the base of our mmapped region, we have to check that
734   // the name that's in the hash table is a pointer to a location within
735   // this mapped region.
736   if (ptr < base_ptr || ptr > base_ptr + archive->central_directory.GetMapLength()) {
737     ALOGW("Zip: Invalid entry pointer");
738     return kInvalidOffset;
739   }
740 
741   auto cdr = reinterpret_cast<const CentralDirectoryRecord*>(ptr);
742 
743   // The offset of the start of the central directory in the zipfile.
744   // We keep this lying around so that we can check all our lengths
745   // and our per-file structures.
746   const off64_t cd_offset = archive->directory_offset;
747 
748   // Fill out the compression method, modification time, crc32
749   // and other interesting attributes from the central directory. These
750   // will later be compared against values from the local file header.
751   data->method = cdr->compression_method;
752   data->mod_time = cdr->last_mod_date << 16 | cdr->last_mod_time;
753   data->crc32 = cdr->crc32;
754   data->compressed_length = cdr->compressed_size;
755   data->uncompressed_length = cdr->uncompressed_size;
756 
757   // Figure out the local header offset from the central directory. The
758   // actual file data will begin after the local header and the name /
759   // extra comments.
760   off64_t local_header_offset = cdr->local_file_header_offset;
761   // One of the info field is UINT32_MAX, try to parse the real value in the zip64 extended info in
762   // the extra field.
763   if (cdr->uncompressed_size == UINT32_MAX || cdr->compressed_size == UINT32_MAX ||
764       cdr->local_file_header_offset == UINT32_MAX) {
765     const uint8_t* extra_field = ptr + sizeof(CentralDirectoryRecord) + cdr->file_name_length;
766     Zip64ExtendedInfo zip64_info{};
767     if (auto status = ParseZip64ExtendedInfoInExtraField(
768             extra_field, cdr->extra_field_length, cdr->uncompressed_size, cdr->compressed_size,
769             cdr->local_file_header_offset, &zip64_info);
770         status != kSuccess) {
771       return status;
772     }
773 
774     data->uncompressed_length = zip64_info.uncompressed_file_size.value_or(cdr->uncompressed_size);
775     data->compressed_length = zip64_info.compressed_file_size.value_or(cdr->compressed_size);
776     local_header_offset = zip64_info.local_header_offset.value_or(local_header_offset);
777     data->zip64_format_size =
778         cdr->uncompressed_size == UINT32_MAX || cdr->compressed_size == UINT32_MAX;
779   }
780 
781   off64_t local_header_end;
782   if (__builtin_add_overflow(local_header_offset, sizeof(LocalFileHeader), &local_header_end) ||
783       local_header_end >= cd_offset) {
784     // We tested >= because the name that follows can't be zero length.
785     ALOGW("Zip: bad local hdr offset in zip");
786     return kInvalidOffset;
787   }
788 
789   uint8_t lfh_buf[sizeof(LocalFileHeader)];
790   if (!archive->mapped_zip.ReadAtOffset(lfh_buf, sizeof(lfh_buf), local_header_offset)) {
791     ALOGW("Zip: failed reading lfh name from offset %" PRId64,
792           static_cast<int64_t>(local_header_offset));
793     return kIoError;
794   }
795 
796   auto lfh = reinterpret_cast<const LocalFileHeader*>(lfh_buf);
797   if (lfh->lfh_signature != LocalFileHeader::kSignature) {
798     ALOGW("Zip: didn't find signature at start of lfh, offset=%" PRId64,
799           static_cast<int64_t>(local_header_offset));
800     return kInvalidOffset;
801   }
802 
803   // Check that the local file header name matches the declared name in the central directory.
804   CHECK_LE(entryName.size(), UINT16_MAX);
805   auto name_length = static_cast<uint16_t>(entryName.size());
806   if (lfh->file_name_length != name_length) {
807     ALOGW("Zip: lfh name length did not match central directory for %s: %" PRIu16 " %" PRIu16,
808           std::string(entryName).c_str(), lfh->file_name_length, name_length);
809     return kInconsistentInformation;
810   }
811   off64_t name_offset;
812   if (__builtin_add_overflow(local_header_offset, sizeof(LocalFileHeader), &name_offset)) {
813     ALOGW("Zip: lfh name offset invalid");
814     return kInvalidOffset;
815   }
816   off64_t name_end;
817   if (__builtin_add_overflow(name_offset, name_length, &name_end) || name_end > cd_offset) {
818     // We tested > cd_offset here because the file data that follows can be zero length.
819     ALOGW("Zip: lfh name length invalid");
820     return kInvalidOffset;
821   }
822 
823   name_buf.resize(name_length);
824   if (!archive->mapped_zip.ReadAtOffset(name_buf.data(), name_buf.size(), name_offset)) {
825     ALOGW("Zip: failed reading lfh name from offset %" PRId64, static_cast<int64_t>(name_offset));
826     return kIoError;
827   }
828   if (memcmp(entryName.data(), name_buf.data(), name_buf.size()) != 0) {
829     ALOGW("Zip: lfh name did not match central directory");
830     return kInconsistentInformation;
831   }
832 
833   uint64_t lfh_uncompressed_size = lfh->uncompressed_size;
834   uint64_t lfh_compressed_size = lfh->compressed_size;
835   if (lfh_uncompressed_size == UINT32_MAX || lfh_compressed_size == UINT32_MAX) {
836     if (lfh_uncompressed_size != UINT32_MAX || lfh_compressed_size != UINT32_MAX) {
837       ALOGW(
838           "Zip: The zip64 extended field in the local header MUST include BOTH original and "
839           "compressed file size fields.");
840       return kInvalidFile;
841     }
842 
843     const off64_t lfh_extra_field_offset = name_offset + lfh->file_name_length;
844     const uint16_t lfh_extra_field_size = lfh->extra_field_length;
845     if (lfh_extra_field_offset > cd_offset - lfh_extra_field_size) {
846       ALOGW("Zip: extra field has a bad size for entry %s", std::string(entryName).c_str());
847       return kInvalidOffset;
848     }
849 
850     local_extra_field.resize(lfh_extra_field_size);
851     if (!archive->mapped_zip.ReadAtOffset(local_extra_field.data(), lfh_extra_field_size,
852                                           lfh_extra_field_offset)) {
853       ALOGW("Zip: failed reading lfh extra field from offset %" PRId64, lfh_extra_field_offset);
854       return kIoError;
855     }
856 
857     Zip64ExtendedInfo zip64_info{};
858     if (auto status = ParseZip64ExtendedInfoInExtraField(
859             local_extra_field.data(), lfh_extra_field_size, lfh->uncompressed_size,
860             lfh->compressed_size, std::nullopt, &zip64_info);
861         status != kSuccess) {
862       return status;
863     }
864 
865     CHECK(zip64_info.uncompressed_file_size.has_value());
866     CHECK(zip64_info.compressed_file_size.has_value());
867     lfh_uncompressed_size = zip64_info.uncompressed_file_size.value();
868     lfh_compressed_size = zip64_info.compressed_file_size.value();
869   }
870 
871   // Paranoia: Match the values specified in the local file header
872   // to those specified in the central directory.
873 
874   // Warn if central directory and local file header don't agree on the use
875   // of a trailing Data Descriptor. The reference implementation is inconsistent
876   // and appears to use the LFH value during extraction (unzip) but the CD value
877   // while displayng information about archives (zipinfo). The spec remains
878   // silent on this inconsistency as well.
879   //
880   // For now, always use the version from the LFH but make sure that the values
881   // specified in the central directory match those in the data descriptor.
882   //
883   // NOTE: It's also worth noting that unzip *does* warn about inconsistencies in
884   // bit 11 (EFS: The language encoding flag, marking that filename and comment are
885   // encoded using UTF-8). This implementation does not check for the presence of
886   // that flag and always enforces that entry names are valid UTF-8.
887   if ((lfh->gpb_flags & kGPBDDFlagMask) != (cdr->gpb_flags & kGPBDDFlagMask)) {
888     ALOGW("Zip: gpb flag mismatch at bit 3. expected {%04" PRIx16 "}, was {%04" PRIx16 "}",
889           cdr->gpb_flags, lfh->gpb_flags);
890   }
891 
892   // If there is no trailing data descriptor, verify that the central directory and local file
893   // header agree on the crc, compressed, and uncompressed sizes of the entry.
894   if ((lfh->gpb_flags & kGPBDDFlagMask) == 0) {
895     data->has_data_descriptor = 0;
896     if (data->compressed_length != lfh_compressed_size ||
897         data->uncompressed_length != lfh_uncompressed_size || data->crc32 != lfh->crc32) {
898       ALOGW("Zip: size/crc32 mismatch. expected {%" PRIu64 ", %" PRIu64 ", %" PRIx32
899             "}, was {%" PRIu64 ", %" PRIu64 ", %" PRIx32 "}",
900             data->compressed_length, data->uncompressed_length, data->crc32, lfh_compressed_size,
901             lfh_uncompressed_size, lfh->crc32);
902       return kInconsistentInformation;
903     }
904   } else {
905     data->has_data_descriptor = 1;
906   }
907 
908   // 4.4.2.1: the upper byte of `version_made_by` gives the source OS. Unix is 3.
909   data->version_made_by = cdr->version_made_by;
910   data->external_file_attributes = cdr->external_file_attributes;
911   if ((data->version_made_by >> 8) == 3) {
912     data->unix_mode = (cdr->external_file_attributes >> 16) & 0xffff;
913   } else {
914     data->unix_mode = 0777;
915   }
916 
917   // 4.4.4: general purpose bit flags.
918   data->gpbf = lfh->gpb_flags;
919 
920   // 4.4.14: the lowest bit of the internal file attributes field indicates text.
921   // Currently only needed to implement zipinfo.
922   data->is_text = (cdr->internal_file_attributes & 1);
923 
924   const off64_t data_offset = local_header_offset + sizeof(LocalFileHeader) +
925                               lfh->file_name_length + lfh->extra_field_length;
926   if (data_offset > cd_offset) {
927     ALOGW("Zip: bad data offset %" PRId64 " in zip", static_cast<int64_t>(data_offset));
928     return kInvalidOffset;
929   }
930 
931   if (data->compressed_length > cd_offset - data_offset) {
932     ALOGW("Zip: bad compressed length in zip (%" PRId64 " + %" PRIu64 " > %" PRId64 ")",
933           static_cast<int64_t>(data_offset), data->compressed_length,
934           static_cast<int64_t>(cd_offset));
935     return kInvalidOffset;
936   }
937 
938   if (data->method == kCompressStored && data->uncompressed_length > cd_offset - data_offset) {
939     ALOGW("Zip: bad uncompressed length in zip (%" PRId64 " + %" PRIu64 " > %" PRId64 ")",
940           static_cast<int64_t>(data_offset), data->uncompressed_length,
941           static_cast<int64_t>(cd_offset));
942     return kInvalidOffset;
943   }
944 
945   data->offset = data_offset;
946   return 0;
947 }
948 
949 struct IterationHandle {
950   ZipArchive* archive;
951 
952   std::function<bool(std::string_view)> matcher;
953 
954   uint32_t position = 0;
955 
IterationHandleIterationHandle956   IterationHandle(ZipArchive* archive, std::function<bool(std::string_view)> in_matcher)
957       : archive(archive), matcher(std::move(in_matcher)) {}
958 
MatchIterationHandle959   bool Match(std::string_view entry_name) const { return matcher(entry_name); }
960 };
961 
StartIteration(ZipArchiveHandle archive,void ** cookie_ptr,const std::string_view optional_prefix,const std::string_view optional_suffix)962 int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
963                        const std::string_view optional_prefix,
964                        const std::string_view optional_suffix) {
965   if (optional_prefix.size() > static_cast<size_t>(UINT16_MAX) ||
966       optional_suffix.size() > static_cast<size_t>(UINT16_MAX)) {
967     ALOGW("Zip: prefix/suffix too long");
968     return kInvalidEntryName;
969   }
970   auto matcher = [prefix = std::string(optional_prefix),
971                   suffix = std::string(optional_suffix)](std::string_view name) mutable {
972     return android::base::StartsWith(name, prefix) && android::base::EndsWith(name, suffix);
973   };
974   return StartIteration(archive, cookie_ptr, std::move(matcher));
975 }
976 
StartIteration(ZipArchiveHandle archive,void ** cookie_ptr,std::function<bool (std::string_view)> matcher)977 int32_t StartIteration(ZipArchiveHandle archive, void** cookie_ptr,
978                        std::function<bool(std::string_view)> matcher) {
979   if (archive == nullptr || archive->cd_entry_map == nullptr) {
980     ALOGW("Zip: Invalid ZipArchiveHandle");
981     return kInvalidHandle;
982   }
983 
984   archive->cd_entry_map->ResetIteration();
985   *cookie_ptr = new IterationHandle(archive, std::move(matcher));
986   return 0;
987 }
988 
EndIteration(void * cookie)989 void EndIteration(void* cookie) {
990   delete reinterpret_cast<IterationHandle*>(cookie);
991 }
992 
CopyFromZipEntry64(ZipEntry * dst,const ZipEntry64 * src)993 int32_t ZipEntry::CopyFromZipEntry64(ZipEntry* dst, const ZipEntry64* src) {
994   if (src->compressed_length > UINT32_MAX || src->uncompressed_length > UINT32_MAX) {
995     ALOGW(
996         "Zip: the entry size is too large to fit into the 32 bits ZipEntry, uncompressed "
997         "length %" PRIu64 ", compressed length %" PRIu64,
998         src->uncompressed_length, src->compressed_length);
999     return kUnsupportedEntrySize;
1000   }
1001 
1002   *dst = *src;
1003   dst->uncompressed_length = static_cast<uint32_t>(src->uncompressed_length);
1004   dst->compressed_length = static_cast<uint32_t>(src->compressed_length);
1005   return kSuccess;
1006 }
1007 
FindEntry(const ZipArchiveHandle archive,const std::string_view entryName,ZipEntry * data)1008 int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
1009                   ZipEntry* data) {
1010   ZipEntry64 entry64;
1011   if (auto status = FindEntry(archive, entryName, &entry64); status != kSuccess) {
1012     return status;
1013   }
1014 
1015   return ZipEntry::CopyFromZipEntry64(data, &entry64);
1016 }
1017 
FindEntry(const ZipArchiveHandle archive,const std::string_view entryName,ZipEntry64 * data)1018 int32_t FindEntry(const ZipArchiveHandle archive, const std::string_view entryName,
1019                   ZipEntry64* data) {
1020   if (entryName.empty() || entryName.size() > static_cast<size_t>(UINT16_MAX)) {
1021     ALOGW("Zip: Invalid filename of length %zu", entryName.size());
1022     return kInvalidEntryName;
1023   }
1024 
1025   const auto [result, offset] =
1026       archive->cd_entry_map->GetCdEntryOffset(entryName, archive->central_directory.GetBasePtr());
1027   if (result != 0) {
1028     ALOGV("Zip: Could not find entry %.*s", static_cast<int>(entryName.size()), entryName.data());
1029     return static_cast<int32_t>(result);  // kEntryNotFound is safe to truncate.
1030   }
1031   // We know there are at most hash_table_size entries, safe to truncate.
1032   return FindEntry(archive, entryName, offset, data);
1033 }
1034 
Next(void * cookie,ZipEntry * data,std::string * name)1035 int32_t Next(void* cookie, ZipEntry* data, std::string* name) {
1036   ZipEntry64 entry64;
1037   if (auto status = Next(cookie, &entry64, name); status != kSuccess) {
1038     return status;
1039   }
1040 
1041   return ZipEntry::CopyFromZipEntry64(data, &entry64);
1042 }
1043 
Next(void * cookie,ZipEntry * data,std::string_view * name)1044 int32_t Next(void* cookie, ZipEntry* data, std::string_view* name) {
1045   ZipEntry64 entry64;
1046   if (auto status = Next(cookie, &entry64, name); status != kSuccess) {
1047     return status;
1048   }
1049 
1050   return ZipEntry::CopyFromZipEntry64(data, &entry64);
1051 }
1052 
Next(void * cookie,ZipEntry64 * data,std::string * name)1053 int32_t Next(void* cookie, ZipEntry64* data, std::string* name) {
1054   std::string_view sv;
1055   int32_t result = Next(cookie, data, &sv);
1056   if (result == 0 && name) {
1057     *name = std::string(sv);
1058   }
1059   return result;
1060 }
1061 
Next(void * cookie,ZipEntry64 * data,std::string_view * name)1062 int32_t Next(void* cookie, ZipEntry64* data, std::string_view* name) {
1063   IterationHandle* handle = reinterpret_cast<IterationHandle*>(cookie);
1064   if (handle == nullptr) {
1065     ALOGW("Zip: Null ZipArchiveHandle");
1066     return kInvalidHandle;
1067   }
1068 
1069   ZipArchive* archive = handle->archive;
1070   if (archive == nullptr || archive->cd_entry_map == nullptr) {
1071     ALOGW("Zip: Invalid ZipArchiveHandle");
1072     return kInvalidHandle;
1073   }
1074 
1075   SCOPED_SIGBUS_HANDLER(return kIoError);
1076 
1077   auto entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
1078   while (entry != std::pair<std::string_view, uint64_t>()) {
1079     const auto [entry_name, offset] = entry;
1080     if (handle->Match(entry_name)) {
1081       const int error = FindEntry(archive, entry_name, offset, data);
1082       if (!error && name) {
1083         *name = entry_name;
1084       }
1085       return error;
1086     }
1087     entry = archive->cd_entry_map->Next(archive->central_directory.GetBasePtr());
1088   }
1089 
1090   archive->cd_entry_map->ResetIteration();
1091   return kIterationEnd;
1092 }
1093 
1094 // A Writer that writes data to a fixed size memory region.
1095 // The size of the memory region must be equal to the total size of
1096 // the data appended to it.
1097 class MemoryWriter : public zip_archive::Writer {
1098  public:
Create(uint8_t * buf,size_t size,const ZipEntry64 * entry)1099   static std::optional<MemoryWriter> Create(uint8_t* buf, size_t size,
1100                                             const ZipEntry64* entry) {
1101     const uint64_t declared_length = entry->uncompressed_length;
1102     if (declared_length > size) {
1103       ALOGW("Zip: file size %" PRIu64 " is larger than the buffer size %zu.", declared_length,
1104             size);
1105       return {};
1106     }
1107 
1108     return std::make_optional<MemoryWriter>(buf, size);
1109   }
1110 
Append(uint8_t * buf,size_t buf_size)1111   virtual bool Append(uint8_t* buf, size_t buf_size) override {
1112     if (size_ < buf_size || bytes_written_ > size_ - buf_size) {
1113       ALOGW("Zip: Unexpected size %zu (declared) vs %zu (actual)", size_,
1114             bytes_written_ + buf_size);
1115       return false;
1116     }
1117 
1118     memcpy(buf_ + bytes_written_, buf, buf_size);
1119     bytes_written_ += buf_size;
1120     return true;
1121   }
1122 
MemoryWriter(uint8_t * buf,size_t size)1123   MemoryWriter(uint8_t* buf, size_t size) : Writer(), buf_(buf), size_(size), bytes_written_(0) {}
1124 
1125  private:
1126   uint8_t* const buf_{nullptr};
1127   const size_t size_;
1128   size_t bytes_written_;
1129 };
1130 
1131 // A Writer that appends data to a file |fd| at its current position.
1132 // The file will be truncated to the end of the written data.
1133 class FileWriter : public zip_archive::Writer {
1134  public:
1135   // Creates a FileWriter for |fd| and prepare to write |entry| to it,
1136   // guaranteeing that the file descriptor is valid and that there's enough
1137   // space on the volume to write out the entry completely and that the file
1138   // is truncated to the correct length (no truncation if |fd| references a
1139   // block device).
1140   //
1141   // Returns a valid FileWriter on success, |nullopt| if an error occurred.
Create(int fd,const ZipEntry64 * entry)1142   static std::optional<FileWriter> Create(int fd, const ZipEntry64* entry) {
1143     const uint64_t declared_length = entry->uncompressed_length;
1144     const off64_t current_offset = lseek64(fd, 0, SEEK_CUR);
1145     if (current_offset == -1) {
1146       ALOGW("Zip: unable to seek to current location on fd %d: %s", fd, strerror(errno));
1147       return {};
1148     }
1149 
1150     if (declared_length > SIZE_MAX || declared_length > INT64_MAX) {
1151       ALOGW("Zip: file size %" PRIu64 " is too large to extract.", declared_length);
1152       return {};
1153     }
1154 
1155 #if defined(__linux__)
1156     if (declared_length > 0) {
1157       // Make sure we have enough space on the volume to extract the compressed
1158       // entry. Note that the call to ftruncate below will change the file size but
1159       // will not allocate space on disk and this call to fallocate will not
1160       // change the file size.
1161       // Note: fallocate is only supported by the following filesystems -
1162       // btrfs, ext4, ocfs2, and xfs. Therefore fallocate might fail with
1163       // EOPNOTSUPP error when issued in other filesystems.
1164       // Hence, check for the return error code before concluding that the
1165       // disk does not have enough space.
1166       long result = TEMP_FAILURE_RETRY(fallocate(fd, 0, current_offset, declared_length));
1167       if (result == -1 && errno == ENOSPC) {
1168         ALOGW("Zip: unable to allocate %" PRIu64 " bytes at offset %" PRId64 ": %s",
1169               declared_length, static_cast<int64_t>(current_offset), strerror(errno));
1170         return {};
1171       }
1172     }
1173 #endif  // __linux__
1174 
1175     struct stat sb;
1176     if (fstat(fd, &sb) == -1) {
1177       ALOGW("Zip: unable to fstat file: %s", strerror(errno));
1178       return {};
1179     }
1180 
1181     // Block device doesn't support ftruncate(2).
1182     if (!S_ISBLK(sb.st_mode)) {
1183       long result = TEMP_FAILURE_RETRY(ftruncate(fd, declared_length + current_offset));
1184       if (result == -1) {
1185         ALOGW("Zip: unable to truncate file to %" PRId64 ": %s",
1186               static_cast<int64_t>(declared_length + current_offset), strerror(errno));
1187         return {};
1188       }
1189     }
1190 
1191     return std::make_optional<FileWriter>(fd, declared_length);
1192   }
1193 
Append(uint8_t * buf,size_t buf_size)1194   virtual bool Append(uint8_t* buf, size_t buf_size) override {
1195     if (declared_length_ < buf_size || total_bytes_written_ > declared_length_ - buf_size) {
1196       ALOGW("Zip: Unexpected size %zu  (declared) vs %zu (actual)", declared_length_,
1197             total_bytes_written_ + buf_size);
1198       return false;
1199     }
1200 
1201     const bool result = android::base::WriteFully(fd_, buf, buf_size);
1202     if (result) {
1203       total_bytes_written_ += buf_size;
1204     } else {
1205       ALOGW("Zip: unable to write %zu bytes to file; %s", buf_size, strerror(errno));
1206     }
1207 
1208     return result;
1209   }
1210 
FileWriter(const int fd=-1,const uint64_t declared_length=0)1211   explicit FileWriter(const int fd = -1, const uint64_t declared_length = 0)
1212       : Writer(),
1213         fd_(fd),
1214         declared_length_(static_cast<size_t>(declared_length)),
1215         total_bytes_written_(0) {
1216     CHECK_LE(declared_length, SIZE_MAX);
1217   }
1218 
1219  private:
1220   int fd_;
1221   const size_t declared_length_;
1222   size_t total_bytes_written_;
1223 };
1224 
1225 class EntryReader : public zip_archive::Reader {
1226  public:
EntryReader(const MappedZipFile & zip_file,const ZipEntry64 * entry)1227   EntryReader(const MappedZipFile& zip_file, const ZipEntry64* entry)
1228       : Reader(), zip_file_(zip_file), entry_(entry) {}
1229 
ReadAtOffset(uint8_t * buf,size_t len,off64_t offset) const1230   virtual bool ReadAtOffset(uint8_t* buf, size_t len, off64_t offset) const {
1231     return zip_file_.ReadAtOffset(buf, len, entry_->offset + offset);
1232   }
1233 
~EntryReader()1234   virtual ~EntryReader() {}
1235 
1236  private:
1237   const MappedZipFile& zip_file_;
1238   const ZipEntry64* entry_;
1239 };
1240 
1241 // This method is using libz macros with old-style-casts
1242 #pragma GCC diagnostic push
1243 #pragma GCC diagnostic ignored "-Wold-style-cast"
zlib_inflateInit2(z_stream * stream,int window_bits)1244 static inline int zlib_inflateInit2(z_stream* stream, int window_bits) {
1245   return inflateInit2(stream, window_bits);
1246 }
1247 #pragma GCC diagnostic pop
1248 
1249 namespace zip_archive {
1250 
1251 // Moved out of line to avoid -Wweak-vtables.
~Reader()1252 Reader::~Reader() {}
~Writer()1253 Writer::~Writer() {}
1254 
1255 }  // namespace zip_archive
1256 
1257 template <bool OnIncfs>
inflateImpl(const zip_archive::Reader & reader,const uint64_t compressed_length,const uint64_t uncompressed_length,zip_archive::Writer * writer,uint64_t * crc_out)1258 static int32_t inflateImpl(const zip_archive::Reader& reader,
1259                            const uint64_t compressed_length,
1260                            const uint64_t uncompressed_length,
1261                            zip_archive::Writer* writer, uint64_t* crc_out) {
1262   const size_t kBufSize = 32768;
1263   std::vector<uint8_t> read_buf(kBufSize);
1264   std::vector<uint8_t> write_buf(kBufSize);
1265   z_stream zstream;
1266   int zerr;
1267 
1268   /*
1269    * Initialize the zlib stream struct.
1270    */
1271   memset(&zstream, 0, sizeof(zstream));
1272   zstream.zalloc = Z_NULL;
1273   zstream.zfree = Z_NULL;
1274   zstream.opaque = Z_NULL;
1275   zstream.next_in = NULL;
1276   zstream.avail_in = 0;
1277   zstream.next_out = &write_buf[0];
1278   zstream.avail_out = kBufSize;
1279   zstream.data_type = Z_UNKNOWN;
1280 
1281   /*
1282    * Use the undocumented "negative window bits" feature to tell zlib
1283    * that there's no zlib header waiting for it.
1284    */
1285   zerr = zlib_inflateInit2(&zstream, -MAX_WBITS);
1286   if (zerr != Z_OK) {
1287     if (zerr == Z_VERSION_ERROR) {
1288       ALOGE("Installed zlib is not compatible with linked version (%s)", ZLIB_VERSION);
1289     } else {
1290       ALOGW("Call to inflateInit2 failed (zerr=%d)", zerr);
1291     }
1292 
1293     return kZlibError;
1294   }
1295 
1296   auto zstream_deleter = [](z_stream* stream) {
1297     inflateEnd(stream); /* free up any allocated structures */
1298   };
1299 
1300   std::unique_ptr<z_stream, decltype(zstream_deleter)> zstream_guard(&zstream, zstream_deleter);
1301 
1302   SCOPED_SIGBUS_HANDLER_CONDITIONAL(OnIncfs, {
1303     zstream_guard.reset();
1304     incfs::util::clearAndFree(read_buf);
1305     incfs::util::clearAndFree(write_buf);
1306     return kIoError;
1307   });
1308 
1309   const bool compute_crc = (crc_out != nullptr);
1310   uLong crc = 0;
1311   uint64_t remaining_bytes = compressed_length;
1312   uint64_t total_output = 0;
1313   do {
1314     /* read as much as we can */
1315     if (zstream.avail_in == 0) {
1316       const uint32_t read_size =
1317           (remaining_bytes > kBufSize) ? kBufSize : static_cast<uint32_t>(remaining_bytes);
1318       const off64_t offset = (compressed_length - remaining_bytes);
1319       // Make sure to read at offset to ensure concurrent access to the fd.
1320       if (!reader.ReadAtOffset(read_buf.data(), read_size, offset)) {
1321         ALOGW("Zip: inflate read failed, getSize = %u: %s", read_size, strerror(errno));
1322         return kIoError;
1323       }
1324 
1325       remaining_bytes -= read_size;
1326 
1327       zstream.next_in = &read_buf[0];
1328       zstream.avail_in = read_size;
1329     }
1330 
1331     /* uncompress the data */
1332     zerr = inflate(&zstream, Z_NO_FLUSH);
1333     if (zerr != Z_OK && zerr != Z_STREAM_END) {
1334       ALOGW("Zip: inflate zerr=%d (nIn=%p aIn=%u nOut=%p aOut=%u)", zerr, zstream.next_in,
1335             zstream.avail_in, zstream.next_out, zstream.avail_out);
1336       return kZlibError;
1337     }
1338 
1339     /* write when we're full or when we're done */
1340     if (zstream.avail_out == 0 || (zerr == Z_STREAM_END && zstream.avail_out != kBufSize)) {
1341       const size_t write_size = zstream.next_out - &write_buf[0];
1342       if (!writer->Append(&write_buf[0], write_size)) {
1343         return kIoError;
1344       } else if (compute_crc) {
1345         DCHECK_LE(write_size, kBufSize);
1346         crc = crc32(crc, &write_buf[0], static_cast<uint32_t>(write_size));
1347       }
1348 
1349       total_output += kBufSize - zstream.avail_out;
1350       zstream.next_out = &write_buf[0];
1351       zstream.avail_out = kBufSize;
1352     }
1353   } while (zerr == Z_OK);
1354 
1355   CHECK_EQ(zerr, Z_STREAM_END); /* other errors should've been caught */
1356 
1357   // NOTE: zstream.adler is always set to 0, because we're using the -MAX_WBITS
1358   // "feature" of zlib to tell it there won't be a zlib file header. zlib
1359   // doesn't bother calculating the checksum in that scenario. We just do
1360   // it ourselves above because there are no additional gains to be made by
1361   // having zlib calculate it for us, since they do it by calling crc32 in
1362   // the same manner that we have above.
1363   if (compute_crc) {
1364     *crc_out = crc;
1365   }
1366   if (total_output != uncompressed_length || remaining_bytes != 0) {
1367     ALOGW("Zip: size mismatch on inflated file (%lu vs %" PRIu64 ")", zstream.total_out,
1368           uncompressed_length);
1369     return kInconsistentInformation;
1370   }
1371 
1372   return 0;
1373 }
1374 
InflateEntryToWriter(MappedZipFile & mapped_zip,const ZipEntry64 * entry,zip_archive::Writer * writer,uint64_t * crc_out)1375 static int32_t InflateEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry64* entry,
1376                                     zip_archive::Writer* writer, uint64_t* crc_out) {
1377   const EntryReader reader(mapped_zip, entry);
1378 
1379   return inflateImpl<true>(reader, entry->compressed_length,
1380                            entry->uncompressed_length, writer, crc_out);
1381 }
1382 
CopyEntryToWriter(MappedZipFile & mapped_zip,const ZipEntry64 * entry,zip_archive::Writer * writer,uint64_t * crc_out)1383 static int32_t CopyEntryToWriter(MappedZipFile& mapped_zip, const ZipEntry64* entry,
1384                                  zip_archive::Writer* writer, uint64_t* crc_out) {
1385   static const uint32_t kBufSize = 32768;
1386   std::vector<uint8_t> buf(kBufSize);
1387 
1388   SCOPED_SIGBUS_HANDLER({
1389     incfs::util::clearAndFree(buf);
1390     return kIoError;
1391   });
1392 
1393   const uint64_t length = entry->uncompressed_length;
1394   uint64_t count = 0;
1395   uLong crc = 0;
1396   while (count < length) {
1397     uint64_t remaining = length - count;
1398     off64_t offset = entry->offset + count;
1399 
1400     // Safe conversion because kBufSize is narrow enough for a 32 bit signed value.
1401     const uint32_t block_size =
1402         (remaining > kBufSize) ? kBufSize : static_cast<uint32_t>(remaining);
1403 
1404     // Make sure to read at offset to ensure concurrent access to the fd.
1405     if (!mapped_zip.ReadAtOffset(buf.data(), block_size, offset)) {
1406       ALOGW("CopyFileToFile: copy read failed, block_size = %u, offset = %" PRId64 ": %s",
1407             block_size, static_cast<int64_t>(offset), strerror(errno));
1408       return kIoError;
1409     }
1410 
1411     if (!writer->Append(&buf[0], block_size)) {
1412       return kIoError;
1413     }
1414     if (crc_out) {
1415       crc = crc32(crc, &buf[0], block_size);
1416     }
1417     count += block_size;
1418   }
1419 
1420   if (crc_out) {
1421     *crc_out = crc;
1422   }
1423 
1424   return 0;
1425 }
1426 
extractToWriter(ZipArchiveHandle handle,const ZipEntry64 * entry,zip_archive::Writer * writer)1427 static int32_t extractToWriter(ZipArchiveHandle handle, const ZipEntry64* entry,
1428                                zip_archive::Writer* writer) {
1429   const uint16_t method = entry->method;
1430 
1431   // this should default to kUnknownCompressionMethod.
1432   int32_t return_value = -1;
1433   uint64_t crc = 0;
1434   if (method == kCompressStored) {
1435     return_value =
1436         CopyEntryToWriter(handle->mapped_zip, entry, writer, kCrcChecksEnabled ? &crc : nullptr);
1437   } else if (method == kCompressDeflated) {
1438     return_value =
1439         InflateEntryToWriter(handle->mapped_zip, entry, writer, kCrcChecksEnabled ? &crc : nullptr);
1440   }
1441 
1442   if (!return_value && entry->has_data_descriptor) {
1443     return_value = ValidateDataDescriptor(handle->mapped_zip, entry);
1444     if (return_value) {
1445       return return_value;
1446     }
1447   }
1448 
1449   // Validate that the CRC matches the calculated value.
1450   if (kCrcChecksEnabled && (entry->crc32 != static_cast<uint32_t>(crc))) {
1451     ALOGW("Zip: crc mismatch: expected %" PRIu32 ", was %" PRIu64, entry->crc32, crc);
1452     return kInconsistentInformation;
1453   }
1454 
1455   return return_value;
1456 }
1457 
ExtractToMemory(ZipArchiveHandle archive,const ZipEntry * entry,uint8_t * begin,size_t size)1458 int32_t ExtractToMemory(ZipArchiveHandle archive, const ZipEntry* entry, uint8_t* begin,
1459                         size_t size) {
1460   ZipEntry64 entry64(*entry);
1461   return ExtractToMemory(archive, &entry64, begin, size);
1462 }
1463 
ExtractToMemory(ZipArchiveHandle archive,const ZipEntry64 * entry,uint8_t * begin,size_t size)1464 int32_t ExtractToMemory(ZipArchiveHandle archive, const ZipEntry64* entry, uint8_t* begin,
1465                         size_t size) {
1466   auto writer = MemoryWriter::Create(begin, size, entry);
1467   if (!writer) {
1468     return kIoError;
1469   }
1470 
1471   return extractToWriter(archive, entry, &writer.value());
1472 }
1473 
ExtractEntryToFile(ZipArchiveHandle archive,const ZipEntry * entry,int fd)1474 int32_t ExtractEntryToFile(ZipArchiveHandle archive, const ZipEntry* entry, int fd) {
1475   ZipEntry64 entry64(*entry);
1476   return ExtractEntryToFile(archive, &entry64, fd);
1477 }
1478 
ExtractEntryToFile(ZipArchiveHandle archive,const ZipEntry64 * entry,int fd)1479 int32_t ExtractEntryToFile(ZipArchiveHandle archive, const ZipEntry64* entry, int fd) {
1480   auto writer = FileWriter::Create(fd, entry);
1481   if (!writer) {
1482     return kIoError;
1483   }
1484 
1485   return extractToWriter(archive, entry, &writer.value());
1486 }
1487 
GetFileDescriptor(const ZipArchiveHandle archive)1488 int GetFileDescriptor(const ZipArchiveHandle archive) {
1489   return archive->mapped_zip.GetFileDescriptor();
1490 }
1491 
GetFileDescriptorOffset(const ZipArchiveHandle archive)1492 off64_t GetFileDescriptorOffset(const ZipArchiveHandle archive) {
1493   return archive->mapped_zip.GetFileOffset();
1494 }
1495 
1496 //
1497 // ZIPARCHIVE_DISABLE_CALLBACK_API disables all APIs that accept user callbacks.
1498 // It gets defined for the incfs-supporting version of libziparchive, where one
1499 // has to control all the code accessing the archive. See more at
1500 // incfs_support/signal_handling.h
1501 //
1502 #if !ZIPARCHIVE_DISABLE_CALLBACK_API && !defined(_WIN32)
1503 class ProcessWriter : public zip_archive::Writer {
1504  public:
ProcessWriter(ProcessZipEntryFunction func,void * cookie)1505   ProcessWriter(ProcessZipEntryFunction func, void* cookie)
1506       : Writer(), proc_function_(func), cookie_(cookie) {}
1507 
Append(uint8_t * buf,size_t buf_size)1508   virtual bool Append(uint8_t* buf, size_t buf_size) override {
1509     return proc_function_(buf, buf_size, cookie_);
1510   }
1511 
1512  private:
1513   ProcessZipEntryFunction proc_function_;
1514   void* cookie_;
1515 };
1516 
ProcessZipEntryContents(ZipArchiveHandle archive,const ZipEntry * entry,ProcessZipEntryFunction func,void * cookie)1517 int32_t ProcessZipEntryContents(ZipArchiveHandle archive, const ZipEntry* entry,
1518                                 ProcessZipEntryFunction func, void* cookie) {
1519   ZipEntry64 entry64(*entry);
1520   return ProcessZipEntryContents(archive, &entry64, func, cookie);
1521 }
1522 
ProcessZipEntryContents(ZipArchiveHandle archive,const ZipEntry64 * entry,ProcessZipEntryFunction func,void * cookie)1523 int32_t ProcessZipEntryContents(ZipArchiveHandle archive, const ZipEntry64* entry,
1524                                 ProcessZipEntryFunction func, void* cookie) {
1525   ProcessWriter writer(func, cookie);
1526   return extractToWriter(archive, entry, &writer);
1527 }
1528 
1529 #endif  // !ZIPARCHIVE_DISABLE_CALLBACK_API && !defined(_WIN32)
1530 
GetFileDescriptor() const1531 int MappedZipFile::GetFileDescriptor() const {
1532   if (!has_fd_) {
1533     ALOGW("Zip: MappedZipFile doesn't have a file descriptor.");
1534     return -1;
1535   }
1536   return fd_;
1537 }
1538 
GetBasePtr() const1539 const void* MappedZipFile::GetBasePtr() const {
1540   if (has_fd_) {
1541     ALOGW("Zip: MappedZipFile doesn't have a base pointer.");
1542     return nullptr;
1543   }
1544   return base_ptr_;
1545 }
1546 
GetFileOffset() const1547 off64_t MappedZipFile::GetFileOffset() const {
1548   return fd_offset_;
1549 }
1550 
GetFileLength() const1551 off64_t MappedZipFile::GetFileLength() const {
1552   if (has_fd_) {
1553     if (data_length_ != -1) {
1554       return data_length_;
1555     }
1556     data_length_ = lseek64(fd_, 0, SEEK_END);
1557     if (data_length_ == -1) {
1558       ALOGE("Zip: lseek on fd %d failed: %s", fd_, strerror(errno));
1559     }
1560     return data_length_;
1561   } else {
1562     if (base_ptr_ == nullptr) {
1563       ALOGE("Zip: invalid file map");
1564       return -1;
1565     }
1566     return data_length_;
1567   }
1568 }
1569 
1570 // Attempts to read |len| bytes into |buf| at offset |off|.
ReadAtOffset(uint8_t * buf,size_t len,off64_t off) const1571 bool MappedZipFile::ReadAtOffset(uint8_t* buf, size_t len, off64_t off) const {
1572   if (has_fd_) {
1573     if (off < 0) {
1574       ALOGE("Zip: invalid offset %" PRId64, off);
1575       return false;
1576     }
1577 
1578     off64_t read_offset;
1579     if (__builtin_add_overflow(fd_offset_, off, &read_offset)) {
1580       ALOGE("Zip: invalid read offset %" PRId64 " overflows, fd offset %" PRId64, off, fd_offset_);
1581       return false;
1582     }
1583 
1584     if (data_length_ != -1) {
1585       off64_t read_end;
1586       if (len > std::numeric_limits<off64_t>::max() ||
1587           __builtin_add_overflow(off, static_cast<off64_t>(len), &read_end)) {
1588         ALOGE("Zip: invalid read length %" PRId64 " overflows, offset %" PRId64,
1589               static_cast<off64_t>(len), off);
1590         return false;
1591       }
1592 
1593       if (read_end > data_length_) {
1594         ALOGE("Zip: invalid read length %" PRId64 " exceeds data length %" PRId64 ", offset %"
1595               PRId64, static_cast<off64_t>(len), data_length_, off);
1596         return false;
1597       }
1598     }
1599 
1600     if (!android::base::ReadFullyAtOffset(fd_, buf, len, read_offset)) {
1601       ALOGE("Zip: failed to read at offset %" PRId64, off);
1602       return false;
1603     }
1604   } else {
1605     if (off < 0 || data_length_ < len || off > data_length_ - len) {
1606       ALOGE("Zip: invalid offset: %" PRId64 ", read length: %zu, data length: %" PRId64, off, len,
1607             data_length_);
1608       return false;
1609     }
1610     memcpy(buf, static_cast<const uint8_t*>(base_ptr_) + off, len);
1611   }
1612   return true;
1613 }
1614 
Initialize(const void * map_base_ptr,off64_t cd_start_offset,size_t cd_size)1615 void CentralDirectory::Initialize(const void* map_base_ptr, off64_t cd_start_offset,
1616                                   size_t cd_size) {
1617   base_ptr_ = static_cast<const uint8_t*>(map_base_ptr) + cd_start_offset;
1618   length_ = cd_size;
1619 }
1620 
InitializeCentralDirectory(off64_t cd_start_offset,size_t cd_size)1621 bool ZipArchive::InitializeCentralDirectory(off64_t cd_start_offset, size_t cd_size) {
1622   if (mapped_zip.HasFd()) {
1623     directory_map = android::base::MappedFile::FromFd(mapped_zip.GetFileDescriptor(),
1624                                                       mapped_zip.GetFileOffset() + cd_start_offset,
1625                                                       cd_size, PROT_READ);
1626     if (!directory_map) {
1627       ALOGE("Zip: failed to map central directory (offset %" PRId64 ", size %zu): %s",
1628             cd_start_offset, cd_size, strerror(errno));
1629       return false;
1630     }
1631 
1632     CHECK_EQ(directory_map->size(), cd_size);
1633     central_directory.Initialize(directory_map->data(), 0 /*offset*/, cd_size);
1634   } else {
1635     if (mapped_zip.GetBasePtr() == nullptr) {
1636       ALOGE("Zip: Failed to map central directory, bad mapped_zip base pointer");
1637       return false;
1638     }
1639     if (static_cast<off64_t>(cd_start_offset) + static_cast<off64_t>(cd_size) >
1640         mapped_zip.GetFileLength()) {
1641       ALOGE(
1642           "Zip: Failed to map central directory, offset exceeds mapped memory region ("
1643           "start_offset %" PRId64 ", cd_size %zu, mapped_region_size %" PRId64 ")",
1644           static_cast<int64_t>(cd_start_offset), cd_size, mapped_zip.GetFileLength());
1645       return false;
1646     }
1647 
1648     central_directory.Initialize(mapped_zip.GetBasePtr(), cd_start_offset, cd_size);
1649   }
1650   return true;
1651 }
1652 
1653 // This function returns the embedded timestamp as is and doesn't perform validation.
GetModificationTime() const1654 tm ZipEntryCommon::GetModificationTime() const {
1655   tm t = {};
1656 
1657   t.tm_hour = (mod_time >> 11) & 0x1f;
1658   t.tm_min = (mod_time >> 5) & 0x3f;
1659   t.tm_sec = (mod_time & 0x1f) << 1;
1660 
1661   t.tm_year = ((mod_time >> 25) & 0x7f) + 80;
1662   t.tm_mon = ((mod_time >> 21) & 0xf) - 1;
1663   t.tm_mday = (mod_time >> 16) & 0x1f;
1664 
1665   return t;
1666 }
1667 
1668 namespace zip_archive {
1669 
Inflate(const Reader & reader,const uint64_t compressed_length,const uint64_t uncompressed_length,Writer * writer,uint64_t * crc_out)1670 int32_t Inflate(const Reader& reader, const uint64_t compressed_length,
1671                 const uint64_t uncompressed_length, Writer* writer,
1672                 uint64_t* crc_out) {
1673   return inflateImpl<false>(reader, compressed_length, uncompressed_length,
1674                             writer, crc_out);
1675 }
1676 
1677 //
1678 // ZIPARCHIVE_DISABLE_CALLBACK_API disables all APIs that accept user callbacks.
1679 // It gets defined for the incfs-supporting version of libziparchive, where one
1680 // has to control all the code accessing the archive. See more at
1681 // incfs_support/signal_handling.h
1682 //
1683 #if !ZIPARCHIVE_DISABLE_CALLBACK_API
1684 
ExtractToWriter(ZipArchiveHandle handle,const ZipEntry64 * entry,zip_archive::Writer * writer)1685 int32_t ExtractToWriter(ZipArchiveHandle handle, const ZipEntry64* entry,
1686                         zip_archive::Writer* writer) {
1687   return extractToWriter(handle, entry, writer);
1688 }
1689 
1690 #endif  // !ZIPARCHIVE_DISABLE_CALLBACK_API
1691 
1692 }  // namespace zip_archive
1693