blob: 8c77391e9cb2f19da5c9f54f96e0a1aeb0423c5c [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
225 DCHECK(zerr == Z_STREAM_END); // other errors should've been caught
226
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 -0700260// return new ZipArchive instance on success, NULL on error.
261ZipArchive* 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 }
Elliott Hughes90a33692011-08-30 13:27:07 -0700268 UniquePtr<ZipArchive> zip_archive(new ZipArchive(fd));
269 if (zip_archive.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700270 return NULL;
271 }
272 if (!zip_archive->MapCentralDirectory()) {
273 zip_archive->Close();
274 return NULL;
275 }
276 if (!zip_archive->Parse()) {
277 zip_archive->Close();
278 return NULL;
279 }
280 return zip_archive.release();
281}
282
283ZipEntry* ZipArchive::Find(const char* name) {
284 DCHECK(name != NULL);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700285 DirEntries::const_iterator it = dir_entries_.find(name);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700286 if (it == dir_entries_.end()) {
287 return NULL;
288 }
289 return new ZipEntry(this, (*it).second);
290}
291
292void ZipArchive::Close() {
293 if (fd_ != -1) {
294 close(fd_);
295 }
296 fd_ = -1;
297 num_entries_ = 0;
298 dir_offset_ = 0;
299}
300
301// Find the zip Central Directory and memory-map it.
302//
303// On success, returns true after populating fields from the EOCD area:
304// num_entries_
305// dir_offset_
306// dir_map_
307bool ZipArchive::MapCentralDirectory() {
308 /*
309 * Get and test file length.
310 */
311 off_t file_length = lseek(fd_, 0, SEEK_END);
312 if (file_length < kEOCDLen) {
313 LOG(WARNING) << "Zip: length " << file_length << " is too small to be zip";
314 return false;
315 }
316
317 // Perform the traditional EOCD snipe hunt.
318 //
319 // We're searching for the End of Central Directory magic number,
320 // which appears at the start of the EOCD block. It's followed by
321 // 18 bytes of EOCD stuff and up to 64KB of archive comment. We
322 // need to read the last part of the file into a buffer, dig through
323 // it to find the magic number, parse some values out, and use those
324 // to determine the extent of the CD.
325 //
326 // We start by pulling in the last part of the file.
327 size_t read_amount = kMaxEOCDSearch;
328 if (file_length < off_t(read_amount)) {
329 read_amount = file_length;
330 }
331
Elliott Hughes90a33692011-08-30 13:27:07 -0700332 UniquePtr<uint8_t[]> scan_buf(new uint8_t[read_amount]);
333 if (scan_buf.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700334 return false;
335 }
336
337 off_t search_start = file_length - read_amount;
338
339 if (lseek(fd_, search_start, SEEK_SET) != search_start) {
340 LOG(WARNING) << "Zip: seek " << search_start << " failed: " << strerror(errno);
341 return false;
342 }
343 ssize_t actual = TEMP_FAILURE_RETRY(read(fd_, scan_buf.get(), read_amount));
344 if (actual == -1) {
345 LOG(WARNING) << "Zip: read " << read_amount << " failed: " << strerror(errno);
346 return false;
347 }
348
349
350 // Scan backward for the EOCD magic. In an archive without a trailing
351 // comment, we'll find it on the first try. (We may want to consider
352 // doing an initial minimal read; if we don't find it, retry with a
353 // second read as above.)
354 int i;
355 for (i = read_amount - kEOCDLen; i >= 0; i--) {
356 if (scan_buf.get()[i] == 0x50 && Le32ToHost(&(scan_buf.get())[i]) == kEOCDSignature) {
357 break;
358 }
359 }
360 if (i < 0) {
361 LOG(WARNING) << "Zip: EOCD not found, not a zip file";
362 return false;
363 }
364
365 off_t eocd_offset = search_start + i;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700366 const byte* eocd_ptr = scan_buf.get() + i;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700367
368 DCHECK(eocd_offset < file_length);
369
370 // Grab the CD offset and size, and the number of entries in the
371 // archive. Verify that they look reasonable.
372 uint16_t num_entries = Le16ToHost(eocd_ptr + kEOCDNumEntries);
373 uint32_t dir_size = Le32ToHost(eocd_ptr + kEOCDSize);
374 uint32_t dir_offset = Le32ToHost(eocd_ptr + kEOCDFileOffset);
375
376 if ((uint64_t) dir_offset + (uint64_t) dir_size > (uint64_t) eocd_offset) {
377 LOG(WARNING) << "Zip: bad offsets ("
378 << "dir=" << dir_offset << ", "
379 << "size=" << dir_size << ", "
380 << "eocd=" << eocd_offset << ")";
381 return false;
382 }
383 if (num_entries == 0) {
384 LOG(WARNING) << "Zip: empty archive?";
385 return false;
386 }
387
388 // It all looks good. Create a mapping for the CD.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700389 dir_map_.reset(MemMap::Map(dir_size, PROT_READ, MAP_SHARED, fd_, dir_offset));
Elliott Hughes90a33692011-08-30 13:27:07 -0700390 if (dir_map_.get() == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700391 return false;
392 }
393
394 num_entries_ = num_entries;
395 dir_offset_ = dir_offset;
396 return true;
397}
398
399bool ZipArchive::Parse() {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700400 const byte* cd_ptr = dir_map_->GetAddress();
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700401 size_t cd_length = dir_map_->GetLength();
402
403 // Walk through the central directory, adding entries to the hash
404 // table and verifying values.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700405 const byte* ptr = cd_ptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700406 for (int i = 0; i < num_entries_; i++) {
407 if (Le32ToHost(ptr) != kCDESignature) {
408 LOG(WARNING) << "Zip: missed a central dir sig (at " << i << ")";
409 return false;
410 }
411 if (ptr + kCDELen > cd_ptr + cd_length) {
412 LOG(WARNING) << "Zip: ran off the end (at " << i << ")";
413 return false;
414 }
415
416 int64_t local_hdr_offset = Le32ToHost(ptr + kCDELocalOffset);
417 if (local_hdr_offset >= dir_offset_) {
418 LOG(WARNING) << "Zip: bad LFH offset " << local_hdr_offset << " at entry " << i;
419 return false;
420 }
421
422 uint16_t filename_len = Le16ToHost(ptr + kCDENameLen);
423 uint16_t extra_len = Le16ToHost(ptr + kCDEExtraLen);
424 uint16_t comment_len = Le16ToHost(ptr + kCDECommentLen);
425
426 // add the CDE filename to the hash table
427 const char* name = reinterpret_cast<const char*>(ptr + kCDELen);
428 bool success = dir_entries_.insert(std::make_pair(StringPiece(name, filename_len), ptr)).second;
429 if (!success) {
430 return false;
431 }
432 ptr += kCDELen + filename_len + extra_len + comment_len;
433 if (ptr > cd_ptr + cd_length) {
434 LOG(WARNING) << "Zip: bad CD advance "
435 << "(" << ptr << " vs " << (cd_ptr + cd_length) << ") "
436 << "at entry " << i;
437 return false;
438 }
439 }
440 return true;
441}
442
443} // namespace art