blob: fb5d23c1e84b5aefa8d85302f1e4bf3875d2bcbf [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>
22#include <sys/stat.h>
23#include <sys/types.h>
24#include <unistd.h>
25
Elliott Hughes90a33692011-08-30 13:27:07 -070026#include "UniquePtr.h"
27
Brian Carlstromb0460ea2011-07-29 10:08:05 -070028namespace art {
29
Elliott Hughes3b6baaa2011-10-14 19:13:56 -070030static const size_t kBufSize = 32 * KB;
31
Brian Carlstromb0460ea2011-07-29 10:08:05 -070032// Get 2 little-endian bytes.
Brian Carlstromdb4d5402011-08-09 12:18:28 -070033static uint32_t Le16ToHost(const byte* src) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070034 return ((src[0] << 0) |
35 (src[1] << 8));
36}
37
38// Get 4 little-endian bytes.
Brian Carlstromdb4d5402011-08-09 12:18:28 -070039static uint32_t Le32ToHost(const byte* src) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070040 return ((src[0] << 0) |
41 (src[1] << 8) |
42 (src[2] << 16) |
43 (src[3] << 24));
44}
45
46uint16_t ZipEntry::GetCompressionMethod() {
47 return Le16ToHost(ptr_ + ZipArchive::kCDEMethod);
48}
49
50uint32_t ZipEntry::GetCompressedLength() {
51 return Le32ToHost(ptr_ + ZipArchive::kCDECompLen);
52}
53
54uint32_t ZipEntry::GetUncompressedLength() {
55 return Le32ToHost(ptr_ + ZipArchive::kCDEUncompLen);
56}
57
58uint32_t ZipEntry::GetCrc32() {
59 return Le32ToHost(ptr_ + ZipArchive::kCDECRC);
60}
61
62off_t ZipEntry::GetDataOffset() {
63 // All we have is the offset to the Local File Header, which is
64 // variable size, so we have to read the contents of the struct to
65 // figure out where the actual data starts.
66
67 // We also need to make sure that the lengths are not so large that
68 // somebody trying to map the compressed or uncompressed data runs
69 // off the end of the mapped region.
70
71 off_t dir_offset = zip_archive_->dir_offset_;
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070072 int64_t lfh_offset = Le32ToHost(ptr_ + ZipArchive::kCDELocalOffset);
73 if (lfh_offset + ZipArchive::kLFHLen >= dir_offset) {
74 LOG(WARNING) << "Zip: bad LFH offset in zip";
Brian Carlstromb0460ea2011-07-29 10:08:05 -070075 return -1;
76 }
77
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070078 if (lseek(zip_archive_->fd_, lfh_offset, SEEK_SET) != lfh_offset) {
79 PLOG(WARNING) << "Zip: failed seeking to LFH at offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070080 return -1;
81 }
82
83 uint8_t lfh_buf[ZipArchive::kLFHLen];
84 ssize_t actual = TEMP_FAILURE_RETRY(read(zip_archive_->fd_, lfh_buf, sizeof(lfh_buf)));
85 if (actual != sizeof(lfh_buf)) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070086 LOG(WARNING) << "Zip: failed reading LFH from offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070087 return -1;
88 }
89
90 if (Le32ToHost(lfh_buf) != ZipArchive::kLFHSignature) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070091 LOG(WARNING) << "Zip: didn't find signature at start of LFH, offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070092 return -1;
93 }
94
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070095 off_t data_offset = (lfh_offset + ZipArchive::kLFHLen
Brian Carlstromb0460ea2011-07-29 10:08:05 -070096 + Le16ToHost(lfh_buf + ZipArchive::kLFHNameLen)
97 + Le16ToHost(lfh_buf + ZipArchive::kLFHExtraLen));
98 if (data_offset >= dir_offset) {
99 LOG(WARNING) << "Zip: bad data offset " << data_offset << " in zip";
100 return -1;
101 }
102
103 // check lengths
104
105 if (static_cast<off_t>(data_offset + GetCompressedLength()) > dir_offset) {
106 LOG(WARNING) << "Zip: bad compressed length in zip "
107 << "(" << data_offset << " + " << GetCompressedLength()
108 << " > " << dir_offset << ")";
109 return -1;
110 }
111
112 if (GetCompressionMethod() == kCompressStored
113 && static_cast<off_t>(data_offset + GetUncompressedLength()) > dir_offset) {
114 LOG(WARNING) << "Zip: bad uncompressed length in zip "
115 << "(" << data_offset << " + " << GetUncompressedLength()
116 << " > " << dir_offset << ")";
117 return -1;
118 }
119
120 return data_offset;
121}
122
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700123static bool CopyFdToFile(File& file, int in, size_t count) {
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700124 std::vector<uint8_t> buf(kBufSize);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700125 while (count != 0) {
126 size_t bytes_to_read = (count > kBufSize) ? kBufSize : count;
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700127 ssize_t actual = TEMP_FAILURE_RETRY(read(in, &buf[0], bytes_to_read));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700128 if (actual != static_cast<ssize_t>(bytes_to_read)) {
129 return false;
130 }
Elliott Hughes3b6baaa2011-10-14 19:13:56 -0700131 if (!file.WriteFully(&buf[0], bytes_to_read)) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700132 return false;
133 }
134 count -= bytes_to_read;
135 }
136 return true;
137}
138
139class ZStream {
140 public:
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700141 ZStream(byte* write_buf, size_t write_buf_size) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700142 // Initialize the zlib stream struct.
143 memset(&zstream_, 0, sizeof(zstream_));
144 zstream_.zalloc = Z_NULL;
145 zstream_.zfree = Z_NULL;
146 zstream_.opaque = Z_NULL;
147 zstream_.next_in = NULL;
148 zstream_.avail_in = 0;
149 zstream_.next_out = reinterpret_cast<Bytef*>(write_buf);
150 zstream_.avail_out = write_buf_size;
151 zstream_.data_type = Z_UNKNOWN;
152 }
153
154 z_stream& Get() {
155 return zstream_;
156 }
157
158 ~ZStream() {
159 inflateEnd(&zstream_);
160 }
161 private:
162 z_stream zstream_;
163};
164
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700165static bool InflateToFile(File& out, int in, size_t uncompressed_length, size_t compressed_length) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700166 UniquePtr<uint8_t[]> read_buf(new uint8_t[kBufSize]);
167 UniquePtr<uint8_t[]> write_buf(new uint8_t[kBufSize]);
168 if (read_buf.get() == NULL || write_buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700169 return false;
170 }
171
Elliott Hughes90a33692011-08-30 13:27:07 -0700172 UniquePtr<ZStream> zstream(new ZStream(write_buf.get(), kBufSize));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700173
174 // Use the undocumented "negative window bits" feature to tell zlib
175 // that there's no zlib header waiting for it.
176 int zerr = inflateInit2(&zstream->Get(), -MAX_WBITS);
177 if (zerr != Z_OK) {
178 if (zerr == Z_VERSION_ERROR) {
179 LOG(ERROR) << "Installed zlib is not compatible with linked version (" << ZLIB_VERSION << ")";
180 } else {
181 LOG(WARNING) << "Call to inflateInit2 failed (zerr=" << zerr << ")";
182 }
183 return false;
184 }
185
186 size_t remaining = compressed_length;
187 do {
188 // read as much as we can
189 if (zstream->Get().avail_in == 0) {
190 size_t bytes_to_read = (remaining > kBufSize) ? kBufSize : remaining;
191
192 ssize_t actual = TEMP_FAILURE_RETRY(read(in, read_buf.get(), bytes_to_read));
193 if (actual != static_cast<ssize_t>(bytes_to_read)) {
194 LOG(WARNING) << "Zip: inflate read failed (" << actual << " vs " << bytes_to_read << ")";
195 return false;
196 }
197 remaining -= bytes_to_read;
198 zstream->Get().next_in = read_buf.get();
199 zstream->Get().avail_in = bytes_to_read;
200 }
201
202 // uncompress the data
203 zerr = inflate(&zstream->Get(), Z_NO_FLUSH);
204 if (zerr != Z_OK && zerr != Z_STREAM_END) {
205 LOG(WARNING) << "Zip: inflate zerr=" << zerr
206 << " (nIn=" << zstream->Get().next_in
207 << " aIn=" << zstream->Get().avail_in
208 << " nOut=" << zstream->Get().next_out
209 << " aOut=" << zstream->Get().avail_out
210 << ")";
211 return false;
212 }
213
214 // write when we're full or when we're done
215 if (zstream->Get().avail_out == 0 ||
216 (zerr == Z_STREAM_END && zstream->Get().avail_out != kBufSize)) {
217 size_t bytes_to_write = zstream->Get().next_out - write_buf.get();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700218 if (!out.WriteFully(write_buf.get(), bytes_to_write)) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700219 return false;
220 }
221 zstream->Get().next_out = write_buf.get();
222 zstream->Get().avail_out = kBufSize;
223 }
224 } while (zerr == Z_OK);
225
Elliott Hughesf5a7a472011-10-07 14:31:02 -0700226 DCHECK_EQ(zerr, Z_STREAM_END); // other errors should've been caught
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700227
228 // paranoia
229 if (zstream->Get().total_out != uncompressed_length) {
230 LOG(WARNING) << "Zip: size mismatch on inflated file ("
231 << zstream->Get().total_out << " vs " << uncompressed_length << ")";
232 return false;
233 }
234
235 return true;
236}
237
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700238bool ZipEntry::Extract(File& file) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700239
240 off_t data_offset = GetDataOffset();
241 if (data_offset == -1) {
242 return false;
243 }
244 if (lseek(zip_archive_->fd_, data_offset, SEEK_SET) != data_offset) {
245 PLOG(WARNING) << "Zip: lseek to data at " << data_offset << " failed";
246 return false;
247 }
248
249 // TODO: this doesn't verify the data's CRC, but probably should (especially
250 // for uncompressed data).
251 switch (GetCompressionMethod()) {
252 case kCompressStored:
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700253 return CopyFdToFile(file, zip_archive_->fd_, GetUncompressedLength());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700254 case kCompressDeflated:
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700255 return InflateToFile(file, zip_archive_->fd_, GetUncompressedLength(), GetCompressedLength());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700256 default:
257 return false;
258 }
259}
260
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700261ZipArchive* ZipArchive::Open(const std::string& filename) {
262 DCHECK(!filename.empty());
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700263 int fd = open(filename.c_str(), O_RDONLY | O_CLOEXEC, 0);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700264 if (fd < 0) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700265 PLOG(WARNING) << "Unable to open '" << filename << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700266 return NULL;
267 }
Brian Carlstromb7bbba42011-10-13 14:58:47 -0700268 return Open(fd);
269}
270
271ZipArchive* ZipArchive::Open(int fd) {
Elliott Hughes90a33692011-08-30 13:27:07 -0700272 UniquePtr<ZipArchive> zip_archive(new ZipArchive(fd));
273 if (zip_archive.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700274 return NULL;
275 }
276 if (!zip_archive->MapCentralDirectory()) {
277 zip_archive->Close();
278 return NULL;
279 }
280 if (!zip_archive->Parse()) {
281 zip_archive->Close();
282 return NULL;
283 }
284 return zip_archive.release();
285}
286
287ZipEntry* ZipArchive::Find(const char* name) {
288 DCHECK(name != NULL);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700289 DirEntries::const_iterator it = dir_entries_.find(name);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700290 if (it == dir_entries_.end()) {
291 return NULL;
292 }
293 return new ZipEntry(this, (*it).second);
294}
295
296void ZipArchive::Close() {
297 if (fd_ != -1) {
298 close(fd_);
299 }
300 fd_ = -1;
301 num_entries_ = 0;
302 dir_offset_ = 0;
303}
304
305// Find the zip Central Directory and memory-map it.
306//
307// On success, returns true after populating fields from the EOCD area:
308// num_entries_
309// dir_offset_
310// dir_map_
311bool ZipArchive::MapCentralDirectory() {
312 /*
313 * Get and test file length.
314 */
315 off_t file_length = lseek(fd_, 0, SEEK_END);
316 if (file_length < kEOCDLen) {
317 LOG(WARNING) << "Zip: length " << file_length << " is too small to be zip";
318 return false;
319 }
320
321 // Perform the traditional EOCD snipe hunt.
322 //
323 // We're searching for the End of Central Directory magic number,
324 // which appears at the start of the EOCD block. It's followed by
325 // 18 bytes of EOCD stuff and up to 64KB of archive comment. We
326 // need to read the last part of the file into a buffer, dig through
327 // it to find the magic number, parse some values out, and use those
328 // to determine the extent of the CD.
329 //
330 // We start by pulling in the last part of the file.
331 size_t read_amount = kMaxEOCDSearch;
332 if (file_length < off_t(read_amount)) {
333 read_amount = file_length;
334 }
335
Elliott Hughes90a33692011-08-30 13:27:07 -0700336 UniquePtr<uint8_t[]> scan_buf(new uint8_t[read_amount]);
337 if (scan_buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700338 return false;
339 }
340
341 off_t search_start = file_length - read_amount;
342
343 if (lseek(fd_, search_start, SEEK_SET) != search_start) {
344 LOG(WARNING) << "Zip: seek " << search_start << " failed: " << strerror(errno);
345 return false;
346 }
347 ssize_t actual = TEMP_FAILURE_RETRY(read(fd_, scan_buf.get(), read_amount));
348 if (actual == -1) {
349 LOG(WARNING) << "Zip: read " << read_amount << " failed: " << strerror(errno);
350 return false;
351 }
352
353
354 // Scan backward for the EOCD magic. In an archive without a trailing
355 // comment, we'll find it on the first try. (We may want to consider
356 // doing an initial minimal read; if we don't find it, retry with a
357 // second read as above.)
358 int i;
359 for (i = read_amount - kEOCDLen; i >= 0; i--) {
360 if (scan_buf.get()[i] == 0x50 && Le32ToHost(&(scan_buf.get())[i]) == kEOCDSignature) {
361 break;
362 }
363 }
364 if (i < 0) {
365 LOG(WARNING) << "Zip: EOCD not found, not a zip file";
366 return false;
367 }
368
369 off_t eocd_offset = search_start + i;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700370 const byte* eocd_ptr = scan_buf.get() + i;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700371
372 DCHECK(eocd_offset < file_length);
373
374 // Grab the CD offset and size, and the number of entries in the
375 // archive. Verify that they look reasonable.
376 uint16_t num_entries = Le16ToHost(eocd_ptr + kEOCDNumEntries);
377 uint32_t dir_size = Le32ToHost(eocd_ptr + kEOCDSize);
378 uint32_t dir_offset = Le32ToHost(eocd_ptr + kEOCDFileOffset);
379
380 if ((uint64_t) dir_offset + (uint64_t) dir_size > (uint64_t) eocd_offset) {
381 LOG(WARNING) << "Zip: bad offsets ("
382 << "dir=" << dir_offset << ", "
383 << "size=" << dir_size << ", "
384 << "eocd=" << eocd_offset << ")";
385 return false;
386 }
387 if (num_entries == 0) {
388 LOG(WARNING) << "Zip: empty archive?";
389 return false;
390 }
391
392 // It all looks good. Create a mapping for the CD.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700393 dir_map_.reset(MemMap::Map(dir_size, PROT_READ, MAP_SHARED, fd_, dir_offset));
Elliott Hughes90a33692011-08-30 13:27:07 -0700394 if (dir_map_.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700395 return false;
396 }
397
398 num_entries_ = num_entries;
399 dir_offset_ = dir_offset;
400 return true;
401}
402
403bool ZipArchive::Parse() {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700404 const byte* cd_ptr = dir_map_->GetAddress();
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700405 size_t cd_length = dir_map_->GetLength();
406
407 // Walk through the central directory, adding entries to the hash
408 // table and verifying values.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700409 const byte* ptr = cd_ptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700410 for (int i = 0; i < num_entries_; i++) {
411 if (Le32ToHost(ptr) != kCDESignature) {
412 LOG(WARNING) << "Zip: missed a central dir sig (at " << i << ")";
413 return false;
414 }
415 if (ptr + kCDELen > cd_ptr + cd_length) {
416 LOG(WARNING) << "Zip: ran off the end (at " << i << ")";
417 return false;
418 }
419
420 int64_t local_hdr_offset = Le32ToHost(ptr + kCDELocalOffset);
421 if (local_hdr_offset >= dir_offset_) {
422 LOG(WARNING) << "Zip: bad LFH offset " << local_hdr_offset << " at entry " << i;
423 return false;
424 }
425
426 uint16_t filename_len = Le16ToHost(ptr + kCDENameLen);
427 uint16_t extra_len = Le16ToHost(ptr + kCDEExtraLen);
428 uint16_t comment_len = Le16ToHost(ptr + kCDECommentLen);
429
430 // add the CDE filename to the hash table
431 const char* name = reinterpret_cast<const char*>(ptr + kCDELen);
432 bool success = dir_entries_.insert(std::make_pair(StringPiece(name, filename_len), ptr)).second;
433 if (!success) {
434 return false;
435 }
436 ptr += kCDELen + filename_len + extra_len + comment_len;
437 if (ptr > cd_ptr + cd_length) {
438 LOG(WARNING) << "Zip: bad CD advance "
439 << "(" << ptr << " vs " << (cd_ptr + cd_length) << ") "
440 << "at entry " << i;
441 return false;
442 }
443 }
444 return true;
445}
446
447} // namespace art