blob: db273ec7bf777bcb0d5e2e5b6e763c5ea4828095 [file] [log] [blame]
Brian Carlstromb0460ea2011-07-29 10:08:05 -07001/*
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#include "zip_archive.h"
18
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070019#include <vector>
20
Brian Carlstromb0460ea2011-07-29 10:08:05 -070021#include <fcntl.h>
Ian Rogers8d31bbd2013-10-13 10:44:14 -070022#include <stdio.h>
Brian Carlstromb0460ea2011-07-29 10:08:05 -070023#include <sys/stat.h>
24#include <sys/types.h>
25#include <unistd.h>
26
Ian Rogers8d31bbd2013-10-13 10:44:14 -070027#include "base/stringprintf.h"
Elliott Hughes76160052012-12-12 16:31:20 -080028#include "base/unix_file/fd_file.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070029#include "UniquePtr.h"
30
Brian Carlstromb0460ea2011-07-29 10:08:05 -070031namespace art {
32
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070033static const size_t kBufSize = 32 * KB;
34
Brian Carlstromb0460ea2011-07-29 10:08:05 -070035// Get 2 little-endian bytes.
Brian Carlstromdb4d5402011-08-09 12:18:28 -070036static uint32_t Le16ToHost(const byte* src) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070037 return ((src[0] << 0) |
38 (src[1] << 8));
39}
40
41// Get 4 little-endian bytes.
Brian Carlstromdb4d5402011-08-09 12:18:28 -070042static uint32_t Le32ToHost(const byte* src) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070043 return ((src[0] << 0) |
44 (src[1] << 8) |
45 (src[2] << 16) |
46 (src[3] << 24));
47}
48
49uint16_t ZipEntry::GetCompressionMethod() {
50 return Le16ToHost(ptr_ + ZipArchive::kCDEMethod);
51}
52
53uint32_t ZipEntry::GetCompressedLength() {
54 return Le32ToHost(ptr_ + ZipArchive::kCDECompLen);
55}
56
57uint32_t ZipEntry::GetUncompressedLength() {
58 return Le32ToHost(ptr_ + ZipArchive::kCDEUncompLen);
59}
60
61uint32_t ZipEntry::GetCrc32() {
62 return Le32ToHost(ptr_ + ZipArchive::kCDECRC);
63}
64
Kenny Root72fcca22013-09-19 09:25:34 -070065off64_t ZipEntry::GetDataOffset() {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070066 // All we have is the offset to the Local File Header, which is
67 // variable size, so we have to read the contents of the struct to
68 // figure out where the actual data starts.
69
70 // We also need to make sure that the lengths are not so large that
71 // somebody trying to map the compressed or uncompressed data runs
72 // off the end of the mapped region.
73
Kenny Root72fcca22013-09-19 09:25:34 -070074 off64_t dir_offset = zip_archive_->dir_offset_;
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070075 int64_t lfh_offset = Le32ToHost(ptr_ + ZipArchive::kCDELocalOffset);
76 if (lfh_offset + ZipArchive::kLFHLen >= dir_offset) {
77 LOG(WARNING) << "Zip: bad LFH offset in zip";
Brian Carlstromb0460ea2011-07-29 10:08:05 -070078 return -1;
79 }
80
Kenny Root72fcca22013-09-19 09:25:34 -070081 if (lseek64(zip_archive_->fd_, lfh_offset, SEEK_SET) != lfh_offset) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070082 PLOG(WARNING) << "Zip: failed seeking to LFH at offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070083 return -1;
84 }
85
86 uint8_t lfh_buf[ZipArchive::kLFHLen];
87 ssize_t actual = TEMP_FAILURE_RETRY(read(zip_archive_->fd_, lfh_buf, sizeof(lfh_buf)));
88 if (actual != sizeof(lfh_buf)) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070089 LOG(WARNING) << "Zip: failed reading LFH from offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070090 return -1;
91 }
92
93 if (Le32ToHost(lfh_buf) != ZipArchive::kLFHSignature) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070094 LOG(WARNING) << "Zip: didn't find signature at start of LFH, offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070095 return -1;
96 }
97
Kenny Root72fcca22013-09-19 09:25:34 -070098 uint32_t gpbf = Le16ToHost(lfh_buf + ZipArchive::kLFHGPBFlags);
99 if ((gpbf & ZipArchive::kGPFUnsupportedMask) != 0) {
100 LOG(WARNING) << "Invalid General Purpose Bit Flag: " << gpbf;
101 return -1;
102 }
103
104 off64_t data_offset = (lfh_offset + ZipArchive::kLFHLen
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700105 + Le16ToHost(lfh_buf + ZipArchive::kLFHNameLen)
106 + Le16ToHost(lfh_buf + ZipArchive::kLFHExtraLen));
107 if (data_offset >= dir_offset) {
108 LOG(WARNING) << "Zip: bad data offset " << data_offset << " in zip";
109 return -1;
110 }
111
112 // check lengths
113
Kenny Root72fcca22013-09-19 09:25:34 -0700114 if (static_cast<off64_t>(data_offset + GetCompressedLength()) > dir_offset) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700115 LOG(WARNING) << "Zip: bad compressed length in zip "
116 << "(" << data_offset << " + " << GetCompressedLength()
117 << " > " << dir_offset << ")";
118 return -1;
119 }
120
121 if (GetCompressionMethod() == kCompressStored
Kenny Root72fcca22013-09-19 09:25:34 -0700122 && static_cast<off64_t>(data_offset + GetUncompressedLength()) > dir_offset) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700123 LOG(WARNING) << "Zip: bad uncompressed length in zip "
124 << "(" << data_offset << " + " << GetUncompressedLength()
125 << " > " << dir_offset << ")";
126 return -1;
127 }
128
129 return data_offset;
130}
131
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700132static bool CopyFdToMemory(uint8_t* begin, size_t size, int in, size_t count) {
133 uint8_t* dst = begin;
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700134 std::vector<uint8_t> buf(kBufSize);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700135 while (count != 0) {
136 size_t bytes_to_read = (count > kBufSize) ? kBufSize : count;
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700137 ssize_t actual = TEMP_FAILURE_RETRY(read(in, &buf[0], bytes_to_read));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700138 if (actual != static_cast<ssize_t>(bytes_to_read)) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800139 PLOG(WARNING) << "Zip: short read";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700140 return false;
141 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800142 memcpy(dst, &buf[0], bytes_to_read);
143 dst += bytes_to_read;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700144 count -= bytes_to_read;
145 }
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700146 DCHECK_EQ(dst, begin + size);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700147 return true;
148}
149
150class ZStream {
151 public:
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700152 ZStream(byte* write_buf, size_t write_buf_size) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700153 // Initialize the zlib stream struct.
154 memset(&zstream_, 0, sizeof(zstream_));
155 zstream_.zalloc = Z_NULL;
156 zstream_.zfree = Z_NULL;
157 zstream_.opaque = Z_NULL;
158 zstream_.next_in = NULL;
159 zstream_.avail_in = 0;
160 zstream_.next_out = reinterpret_cast<Bytef*>(write_buf);
161 zstream_.avail_out = write_buf_size;
162 zstream_.data_type = Z_UNKNOWN;
163 }
164
165 z_stream& Get() {
166 return zstream_;
167 }
168
169 ~ZStream() {
170 inflateEnd(&zstream_);
171 }
172 private:
173 z_stream zstream_;
174};
175
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700176static bool InflateToMemory(uint8_t* begin, size_t size,
177 int in, size_t uncompressed_length, size_t compressed_length) {
178 uint8_t* dst = begin;
Elliott Hughes90a33692011-08-30 13:27:07 -0700179 UniquePtr<uint8_t[]> read_buf(new uint8_t[kBufSize]);
180 UniquePtr<uint8_t[]> write_buf(new uint8_t[kBufSize]);
181 if (read_buf.get() == NULL || write_buf.get() == NULL) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800182 LOG(WARNING) << "Zip: failed to allocate buffer to inflate";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700183 return false;
184 }
185
Elliott Hughes90a33692011-08-30 13:27:07 -0700186 UniquePtr<ZStream> zstream(new ZStream(write_buf.get(), kBufSize));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700187
188 // Use the undocumented "negative window bits" feature to tell zlib
189 // that there's no zlib header waiting for it.
190 int zerr = inflateInit2(&zstream->Get(), -MAX_WBITS);
191 if (zerr != Z_OK) {
192 if (zerr == Z_VERSION_ERROR) {
193 LOG(ERROR) << "Installed zlib is not compatible with linked version (" << ZLIB_VERSION << ")";
194 } else {
195 LOG(WARNING) << "Call to inflateInit2 failed (zerr=" << zerr << ")";
196 }
197 return false;
198 }
199
200 size_t remaining = compressed_length;
201 do {
202 // read as much as we can
203 if (zstream->Get().avail_in == 0) {
204 size_t bytes_to_read = (remaining > kBufSize) ? kBufSize : remaining;
205
206 ssize_t actual = TEMP_FAILURE_RETRY(read(in, read_buf.get(), bytes_to_read));
207 if (actual != static_cast<ssize_t>(bytes_to_read)) {
208 LOG(WARNING) << "Zip: inflate read failed (" << actual << " vs " << bytes_to_read << ")";
209 return false;
210 }
211 remaining -= bytes_to_read;
212 zstream->Get().next_in = read_buf.get();
213 zstream->Get().avail_in = bytes_to_read;
214 }
215
216 // uncompress the data
217 zerr = inflate(&zstream->Get(), Z_NO_FLUSH);
218 if (zerr != Z_OK && zerr != Z_STREAM_END) {
219 LOG(WARNING) << "Zip: inflate zerr=" << zerr
Elliott Hughes24edeb52012-06-18 15:29:46 -0700220 << " (next_in=" << zstream->Get().next_in
221 << " avail_in=" << zstream->Get().avail_in
222 << " next_out=" << zstream->Get().next_out
223 << " avail_out=" << zstream->Get().avail_out
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700224 << ")";
225 return false;
226 }
227
228 // write when we're full or when we're done
229 if (zstream->Get().avail_out == 0 ||
230 (zerr == Z_STREAM_END && zstream->Get().avail_out != kBufSize)) {
231 size_t bytes_to_write = zstream->Get().next_out - write_buf.get();
Brian Carlstrom89521892011-12-07 22:05:07 -0800232 memcpy(dst, write_buf.get(), bytes_to_write);
233 dst += bytes_to_write;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700234 zstream->Get().next_out = write_buf.get();
235 zstream->Get().avail_out = kBufSize;
236 }
237 } while (zerr == Z_OK);
238
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700239 DCHECK_EQ(zerr, Z_STREAM_END); // other errors should've been caught
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700240
241 // paranoia
242 if (zstream->Get().total_out != uncompressed_length) {
243 LOG(WARNING) << "Zip: size mismatch on inflated file ("
244 << zstream->Get().total_out << " vs " << uncompressed_length << ")";
245 return false;
246 }
247
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700248 DCHECK_EQ(dst, begin + size);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700249 return true;
250}
251
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700252bool ZipEntry::ExtractToFile(File& file, std::string* error_msg) {
Brian Carlstrom89521892011-12-07 22:05:07 -0800253 uint32_t length = GetUncompressedLength();
254 int result = TEMP_FAILURE_RETRY(ftruncate(file.Fd(), length));
255 if (result == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700256 *error_msg = StringPrintf("Zip: failed to ftruncate '%s' to length %ud", file.GetPath().c_str(),
257 length);
Brian Carlstrom89521892011-12-07 22:05:07 -0800258 return false;
259 }
260
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700261 UniquePtr<MemMap> map(MemMap::MapFile(length, PROT_READ | PROT_WRITE, MAP_SHARED, file.Fd(), 0,
262 file.GetPath().c_str(), error_msg));
Brian Carlstrom89521892011-12-07 22:05:07 -0800263 if (map.get() == NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700264 *error_msg = StringPrintf("Zip: failed to mmap space for '%s': %s", file.GetPath().c_str(),
265 error_msg->c_str());
Brian Carlstrom89521892011-12-07 22:05:07 -0800266 return false;
267 }
268
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700269 return ExtractToMemory(map->Begin(), map->Size(), error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -0800270}
271
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700272bool ZipEntry::ExtractToMemory(uint8_t* begin, size_t size, std::string* error_msg) {
Brian Carlstromafa8ff62013-07-26 15:58:56 -0700273 // If size is zero, data offset will be meaningless, so bail out early.
274 if (size == 0) {
275 return true;
276 }
Kenny Root72fcca22013-09-19 09:25:34 -0700277 off64_t data_offset = GetDataOffset();
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700278 if (data_offset == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700279 *error_msg = StringPrintf("Zip: data_offset=%lld", data_offset);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700280 return false;
281 }
Kenny Root72fcca22013-09-19 09:25:34 -0700282 if (lseek64(zip_archive_->fd_, data_offset, SEEK_SET) != data_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700283 *error_msg = StringPrintf("Zip: lseek to data at %lld failed", data_offset);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700284 return false;
285 }
286
287 // TODO: this doesn't verify the data's CRC, but probably should (especially
288 // for uncompressed data).
289 switch (GetCompressionMethod()) {
290 case kCompressStored:
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700291 return CopyFdToMemory(begin, size, zip_archive_->fd_, GetUncompressedLength());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700292 case kCompressDeflated:
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700293 return InflateToMemory(begin, size, zip_archive_->fd_,
294 GetUncompressedLength(), GetCompressedLength());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700295 default:
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700296 *error_msg = StringPrintf("Zip: unknown compression method 0x%x", GetCompressionMethod());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700297 return false;
298 }
299}
300
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700301MemMap* ZipEntry::ExtractToMemMap(const char* entry_filename, std::string* error_msg) {
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700302 std::string name(entry_filename);
303 name += " extracted in memory from ";
304 name += entry_filename;
305 UniquePtr<MemMap> map(MemMap::MapAnonymous(name.c_str(),
306 NULL,
307 GetUncompressedLength(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700308 PROT_READ | PROT_WRITE, error_msg));
309 if (map.get() == nullptr) {
310 DCHECK(!error_msg->empty());
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700311 return NULL;
312 }
313
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700314 bool success = ExtractToMemory(map->Begin(), map->Size(), error_msg);
Brian Carlstrom4922e9d2013-07-09 17:18:47 -0700315 if (!success) {
316 LOG(ERROR) << "Zip: Failed to extract '" << entry_filename << "' to memory";
317 return NULL;
318 }
319
320 return map.release();
321}
322
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800323static void SetCloseOnExec(int fd) {
324 // This dance is more portable than Linux's O_CLOEXEC open(2) flag.
325 int flags = fcntl(fd, F_GETFD);
326 if (flags == -1) {
327 PLOG(WARNING) << "fcntl(" << fd << ", F_GETFD) failed";
328 return;
329 }
330 int rc = fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
331 if (rc == -1) {
332 PLOG(WARNING) << "fcntl(" << fd << ", F_SETFD, " << flags << ") failed";
333 return;
334 }
335}
336
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700337ZipArchive* ZipArchive::Open(const char* filename, std::string* error_msg) {
338 DCHECK(filename != nullptr);
339 int fd = open(filename, O_RDONLY, 0);
Elliott Hughesad6c9c32012-01-19 17:39:12 -0800340 if (fd == -1) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700341 *error_msg = StringPrintf("Zip: unable to open '%s': %s", filename, strerror(errno));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700342 return NULL;
343 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700344 return OpenFromFd(fd, filename, error_msg);
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700345}
346
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700347ZipArchive* ZipArchive::OpenFromFd(int fd, const char* filename, std::string* error_msg) {
Brian Carlstrom7c3d13a2013-09-04 17:15:11 -0700348 SetCloseOnExec(fd);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700349 UniquePtr<ZipArchive> zip_archive(new ZipArchive(fd, filename));
350 CHECK(zip_archive.get() != nullptr);
351 if (!zip_archive->MapCentralDirectory(error_msg)) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700352 zip_archive->Close();
353 return NULL;
354 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700355 if (!zip_archive->Parse(error_msg)) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700356 zip_archive->Close();
357 return NULL;
358 }
359 return zip_archive.release();
360}
361
Brian Carlstroma6cc8932012-01-04 14:44:07 -0800362ZipEntry* ZipArchive::Find(const char* name) const {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700363 DCHECK(name != NULL);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700364 DirEntries::const_iterator it = dir_entries_.find(name);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700365 if (it == dir_entries_.end()) {
366 return NULL;
367 }
368 return new ZipEntry(this, (*it).second);
369}
370
371void ZipArchive::Close() {
372 if (fd_ != -1) {
373 close(fd_);
374 }
375 fd_ = -1;
376 num_entries_ = 0;
377 dir_offset_ = 0;
378}
379
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700380std::string ZipArchive::ErrorStringPrintf(const char* fmt, ...) {
381 va_list ap;
382 va_start(ap, fmt);
383 std::string result(StringPrintf("Zip '%s' : ", filename_.c_str()));
384 StringAppendV(&result, fmt, ap);
385 va_end(ap);
386 return result;
387}
388
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700389// Find the zip Central Directory and memory-map it.
390//
391// On success, returns true after populating fields from the EOCD area:
392// num_entries_
393// dir_offset_
394// dir_map_
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700395bool ZipArchive::MapCentralDirectory(std::string* error_msg) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700396 /*
397 * Get and test file length.
398 */
Kenny Root72fcca22013-09-19 09:25:34 -0700399 off64_t file_length = lseek64(fd_, 0, SEEK_END);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700400 if (file_length < kEOCDLen) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700401 *error_msg = ErrorStringPrintf("length %lld is too small to be zip", file_length);
Kenny Root72fcca22013-09-19 09:25:34 -0700402 return false;
403 }
404
405 size_t read_amount = kMaxEOCDSearch;
406 if (file_length < off64_t(read_amount)) {
407 read_amount = file_length;
408 }
409
410 UniquePtr<uint8_t[]> scan_buf(new uint8_t[read_amount]);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700411 CHECK(scan_buf.get() != nullptr);
Kenny Root72fcca22013-09-19 09:25:34 -0700412
413 /*
414 * Make sure this is a Zip archive.
415 */
416 if (lseek64(fd_, 0, SEEK_SET) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700417 *error_msg = ErrorStringPrintf("seek to start failed: %s", strerror(errno));
Kenny Root72fcca22013-09-19 09:25:34 -0700418 return false;
419 }
420
421 ssize_t actual = TEMP_FAILURE_RETRY(read(fd_, scan_buf.get(), sizeof(int32_t)));
422 if (actual != static_cast<ssize_t>(sizeof(int32_t))) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700423 *error_msg = ErrorStringPrintf("couldn\'t read first signature from zip archive: %s",
424 strerror(errno));
Kenny Root72fcca22013-09-19 09:25:34 -0700425 return false;
426 }
427
428 unsigned int header = Le32ToHost(scan_buf.get());
429 if (header != kLFHSignature) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700430 *error_msg = ErrorStringPrintf("not a zip archive (found 0x%x)", header);
Kenny Root72fcca22013-09-19 09:25:34 -0700431 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700432 }
433
434 // Perform the traditional EOCD snipe hunt.
435 //
436 // We're searching for the End of Central Directory magic number,
437 // which appears at the start of the EOCD block. It's followed by
438 // 18 bytes of EOCD stuff and up to 64KB of archive comment. We
439 // need to read the last part of the file into a buffer, dig through
440 // it to find the magic number, parse some values out, and use those
441 // to determine the extent of the CD.
442 //
443 // We start by pulling in the last part of the file.
Kenny Root72fcca22013-09-19 09:25:34 -0700444 off64_t search_start = file_length - read_amount;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700445
Kenny Root72fcca22013-09-19 09:25:34 -0700446 if (lseek64(fd_, search_start, SEEK_SET) != search_start) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700447 *error_msg = ErrorStringPrintf("seek %lld failed: %s", search_start, strerror(errno));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700448 return false;
449 }
Kenny Root72fcca22013-09-19 09:25:34 -0700450 actual = TEMP_FAILURE_RETRY(read(fd_, scan_buf.get(), read_amount));
451 if (actual != static_cast<ssize_t>(read_amount)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700452 *error_msg = ErrorStringPrintf("read %lld, expected %zd. %s", search_start, read_amount,
453 strerror(errno));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700454 return false;
455 }
456
457
458 // Scan backward for the EOCD magic. In an archive without a trailing
459 // comment, we'll find it on the first try. (We may want to consider
460 // doing an initial minimal read; if we don't find it, retry with a
461 // second read as above.)
462 int i;
463 for (i = read_amount - kEOCDLen; i >= 0; i--) {
464 if (scan_buf.get()[i] == 0x50 && Le32ToHost(&(scan_buf.get())[i]) == kEOCDSignature) {
465 break;
466 }
467 }
468 if (i < 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700469 *error_msg = ErrorStringPrintf("EOCD not found, not a zip file");
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700470 return false;
471 }
472
Kenny Root72fcca22013-09-19 09:25:34 -0700473 off64_t eocd_offset = search_start + i;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700474 const byte* eocd_ptr = scan_buf.get() + i;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700475
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700476 CHECK(eocd_offset < file_length);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700477
478 // Grab the CD offset and size, and the number of entries in the
479 // archive. Verify that they look reasonable.
Kenny Root72fcca22013-09-19 09:25:34 -0700480 uint16_t disk_number = Le16ToHost(eocd_ptr + kEOCDDiskNumber);
481 uint16_t disk_with_central_dir = Le16ToHost(eocd_ptr + kEOCDDiskNumberForCD);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700482 uint16_t num_entries = Le16ToHost(eocd_ptr + kEOCDNumEntries);
Kenny Root72fcca22013-09-19 09:25:34 -0700483 uint16_t total_num_entries = Le16ToHost(eocd_ptr + kEOCDTotalNumEntries);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700484 uint32_t dir_size = Le32ToHost(eocd_ptr + kEOCDSize);
485 uint32_t dir_offset = Le32ToHost(eocd_ptr + kEOCDFileOffset);
Kenny Root72fcca22013-09-19 09:25:34 -0700486 uint16_t comment_size = Le16ToHost(eocd_ptr + kEOCDCommentSize);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700487
488 if ((uint64_t) dir_offset + (uint64_t) dir_size > (uint64_t) eocd_offset) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700489 *error_msg = ErrorStringPrintf("bad offsets (dir=%ud, size=%ud, eocd=%lld)",
490 dir_offset, dir_size, eocd_offset);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700491 return false;
492 }
493 if (num_entries == 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700494 *error_msg = ErrorStringPrintf("empty archive?");
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700495 return false;
Kenny Root72fcca22013-09-19 09:25:34 -0700496 } else if (num_entries != total_num_entries || disk_number != 0 || disk_with_central_dir != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700497 *error_msg = ErrorStringPrintf("spanned archives not supported");
Kenny Root72fcca22013-09-19 09:25:34 -0700498 return false;
499 }
500
501 // Check to see if comment is a sane size
502 if ((comment_size > (file_length - kEOCDLen))
503 || (eocd_offset > (file_length - kEOCDLen) - comment_size)) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700504 *error_msg = ErrorStringPrintf("comment size runs off end of file");
Kenny Root72fcca22013-09-19 09:25:34 -0700505 return false;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700506 }
507
508 // It all looks good. Create a mapping for the CD.
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700509 dir_map_.reset(MemMap::MapFile(dir_size, PROT_READ, MAP_SHARED, fd_, dir_offset,
510 filename_.c_str(), error_msg));
Elliott Hughes90a33692011-08-30 13:27:07 -0700511 if (dir_map_.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700512 return false;
513 }
514
515 num_entries_ = num_entries;
516 dir_offset_ = dir_offset;
517 return true;
518}
519
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700520bool ZipArchive::Parse(std::string* error_msg) {
Ian Rogers30fab402012-01-23 15:43:46 -0800521 const byte* cd_ptr = dir_map_->Begin();
522 size_t cd_length = dir_map_->Size();
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700523
524 // Walk through the central directory, adding entries to the hash
525 // table and verifying values.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700526 const byte* ptr = cd_ptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700527 for (int i = 0; i < num_entries_; i++) {
528 if (Le32ToHost(ptr) != kCDESignature) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700529 *error_msg = ErrorStringPrintf("missed a central dir sig (at %d)", i);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700530 return false;
531 }
532 if (ptr + kCDELen > cd_ptr + cd_length) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700533 *error_msg = ErrorStringPrintf("ran off the end (at %d)", i);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700534 return false;
535 }
536
537 int64_t local_hdr_offset = Le32ToHost(ptr + kCDELocalOffset);
538 if (local_hdr_offset >= dir_offset_) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700539 *error_msg = ErrorStringPrintf("bad LFH offset %lld at entry %d", local_hdr_offset, i);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700540 return false;
541 }
542
Kenny Root72fcca22013-09-19 09:25:34 -0700543 uint16_t gpbf = Le16ToHost(ptr + kCDEGPBFlags);
544 if ((gpbf & kGPFUnsupportedMask) != 0) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700545 *error_msg = ErrorStringPrintf("invalid general purpose bit flag %x", gpbf);
Kenny Root72fcca22013-09-19 09:25:34 -0700546 return false;
547 }
548
549 uint16_t name_len = Le16ToHost(ptr + kCDENameLen);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700550 uint16_t extra_len = Le16ToHost(ptr + kCDEExtraLen);
551 uint16_t comment_len = Le16ToHost(ptr + kCDECommentLen);
552
553 // add the CDE filename to the hash table
554 const char* name = reinterpret_cast<const char*>(ptr + kCDELen);
Kenny Root72fcca22013-09-19 09:25:34 -0700555
556 // Check name for NULL characters
557 if (memchr(name, 0, name_len) != NULL) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700558 *error_msg = ErrorStringPrintf("filename contains NUL byte");
Kenny Root72fcca22013-09-19 09:25:34 -0700559 return false;
560 }
561
562 dir_entries_.Put(StringPiece(name, name_len), ptr);
563 ptr += kCDELen + name_len + extra_len + comment_len;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700564 if (ptr > cd_ptr + cd_length) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700565 *error_msg = ErrorStringPrintf("bad CD advance (%p vs %p) at entry %d",
566 ptr, cd_ptr + cd_length, i);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700567 return false;
568 }
569 }
570 return true;
571}
572
573} // namespace art