blob: cccaf82d603d5214ed2f957d8af4cd43f0407220 [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
24namespace art {
25
26// Get 2 little-endian bytes.
Brian Carlstromdb4d5402011-08-09 12:18:28 -070027static uint32_t Le16ToHost(const byte* src) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070028 return ((src[0] << 0) |
29 (src[1] << 8));
30}
31
32// Get 4 little-endian bytes.
Brian Carlstromdb4d5402011-08-09 12:18:28 -070033static uint32_t Le32ToHost(const byte* src) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -070034 return ((src[0] << 0) |
35 (src[1] << 8) |
36 (src[2] << 16) |
37 (src[3] << 24));
38}
39
40uint16_t ZipEntry::GetCompressionMethod() {
41 return Le16ToHost(ptr_ + ZipArchive::kCDEMethod);
42}
43
44uint32_t ZipEntry::GetCompressedLength() {
45 return Le32ToHost(ptr_ + ZipArchive::kCDECompLen);
46}
47
48uint32_t ZipEntry::GetUncompressedLength() {
49 return Le32ToHost(ptr_ + ZipArchive::kCDEUncompLen);
50}
51
52uint32_t ZipEntry::GetCrc32() {
53 return Le32ToHost(ptr_ + ZipArchive::kCDECRC);
54}
55
56off_t ZipEntry::GetDataOffset() {
57 // All we have is the offset to the Local File Header, which is
58 // variable size, so we have to read the contents of the struct to
59 // figure out where the actual data starts.
60
61 // We also need to make sure that the lengths are not so large that
62 // somebody trying to map the compressed or uncompressed data runs
63 // off the end of the mapped region.
64
65 off_t dir_offset = zip_archive_->dir_offset_;
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070066 int64_t lfh_offset = Le32ToHost(ptr_ + ZipArchive::kCDELocalOffset);
67 if (lfh_offset + ZipArchive::kLFHLen >= dir_offset) {
68 LOG(WARNING) << "Zip: bad LFH offset in zip";
Brian Carlstromb0460ea2011-07-29 10:08:05 -070069 return -1;
70 }
71
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070072 if (lseek(zip_archive_->fd_, lfh_offset, SEEK_SET) != lfh_offset) {
73 PLOG(WARNING) << "Zip: failed seeking to LFH at offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070074 return -1;
75 }
76
77 uint8_t lfh_buf[ZipArchive::kLFHLen];
78 ssize_t actual = TEMP_FAILURE_RETRY(read(zip_archive_->fd_, lfh_buf, sizeof(lfh_buf)));
79 if (actual != sizeof(lfh_buf)) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070080 LOG(WARNING) << "Zip: failed reading LFH from offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070081 return -1;
82 }
83
84 if (Le32ToHost(lfh_buf) != ZipArchive::kLFHSignature) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070085 LOG(WARNING) << "Zip: didn't find signature at start of LFH, offset " << lfh_offset;
Brian Carlstromb0460ea2011-07-29 10:08:05 -070086 return -1;
87 }
88
Brian Carlstrom0024d6c2011-08-09 08:26:12 -070089 off_t data_offset = (lfh_offset + ZipArchive::kLFHLen
Brian Carlstromb0460ea2011-07-29 10:08:05 -070090 + Le16ToHost(lfh_buf + ZipArchive::kLFHNameLen)
91 + Le16ToHost(lfh_buf + ZipArchive::kLFHExtraLen));
92 if (data_offset >= dir_offset) {
93 LOG(WARNING) << "Zip: bad data offset " << data_offset << " in zip";
94 return -1;
95 }
96
97 // check lengths
98
99 if (static_cast<off_t>(data_offset + GetCompressedLength()) > dir_offset) {
100 LOG(WARNING) << "Zip: bad compressed length in zip "
101 << "(" << data_offset << " + " << GetCompressedLength()
102 << " > " << dir_offset << ")";
103 return -1;
104 }
105
106 if (GetCompressionMethod() == kCompressStored
107 && static_cast<off_t>(data_offset + GetUncompressedLength()) > dir_offset) {
108 LOG(WARNING) << "Zip: bad uncompressed length in zip "
109 << "(" << data_offset << " + " << GetUncompressedLength()
110 << " > " << dir_offset << ")";
111 return -1;
112 }
113
114 return data_offset;
115}
116
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700117static bool CopyFdToFile(File& file, int in, size_t count) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700118 const size_t kBufSize = 32768;
119 uint8_t buf[kBufSize];
120
121 while (count != 0) {
122 size_t bytes_to_read = (count > kBufSize) ? kBufSize : count;
123 ssize_t actual = TEMP_FAILURE_RETRY(read(in, buf, bytes_to_read));
124 if (actual != static_cast<ssize_t>(bytes_to_read)) {
125 return false;
126 }
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700127 if (!file.WriteFully(buf, bytes_to_read)) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700128 return false;
129 }
130 count -= bytes_to_read;
131 }
132 return true;
133}
134
135class ZStream {
136 public:
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700137 ZStream(byte* write_buf, size_t write_buf_size) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700138 // Initialize the zlib stream struct.
139 memset(&zstream_, 0, sizeof(zstream_));
140 zstream_.zalloc = Z_NULL;
141 zstream_.zfree = Z_NULL;
142 zstream_.opaque = Z_NULL;
143 zstream_.next_in = NULL;
144 zstream_.avail_in = 0;
145 zstream_.next_out = reinterpret_cast<Bytef*>(write_buf);
146 zstream_.avail_out = write_buf_size;
147 zstream_.data_type = Z_UNKNOWN;
148 }
149
150 z_stream& Get() {
151 return zstream_;
152 }
153
154 ~ZStream() {
155 inflateEnd(&zstream_);
156 }
157 private:
158 z_stream zstream_;
159};
160
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700161static bool InflateToFile(File& out, int in, size_t uncompressed_length, size_t compressed_length) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700162 const size_t kBufSize = 32768;
Elliott Hughese0fc0ef2011-08-12 17:39:17 -0700163 scoped_array<uint8_t> read_buf(new uint8_t[kBufSize]);
164 scoped_array<uint8_t> write_buf(new uint8_t[kBufSize]);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700165 if (read_buf == NULL || write_buf == NULL) {
166 return false;
167 }
168
169 scoped_ptr<ZStream> zstream(new ZStream(write_buf.get(), kBufSize));
170
171 // Use the undocumented "negative window bits" feature to tell zlib
172 // that there's no zlib header waiting for it.
173 int zerr = inflateInit2(&zstream->Get(), -MAX_WBITS);
174 if (zerr != Z_OK) {
175 if (zerr == Z_VERSION_ERROR) {
176 LOG(ERROR) << "Installed zlib is not compatible with linked version (" << ZLIB_VERSION << ")";
177 } else {
178 LOG(WARNING) << "Call to inflateInit2 failed (zerr=" << zerr << ")";
179 }
180 return false;
181 }
182
183 size_t remaining = compressed_length;
184 do {
185 // read as much as we can
186 if (zstream->Get().avail_in == 0) {
187 size_t bytes_to_read = (remaining > kBufSize) ? kBufSize : remaining;
188
189 ssize_t actual = TEMP_FAILURE_RETRY(read(in, read_buf.get(), bytes_to_read));
190 if (actual != static_cast<ssize_t>(bytes_to_read)) {
191 LOG(WARNING) << "Zip: inflate read failed (" << actual << " vs " << bytes_to_read << ")";
192 return false;
193 }
194 remaining -= bytes_to_read;
195 zstream->Get().next_in = read_buf.get();
196 zstream->Get().avail_in = bytes_to_read;
197 }
198
199 // uncompress the data
200 zerr = inflate(&zstream->Get(), Z_NO_FLUSH);
201 if (zerr != Z_OK && zerr != Z_STREAM_END) {
202 LOG(WARNING) << "Zip: inflate zerr=" << zerr
203 << " (nIn=" << zstream->Get().next_in
204 << " aIn=" << zstream->Get().avail_in
205 << " nOut=" << zstream->Get().next_out
206 << " aOut=" << zstream->Get().avail_out
207 << ")";
208 return false;
209 }
210
211 // write when we're full or when we're done
212 if (zstream->Get().avail_out == 0 ||
213 (zerr == Z_STREAM_END && zstream->Get().avail_out != kBufSize)) {
214 size_t bytes_to_write = zstream->Get().next_out - write_buf.get();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700215 if (!out.WriteFully(write_buf.get(), bytes_to_write)) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700216 return false;
217 }
218 zstream->Get().next_out = write_buf.get();
219 zstream->Get().avail_out = kBufSize;
220 }
221 } while (zerr == Z_OK);
222
223 DCHECK(zerr == Z_STREAM_END); // other errors should've been caught
224
225 // paranoia
226 if (zstream->Get().total_out != uncompressed_length) {
227 LOG(WARNING) << "Zip: size mismatch on inflated file ("
228 << zstream->Get().total_out << " vs " << uncompressed_length << ")";
229 return false;
230 }
231
232 return true;
233}
234
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700235bool ZipEntry::Extract(File& file) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700236
237 off_t data_offset = GetDataOffset();
238 if (data_offset == -1) {
239 return false;
240 }
241 if (lseek(zip_archive_->fd_, data_offset, SEEK_SET) != data_offset) {
242 PLOG(WARNING) << "Zip: lseek to data at " << data_offset << " failed";
243 return false;
244 }
245
246 // TODO: this doesn't verify the data's CRC, but probably should (especially
247 // for uncompressed data).
248 switch (GetCompressionMethod()) {
249 case kCompressStored:
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700250 return CopyFdToFile(file, zip_archive_->fd_, GetUncompressedLength());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700251 case kCompressDeflated:
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700252 return InflateToFile(file, zip_archive_->fd_, GetUncompressedLength(), GetCompressedLength());
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700253 default:
254 return false;
255 }
256}
257
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700258// return new ZipArchive instance on success, NULL on error.
259ZipArchive* ZipArchive::Open(const std::string& filename) {
260 DCHECK(!filename.empty());
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700261 int fd = open(filename.c_str(), O_RDONLY | O_CLOEXEC, 0);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700262 if (fd < 0) {
Brian Carlstrom0024d6c2011-08-09 08:26:12 -0700263 PLOG(WARNING) << "Unable to open '" << filename << "'";
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700264 return NULL;
265 }
266 scoped_ptr<ZipArchive> zip_archive(new ZipArchive(fd));
267 if (zip_archive == NULL) {
268 return NULL;
269 }
270 if (!zip_archive->MapCentralDirectory()) {
271 zip_archive->Close();
272 return NULL;
273 }
274 if (!zip_archive->Parse()) {
275 zip_archive->Close();
276 return NULL;
277 }
278 return zip_archive.release();
279}
280
281ZipEntry* ZipArchive::Find(const char* name) {
282 DCHECK(name != NULL);
Brian Carlstrom7e93b502011-08-04 14:16:22 -0700283 DirEntries::const_iterator it = dir_entries_.find(name);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700284 if (it == dir_entries_.end()) {
285 return NULL;
286 }
287 return new ZipEntry(this, (*it).second);
288}
289
290void ZipArchive::Close() {
291 if (fd_ != -1) {
292 close(fd_);
293 }
294 fd_ = -1;
295 num_entries_ = 0;
296 dir_offset_ = 0;
297}
298
299// Find the zip Central Directory and memory-map it.
300//
301// On success, returns true after populating fields from the EOCD area:
302// num_entries_
303// dir_offset_
304// dir_map_
305bool ZipArchive::MapCentralDirectory() {
306 /*
307 * Get and test file length.
308 */
309 off_t file_length = lseek(fd_, 0, SEEK_END);
310 if (file_length < kEOCDLen) {
311 LOG(WARNING) << "Zip: length " << file_length << " is too small to be zip";
312 return false;
313 }
314
315 // Perform the traditional EOCD snipe hunt.
316 //
317 // We're searching for the End of Central Directory magic number,
318 // which appears at the start of the EOCD block. It's followed by
319 // 18 bytes of EOCD stuff and up to 64KB of archive comment. We
320 // need to read the last part of the file into a buffer, dig through
321 // it to find the magic number, parse some values out, and use those
322 // to determine the extent of the CD.
323 //
324 // We start by pulling in the last part of the file.
325 size_t read_amount = kMaxEOCDSearch;
326 if (file_length < off_t(read_amount)) {
327 read_amount = file_length;
328 }
329
Elliott Hughes40ef99e2011-08-11 17:44:34 -0700330 scoped_array<uint8_t> scan_buf(new uint8_t[read_amount]);
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700331 if (scan_buf == NULL) {
332 return false;
333 }
334
335 off_t search_start = file_length - read_amount;
336
337 if (lseek(fd_, search_start, SEEK_SET) != search_start) {
338 LOG(WARNING) << "Zip: seek " << search_start << " failed: " << strerror(errno);
339 return false;
340 }
341 ssize_t actual = TEMP_FAILURE_RETRY(read(fd_, scan_buf.get(), read_amount));
342 if (actual == -1) {
343 LOG(WARNING) << "Zip: read " << read_amount << " failed: " << strerror(errno);
344 return false;
345 }
346
347
348 // Scan backward for the EOCD magic. In an archive without a trailing
349 // comment, we'll find it on the first try. (We may want to consider
350 // doing an initial minimal read; if we don't find it, retry with a
351 // second read as above.)
352 int i;
353 for (i = read_amount - kEOCDLen; i >= 0; i--) {
354 if (scan_buf.get()[i] == 0x50 && Le32ToHost(&(scan_buf.get())[i]) == kEOCDSignature) {
355 break;
356 }
357 }
358 if (i < 0) {
359 LOG(WARNING) << "Zip: EOCD not found, not a zip file";
360 return false;
361 }
362
363 off_t eocd_offset = search_start + i;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700364 const byte* eocd_ptr = scan_buf.get() + i;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700365
366 DCHECK(eocd_offset < file_length);
367
368 // Grab the CD offset and size, and the number of entries in the
369 // archive. Verify that they look reasonable.
370 uint16_t num_entries = Le16ToHost(eocd_ptr + kEOCDNumEntries);
371 uint32_t dir_size = Le32ToHost(eocd_ptr + kEOCDSize);
372 uint32_t dir_offset = Le32ToHost(eocd_ptr + kEOCDFileOffset);
373
374 if ((uint64_t) dir_offset + (uint64_t) dir_size > (uint64_t) eocd_offset) {
375 LOG(WARNING) << "Zip: bad offsets ("
376 << "dir=" << dir_offset << ", "
377 << "size=" << dir_size << ", "
378 << "eocd=" << eocd_offset << ")";
379 return false;
380 }
381 if (num_entries == 0) {
382 LOG(WARNING) << "Zip: empty archive?";
383 return false;
384 }
385
386 // It all looks good. Create a mapping for the CD.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700387 dir_map_.reset(MemMap::Map(dir_size, PROT_READ, MAP_SHARED, fd_, dir_offset));
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700388 if (dir_map_ == NULL) {
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700389 return false;
390 }
391
392 num_entries_ = num_entries;
393 dir_offset_ = dir_offset;
394 return true;
395}
396
397bool ZipArchive::Parse() {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700398 const byte* cd_ptr = dir_map_->GetAddress();
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700399 size_t cd_length = dir_map_->GetLength();
400
401 // Walk through the central directory, adding entries to the hash
402 // table and verifying values.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700403 const byte* ptr = cd_ptr;
Brian Carlstromb0460ea2011-07-29 10:08:05 -0700404 for (int i = 0; i < num_entries_; i++) {
405 if (Le32ToHost(ptr) != kCDESignature) {
406 LOG(WARNING) << "Zip: missed a central dir sig (at " << i << ")";
407 return false;
408 }
409 if (ptr + kCDELen > cd_ptr + cd_length) {
410 LOG(WARNING) << "Zip: ran off the end (at " << i << ")";
411 return false;
412 }
413
414 int64_t local_hdr_offset = Le32ToHost(ptr + kCDELocalOffset);
415 if (local_hdr_offset >= dir_offset_) {
416 LOG(WARNING) << "Zip: bad LFH offset " << local_hdr_offset << " at entry " << i;
417 return false;
418 }
419
420 uint16_t filename_len = Le16ToHost(ptr + kCDENameLen);
421 uint16_t extra_len = Le16ToHost(ptr + kCDEExtraLen);
422 uint16_t comment_len = Le16ToHost(ptr + kCDECommentLen);
423
424 // add the CDE filename to the hash table
425 const char* name = reinterpret_cast<const char*>(ptr + kCDELen);
426 bool success = dir_entries_.insert(std::make_pair(StringPiece(name, filename_len), ptr)).second;
427 if (!success) {
428 return false;
429 }
430 ptr += kCDELen + filename_len + extra_len + comment_len;
431 if (ptr > cd_ptr + cd_length) {
432 LOG(WARNING) << "Zip: bad CD advance "
433 << "(" << ptr << " vs " << (cd_ptr + cd_length) << ") "
434 << "at entry " << i;
435 return false;
436 }
437 }
438 return true;
439}
440
441} // namespace art