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